docs(agents): 同步 drizzle 0.x 降级后的指引

修正 AGENTS.md 里与 1.0 beta 相关的过时条目(drizzle-orm/zod、
defineRelations、RQB v2 对象语法等),改为记录当前真实用法:
drizzle-zod 包、`drizzle({ schema })`、RQB v1 回调写法。顺手裁掉
通用的 Biome/TS 说明,补上几条仓库特有的坑(Nitro 插件在 vite.config
里注册、distroless cc 变体、无 CI/pre-commit 等)。
This commit is contained in:
2026-04-24 20:13:56 +08:00
parent 75c77159b4
commit 4518a63959
+96 -136
View File
@@ -1,167 +1,127 @@
# AGENTS.md — AI Coding Agent Guidelines # AGENTS.md
## Project Overview Compact, repo-specific notes for AI agents. Generic language/framework knowledge is omitted — only things that will bite you if you don't know.
> **This project uses [Bun](https://bun.sh) exclusively. Do NOT use Node.js / npm / yarn / pnpm. Always use `bun run <script>` (not `bun <script>`) to avoid conflicts with Bun built-in subcommands.** ## Stack & runtime
- **Framework**: TanStack Start (React 19 SSR, file-based routing) - **Bun-only** (`mise.toml` pins `bun = 1.3.13`). Never invoke `npm`/`npx`/`node`/`yarn`/`pnpm`. Use `bun run <script>` (bare `bun <script>` can collide with Bun built-in subcommands).
- **Runtime/PM**: Bun (see `mise.toml`) — **NOT Node.js / npm / yarn / pnpm** - TanStack Start (React 19 SSR, file-routed) + Vite 8 + Nitro (nightly, preset `bun`). Vite dev port is **strict 3000**.
- **Language**: TypeScript (strict mode) | **Styling**: Tailwind CSS v4 - PostgreSQL + **Drizzle ORM `0.45.2` (0.x, NOT 1.0 beta)** — see "Drizzle" section, this matters a lot.
- **Database**: PostgreSQL + Drizzle ORM v1 beta (`drizzle-orm/postgres-js`, RQBv2) - ORPC (contract-first), TanStack Query v5, Tailwind v4.
- **State**: TanStack Query v5 | **RPC**: ORPC (contract-first) | **Build**: Vite + Nitro
## Commands ## Scripts
```bash ```bash
bun run dev # Vite dev server (localhost:3000) bun run dev # bunx --bun vite dev (localhost:3000)
bun run build # Production build → .output/ bun run build # bunx --bun vite build → .output/
bun run compile # Compile to standalone binary (current platform) bun run compile # bun compile.ts → out/server-<target> (standalone binary)
bun run fix # Biome auto-fix (lint + format, runs `biome check --write`) bun run typecheck # tsc --noEmit
bun run typecheck # TypeScript check (`tsc --noEmit`) bun run fix # biome check --write (lint + format + organize imports)
bun run db:push # Push schema to dev DB (dev only, fast iteration) bun run db:push # dev only — push schema to DB, no migration file
bun run db:generate # Generate migration SQL files (for production) bun run db:generate # produce SQL migration files in ./drizzle
bun run db:migrate # Apply migrations (production deployment) bun run db:migrate # apply migrations (also auto-run at prod server startup)
bun run db:studio # Drizzle Studio GUI bun run db:studio # Drizzle Studio
bun test path/to/test.ts # Run single test (not yet configured)
docker compose up --build # Build image & start app + postgres
docker compose up -d # Start in background (detached)
docker compose down # Stop and remove containers
``` ```
## Code Style Cross-compile targets live under `compile:{linux,darwin,windows}[:arch]`. `compile.ts` accepts `--target bun-<os>-<arch>`; default derives from host.
**Formatting (Biome):** 2-space indent, LF, single quotes, semicolons as needed (omitted unless syntactically required), max line width **120**, arrow parens always `(x) => x` Before committing: `bun run fix && bun run typecheck`. No CI, no pre-commit hooks, no lint-staged — so these are on you.
**Imports** — Biome auto-organizes alphabetically within two groups. `import type` is interleaved in its group alphabetically, NOT a separate group: ## Drizzle (v0.x — critical)
```typescript
// 1) External packages (alphabetical, types interleaved)
import { useSuspenseQuery } from '@tanstack/react-query'
import { createFileRoute } from '@tanstack/react-router'
import type { ReactNode } from 'react'
// 2) @/* aliases (alphabetical, types interleaved)
import { orpc } from '@/client/orpc'
import { TodoForm } from '@/components/TodoForm'
import type { RouterClient } from '@/server/api/types'
```
**TypeScript:** `strict: true`, `noUncheckedIndexedAccess`, `verbatimModuleSyntax`, `erasableSyntaxOnly`. Use `@/*` path aliases (→ `src/*`). For root-level files outside `src/`, use `@/../file` (e.g., `@/../package.json`). **Why it matters:** the project was on 1.0 beta and was rolled back. Online docs default to 1.0 beta APIs that do NOT exist here. If typecheck complains, you are probably importing a 1.0 beta API.
**Naming:** Files (utils): `kebab-case.ts` | Files (components): `PascalCase.tsx` | Components: `const Button = () => {}` | Functions: `camelCase` | Constants: `UPPER_SNAKE` | Types: `PascalCase` - Driver: `drizzle-orm/postgres-js`. Do NOT use `drizzle-orm/bun-sql`.
- `drizzle()` is called with `{ connection, schema }` where `schema = import * as schema from '@/server/db/schema'`. There is **no `relations.ts`** and **no `defineRelations`** in 0.x.
- Zod generators live in the separate `drizzle-zod` package (`^0.8.3`). Import from `drizzle-zod`, **not** `drizzle-orm/zod` (that subpath only exists in 1.0 beta).
- Relational queries use **RQB v1 callback syntax**:
```ts
db.query.todoTable.findMany({
orderBy: (t, { desc }) => desc(t.createdAt),
})
```
Do NOT use the v2 object form (`orderBy: { createdAt: 'desc' }`, `where: { id }`) — it won't type-check.
- To add relations later: declare per-table with `relations()` from `drizzle-orm` and export them from the same file as the table; they get picked up automatically because `index.ts` does `drizzle({ schema })` via `import *`.
- Every table must spread `...generatedFields` from `src/server/db/fields.ts` (gives `id` UUIDv7 with `$defaultFn` fallback, `createdAt`, `updatedAt` with `$onUpdateFn`). There's also a `generatedFieldKeys` helper to feed `createInsertSchema(...).omit(...)`.
- `drizzle.config.ts` runs outside Vite — `@/*` path aliases do NOT resolve there. It currently does `import { env } from './src/env'` (relative). Preserve that.
- The `./drizzle/` migrations directory is gitignored-by-absence right now (no migrations yet). `src/server/plugins/migrate.ts` runs `migrate(db, { migrationsFolder: './drizzle' })` at server startup, but only when `!import.meta.dev`. Dev uses `db:push`. Don't mix `push` and `migrate` on the same DB.
**React:** Arrow function components (Biome enforced via `useArrowFunction: "error"`). Routes: `export const Route = createFileRoute(...)`. Data: `useSuspenseQuery(orpc.feature.list.queryOptions())` ## ORPC
**Errors:** `ORPCError` with codes (`NOT_FOUND`, `INTERNAL_SERVER_ERROR`, `INPUT_VALIDATION_FAILED`). Never empty catch blocks. Validation errors are auto-transformed by interceptors (see ORPC section). Contract → Router → Handler → Client, all type-safe from a single contract.
## ORPC Pattern - `os` is built in `src/server/api/server.ts` via `implement(contract).$context<BaseContext>()`. **Always import `os` from `@/server/api/server`**, never from `@orpc/server` directly. `ORPCError`, `onError`, `ValidationError` come from `@orpc/server`.
- Contracts (`src/server/api/contracts/*.contract.ts`) generate Zod from Drizzle tables via `drizzle-zod`:
```ts
const insertSchema = createInsertSchema(todoTable).omit(generatedFieldKeys)
```
Barrel-aggregated in `contracts/index.ts` as `export const contract = { todo }`.
- Routers chain the `db` middleware (`src/server/api/middlewares/db.middleware.ts`, injects the `getDB()` singleton into context). Barrel in `routers/index.ts` builds `os.router({ todo })`.
- **Interceptors are attached at the handler level, not in `server.ts` and not on `os`.** Both `src/routes/api/rpc.$.ts` (`RPCHandler`) and `src/routes/api/$.ts` (`OpenAPIHandler`) register `[onError(logError)]` (server) and `[onError(handleValidationError)]` (client). The validation interceptor rewrites `BAD_REQUEST + ValidationError` into `INPUT_VALIDATION_FAILED` (422) and output validation errors into `OUTPUT_VALIDATION_FAILED`.
- OpenAPI/Scalar: docs at `/api/docs`, spec at `/api/spec.json` (handler prefix `/api`, plugin paths `/docs` and `/spec.json`).
- **SSR isomorphism** (`src/client/orpc.ts`): `createIsomorphicFn().server(createRouterClient(...)).client(new RPCLink(...))`. Server branch reads `getRequestHeaders()` for context; client branch POSTs to `${origin}/api/rpc`.
- **Global mutation invalidation** uses `experimental_defaults` in `createTanstackQueryUtils(...)` — currently invalidates `orpc.todo.list.key()` on every `todo.{create,update,remove}` success. Add new features here rather than in each mutation site.
- SSR prefetch in route loaders: `await context.queryClient.ensureQueryData(orpc.todo.list.queryOptions())`. Components use `useSuspenseQuery(orpc.feature.list.queryOptions())`.
**Contract → Router → Handler → Client** (fully type-safe, zero manual type definitions): ## Code style (Biome)
**1. Contract** (`src/server/api/contracts/feature.contract.ts`) — Zod schemas **generated from Drizzle tables**: - 2-space, LF, single quotes, **semicolons as-needed** (omitted unless required), 120-col, arrow parens always, `useArrowFunction: "error"` — so React components must be `const Foo = () => {...}` not `function Foo() {}`. Also `noReactPropAssignments: "error"`.
```typescript - Imports are auto-organized into two groups (external, then `@/*`), each alphabetical, with `import type` interleaved (NOT a separate group). `bun run fix` handles this; don't hand-sort.
const selectSchema = createSelectSchema(featureTable) - Files: utils `kebab-case.ts`, components `PascalCase.tsx`.
const insertSchema = createInsertSchema(featureTable).omit(generatedFieldKeys) - `routeTree.gen.ts` is generated — ignored by Biome, never edit.
export const list = oc.input(z.void()).output(z.array(selectSchema))
export const create = oc.input(insertSchema).output(selectSchema)
```
**2. Router** (`src/server/api/routers/feature.router.ts`) — Handlers chaining `db` middleware: ## TypeScript
```typescript
export const list = os.feature.list.use(db).handler(async ({ context }) => {
return context.db.query.featureTable.findMany({ orderBy: { createdAt: 'desc' } })
})
```
**3. Register** — Add to `contracts/index.ts` and `routers/index.ts` (barrel exports) Strict mode, plus `noUncheckedIndexedAccess`, `verbatimModuleSyntax`, `erasableSyntaxOnly`, `noImplicitOverride`. No `as any` / `@ts-ignore` / `@ts-expect-error`.
**4. Client**`useSuspenseQuery(orpc.feature.list.queryOptions())` / `useMutation(orpc.feature.create.mutationOptions())`. Mutation invalidation is configured globally via `experimental_defaults` in `src/client/orpc.ts`. Path alias: `@/* → src/*`. For files outside `src/` use `@/../<file>` (example in the codebase: `src/routes/api/$.ts` imports `name, version` from `@/../package.json`).
**5. Interceptors** — Registered at **Handler level** (`RPCHandler`/`OpenAPIHandler` in route files), NOT in `server.ts`: ## Env
```typescript
const handler = new RPCHandler(router, {
interceptors: [onError(logError)],
clientInterceptors: [onError(handleValidationError)],
})
```
**6. SSR**`createIsomorphicFn()` in `src/client/orpc.ts` switches between `createRouterClient` (server) and `RPCLink` (client). Routes use `ensureQueryData` in loaders for SSR prefetch. `src/env.ts` via `@t3-oss/env-core`. Server: `DATABASE_URL` (required, `z.url()`). Client needs `VITE_` prefix (`VITE_APP_TITLE` optional). Never commit `.env`.
**7. OpenAPI**`OpenAPIHandler` + `OpenAPIReferencePlugin` with Scalar docs at `/api/docs`, spec at `/api/spec.json`. ## Docker / deploy
## Database (Drizzle ORM v1 beta) - Multi-stage: `oven/bun:1.3.13` builds and runs `bun compile.ts`, then `gcr.io/distroless/cc-debian13:nonroot` runs the single `./server` binary. The `cc` (glibc) distroless variant is required because Bun's compiled binary links glibc.
- `drizzle/` folder is copied into the runtime image so `migrate.ts` plugin can find migrations at startup.
- `compose.yaml`: `app` waits on `db` healthcheck (`pg_isready`); `DATABASE_URL=postgres://postgres:postgres@db:5432/postgres`.
- **Driver**: `drizzle-orm/postgres-js` (NOT `bun-sql`) | **Validation**: `drizzle-orm/zod` (NOT `drizzle-zod`) ## Layout (non-obvious parts only)
- **Relations**: `defineRelations()` in `src/server/db/relations.ts` (RQBv2 — `drizzle()` only needs `{ relations }`)
- **Query style**: RQBv2 object syntax — `orderBy: { createdAt: 'desc' }`, `where: { id: 1 }`
- **Schema**: All tables spread `...generatedFields` for `id` (UUIDv7), `createdAt`, `updatedAt` (see `src/server/db/fields.ts`)
### Database Workflow
- **Local dev**: `db:push` — fast iteration, no migration files needed
- **Production**: `db:generate` → review SQL → `db:migrate` — versioned, auditable
- **Never mix** `push` and `migrate` on the same database instance
- `drizzle/` migration directory is committed to Git
### ⚠️ drizzle.config.ts Caveat
`drizzle.config.ts` runs outside Vite — **`@/*` path aliases do not work**. Use relative imports (`./src/env`).
## Environment Variables
- Validated via `@t3-oss/env-core` + Zod in `src/env.ts`
- Server vars: no prefix | Client vars: `VITE_` prefix required
- Never commit `.env` files
## Development Principles
1. **No backward compatibility** — Rapid iteration. Always use latest API/patterns. No deprecated fallbacks.
2. **Always sync documentation** — Code changes → immediately update `AGENTS.md` and related docs.
3. **Forward-only migration** — Fully adopt new APIs when upgrading. No mixing old/new patterns.
## Critical Rules
**DO:** `bun run fix` before committing | `@/*` path aliases | `...generatedFields` on all tables | `ORPCError` with proper codes | `drizzle-orm/zod` for validation | RQBv2 object syntax | Update docs with code changes
**DON'T:** `npm`/`npx`/`node`/`yarn`/`pnpm` | Edit `routeTree.gen.ts` | `as any`/`@ts-ignore`/`@ts-expect-error` | Commit `.env` | Empty catch blocks | Import from `drizzle-zod` | RQBv1 callback-style API | `drizzle-orm/bun-sql` driver | Pass `schema` to `drizzle()` | Import `os` from `@orpc/server` in middleware (use `@/server/api/server`) | Leave docs out of sync
## Docker
- **Dockerfile**: Multi-stage — `oven/bun:1` (build + compile) → `gcr.io/distroless/cc-debian13:nonroot` (runtime)
- **Runtime**: Bun-compiled standalone binary (glibc-linked, requires `cc` distroless variant)
- **Compose**: `app` + `db` with health check dependency
- **Migrations**: Nitro plugin runs `migrate()` at server startup (see `src/server/plugins/migrate.ts`)
- **Env**: `DATABASE_URL` set in `compose.yaml` pointing to the `db` service
## Git Workflow
1. Make changes → 2. `bun run fix` → 3. `bun run typecheck` → 4. `bun run dev` (test) → 5. Commit
## Directory Structure
``` ```
src/ src/
├── client/orpc.ts # ORPC client (isomorphic SSR/CSR) + TanStack Query utils ├── client/orpc.ts # isomorphic ORPC client + experimental_defaults invalidation
├── components/ # React components (PascalCase.tsx, flat structure) ├── routes/api/
├── routes/ # TanStack Router file routes │ ├── $.ts # OpenAPI + Scalar; interceptors registered here
── __root.tsx # Root layout (shell, meta, error/notFound, DevTools) ── rpc.$.ts # RPC; interceptors registered here
│ ├── index.tsx # Home route (loader + component)
│ └── api/ # API routes
│ ├── $.ts # OpenAPI handler (Scalar docs + spec)
│ ├── rpc.$.ts # RPC handler (interceptors registered here)
│ └── health.ts # Health check endpoint
├── server/ ├── server/
│ ├── api/ │ ├── api/
│ │ ├── contracts/ # ORPC contracts (Zod schemas from Drizzle tables) │ │ ├── server.ts # the ONLY place to build `os`
│ │ ├── routers/ # ORPC handlers (use db middleware, throw ORPCError) │ │ ├── context.ts # BaseContext / DBContext types
│ │ ├── middlewares/ # Middleware (db context injection) │ │ ├── interceptors.ts # logError, handleValidationError
│ │ ├── interceptors.ts # Error interceptors (registered in route handlers) │ │ ├── contracts/ # Zod schemas from Drizzle tables (barrel: contract)
│ │ ├── context.ts # Request context types (BaseContext, DBContext) │ │ ├── routers/ # os.* handlers (barrel: router)
│ │ ── server.ts # implement(contract).$context<BaseContext>() │ │ ── middlewares/ # db middleware injects getDB() singleton
── types.ts # RouterClient, RouterInputs, RouterOutputs ── db/
└── db/ │ ├── index.ts # createDB({ connection, schema }) + getDB()/closeDB() singleton
├── schema/ # Drizzle table definitions (...generatedFields spread) ├── fields.ts # pk (UUIDv7), createdAt, updatedAt, generatedFields(Keys)
── fields.ts # Shared fields: pk (UUIDv7), createdAt, updatedAt ── schema/ # pgTable definitions; also put `relations()` here when adding
├── relations.ts # Drizzle relations (RQBv2 defineRelations) └── plugins/
── index.ts # DB factory (createDB, getDB singleton) ── migrate.ts # Nitro plugin: runs drizzle migrate at prod startup
├── env.ts # Environment variable validation (@t3-oss/env-core) │ └── shutdown.ts # SIGINT/SIGTERM → closeDB() with 500ms delay
├── router.tsx # Router + QueryClient + SSR query integration ├── env.ts # t3-oss env validation
├── routeTree.gen.ts # Auto-generated (DO NOT EDIT) ├── router.tsx # QueryClient + setupRouterSsrQueryIntegration
└── styles.css # Tailwind entry (@import "tailwindcss") └── routeTree.gen.ts # auto-generated, do not edit
``` ```
Nitro plugins are wired in `vite.config.ts` (`nitro({ plugins: [...] })`), not via a Nitro config file.
## Don'ts (specific, non-obvious)
- Don't edit `routeTree.gen.ts`.
- Don't import `os` from `@orpc/server` in middleware/routers — always `@/server/api/server`.
- Don't import from `drizzle-orm/zod` (1.0 beta only). Use `drizzle-zod`.
- Don't use RQB v2 object syntax, `defineRelations`, or pass `relations` to `drizzle()`. All are 1.0 beta.
- Don't use `drizzle-orm/bun-sql`.
- Don't use `@/*` aliases in `drizzle.config.ts`.
- Don't commit `.env`.