refactor(layout): 根目录脚本归位 src/ 与 scripts/,sql.d.ts 下沉到 db/
- bin.ts → src/bin.ts (生产入口归并到 src/,import 改用 #package + @/cli/*) - compile.ts → scripts/compile.ts (开发期工具) - embed-migrations.ts → scripts/embed-migrations.ts (codegen) - src/sql.d.ts → src/server/db/sql.d.ts (与唯一消费者 migrations.gen.ts 共址) 效果:项目根从 3 个零散 .ts 减为 0 个,src/ 是完整应用源码,scripts/ 明确区分开发期工具。所有 package.json scripts、AGENTS.md layout/CLI 章节、 compile.ts ENTRYPOINT 与 .js.map 清理路径同步更新。 验证:fix / typecheck / test 3/3 / build 570ms / compile 117M / docker compose 全套(migrate 干净的 logger=cli.migrate JSON 日志、app /health 200、POST /api/todo/create 成功)。
This commit is contained in:
@@ -15,19 +15,19 @@ 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 CLI binary)
|
||||
bun run cli <cmd> # bun bin.ts <cmd> — run a CLI subcommand in source (dev)
|
||||
bun run compile # bun scripts/compile.ts → out/server-<target> (standalone CLI binary)
|
||||
bun run cli <cmd> # bun src/bin.ts <cmd> — run a CLI subcommand in source (dev)
|
||||
bun run typecheck # tsc --noEmit
|
||||
bun run test # bun test — runs all *.test.ts files (colocated with source)
|
||||
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 # drizzle-kit generate && embed-migrations.ts (regenerates migrations.gen.ts)
|
||||
bun run db:embed # embed-migrations.ts only — regenerate migrations.gen.ts from ./drizzle/
|
||||
bun run db:generate # drizzle-kit generate && scripts/embed-migrations.ts (regenerates migrations.gen.ts)
|
||||
bun run db:embed # scripts/embed-migrations.ts only — regenerate migrations.gen.ts from ./drizzle/
|
||||
bun run db:migrate # apply migrations via drizzle-kit (local dev convenience; prod uses ./server migrate)
|
||||
bun run db:studio # Drizzle Studio
|
||||
```
|
||||
|
||||
Cross-compile targets live under `compile:{linux,darwin,windows}[:arch]`. `compile.ts` accepts `--target bun-<os>-<arch>`; default derives from host.
|
||||
Cross-compile targets live under `compile:{linux,darwin,windows}[:arch]`. `scripts/compile.ts` accepts `--target bun-<os>-<arch>`; default derives from host.
|
||||
|
||||
Before committing: `bun run fix && bun run typecheck && bun run test`. No CI, no pre-commit hooks, no lint-staged — so these are on you.
|
||||
|
||||
@@ -49,11 +49,11 @@ Before committing: `bun run fix && bun run typecheck && bun run test`. No CI, no
|
||||
- Every table must spread `...generatedFields` from `src/server/db/fields.ts` (`id` UUIDv7 via `$defaultFn(uuidv7)`, `createdAt`, `updatedAt` with `$onUpdateFn`). `generatedFieldKeys` is hand-written and uses `satisfies Record<keyof typeof generatedFields, true>` so any field-key drift fails typecheck; it feeds `createInsertSchema(...).omit(...)` / `createUpdateSchema(...).omit(...)`.
|
||||
- `src/server/db/index.ts` exports a module-level `const db = drizzle(...)` — not a lazy singleton. On Bun this is a long-lived process, so top-level side effects are fine and requested. Don't reintroduce `getDB/closeDB` ceremony; the Nitro shutdown plugin calls `db.$client.end()` directly. (Cloudflare Workers would need per-request init — we don't support that deployment target.)
|
||||
- `drizzle.config.ts` runs outside Vite — `@/*` path aliases do NOT resolve there. It currently does `import { env } from './src/env'` (relative). Preserve that.
|
||||
- **Migrations are embedded in the binary, not read from disk.** `bun run db:generate` chains `drizzle-kit generate && bun embed-migrations.ts`, which regenerates `src/server/db/migrations.gen.ts` (committed, AUTO-GENERATED header) by `import sql_<idx> from '../../../drizzle/<tag>.sql' with { type: 'text' }`. `src/cli/migrate.ts` reads `embeddedMigrations`, **validates SHA-256 hash of every already-applied migration against the embedded SQL** (rejects schema drift if anyone edited an applied migration), then applies pending entries via `db.execute(sql\`...\`)` + `db.transaction(...)` against the `drizzle.__drizzle_migrations` book-keeping table — public APIs only, no `db.dialect`/`db.session` (those are `@internal`). Each migration is split on `--> statement-breakpoint`; empty fragments are trimmed and skipped. Dev helpers `db:push` / `drizzle-kit migrate` still read `./drizzle/`.
|
||||
- **Migrations are embedded in the binary, not read from disk.** `bun run db:generate` chains `drizzle-kit generate && bun scripts/embed-migrations.ts`, which regenerates `src/server/db/migrations.gen.ts` (committed, AUTO-GENERATED header) by `import sql_<idx> from '#drizzle/<tag>.sql' with { type: 'text' }`. `src/cli/migrate.ts` reads `embeddedMigrations`, **validates SHA-256 hash of every already-applied migration against the embedded SQL** (rejects schema drift if anyone edited an applied migration), then applies pending entries via `db.execute(sql\`...\`)` + `db.transaction(...)` against the `drizzle.__drizzle_migrations` book-keeping table — public APIs only, no `db.dialect`/`db.session` (those are `@internal`). Each migration is split on `--> statement-breakpoint`; empty fragments are trimmed and skipped. Dev helpers `db:push` / `drizzle-kit migrate` still read `./drizzle/`.
|
||||
|
||||
## 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/`.
|
||||
`bun run compile` produces a single executable that dispatches subcommands via [citty](https://github.com/unjs/citty). Entry is `src/bin.ts`; subcommands live in `src/cli/`.
|
||||
|
||||
```
|
||||
./server [serve] # default — start the HTTP server
|
||||
@@ -61,21 +61,21 @@ Before committing: `bun run fix && bun run typecheck && bun run test`. No CI, no
|
||||
./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.
|
||||
**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. `src/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()`.
|
||||
Add a subcommand: drop a file in `src/cli/` that default-exports `defineCommand({...})`, then register it in `src/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.** Migrations are embedded in the binary (see "Drizzle" section), so the binary is the only artifact — no `./drizzle/` directory at runtime. Dockerfile copies just `./server`. `compose.yaml` models the pattern 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.
|
||||
|
||||
## Compile flags
|
||||
|
||||
`compile.ts` builds with `--minify --bytecode --sourcemap=inline`:
|
||||
`scripts/compile.ts` builds with `--minify --bytecode --sourcemap=inline`:
|
||||
|
||||
- **`bytecode`** — pre-compiles JS to bytecode and embeds it in the binary; ~2x startup on app-sized binaries (Bun docs benchmark). Requires `--compile`; top-level `await` must live inside `async` functions (it already does in this repo).
|
||||
- **`minify`** — shrinks the binary and the bytecode it derives from.
|
||||
- **`sourcemap: 'inline'`** — embeds the source map in the binary so error stack traces stay decodable. Bun also writes a residual `out/bin.js.map` next to the output; `compile.ts` removes it so the binary is the only artifact.
|
||||
- **`sourcemap: 'inline'`** — embeds the source map in the binary so error stack traces stay decodable. Bun also writes a residual `out/bin.js.map` next to the output; `scripts/compile.ts` removes it so the binary is the only artifact.
|
||||
|
||||
## ORPC
|
||||
|
||||
@@ -143,7 +143,7 @@ logger.error('DB write failed', { error })
|
||||
|
||||
## 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.
|
||||
- Multi-stage: `oven/bun:1.3.13` builds and runs `bun scripts/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.
|
||||
- `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`.
|
||||
|
||||
@@ -151,13 +151,14 @@ logger.error('DB write failed', { error })
|
||||
|
||||
```
|
||||
src/
|
||||
├── bin.ts # citty entry — keep imports minimal (see "CLI" section)
|
||||
├── client/
|
||||
│ ├── orpc.ts # isomorphic ORPC client + TanStack Query utils (no global invalidation defaults)
|
||||
│ └── queries/ # per-feature query hooks: keys, options, `useInvalidate<Feature>` helpers
|
||||
├── cli/ # CLI subcommands (loaded lazily by bin.ts via citty)
|
||||
├── cli/ # CLI subcommands (loaded lazily by src/bin.ts via citty)
|
||||
│ ├── serve.ts # `./server serve` — imports the Nitro bridge on demand
|
||||
│ ├── migrate.ts # `./server migrate` — applies embedded migrations via public `db.execute(sql)` + `db.transaction()`
|
||||
│ ├── _serve-nitro.mjs # bridge: `import('../../.output/server/index.mjs')`
|
||||
│ ├── _serve-nitro.mjs # bridge: `import('#server')` (subpath import → .output/server/index.mjs)
|
||||
│ └── _serve-nitro.d.mts # types for the bridge (build output has no .d.ts)
|
||||
├── routes/
|
||||
│ ├── __root.tsx # root route + RootDocument shell
|
||||
@@ -179,18 +180,18 @@ src/
|
||||
│ │ ├── index.ts # module-level `export const db = drizzle({...})`
|
||||
│ │ ├── fields.ts # generatedFields (id/createdAt/updatedAt) + generatedFieldKeys
|
||||
│ │ ├── migrations.gen.ts # AUTO-GENERATED by `bun run db:embed`; embeds ./drizzle/*.sql via `with { type: 'text' }`
|
||||
│ │ ├── sql.d.ts # ambient `declare module '*.sql'` — load-bearing for `with { type: 'text' }` imports in migrations.gen.ts
|
||||
│ │ └── schema/ # pgTable definitions; also put `relations()` here when adding
|
||||
│ └── plugins/
|
||||
│ └── shutdown.ts # SIGINT/SIGTERM → db.$client.end() with 500ms delay (prod only)
|
||||
├── components/ # non-route UI primitives (PascalCase, arrow const)
|
||||
├── env.ts # t3-oss env validation
|
||||
├── router.tsx # QueryClient + setupRouterSsrQueryIntegration
|
||||
├── sql.d.ts # ambient `declare module '*.sql'` — load-bearing for `with { type: 'text' }` imports in migrations.gen.ts
|
||||
├── styles.css # Tailwind v4 entry
|
||||
└── routeTree.gen.ts # auto-generated, do not edit
|
||||
bin.ts # citty entry (root) — keep imports minimal (see "CLI" section)
|
||||
compile.ts # `bun build --compile` driver; resolves --target; sets minify/bytecode/sourcemap
|
||||
embed-migrations.ts # codegen: scans ./drizzle/meta/_journal.json → src/server/db/migrations.gen.ts
|
||||
scripts/
|
||||
├── compile.ts # `bun build --compile` driver; resolves --target; sets minify/bytecode/sourcemap
|
||||
└── embed-migrations.ts # codegen: scans ./drizzle/meta/_journal.json → src/server/db/migrations.gen.ts
|
||||
drizzle/ # SQL migrations (source of truth for `db:generate`; not shipped in binary)
|
||||
```
|
||||
|
||||
@@ -199,7 +200,7 @@ Nitro plugins are wired in `vite.config.ts` (`nitro({ plugins: [...] })`), not v
|
||||
## Don'ts (specific, non-obvious)
|
||||
|
||||
- Don't edit `routeTree.gen.ts` or `src/server/db/migrations.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 eager-import anything from `.output/` in `src/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 reach into `db.dialect`/`db.session` from `migrate.ts` — they're `@internal`. The current implementation uses public `db.execute(sql)` + `db.transaction(...)` against the documented `drizzle.__drizzle_migrations` schema.
|
||||
- Don't add `./drizzle/` back to the runtime image — migrations are embedded into the binary.
|
||||
@@ -223,5 +224,5 @@ These keep the starter from setting bad precedents as it grows. Append, don't re
|
||||
6. One file per Drizzle table. Relations live in the same file and are exported as `<entity>Relations`. No global `relations.ts`.
|
||||
7. One router file per feature (`routers/<feature>.router.ts`). Only introduce `routers/<domain>/index.ts` when a domain grows past ~5 router files or needs shared domain helpers.
|
||||
8. All server-side logging goes through `getLogger([...])` from `@/server/logger`. Use a hierarchical category (`['api']`, `['db']`, `['cli', 'migrate']`, etc.) — these become dot-paths in JSON output and let you filter by prefix. Use the `{name}` placeholder + properties form, not string interpolation. `console.*` is forbidden in business code.
|
||||
9. CLI subcommand modules keep top-level imports to `citty` + Node built-ins. Env, db, and server code are `await import(...)`-ed inside `run()` (see `bin.ts` comment for why).
|
||||
9. CLI subcommand modules keep top-level imports to `citty` + Node built-ins. Env, db, and server code are `await import(...)`-ed inside `run()` (see `src/bin.ts` comment for why).
|
||||
10. Every new business feature ships with at least one `bun test` covering a contract schema, a pure helper, or a router behavior.
|
||||
|
||||
Reference in New Issue
Block a user