feat(cli): 引入 citty CLI,迁移改为显式 ./server migrate
- 顶层新增 bin.ts 作为编译入口,citty 懒加载 src/cli/ 下子命令 - src/cli/serve.ts 通过 _serve-nitro.mjs 桥接启动 Nitro(规避 .output/server/index.mjs 顶层 serve(...) 的副作用导入) - src/cli/migrate.ts 显式跑 drizzle migrate;env / drizzle 都在 run() 里 await import,避免 citty --help 遍历 subCommands 时触发 env 校验 - compile.ts 入口切到 bin.ts;移除 src/server/plugins/migrate.ts 与 vite.config.ts 中的启动时自动迁移 - compose.yaml 新增一次性 migrate 服务,app depends_on service_completed_successfully,保证迁移先行再起服 - tsconfig 排除 .output / out;AGENTS.md 补充 CLI 与部署规约
This commit is contained in:
@@ -14,12 +14,13 @@ Compact, repo-specific notes for AI agents. Generic language/framework knowledge
|
||||
```bash
|
||||
bun run dev # bunx --bun vite dev (localhost:3000)
|
||||
bun run build # bunx --bun vite build → .output/
|
||||
bun run compile # bun compile.ts → out/server-<target> (standalone binary)
|
||||
bun run compile # bun compile.ts → out/server-<target> (standalone CLI binary)
|
||||
bun run cli <cmd> # bun bin.ts <cmd> — run a CLI subcommand in source (dev)
|
||||
bun run typecheck # tsc --noEmit
|
||||
bun run fix # biome check --write (lint + format + organize imports)
|
||||
bun run db:push # dev only — push schema to DB, no migration file
|
||||
bun run db:generate # produce SQL migration files in ./drizzle
|
||||
bun run db:migrate # apply migrations (also auto-run at prod server startup)
|
||||
bun run db:migrate # apply migrations via drizzle-kit (local convenience)
|
||||
bun run db:studio # Drizzle Studio
|
||||
```
|
||||
|
||||
@@ -44,7 +45,25 @@ Before committing: `bun run fix && bun run typecheck`. No CI, no pre-commit hook
|
||||
- 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.
|
||||
- The `./drizzle/` migrations directory is gitignored-by-absence right now (no migrations yet). Migrations are applied via the CLI (`./server migrate`, see "CLI & single-binary deploy" below), NOT at server startup. Dev uses `db:push`. Don't mix `push` and `migrate` on the same DB.
|
||||
|
||||
## CLI & single-binary deploy
|
||||
|
||||
`bun run compile` produces a single executable that dispatches subcommands via [citty](https://github.com/unjs/citty). Entry is `bin.ts` at repo root, subcommands live in `src/cli/`.
|
||||
|
||||
```
|
||||
./server [serve] # default — start the HTTP server
|
||||
./server migrate # apply migrations from ./drizzle
|
||||
./server --help
|
||||
```
|
||||
|
||||
**Nitro side-effect pitfall (important).** Under the `bun` preset, `.output/server/index.mjs` has a top-level `serve(...)` call — merely importing it starts the HTTP server. `bin.ts` therefore must not eager-import any subcommand module, and `src/cli/serve.ts` reaches `.output/server/index.mjs` through the `src/cli/_serve-nitro.mjs` bridge (with `_serve-nitro.d.mts` for types, since `.output/` doesn't exist at typecheck time). Citty's `subCommands: { x: () => import('...') }` lazy-loader is what keeps `--help` and `migrate` from booting the server.
|
||||
|
||||
**Citty eager-loads subcommand modules for `--help`** to read each subcommand's `meta`. So every `src/cli/*.ts` module body must be side-effect-free: do NOT static-import `@/env`, `@/server/db/*`, or anything that reads env at module-load time. Use `await import('@/env')` inside `run()`. Otherwise `./server --help` (or any subcommand's help) will fail with env validation errors before printing.
|
||||
|
||||
Add a subcommand: drop a file in `src/cli/` that default-exports `defineCommand({...})`, then register it in `bin.ts`'s `subCommands` with a `() => import(...)` thunk. Keep top-level imports limited to `citty` + Node built-ins; pull env / db / etc. via `await import(...)` inside `run()`.
|
||||
|
||||
**Deploy flow is always migrate-then-serve.** The compiled binary bundles neither the `./drizzle/` SQL files nor the app schema migrations at runtime — they're read from disk next to the binary. Dockerfile copies `drizzle/` alongside `./server`, and `compose.yaml` models this with a one-shot `migrate` service that `app` `depends_on: service_completed_successfully`. On k8s, run `./server migrate` as an initContainer or a Helm `pre-upgrade` Job; run `./server` (= `./server serve`) as the main container.
|
||||
|
||||
## ORPC
|
||||
|
||||
@@ -83,14 +102,20 @@ Path alias: `@/* → src/*`. For files outside `src/` use `@/../<file>` (example
|
||||
## Docker / deploy
|
||||
|
||||
- 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`.
|
||||
- `drizzle/` folder is copied into the runtime image so `./server migrate` can find migrations at runtime.
|
||||
- `compose.yaml`: one-shot `migrate` service runs `./server migrate` with `restart: "no"`, then `app` starts (`depends_on: migrate: service_completed_successfully`). `DATABASE_URL=postgres://postgres:postgres@db:5432/postgres` for both.
|
||||
- Distroless has no shell, so any init-then-serve pattern must use exec-form `command: [...]`, not `sh -c`.
|
||||
|
||||
## Layout (non-obvious parts only)
|
||||
|
||||
```
|
||||
src/
|
||||
├── client/orpc.ts # isomorphic ORPC client + experimental_defaults invalidation
|
||||
├── cli/ # CLI subcommands (loaded lazily by bin.ts via citty)
|
||||
│ ├── serve.ts # `./server serve` — imports the Nitro bridge on demand
|
||||
│ ├── migrate.ts # `./server migrate` — drizzle migrate against ./drizzle
|
||||
│ ├── _serve-nitro.mjs # bridge: `import('../../.output/server/index.mjs')`
|
||||
│ └── _serve-nitro.d.mts # types for the bridge (build output has no .d.ts)
|
||||
├── routes/api/
|
||||
│ ├── $.ts # OpenAPI + Scalar; interceptors registered here
|
||||
│ └── rpc.$.ts # RPC; interceptors registered here
|
||||
@@ -107,11 +132,11 @@ src/
|
||||
│ │ ├── fields.ts # pk (UUIDv7), createdAt, updatedAt, generatedFields(Keys)
|
||||
│ │ └── schema/ # pgTable definitions; also put `relations()` here when adding
|
||||
│ └── plugins/
|
||||
│ ├── migrate.ts # Nitro plugin: runs drizzle migrate at prod startup
|
||||
│ └── shutdown.ts # SIGINT/SIGTERM → closeDB() with 500ms delay
|
||||
├── env.ts # t3-oss env validation
|
||||
├── router.tsx # QueryClient + setupRouterSsrQueryIntegration
|
||||
└── routeTree.gen.ts # auto-generated, do not edit
|
||||
bin.ts # citty entry (root) — keep imports minimal (see "CLI" section)
|
||||
```
|
||||
|
||||
Nitro plugins are wired in `vite.config.ts` (`nitro({ plugins: [...] })`), not via a Nitro config file.
|
||||
@@ -119,6 +144,8 @@ Nitro plugins are wired in `vite.config.ts` (`nitro({ plugins: [...] })`), not v
|
||||
## Don'ts (specific, non-obvious)
|
||||
|
||||
- Don't edit `routeTree.gen.ts`.
|
||||
- Don't eager-import anything from `.output/` in `bin.ts` or any module it statically imports — it starts the HTTP server as a side effect. Subcommands must be lazy via citty's `() => import(...)` thunks.
|
||||
- Don't re-add an auto-migrate Nitro plugin. Migrations are an explicit deploy step via `./server migrate`.
|
||||
- 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.
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { defineCommand, runMain } from 'citty'
|
||||
import { name, version } from './package.json' with { type: 'json' }
|
||||
|
||||
// IMPORTANT: keep this file's static imports minimal. Nitro's bun preset
|
||||
// emits `.output/server/index.mjs` with a top-level `serve(...)` call, so any
|
||||
// eager (transitive) import of it would start the HTTP server even for
|
||||
// `migrate` or `--help`. All subcommands are lazy-loaded via citty.
|
||||
const main = defineCommand({
|
||||
meta: {
|
||||
name,
|
||||
version,
|
||||
description: 'Fullstack server binary (default subcommand: serve)',
|
||||
},
|
||||
subCommands: {
|
||||
serve: () => import('./src/cli/serve').then((m) => m.default),
|
||||
migrate: () => import('./src/cli/migrate').then((m) => m.default),
|
||||
},
|
||||
})
|
||||
|
||||
runMain(main)
|
||||
@@ -16,6 +16,7 @@
|
||||
"@tanstack/react-router": "^1.168.23",
|
||||
"@tanstack/react-router-ssr-query": "^1.166.11",
|
||||
"@tanstack/react-start": "^1.167.43",
|
||||
"citty": "^0.2.2",
|
||||
"drizzle-orm": "0.45.2",
|
||||
"drizzle-zod": "^0.8.3",
|
||||
"postgres": "^3.4.9",
|
||||
@@ -406,6 +407,8 @@
|
||||
|
||||
"chokidar": ["chokidar@3.6.0", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="],
|
||||
|
||||
"citty": ["citty@0.2.2", "", {}, "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w=="],
|
||||
|
||||
"clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
|
||||
|
||||
"consola": ["consola@3.4.2", "", {}, "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA=="],
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { mkdir, rm } from 'node:fs/promises'
|
||||
import { parseArgs } from 'node:util'
|
||||
|
||||
const ENTRYPOINT = '.output/server/index.mjs'
|
||||
const ENTRYPOINT = 'bin.ts'
|
||||
const OUTDIR = 'out'
|
||||
|
||||
const SUPPORTED_TARGETS: readonly Bun.Build.CompileTarget[] = [
|
||||
|
||||
@@ -1,9 +1,21 @@
|
||||
services:
|
||||
migrate:
|
||||
build: .
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
- DATABASE_URL=postgres://postgres:postgres@db:5432/postgres
|
||||
command: ["./server", "migrate"]
|
||||
restart: "no"
|
||||
|
||||
app:
|
||||
build: .
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "bunx --bun vite build",
|
||||
"cli": "bun bin.ts",
|
||||
"compile": "bun compile.ts",
|
||||
"compile:darwin": "bun run compile:darwin:arm64 && bun run compile:darwin:x64",
|
||||
"compile:darwin:arm64": "bun compile.ts --target bun-darwin-arm64",
|
||||
@@ -34,6 +35,7 @@
|
||||
"@tanstack/react-router": "^1.168.23",
|
||||
"@tanstack/react-router-ssr-query": "^1.166.11",
|
||||
"@tanstack/react-start": "^1.167.43",
|
||||
"citty": "^0.2.2",
|
||||
"drizzle-orm": "0.45.2",
|
||||
"drizzle-zod": "^0.8.3",
|
||||
"postgres": "^3.4.9",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export default function startNitroServer(): Promise<void>
|
||||
@@ -0,0 +1,3 @@
|
||||
export default async function startNitroServer() {
|
||||
await import('../../.output/server/index.mjs')
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { defineCommand } from 'citty'
|
||||
|
||||
const MIGRATIONS_FOLDER = './drizzle'
|
||||
|
||||
export default defineCommand({
|
||||
meta: {
|
||||
name: 'migrate',
|
||||
description: 'Apply pending database migrations from ./drizzle',
|
||||
},
|
||||
async run() {
|
||||
if (!existsSync(MIGRATIONS_FOLDER)) {
|
||||
console.log(`No ${MIGRATIONS_FOLDER} directory; nothing to apply (use db:push in dev).`)
|
||||
return
|
||||
}
|
||||
|
||||
const [{ env }, { drizzle }, { migrate }] = await Promise.all([
|
||||
import('@/env'),
|
||||
import('drizzle-orm/postgres-js'),
|
||||
import('drizzle-orm/postgres-js/migrator'),
|
||||
])
|
||||
|
||||
const db = drizzle({ connection: { url: env.DATABASE_URL, max: 1 } })
|
||||
try {
|
||||
console.log('Applying migrations...')
|
||||
await migrate(db, { migrationsFolder: MIGRATIONS_FOLDER })
|
||||
console.log('Migrations applied.')
|
||||
} finally {
|
||||
await db.$client.end()
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineCommand } from 'citty'
|
||||
|
||||
export default defineCommand({
|
||||
meta: {
|
||||
name: 'serve',
|
||||
description: 'Start the HTTP server',
|
||||
},
|
||||
async run() {
|
||||
const { default: startNitroServer } = await import('./_serve-nitro.mjs')
|
||||
await startNitroServer()
|
||||
},
|
||||
})
|
||||
@@ -1,17 +0,0 @@
|
||||
import { drizzle } from 'drizzle-orm/postgres-js'
|
||||
import { migrate } from 'drizzle-orm/postgres-js/migrator'
|
||||
import { env } from '@/env'
|
||||
|
||||
export default async () => {
|
||||
if (import.meta.dev) return
|
||||
|
||||
const db = drizzle({ connection: { url: env.DATABASE_URL, max: 1 } })
|
||||
|
||||
try {
|
||||
console.log('Applying migrations...')
|
||||
await migrate(db, { migrationsFolder: './drizzle' })
|
||||
console.log('Migrations applied successfully.')
|
||||
} finally {
|
||||
await db.$client.end()
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -28,5 +28,5 @@
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"exclude": ["node_modules"]
|
||||
"exclude": ["node_modules", ".output", "out"]
|
||||
}
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ export default defineConfig({
|
||||
nitro({
|
||||
preset: 'bun',
|
||||
serveStatic: 'inline',
|
||||
plugins: ['./src/server/plugins/migrate.ts', './src/server/plugins/shutdown.ts'],
|
||||
plugins: ['./src/server/plugins/shutdown.ts'],
|
||||
}),
|
||||
],
|
||||
resolve: {
|
||||
|
||||
Reference in New Issue
Block a user