Compare commits
3 Commits
main
..
f7f86e4462
| Author | SHA1 | Date | |
|---|---|---|---|
| f7f86e4462 | |||
| 5cc476cedc | |||
| 1ccda13cdf |
@@ -1,13 +0,0 @@
|
||||
node_modules/
|
||||
.output/
|
||||
.tanstack/
|
||||
out/
|
||||
.git/
|
||||
.env
|
||||
.env.*
|
||||
|
||||
*.md
|
||||
*.tsbuildinfo
|
||||
*.bun-build
|
||||
|
||||
.vscode/
|
||||
@@ -1,6 +1 @@
|
||||
DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres
|
||||
|
||||
# Optional logging knobs (defaults are usually fine):
|
||||
# LOG_LEVEL=info # trace|debug|info|warning|error|fatal
|
||||
# LOG_FORMAT=pretty # pretty|json — defaults to TTY ? pretty : json
|
||||
# LOG_DB=false # true to log every Drizzle SQL query
|
||||
|
||||
@@ -1,23 +1,157 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
### Custom ###
|
||||
|
||||
# Build output
|
||||
.output/
|
||||
# TanStack
|
||||
.tanstack/
|
||||
.vite/
|
||||
out/
|
||||
*.bun-build
|
||||
*.tsbuildinfo
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
|
||||
# Env
|
||||
# Nitro
|
||||
.output/
|
||||
|
||||
# Bun build
|
||||
*.bun-build
|
||||
|
||||
# Turborepo
|
||||
.turbo/
|
||||
|
||||
### Node ###
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Snowpack dependency directory (https://snowpack.dev/)
|
||||
web_modules/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Optional stylelint cache
|
||||
.stylelintcache
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
.parcel-cache
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
# Next.js build output
|
||||
.next
|
||||
out
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
.output
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# vuepress v2.x temp and cache directory
|
||||
.temp
|
||||
.cache
|
||||
|
||||
# Sveltekit cache directory
|
||||
.svelte-kit/
|
||||
|
||||
# vitepress build output
|
||||
**/.vitepress/dist
|
||||
|
||||
# vitepress cache directory
|
||||
**/.vitepress/cache
|
||||
|
||||
# Docusaurus cache and generated files
|
||||
.docusaurus
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# Firebase cache directory
|
||||
.firebase/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
|
||||
# yarn v3
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/sdks
|
||||
!.yarn/versions
|
||||
|
||||
# Vite files
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
.vite/
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"biomejs.biome",
|
||||
"codezombiech.gitignore",
|
||||
"hverlin.mise-vscode",
|
||||
"mikestead.dotenv",
|
||||
"oven.bun-vscode",
|
||||
"redhat.vscode-yaml",
|
||||
"rust-lang.rust-analyzer",
|
||||
"tamasfe.even-better-toml",
|
||||
"unional.vscode-sort-package-json"
|
||||
"tauri-apps.tauri-vscode"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,50 +1,54 @@
|
||||
{
|
||||
// Disable the default formatter & linter, use biome instead
|
||||
"prettier.enable": false,
|
||||
"eslint.enable": false,
|
||||
|
||||
// Auto fix
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.biome": "explicit",
|
||||
"source.organizeImports.biome": "explicit"
|
||||
},
|
||||
"editor.defaultFormatter": "biomejs.biome",
|
||||
"editor.formatOnSave": true,
|
||||
"[javascript]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[javascriptreact]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[typescript]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[typescriptreact]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[json]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[jsonc]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[toml]": {
|
||||
"editor.defaultFormatter": "tamasfe.even-better-toml"
|
||||
},
|
||||
"[typescript]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[typescriptreact]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[yaml]": {
|
||||
"editor.defaultFormatter": "redhat.vscode-yaml"
|
||||
},
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.biome": "explicit",
|
||||
"source.organizeImports.biome": "explicit"
|
||||
"[toml]": {
|
||||
"editor.defaultFormatter": "tamasfe.even-better-toml"
|
||||
},
|
||||
"editor.defaultFormatter": "biomejs.biome",
|
||||
"editor.formatOnSave": true,
|
||||
"files.associations": {
|
||||
".env": "dotenv",
|
||||
".env.*": "dotenv",
|
||||
"**/tsconfig*.json": "jsonc",
|
||||
"**/biome.json": "jsonc",
|
||||
"**/opencode.json": "jsonc",
|
||||
"**/tsconfig.*.json": "jsonc",
|
||||
"**/tsconfig.json": "jsonc"
|
||||
"**/opencode.json": "jsonc"
|
||||
},
|
||||
|
||||
// TanStack Router
|
||||
"files.readonlyInclude": {
|
||||
"**/routeTree.gen.ts": true
|
||||
},
|
||||
"files.watcherExclude": {
|
||||
"**/routeTree.gen.ts": true
|
||||
},
|
||||
"js/ts.tsdk.path": "node_modules/typescript/lib",
|
||||
"js/ts.tsdk.promptToUseWorkspaceVersion": true,
|
||||
"search.exclude": {
|
||||
"**/routeTree.gen.ts": true
|
||||
}
|
||||
|
||||
@@ -1,232 +1,193 @@
|
||||
# AGENTS.md
|
||||
# AGENTS.md - AI Coding Agent Guidelines
|
||||
|
||||
Compact, repo-specific notes for AI agents. Generic language/framework knowledge is omitted — only things that will bite you if you don't know. Pair this with `README.md` (user-facing quick-start + add-a-feature checklist + deploy flow).
|
||||
## Project Overview
|
||||
|
||||
## Stack & runtime
|
||||
TanStack Start fullstack app with Tauri desktop shell.
|
||||
|
||||
- **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).
|
||||
- **Prefer Bun-native APIs over external packages and `node:*` polyfills.** UUIDv7 in app code → `Bun.randomUUIDv7()` (not the `uuid` package); DB primary keys are a separate matter — those go through PG18's `uuidv7()`, see "Drizzle" section. SHA-256 → `Bun.CryptoHasher.hash('sha256', s, 'hex')` (not `node:crypto.createHash`); short sleeps → `Bun.sleep(ms)` (not raw `setTimeout` with promise wrapping); file I/O in build scripts → `Bun.file` / `Bun.write` are fine. The runtime is Bun, the deployment target is Bun, the test runner is Bun — there is no "portability" concern that would justify dragging in npm packages or Node compat shims for things Bun ships natively.
|
||||
- TanStack Start (React 19 SSR, file-routed) + Vite 8 + Nitro (nightly, preset `bun`). Dev server defaults to Vite's port (3000); not pinned, override via `vite dev --port <n>` if you need to.
|
||||
- **PostgreSQL 18+ only** (`compose.yaml` pins `postgres:18-alpine`). The starter relies on PG18's built-in `uuidv7()` function for primary-key generation — see "Drizzle" section. Do not soften this to support older PG; if you need PG <18 compatibility, fork and reintroduce app-side UUIDv7 (e.g. `Bun.randomUUIDv7()` or the `uuid` package) yourself.
|
||||
- **Drizzle ORM `0.45.2` (0.x, NOT 1.0 beta)** — see "Drizzle" section, this matters a lot.
|
||||
- ORPC (contract-first), TanStack Query v5, Tailwind v4.
|
||||
- **Logging via [LogTape](https://logtape.org/)** (zero-dep, runtime-agnostic) — see "Logging" section. `console.*` is forbidden in business code.
|
||||
| Layer | Tech |
|
||||
|-------|------|
|
||||
| Framework | TanStack Start (React SSR, file-based routing) |
|
||||
| Runtime | Bun |
|
||||
| Language | TypeScript (strict mode) |
|
||||
| Styling | Tailwind CSS v4 |
|
||||
| Database | PostgreSQL + Drizzle ORM |
|
||||
| RPC | ORPC (contract-first, type-safe) |
|
||||
| Build | Vite + Turbo |
|
||||
| Linting | Biome |
|
||||
| Desktop | Tauri v2 (optional, see `src-tauri/AGENTS.md`) |
|
||||
|
||||
## Scripts
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
bun run dev # bunx --bun vite dev (localhost:3000)
|
||||
bun run build # bunx --bun vite build → .output/
|
||||
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 && 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
|
||||
# Development
|
||||
bun dev # Start Tauri + Vite via Turbo
|
||||
bun dev:vite # Vite only (localhost:3000)
|
||||
bun db:studio # Drizzle Studio
|
||||
|
||||
# Build
|
||||
bun build # Full build (Vite → compile → Tauri)
|
||||
bun build:vite # Vite only (outputs to .output/)
|
||||
|
||||
# Code Quality
|
||||
bun typecheck # TypeScript check (tsc -b)
|
||||
bun fix # Biome auto-fix (format + lint)
|
||||
|
||||
# Database
|
||||
bun db:generate # Generate migrations from schema
|
||||
bun db:migrate # Run migrations
|
||||
bun db:push # Push schema changes (dev only)
|
||||
|
||||
# Testing (not configured yet)
|
||||
# When adding tests, use Vitest or Bun test runner:
|
||||
# bun test path/to/test.ts # Single file
|
||||
# bun test -t "pattern" # By test name
|
||||
```
|
||||
|
||||
Cross-compile targets live under `compile:{linux,darwin,windows}[:arch]`. `scripts/compile.ts` accepts `--target bun-<os>-<arch>`; default derives from host.
|
||||
## Code Style
|
||||
|
||||
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.
|
||||
### Formatting (Biome enforced)
|
||||
|
||||
## Drizzle (v0.x — critical)
|
||||
- **Indent**: 2 spaces
|
||||
- **Line endings**: LF
|
||||
- **Quotes**: Single `'string'`
|
||||
- **Semicolons**: As needed (ASI)
|
||||
- **Arrow parens**: Always `(x) => x`
|
||||
|
||||
**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.
|
||||
### Imports
|
||||
|
||||
- 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),
|
||||
Biome auto-organizes. Order: external → internal (`@/*`) → type-only imports.
|
||||
|
||||
```typescript
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { z } from 'zod'
|
||||
import { db } from '@/db'
|
||||
import type { ReactNode } from 'react'
|
||||
```
|
||||
|
||||
### TypeScript
|
||||
|
||||
Strict mode with extra checks:
|
||||
- `noUncheckedIndexedAccess: true` - array/object index returns `T | undefined`
|
||||
- `noImplicitOverride: true`
|
||||
- `verbatimModuleSyntax: true`
|
||||
|
||||
Path alias: `@/*` → `src/*`
|
||||
|
||||
### Naming
|
||||
|
||||
| Entity | Convention | Example |
|
||||
|--------|------------|---------|
|
||||
| Files (utils) | kebab-case | `utils.ts`, `db-provider.ts` |
|
||||
| Files (components) | PascalCase | `NotFound.tsx` |
|
||||
| Routes | TanStack conventions | `routes/index.tsx`, `routes/__root.tsx` |
|
||||
| Components | PascalCase arrow functions | `const MyComponent = () => {}` |
|
||||
| Functions | camelCase | `handleSubmit` |
|
||||
| Constants | UPPER_SNAKE_CASE | `MAX_RETRIES` |
|
||||
| Types/Interfaces | PascalCase | `TodoItem`, `RouterContext` |
|
||||
|
||||
### React Patterns
|
||||
|
||||
```typescript
|
||||
// Components: arrow functions (Biome enforces)
|
||||
const MyComponent = ({ title }: { title: string }) => {
|
||||
return <div>{title}</div>
|
||||
}
|
||||
|
||||
// Routes: createFileRoute
|
||||
export const Route = createFileRoute('/')({
|
||||
component: Home,
|
||||
loader: async ({ context }) => {
|
||||
await context.queryClient.ensureQueryData(orpc.todo.list.queryOptions())
|
||||
},
|
||||
})
|
||||
|
||||
// Data fetching: TanStack Query
|
||||
const query = useSuspenseQuery(orpc.todo.list.queryOptions())
|
||||
const mutation = useMutation(orpc.todo.create.mutationOptions())
|
||||
```
|
||||
|
||||
### ORPC Pattern (Contract-First RPC)
|
||||
|
||||
1. **Define contract** (`src/orpc/contracts/my-feature.ts`):
|
||||
```typescript
|
||||
import { oc } from '@orpc/contract'
|
||||
import { z } from 'zod'
|
||||
|
||||
export const get = oc.input(z.object({ id: z.uuid() })).output(schema)
|
||||
export const create = oc.input(insertSchema).output(schema)
|
||||
```
|
||||
|
||||
2. **Implement handler** (`src/orpc/handlers/my-feature.ts`):
|
||||
```typescript
|
||||
import { os } from '@/orpc/server'
|
||||
import { dbProvider } from '@/orpc/middlewares'
|
||||
|
||||
export const get = os.myFeature.get
|
||||
.use(dbProvider)
|
||||
.handler(async ({ context, input }) => {
|
||||
return await context.db.query.myTable.findFirst(...)
|
||||
})
|
||||
```
|
||||
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` (`id uuid PRIMARY KEY DEFAULT uuidv7() NOT NULL` — **Postgres-side generation**, requires PG18+; `createdAt`, `updatedAt` with `$onUpdateFn`). The DB is the single source of UUIDv7 truth: monotonic per cluster, uses DB clock, no app-side round-trip. **Do not reintroduce `$defaultFn(() => Bun.randomUUIDv7())`** — the SQL default is what the migration emits and what `drizzle-zod` reads as "optional in insert schema". `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 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
|
||||
3. **Register** in `contract.ts` and `router.ts`
|
||||
4. **Use** in components via `orpc.myFeature.get.queryOptions()`
|
||||
|
||||
`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/`.
|
||||
### Drizzle Schema
|
||||
|
||||
```
|
||||
./server [serve] # default — start the HTTP server
|
||||
./server migrate # apply embedded migrations
|
||||
./server --help
|
||||
```typescript
|
||||
import { sql } from 'drizzle-orm'
|
||||
import { pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core'
|
||||
|
||||
export const myTable = pgTable('my_table', {
|
||||
id: uuid('id').primaryKey().default(sql`uuidv7()`),
|
||||
name: text('name').notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow().$onUpdateFn(() => new Date()),
|
||||
})
|
||||
```
|
||||
|
||||
**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.
|
||||
### Environment Variables
|
||||
|
||||
**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.
|
||||
- Server: no prefix (e.g., `DATABASE_URL`)
|
||||
- Client: `VITE_` prefix required
|
||||
- Validated via `@t3-oss/env-core` in `src/env.ts`
|
||||
|
||||
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
|
||||
|
||||
`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; `scripts/compile.ts` removes it so the binary is the only artifact.
|
||||
|
||||
## ORPC
|
||||
|
||||
Contract → Router → Handler → Client, all type-safe from a single contract.
|
||||
|
||||
- `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 (`src/server/api/routers/*.router.ts`) import `db` directly from `@/server/db` in their handlers. There is **no `middlewares/` directory** by default — `db` doesn't need one (module-level const). When you actually need per-request context (auth, tenant, rate-limit), create `src/server/api/middlewares/<name>.middleware.ts` with `os.middleware(...)` and extend `BaseContext` in `context.ts`.
|
||||
- **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`. `logError` resolves a `getLogger(['api'])` LogTape category — never `console.*` directly. See "Logging" section.
|
||||
- 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`.
|
||||
- **Mutation invalidation is colocated at the call site** via `mutationOptions({ onSuccess })`, not in `src/client/orpc.ts`. `orpc` in `src/client/orpc.ts` is a plain `createTanstackQueryUtils(client)` — no `experimental_defaults`. Per-feature query helpers live in `src/client/queries/<feature>.ts` (e.g. `useInvalidateTodos`); routes/components compose those hooks rather than holding query keys inline. See `src/client/queries/todo.ts` + `src/routes/index.tsx` for the canonical shape.
|
||||
- SSR prefetch in route loaders: `await context.queryClient.ensureQueryData(orpc.todo.list.queryOptions())`. Components use `useSuspenseQuery(orpc.feature.list.queryOptions())`.
|
||||
|
||||
## Code style (Biome)
|
||||
|
||||
- 2-space, LF, single quotes, **semicolons as-needed** (omitted unless required), 120-col, arrow parens always, `useArrowFunction: "error"` (covers function *expressions* only). Also `noReactPropAssignments: "error"`.
|
||||
- Lint domains enabled (Biome 2.4): `types: "all"` (catches `noFloatingPromises`, `noMisusedPromises`, `useAwaitThenable`, `noUnnecessaryConditions` — TS-aware async/promise traps), `drizzle: "recommended"`, `react: "recommended"`. `noImportCycles` is on under `suspicious`.
|
||||
- **Route components use `function Foo()` declarations**, placed below the `Route` config so the file reads top-down (route on top, component below). This is the official TanStack Router/Start pattern and relies on hoisting — `const Foo = () => {}` would TDZ-error when referenced from `createFileRoute({ component: Foo })` above it. Inline arrows are fine for trivial leaf components (e.g. plain redirect routes). Non-route components (UI primitives in `src/components/`) use `const Foo = () => {}`.
|
||||
- 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.
|
||||
- Files: utils `kebab-case.ts`, components `PascalCase.tsx`.
|
||||
- `routeTree.gen.ts` is generated — ignored by Biome, never edit.
|
||||
|
||||
## Testing
|
||||
|
||||
`bun test` runs all `*.test.ts` files. Tests are colocated next to the source they exercise (e.g. `src/server/api/contracts/todo.contract.test.ts`). Use `import { describe, expect, test } from 'bun:test'`. The `@/*` alias resolves in tests via tsconfig paths. No Vitest, no Jest, no separate test config — keep it that way unless you need a browser/JSDOM environment.
|
||||
|
||||
## Endpoints
|
||||
|
||||
- `/` — Todos UI (file route).
|
||||
- `/health` — bare `GET` returning `ok` (200, `text/plain`). Liveness only — no DB check, so it stays green even when Postgres is down. Add a separate `/ready` if you ever need readiness.
|
||||
- `/api/rpc` — ORPC RPC handler (POST).
|
||||
- `/api/*` — ORPC OpenAPI handler. Docs at `/api/docs`, spec at `/api/spec.json`.
|
||||
|
||||
## TypeScript
|
||||
|
||||
Strict mode, plus `noUncheckedIndexedAccess`, `verbatimModuleSyntax`, `erasableSyntaxOnly`, `noImplicitOverride`. No `as any` / `@ts-ignore` / `@ts-expect-error`.
|
||||
|
||||
Path alias: `@/* → src/*`. For files outside `src/` use `@/../<file>` (example in the codebase: `src/routes/api/$.ts` imports `name, version` from `@/../package.json`).
|
||||
|
||||
## Env
|
||||
|
||||
`src/env.ts` via `@t3-oss/env-core`. Server: `DATABASE_URL` (required, `z.url()`), `LOG_LEVEL` (`trace|debug|info|warning|error|fatal`, default `info`), `LOG_FORMAT` (`pretty|json`, default = TTY ? `pretty` : `json`), `LOG_DB` (`stringbool`, default `false` — flips on Drizzle SQL query logging). `client: {}` is empty by default — any client-side env must be `VITE_`-prefixed. Never commit `.env`.
|
||||
|
||||
## Logging
|
||||
|
||||
All server-side logging goes through `src/server/logger.ts`, a thin wrapper over [LogTape](https://logtape.org/). The module configures LogTape on import (via `configureSync`, no top-level await — works under `--bytecode`) and re-exports `getLogger`.
|
||||
|
||||
```ts
|
||||
import { getLogger } from '@/server/logger'
|
||||
const logger = getLogger(['feature', 'subsystem'])
|
||||
logger.info('Created todo {id}', { id })
|
||||
logger.error('DB write failed', { error })
|
||||
```
|
||||
|
||||
- Categories are hierarchical arrays — they show up as dot-paths in JSON output (`"logger":"feature.subsystem"`) and let you filter by prefix when shipping logs.
|
||||
- The `{name}` placeholders are for **primitive** values you want rendered inline (numbers, short strings, IDs). For objects, errors, and anything multi-field, omit the placeholder and just pass the value in properties — `logger.error('Auth failed', { error, userId })` keeps the message clean while properties stay structured. Never string-concatenate or template-literal — that defeats structured logging.
|
||||
- Format is `pretty` (icons + ANSI) on TTY, `json` (one-line JSON) when piped — perfect for Loki/Datadog/CloudWatch ingestion. Override with `LOG_FORMAT`.
|
||||
- Drizzle SQL queries are logged at `info` under category `['db']` when `LOG_DB=true`, via `@logtape/drizzle-orm`'s `DrizzleLogger` adapter (constructed in `src/server/db/index.ts`). The `info` level is intentional: flipping `LOG_DB=true` alone is enough — no need to also lower `LOG_LEVEL`.
|
||||
- `src/server/api/interceptors.ts` calls `getLogger(['api']).error(...)` from `logError`. CLI subcommands lazy-import the logger inside `run()` — they are still required to be side-effect-free at module top (citty eager-loads for `--help`).
|
||||
- Bun-specific: `process.env.NODE_ENV` is **inlined at build time** by `bun build --minify` — do NOT branch on it for logger config (use `process.stdout.isTTY` or `LOG_FORMAT` instead). pino is unusable here because its worker-thread transports crash inside the `/$bunfs/` virtual filesystem of compiled binaries; LogTape has zero workers and zero dynamic require, so it ships cleanly into the single binary.
|
||||
|
||||
## Docker / deploy
|
||||
|
||||
- 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`.
|
||||
|
||||
## Layout (non-obvious parts only)
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
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 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('#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
|
||||
│ ├── index.tsx # Todos UI
|
||||
│ ├── health.ts # GET /health → "ok" (no DB)
|
||||
│ └── api/
|
||||
│ ├── $.ts # OpenAPI + Scalar; interceptors registered here
|
||||
│ └── rpc.$.ts # RPC; interceptors registered here
|
||||
├── server/
|
||||
│ ├── logger.ts # LogTape `configureSync` + `getLogger` re-export — the only log entrypoint
|
||||
│ ├── api/
|
||||
│ │ ├── server.ts # the ONLY place to build `os`
|
||||
│ │ ├── context.ts # BaseContext (add per-request fields when you add middlewares)
|
||||
│ │ ├── interceptors.ts # logError (→ logger), handleValidationError
|
||||
│ │ ├── types.ts # Router{Client,Inputs,Outputs} derived from Contract
|
||||
│ │ ├── contracts/ # Zod schemas from Drizzle tables (barrel: contract); colocated *.test.ts
|
||||
│ │ └── routers/ # os.* handlers (barrel: router) — import db directly
|
||||
│ ├── db/
|
||||
│ │ ├── 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
|
||||
├── styles.css # Tailwind v4 entry
|
||||
└── routeTree.gen.ts # auto-generated, do not edit
|
||||
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)
|
||||
├── components/ # Reusable React components
|
||||
├── db/
|
||||
│ ├── schema/ # Drizzle schema definitions
|
||||
│ └── index.ts # Database instance
|
||||
├── integrations/ # TanStack Query/Router setup
|
||||
├── lib/ # Utility functions
|
||||
├── orpc/
|
||||
│ ├── contracts/ # Input/output schemas
|
||||
│ ├── handlers/ # Server procedure implementations
|
||||
│ ├── middlewares/ # Middleware (e.g., dbProvider)
|
||||
│ ├── contract.ts # Contract aggregation
|
||||
│ ├── router.ts # Router composition
|
||||
│ └── client.ts # Isomorphic client
|
||||
├── routes/ # File-based routes
|
||||
│ ├── __root.tsx # Root layout
|
||||
│ └── api/rpc.$.ts # ORPC HTTP endpoint
|
||||
└── env.ts # Environment validation
|
||||
```
|
||||
|
||||
Nitro plugins are wired in `vite.config.ts` (`nitro({ plugins: [...] })`), not via a Nitro config file.
|
||||
## Critical Rules
|
||||
|
||||
## Don'ts (specific, non-obvious)
|
||||
- **DO NOT** edit `src/routeTree.gen.ts` (auto-generated)
|
||||
- **DO NOT** commit `.env` files
|
||||
- **MUST** run `bun fix` before commits
|
||||
- **MUST** use `@/*` path alias (not relative imports)
|
||||
- **MUST** use React Compiler (no manual memoization needed)
|
||||
- **MUST** use `Readonly<T>` for immutable props
|
||||
|
||||
- **Don't run `bun run db:generate` (or `drizzle-kit generate`) as an AI agent.** Migration generation is reserved for the human. Make schema changes in `src/server/db/schema/*` + `src/server/db/fields.ts`, push the code changes, and stop — the human will run `bun run db:generate` and commit the resulting `drizzle/*.sql` + `src/server/db/migrations.gen.ts` themselves. (`bun run db:embed` is also off-limits because it's the codegen tail of `db:generate`.)
|
||||
- Don't edit `routeTree.gen.ts` or `src/server/db/migrations.gen.ts`.
|
||||
- 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.
|
||||
- Don't reintroduce `getDB/closeDB` or any "lazy DB init" pattern — that's a Cloudflare Workers shape; we deploy on Bun processes.
|
||||
- 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`.
|
||||
## Git Workflow
|
||||
|
||||
## Room-to-grow rules (discipline for the first real feature)
|
||||
|
||||
These keep the starter from setting bad precedents as it grows. Append, don't restructure.
|
||||
|
||||
1. Per-feature client query code — keys, options, `useInvalidate<Feature>` helpers — lives in `src/client/queries/<feature>.ts`. Routes/components compose these hooks; they don't hold query keys inline.
|
||||
2. Mutation invalidation stays explicit at the mutation call site (`mutationOptions({ onSuccess })`) or in a feature query helper. Do not reintroduce global `experimental_defaults` or any implicit cache policy.
|
||||
3. Client state defaults to route/component local state. Create a store (zustand or equivalent) only when state is shared across routes or needs persistence.
|
||||
4. Middlewares (`src/server/api/middlewares/<name>.middleware.ts`) derive request-scoped context or gate access. They do NOT orchestrate business flow, hold side effects, or replace handlers/services.
|
||||
5. Interceptors (`src/server/api/interceptors.ts`) do cross-cutting error logging, transport normalization, and validation rewrites. They do NOT read business data.
|
||||
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 `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.
|
||||
1. Make changes following style guide
|
||||
2. Run `bun fix` (format + lint)
|
||||
3. Run `bun typecheck` (type safety)
|
||||
4. Test with `bun dev`
|
||||
5. Commit with descriptive message
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
FROM oven/bun:1.3.13 AS build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json bun.lock ./
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
COPY . .
|
||||
RUN bun run build \
|
||||
&& bun run compile \
|
||||
&& mv out/server-* out/server
|
||||
|
||||
FROM gcr.io/distroless/cc-debian13:nonroot
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=build --chown=nonroot:nonroot /app/out/server ./server
|
||||
|
||||
ENV HOST=0.0.0.0
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["./server"]
|
||||
@@ -1,112 +0,0 @@
|
||||
# fullstack-starter
|
||||
|
||||
一个**单二进制**的全栈应用 starter——`bun run compile` 出来的 `./server` 文件就是你要部署的全部产物,自带 HTTP 服务、SSR、API、嵌入式 SQL 迁移,运行时不依赖 Node、不依赖源码、不依赖外部 migration 目录。
|
||||
|
||||
技术栈:Bun · TanStack Start (React 19 SSR) · ORPC(契约优先 API)· Drizzle ORM · PostgreSQL 18+ · Tailwind v4 · Biome。
|
||||
|
||||
## 为什么用这个
|
||||
|
||||
- **部署最简**:发布只拷一个二进制文件。先 `./server migrate` 再 `./server`,完事。
|
||||
- **契约优先**:在 `*.contract.ts` 用 Zod 定义一次,前端、后端、OpenAPI 文档自动同步。
|
||||
- **类型严格**:TypeScript strict,杜绝 `any` / `@ts-ignore` / `as any` 等类型逃逸。
|
||||
- **开箱可跑**:路径别名、文件路由、ORPC 接线、Tailwind、热重载、错误页全部预接好。
|
||||
|
||||
## 快速开始
|
||||
|
||||
> **需要 PostgreSQL 18+**——schema 用 PG 原生的 `uuidv7()` 生成主键(`compose.yaml` 已锁 `postgres:18-alpine`)。要兼容更老的 PG,把 `src/server/db/fields.ts` 里的 `default(sql\`uuidv7()\`)` 换成 `$defaultFn(() => Bun.randomUUIDv7())`,再跑 `bun run db:generate`。
|
||||
|
||||
```bash
|
||||
cp .env.example .env # 把里面的 DATABASE_URL 改成你的 Postgres
|
||||
bun install
|
||||
bun run db:push # 开发期:把 schema 直接同步到 DB(不写 migration 文件)
|
||||
bun run dev # http://localhost:3000
|
||||
```
|
||||
|
||||
打开浏览器:
|
||||
|
||||
- `http://localhost:3000/` — Todo 示例页
|
||||
- `http://localhost:3000/api/docs` — Scalar 渲染的 API 文档
|
||||
|
||||
## 目录结构(你需要关心的部分)
|
||||
|
||||
```
|
||||
src/
|
||||
├── routes/ # 文件路由:页面 + API 端点
|
||||
├── server/
|
||||
│ ├── api/
|
||||
│ │ ├── contracts/ # Zod 契约(client / server 共享)
|
||||
│ │ └── routers/ # 业务实现
|
||||
│ └── db/ # Drizzle schema + 嵌入式 migrations
|
||||
├── client/ # 前端 hooks、ORPC 客户端
|
||||
└── components/ # UI 组件
|
||||
```
|
||||
|
||||
## 加一个功能(以 `post` 为例)
|
||||
|
||||
每一步都很短,按顺序填即可:
|
||||
|
||||
1. **建表**:`src/server/db/schema/post.ts` 定义 `postTable`,记得展开 `...generatedFields`(自动注入 `id` / `createdAt` / `updatedAt`)。
|
||||
2. **导出表**:在 `src/server/db/schema/index.ts` 加 `export * from './post'`。
|
||||
3. **写契约**:`src/server/api/contracts/post.contract.ts` 用 `drizzle-zod` 从表派生 Zod schema。
|
||||
4. **挂契约**:在 `src/server/api/contracts/index.ts` 把 `post` 加进 `contract` 对象。
|
||||
5. **写实现**:`src/server/api/routers/post.router.ts` 实现 `os.post.*.handler(...)`。
|
||||
6. **挂路由**:在 `src/server/api/routers/index.ts` 把 `post` 加进 `router` 对象。
|
||||
7. **写前端 hook**:`src/client/queries/post.ts` 导出 `useInvalidatePosts` 等失效辅助。
|
||||
8. **写页面**:`src/routes/<page>.tsx` 用 `useSuspenseQuery` 读、`mutate` 写;mutation 的 `onSuccess` 调用第 7 步的 helper。
|
||||
9. **生成 migration**:`bun run db:generate` 把 SQL 写到 `./drizzle/` 并嵌入二进制。
|
||||
|
||||
完工。`bun run dev` 已自动热重载。
|
||||
|
||||
## 部署
|
||||
|
||||
**永远先 migrate 再 serve**。Migration 已嵌入二进制;部署只发一个 `./server` 文件。
|
||||
|
||||
```bash
|
||||
./server migrate # 应用嵌入式 migration(用 $DATABASE_URL)
|
||||
./server # 启动 HTTP 服务(默认子命令)
|
||||
./server --help # 列出所有子命令
|
||||
```
|
||||
|
||||
仓库自带 `compose.yaml`(一次性 `migrate` 服务先跑完,再启动 `app`):
|
||||
|
||||
```bash
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
Kubernetes 上:把 `./server migrate` 放进 initContainer 或 Helm `pre-upgrade` Job,主容器跑 `./server`。
|
||||
|
||||
## 脚本一览
|
||||
|
||||
| 命令 | 作用 |
|
||||
| --- | --- |
|
||||
| `bun run dev` | Vite 开发服务器(默认端口 3000) |
|
||||
| `bun run build` | 构建到 `.output/`(`bun run compile` 会用到) |
|
||||
| `bun run compile` | 生成单二进制 `out/server-<target>` |
|
||||
| `bun run typecheck` | TypeScript 类型检查 |
|
||||
| `bun run test` | 运行所有 `*.test.ts` |
|
||||
| `bun run fix` | Biome 格式化 + lint + 整理 imports |
|
||||
| `bun run db:push` | 开发期:直接同步 schema 到 DB(不写 migration 文件) |
|
||||
| `bun run db:generate` | 写 SQL migration 到 `./drizzle/` 并嵌入二进制 |
|
||||
| `bun run db:embed` | 仅重生 `migrations.gen.ts`(手改了 `./drizzle/*.sql` 后用) |
|
||||
| `bun run db:migrate` | 通过 drizzle-kit 在本地应用 migration(开发便利) |
|
||||
| `bun run db:studio` | Drizzle Studio(可视化 DB) |
|
||||
|
||||
跨平台编译:`bun run compile:{linux,darwin,windows}[:arch]`。
|
||||
|
||||
## 端点
|
||||
|
||||
| 路径 | 用途 |
|
||||
| --- | --- |
|
||||
| `/` | Todo 示例 UI |
|
||||
| `/health` | 存活探针(不查 DB,纯文本 `ok`) |
|
||||
| `/api/rpc` | ORPC RPC 端点(client 直连) |
|
||||
| `/api/docs` | Scalar 渲染的 API 文档 |
|
||||
| `/api/spec.json` | OpenAPI spec |
|
||||
|
||||
## 提交前
|
||||
|
||||
```bash
|
||||
bun run fix && bun run typecheck && bun run test
|
||||
```
|
||||
|
||||
没有 CI、没有 pre-commit hook——上面三条由你自觉跑。
|
||||
@@ -6,22 +6,16 @@
|
||||
"useIgnoreFile": true
|
||||
},
|
||||
"files": {
|
||||
"ignoreUnknown": false,
|
||||
"includes": ["**", "!**/routeTree.gen.ts", "!**/migrations.gen.ts"]
|
||||
"includes": ["**", "!**/routeTree.gen.ts"],
|
||||
"ignoreUnknown": false
|
||||
},
|
||||
"formatter": {
|
||||
"enabled": true,
|
||||
"indentStyle": "space",
|
||||
"lineEnding": "lf",
|
||||
"lineWidth": 120
|
||||
"lineEnding": "lf"
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"domains": {
|
||||
"drizzle": "recommended",
|
||||
"react": "recommended",
|
||||
"types": "all"
|
||||
},
|
||||
"rules": {
|
||||
"recommended": true,
|
||||
"complexity": {
|
||||
@@ -29,14 +23,6 @@
|
||||
},
|
||||
"correctness": {
|
||||
"noReactPropAssignments": "error"
|
||||
},
|
||||
"style": {
|
||||
"noNonNullAssertion": "error"
|
||||
},
|
||||
"suspicious": {
|
||||
"noExplicitAny": "error",
|
||||
"noImportCycles": "error",
|
||||
"noTsIgnore": "error"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -47,11 +33,6 @@
|
||||
"arrowParentheses": "always"
|
||||
}
|
||||
},
|
||||
"css": {
|
||||
"parser": {
|
||||
"tailwindDirectives": true
|
||||
}
|
||||
},
|
||||
"assist": {
|
||||
"enabled": true,
|
||||
"actions": {
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
import { Schema } from '@effect/schema'
|
||||
import { $ } from 'bun'
|
||||
import { Console, Context, Data, Effect, Layer } from 'effect'
|
||||
|
||||
// ============================================================================
|
||||
// Domain Models & Schema
|
||||
// ============================================================================
|
||||
|
||||
const targetMap = {
|
||||
'bun-windows-x64': 'x86_64-pc-windows-msvc',
|
||||
'bun-darwin-arm64': 'aarch64-apple-darwin',
|
||||
'bun-darwin-x64': 'x86_64-apple-darwin',
|
||||
'bun-linux-x64': 'x86_64-unknown-linux-gnu',
|
||||
'bun-linux-arm64': 'aarch64-unknown-linux-gnu',
|
||||
} as const
|
||||
|
||||
const BunTargetSchema = Schema.Literal(
|
||||
'bun-windows-x64',
|
||||
'bun-darwin-arm64',
|
||||
'bun-darwin-x64',
|
||||
'bun-linux-x64',
|
||||
'bun-linux-arm64',
|
||||
)
|
||||
|
||||
type BunTarget = Schema.Schema.Type<typeof BunTargetSchema>
|
||||
|
||||
const BuildConfigSchema = Schema.Struct({
|
||||
entrypoint: Schema.String.pipe(Schema.nonEmptyString()),
|
||||
outputDir: Schema.String.pipe(Schema.nonEmptyString()),
|
||||
targets: Schema.Array(BunTargetSchema).pipe(Schema.minItems(1)),
|
||||
})
|
||||
|
||||
type BuildConfig = Schema.Schema.Type<typeof BuildConfigSchema>
|
||||
|
||||
const BuildResultSchema = Schema.Struct({
|
||||
target: BunTargetSchema,
|
||||
outputs: Schema.Array(Schema.String),
|
||||
})
|
||||
|
||||
type BuildResult = Schema.Schema.Type<typeof BuildResultSchema>
|
||||
|
||||
// ============================================================================
|
||||
// Error Models (使用 Data.TaggedError)
|
||||
// ============================================================================
|
||||
|
||||
class CleanError extends Data.TaggedError('CleanError')<{
|
||||
readonly dir: string
|
||||
readonly cause: unknown
|
||||
}> {}
|
||||
|
||||
class BuildError extends Data.TaggedError('BuildError')<{
|
||||
readonly target: BunTarget
|
||||
readonly cause: unknown
|
||||
}> {}
|
||||
|
||||
class ConfigError extends Data.TaggedError('ConfigError')<{
|
||||
readonly message: string
|
||||
readonly cause: unknown
|
||||
}> {}
|
||||
|
||||
// ============================================================================
|
||||
// Services
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 配置服务
|
||||
*/
|
||||
class BuildConfigService extends Context.Tag('BuildConfigService')<
|
||||
BuildConfigService,
|
||||
BuildConfig
|
||||
>() {
|
||||
/**
|
||||
* 从原始数据创建并验证配置
|
||||
*/
|
||||
static fromRaw = (raw: unknown) =>
|
||||
Effect.gen(function* () {
|
||||
const decoded = yield* Schema.decodeUnknown(BuildConfigSchema)(raw)
|
||||
return decoded
|
||||
}).pipe(
|
||||
Effect.catchAll((error) =>
|
||||
Effect.fail(
|
||||
new ConfigError({
|
||||
message: '配置验证失败',
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* 默认配置 Layer
|
||||
*/
|
||||
static readonly Live = Layer.effect(
|
||||
BuildConfigService,
|
||||
BuildConfigService.fromRaw({
|
||||
entrypoint: '.output/server/index.mjs',
|
||||
// outputDir: 'out',
|
||||
outputDir: 'src-tauri/binaries',
|
||||
targets: ['bun-windows-x64', 'bun-darwin-arm64', 'bun-linux-x64'],
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件系统服务
|
||||
*/
|
||||
class FileSystemService extends Context.Tag('FileSystemService')<
|
||||
FileSystemService,
|
||||
{
|
||||
readonly cleanDir: (dir: string) => Effect.Effect<void, CleanError>
|
||||
}
|
||||
>() {
|
||||
static readonly Live = Layer.succeed(FileSystemService, {
|
||||
cleanDir: (dir: string) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
await $`rm -rf ${dir}`
|
||||
},
|
||||
catch: (cause: unknown) =>
|
||||
new CleanError({
|
||||
dir,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建服务
|
||||
*/
|
||||
class BuildService extends Context.Tag('BuildService')<
|
||||
BuildService,
|
||||
{
|
||||
readonly buildForTarget: (
|
||||
config: BuildConfig,
|
||||
target: BunTarget,
|
||||
) => Effect.Effect<BuildResult, BuildError>
|
||||
readonly buildAll: (
|
||||
config: BuildConfig,
|
||||
) => Effect.Effect<ReadonlyArray<BuildResult>, BuildError>
|
||||
}
|
||||
>() {
|
||||
static readonly Live = Layer.succeed(BuildService, {
|
||||
buildForTarget: (config: BuildConfig, target: BunTarget) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Console.log(`🔨 开始构建: ${target}`)
|
||||
|
||||
const output = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Bun.build({
|
||||
entrypoints: [config.entrypoint],
|
||||
compile: {
|
||||
outfile: `app-${targetMap[target]}`,
|
||||
target: target,
|
||||
},
|
||||
outdir: config.outputDir,
|
||||
}),
|
||||
catch: (cause: unknown) =>
|
||||
new BuildError({
|
||||
target,
|
||||
cause,
|
||||
}),
|
||||
})
|
||||
|
||||
const paths = output.outputs.map((item: { path: string }) => item.path)
|
||||
|
||||
return {
|
||||
target,
|
||||
outputs: paths,
|
||||
} satisfies BuildResult
|
||||
}),
|
||||
|
||||
buildAll: (config: BuildConfig) =>
|
||||
Effect.gen(function* () {
|
||||
const effects = config.targets.map((target) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Console.log(`🔨 开始构建: ${target}`)
|
||||
|
||||
const output = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Bun.build({
|
||||
entrypoints: [config.entrypoint],
|
||||
compile: {
|
||||
outfile: `app-${targetMap[target]}`,
|
||||
target: target,
|
||||
},
|
||||
outdir: config.outputDir,
|
||||
}),
|
||||
catch: (cause: unknown) =>
|
||||
new BuildError({
|
||||
target,
|
||||
cause,
|
||||
}),
|
||||
})
|
||||
|
||||
const paths = output.outputs.map(
|
||||
(item: { path: string }) => item.path,
|
||||
)
|
||||
|
||||
return {
|
||||
target,
|
||||
outputs: paths,
|
||||
} satisfies BuildResult
|
||||
}),
|
||||
)
|
||||
return yield* Effect.all(effects, { concurrency: 'unbounded' })
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 报告服务
|
||||
*/
|
||||
class ReporterService extends Context.Tag('ReporterService')<
|
||||
ReporterService,
|
||||
{
|
||||
readonly printSummary: (
|
||||
results: ReadonlyArray<BuildResult>,
|
||||
) => Effect.Effect<void>
|
||||
}
|
||||
>() {
|
||||
static readonly Live = Layer.succeed(ReporterService, {
|
||||
printSummary: (results: ReadonlyArray<BuildResult>) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Console.log('\n📦 构建完成:')
|
||||
for (const result of results) {
|
||||
yield* Console.log(` ${result.target}:`)
|
||||
for (const path of result.outputs) {
|
||||
yield* Console.log(` - ${path}`)
|
||||
}
|
||||
}
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Main Program
|
||||
// ============================================================================
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const config = yield* BuildConfigService
|
||||
const fs = yield* FileSystemService
|
||||
const builder = yield* BuildService
|
||||
const reporter = yield* ReporterService
|
||||
|
||||
// 1. 清理输出目录
|
||||
yield* fs.cleanDir(config.outputDir)
|
||||
yield* Console.log(`✓ 已清理输出目录: ${config.outputDir}`)
|
||||
|
||||
// 2. 并行构建所有目标
|
||||
const results = yield* builder.buildAll(config)
|
||||
|
||||
// 3. 输出构建摘要
|
||||
yield* reporter.printSummary(results)
|
||||
|
||||
return results
|
||||
})
|
||||
|
||||
// ============================================================================
|
||||
// Layer Composition
|
||||
// ============================================================================
|
||||
|
||||
const MainLayer = Layer.mergeAll(
|
||||
BuildConfigService.Live,
|
||||
FileSystemService.Live,
|
||||
BuildService.Live,
|
||||
ReporterService.Live,
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// Runner
|
||||
// ============================================================================
|
||||
|
||||
const runnable = program.pipe(
|
||||
Effect.provide(MainLayer),
|
||||
Effect.catchTags({
|
||||
CleanError: (error) =>
|
||||
Console.error(`❌ 清理目录失败: ${error.dir}`, error.cause),
|
||||
BuildError: (error) =>
|
||||
Console.error(`❌ 构建失败 [${error.target}]:`, error.cause),
|
||||
ConfigError: (error) =>
|
||||
Console.error(`❌ 配置错误: ${error.message}`, error.cause),
|
||||
}),
|
||||
Effect.tapErrorCause((cause) => Console.error('❌ 未预期的错误:', cause)),
|
||||
)
|
||||
|
||||
Effect.runPromise(runnable).catch(() => {
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -1,39 +0,0 @@
|
||||
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:
|
||||
- DATABASE_URL=postgres://postgres:postgres@db:5432/postgres
|
||||
|
||||
db:
|
||||
image: postgres:18-alpine
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: postgres
|
||||
healthcheck:
|
||||
test: [ "CMD", "pg_isready", "-U", "postgres" ]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
@@ -1,9 +1,9 @@
|
||||
import { defineConfig } from 'drizzle-kit'
|
||||
import { env } from './src/env'
|
||||
import { env } from '@/env'
|
||||
|
||||
export default defineConfig({
|
||||
out: './drizzle',
|
||||
schema: './src/server/db/schema/index.ts',
|
||||
schema: './src/db/schema/index.ts',
|
||||
dialect: 'postgresql',
|
||||
dbCredentials: {
|
||||
url: env.DATABASE_URL,
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
CREATE TABLE "todo" (
|
||||
"id" uuid PRIMARY KEY NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"title" text NOT NULL,
|
||||
"completed" boolean DEFAULT false NOT NULL
|
||||
);
|
||||
@@ -1,65 +0,0 @@
|
||||
{
|
||||
"id": "4ece5479-57bf-473d-b806-c1176c972e7f",
|
||||
"prevId": "00000000-0000-0000-0000-000000000000",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
"public.todo": {
|
||||
"name": "todo",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"title": {
|
||||
"name": "title",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"completed": {
|
||||
"name": "completed",
|
||||
"type": "boolean",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
}
|
||||
},
|
||||
"enums": {},
|
||||
"schemas": {},
|
||||
"sequences": {},
|
||||
"roles": {},
|
||||
"policies": {},
|
||||
"views": {},
|
||||
"_meta": {
|
||||
"columns": {},
|
||||
"schemas": {},
|
||||
"tables": {}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "7",
|
||||
"when": 1777096386609,
|
||||
"tag": "0000_loving_thunderbird",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,2 +1,4 @@
|
||||
[tools]
|
||||
bun = "1.3.13"
|
||||
node = "24"
|
||||
bun = "1"
|
||||
rust = 'latest'
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"mcp": {
|
||||
"shadcn": {
|
||||
"type": "local",
|
||||
"command": ["bunx", "--bun", "shadcn", "mcp"]
|
||||
},
|
||||
"tanstack": {
|
||||
"type": "remote",
|
||||
"url": "https://tanstack.com/api/mcp"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,71 +1,64 @@
|
||||
{
|
||||
"name": "fullstack-starter",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"imports": {
|
||||
"#drizzle/*.sql": "./drizzle/*.sql",
|
||||
"#package": "./package.json",
|
||||
"#server": "./.output/server/index.mjs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "bunx --bun vite build",
|
||||
"cli": "bun src/bin.ts",
|
||||
"compile": "bun scripts/compile.ts",
|
||||
"compile:darwin": "bun run compile:darwin:arm64 && bun run compile:darwin:x64",
|
||||
"compile:darwin:arm64": "bun scripts/compile.ts --target bun-darwin-arm64",
|
||||
"compile:darwin:x64": "bun scripts/compile.ts --target bun-darwin-x64",
|
||||
"compile:linux": "bun run compile:linux:x64 && bun run compile:linux:arm64",
|
||||
"compile:linux:arm64": "bun scripts/compile.ts --target bun-linux-arm64",
|
||||
"compile:linux:x64": "bun scripts/compile.ts --target bun-linux-x64",
|
||||
"compile:windows": "bun run compile:windows:x64",
|
||||
"compile:windows:x64": "bun scripts/compile.ts --target bun-windows-x64",
|
||||
"db:embed": "bun scripts/embed-migrations.ts",
|
||||
"db:generate": "drizzle-kit generate && bun scripts/embed-migrations.ts",
|
||||
"build": "turbo build:tauri",
|
||||
"build:compile": "bun build.ts",
|
||||
"build:tauri": "NO_STRIP=1 tauri build",
|
||||
"build:vite": "vite build",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "drizzle-kit migrate",
|
||||
"db:push": "drizzle-kit push",
|
||||
"db:studio": "drizzle-kit studio",
|
||||
"dev": "bunx --bun vite dev",
|
||||
"dev": "turbo dev:tauri",
|
||||
"dev:tauri": "tauri dev",
|
||||
"dev:vite": "vite dev",
|
||||
"fix": "biome check --write",
|
||||
"test": "bun test",
|
||||
"typecheck": "tsc --noEmit"
|
||||
"typecheck": "tsc -b"
|
||||
},
|
||||
"dependencies": {
|
||||
"@logtape/drizzle-orm": "^2.0.5",
|
||||
"@logtape/logtape": "^2.0.5",
|
||||
"@logtape/pretty": "^2.0.5",
|
||||
"@orpc/client": "^1.14.0",
|
||||
"@orpc/contract": "^1.14.0",
|
||||
"@orpc/openapi": "^1.14.0",
|
||||
"@orpc/server": "^1.14.0",
|
||||
"@orpc/tanstack-query": "^1.14.0",
|
||||
"@orpc/zod": "^1.14.0",
|
||||
"@t3-oss/env-core": "^0.13.11",
|
||||
"@tanstack/react-query": "^5.100.1",
|
||||
"@tanstack/react-router": "^1.168.24",
|
||||
"@tanstack/react-router-ssr-query": "^1.166.11",
|
||||
"@tanstack/react-start": "^1.167.48",
|
||||
"citty": "^0.2.2",
|
||||
"drizzle-orm": "0.45.2",
|
||||
"@orpc/client": "^1.13.4",
|
||||
"@orpc/contract": "^1.13.4",
|
||||
"@orpc/server": "^1.13.4",
|
||||
"@orpc/tanstack-query": "^1.13.4",
|
||||
"@orpc/zod": "^1.13.4",
|
||||
"@t3-oss/env-core": "^0.13.10",
|
||||
"@tanstack/react-query": "^5.90.20",
|
||||
"@tanstack/react-router": "^1.158.1",
|
||||
"@tanstack/react-router-ssr-query": "^1.158.1",
|
||||
"@tanstack/react-start": "^1.158.3",
|
||||
"@tauri-apps/api": "^2.10.1",
|
||||
"drizzle-orm": "^0.45.1",
|
||||
"drizzle-zod": "^0.8.3",
|
||||
"postgres": "^3.4.9",
|
||||
"react": "^19.2.5",
|
||||
"react-dom": "^19.2.5",
|
||||
"postgres": "^3.4.8",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "^2.4.13",
|
||||
"@tailwindcss/vite": "^4.2.4",
|
||||
"@tanstack/devtools-vite": "^0.6.0",
|
||||
"@tanstack/react-devtools": "^0.10.2",
|
||||
"@tanstack/react-query-devtools": "^5.100.1",
|
||||
"@tanstack/react-router-devtools": "^1.166.13",
|
||||
"@types/bun": "^1.3.13",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"drizzle-kit": "0.31.10",
|
||||
"nitro": "npm:nitro-nightly@3.0.1-20260424-182106-f8cf6ccc",
|
||||
"tailwindcss": "^4.2.4",
|
||||
"typescript": "^6.0.3",
|
||||
"vite": "^8.0.10"
|
||||
"@biomejs/biome": "^2.3.14",
|
||||
"@effect/platform": "^0.94.3",
|
||||
"@effect/schema": "^0.75.5",
|
||||
"@tailwindcss/vite": "^4.1.18",
|
||||
"@tanstack/devtools-vite": "^0.4.1",
|
||||
"@tanstack/react-devtools": "^0.9.4",
|
||||
"@tanstack/react-query-devtools": "^5.91.3",
|
||||
"@tanstack/react-router-devtools": "^1.158.1",
|
||||
"@tauri-apps/cli": "^2.10.0",
|
||||
"@types/bun": "^1.3.8",
|
||||
"@vitejs/plugin-react": "^5.1.3",
|
||||
"babel-plugin-react-compiler": "^1.0.0",
|
||||
"drizzle-kit": "^0.31.8",
|
||||
"effect": "^3.19.16",
|
||||
"nitro": "npm:nitro-nightly@latest",
|
||||
"tailwindcss": "^4.1.18",
|
||||
"turbo": "^2.8.3",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^8.0.0-beta.13",
|
||||
"vite-tsconfig-paths": "^6.0.5"
|
||||
},
|
||||
"overrides": {
|
||||
"@tanstack/query-core": "^5.90.20"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
import { mkdir, rm } from 'node:fs/promises'
|
||||
import { basename } from 'node:path'
|
||||
import { parseArgs } from 'node:util'
|
||||
|
||||
const ENTRYPOINT = 'src/bin.ts'
|
||||
const OUTDIR = 'out'
|
||||
|
||||
const SUPPORTED_TARGETS: readonly Bun.Build.CompileTarget[] = [
|
||||
'bun-windows-x64',
|
||||
'bun-darwin-arm64',
|
||||
'bun-darwin-x64',
|
||||
'bun-linux-x64',
|
||||
'bun-linux-arm64',
|
||||
]
|
||||
|
||||
const SUPPORTED_TARGET_SET: ReadonlySet<string> = new Set(SUPPORTED_TARGETS)
|
||||
|
||||
const isSupportedTarget = (value: string): value is Bun.Build.CompileTarget => SUPPORTED_TARGET_SET.has(value)
|
||||
|
||||
const { values } = parseArgs({
|
||||
options: { target: { type: 'string' } },
|
||||
strict: true,
|
||||
allowPositionals: false,
|
||||
})
|
||||
|
||||
const resolveTarget = (): Bun.Build.CompileTarget => {
|
||||
if (values.target !== undefined) {
|
||||
if (!isSupportedTarget(values.target)) {
|
||||
throw new Error(`Invalid target: ${values.target}\nAllowed: ${SUPPORTED_TARGETS.join(', ')}`)
|
||||
}
|
||||
return values.target
|
||||
}
|
||||
|
||||
const os = process.platform === 'win32' ? 'windows' : process.platform
|
||||
const candidate = `bun-${os}-${process.arch}`
|
||||
if (!isSupportedTarget(candidate)) {
|
||||
throw new Error(`Unsupported host: ${process.platform}-${process.arch}`)
|
||||
}
|
||||
return candidate
|
||||
}
|
||||
|
||||
const main = async () => {
|
||||
const target = resolveTarget()
|
||||
const suffix = target.replace('bun-', '')
|
||||
const outfile = `server-${suffix}`
|
||||
|
||||
await mkdir(OUTDIR, { recursive: true })
|
||||
await Promise.all([rm(`${OUTDIR}/${outfile}`, { force: true }), rm(`${OUTDIR}/${outfile}.exe`, { force: true })])
|
||||
|
||||
const result = await Bun.build({
|
||||
entrypoints: [ENTRYPOINT],
|
||||
outdir: OUTDIR,
|
||||
// autoloadDotenv: false — produce a deterministic binary; it must not silently consume a .env from cwd.
|
||||
compile: { outfile, target, autoloadDotenv: false },
|
||||
minify: true,
|
||||
bytecode: true,
|
||||
sourcemap: 'inline',
|
||||
})
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.logs.map(String).join('\n'))
|
||||
}
|
||||
|
||||
// Bun bundler still writes *.js.map next to the binary even with inline sourcemap.
|
||||
await rm(`${OUTDIR}/${basename(ENTRYPOINT, '.ts')}.js.map`, { force: true })
|
||||
|
||||
console.log(`✓ ${target} → ${OUTDIR}/${outfile}`)
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('❌', err instanceof Error ? err.message : err)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -1,51 +0,0 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { readFile, writeFile } from 'node:fs/promises'
|
||||
import { z } from 'zod'
|
||||
|
||||
const JOURNAL = './drizzle/meta/_journal.json'
|
||||
const OUTPUT = './src/server/db/migrations.gen.ts'
|
||||
|
||||
const journalEntrySchema = z.object({
|
||||
idx: z.number().int().nonnegative(),
|
||||
tag: z.string().regex(/^\d{4}_[a-z0-9_]+$/),
|
||||
when: z.number().int().nonnegative(),
|
||||
breakpoints: z.boolean(),
|
||||
})
|
||||
const journalSchema = z.object({ entries: z.array(journalEntrySchema).default([]) })
|
||||
|
||||
type JournalEntry = z.infer<typeof journalEntrySchema>
|
||||
|
||||
const readJournalEntries = async (): Promise<JournalEntry[]> => {
|
||||
if (!existsSync(JOURNAL)) {
|
||||
return []
|
||||
}
|
||||
const raw: unknown = JSON.parse(await readFile(JOURNAL, 'utf-8'))
|
||||
return journalSchema.parse(raw).entries.sort((a, b) => a.idx - b.idx)
|
||||
}
|
||||
|
||||
const main = async () => {
|
||||
const entries = await readJournalEntries()
|
||||
|
||||
const imports = entries
|
||||
.map((e) => `import sql_${e.idx} from '#drizzle/${e.tag}.sql' with { type: 'text' }`)
|
||||
.join('\n')
|
||||
|
||||
const arrayBody = entries.length
|
||||
? `[\n${entries.map((e) => ` { tag: '${e.tag}', sql: sql_${e.idx}, when: ${e.when}, breakpoints: ${e.breakpoints} },`).join('\n')}\n]`
|
||||
: '[]'
|
||||
|
||||
const out = `// AUTO-GENERATED by \`bun run db:embed\`. Do not edit.
|
||||
${imports ? `${imports}\n` : ''}
|
||||
export type EmbeddedMigration = { tag: string; sql: string; when: number; breakpoints: boolean }
|
||||
|
||||
export const embeddedMigrations: readonly EmbeddedMigration[] = ${arrayBody}
|
||||
`
|
||||
|
||||
await writeFile(OUTPUT, out)
|
||||
console.log(`✓ ${OUTPUT} (${entries.length} migration${entries.length === 1 ? '' : 's'})`)
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('❌', err instanceof Error ? err.message : err)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
|
||||
# Generated by Tauri
|
||||
# will have schema files for capabilities auto-completion
|
||||
/gen/schemas
|
||||
|
||||
# Tauri Sidecar
|
||||
binaries/
|
||||
@@ -0,0 +1,357 @@
|
||||
# AGENTS.md - Tauri Shell 项目开发指南
|
||||
|
||||
本文档为 AI 编程助手和开发者提供项目规范、构建命令和代码风格指南。
|
||||
|
||||
## 项目概览
|
||||
|
||||
- **项目类型**: Tauri v2 桌面应用(轻量级壳子)
|
||||
- **后端**: Rust (Edition 2021)
|
||||
- **架构**: Sidecar 模式 - Sidecar App 承载主要业务逻辑
|
||||
- **设计理念**: Tauri 仅提供原生桌面能力(文件对话框、系统通知等),Web 逻辑全部由 Sidecar App 处理
|
||||
- **开发模式**: 使用 localhost:3000(需手动启动开发服务器)
|
||||
- **生产模式**: 自动启动 Sidecar 二进制
|
||||
- **异步运行时**: Tokio
|
||||
- **Rust 版本**: 1.92.0+
|
||||
- **工具管理**: 使用 mise 管理 Rust 和 Tauri CLI 版本(见 `mise.toml`)
|
||||
|
||||
## 构建、测试、运行命令
|
||||
|
||||
### 开发运行
|
||||
```bash
|
||||
# 开发模式运行 (需要先启动开发服务器)
|
||||
# 终端 1: 启动前端开发服务器
|
||||
bun run dev
|
||||
|
||||
# 终端 2: 启动 Tauri 应用
|
||||
tauri dev
|
||||
|
||||
# 或者使用单命令并行启动(需要配置 package.json)
|
||||
bun run dev:tauri
|
||||
```
|
||||
|
||||
**开发模式说明**:
|
||||
- 开发模式下,Tauri 直接连接到 `localhost:3000`(不启动 sidecar 二进制)
|
||||
- 需要手动运行 `bun run dev` 来启动开发服务器
|
||||
- 支持热重载(HMR),无需重启 Tauri 应用
|
||||
|
||||
### 构建
|
||||
```bash
|
||||
# 开发构建 (debug mode)
|
||||
cargo build
|
||||
|
||||
# 生产构建
|
||||
cargo build --release
|
||||
|
||||
# Tauri 应用打包 (生成安装程序)
|
||||
tauri build
|
||||
```
|
||||
|
||||
### 代码检查
|
||||
```bash
|
||||
# 编译检查 (不生成二进制)
|
||||
cargo check
|
||||
|
||||
# Clippy 代码质量检查
|
||||
cargo clippy
|
||||
|
||||
# Clippy 严格模式 (所有警告视为错误)
|
||||
cargo clippy -- -D warnings
|
||||
|
||||
# 代码格式化检查
|
||||
cargo fmt -- --check
|
||||
|
||||
# 自动格式化代码
|
||||
cargo fmt
|
||||
```
|
||||
|
||||
### 测试
|
||||
```bash
|
||||
# 运行所有测试
|
||||
cargo test
|
||||
|
||||
# 运行单个测试 (按名称过滤)
|
||||
cargo test test_function_name
|
||||
|
||||
# 运行特定模块的测试
|
||||
cargo test module_name::
|
||||
|
||||
# 显示测试输出 (包括 println!)
|
||||
cargo test -- --nocapture
|
||||
|
||||
# 运行单个测试并显示输出
|
||||
cargo test test_name -- --nocapture
|
||||
```
|
||||
|
||||
### 清理
|
||||
```bash
|
||||
# 清理构建产物
|
||||
cargo clean
|
||||
```
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
app-desktop/
|
||||
├── src/
|
||||
│ ├── main.rs # 入口文件 (仅调用 lib::run)
|
||||
│ ├── lib.rs # 核心应用逻辑 (注册插件、命令、状态)
|
||||
│ ├── commands/
|
||||
│ │ └── mod.rs # 原生桌面功能命令 (文件对话框、通知等)
|
||||
│ └── sidecar.rs # Sidecar 进程管理 (启动、端口扫描、清理)
|
||||
├── binaries/ # Sidecar 二进制文件
|
||||
│ └── app-* # Sidecar App 可执行文件 (示例: app)
|
||||
├── capabilities/ # Tauri v2 权限配置
|
||||
│ └── default.json
|
||||
├── icons/ # 应用图标资源
|
||||
├── gen/schemas/ # 自动生成的 Schema (不要手动编辑)
|
||||
├── Cargo.toml # Rust 项目配置
|
||||
├── tauri.conf.json # Tauri 应用配置
|
||||
├── build.rs # Rust 构建脚本
|
||||
└── mise.toml # 开发工具版本管理
|
||||
```
|
||||
|
||||
## Rust 代码风格指南
|
||||
|
||||
### 导入 (Imports)
|
||||
|
||||
- 使用标准库、外部 crate、当前 crate 的顺序,用空行分隔
|
||||
- 按字母顺序排列
|
||||
- 优先使用具体导入而非通配符 `*`
|
||||
|
||||
```rust
|
||||
// ✅ 推荐
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use tauri::Manager;
|
||||
use tauri_plugin_shell::ShellExt;
|
||||
use tauri_plugin_shell::process::{CommandEvent, CommandChild};
|
||||
|
||||
// ❌ 避免
|
||||
use tauri::*;
|
||||
```
|
||||
|
||||
### 命名规范
|
||||
|
||||
- **函数和变量**: `snake_case`
|
||||
- **类型、结构体、枚举、Trait**: `PascalCase`
|
||||
- **常量和静态变量**: `SCREAMING_SNAKE_CASE`
|
||||
- **生命周期参数**: 简短小写字母,如 `'a`, `'b`
|
||||
|
||||
```rust
|
||||
// ✅ 推荐
|
||||
struct SidecarProcess(Mutex<Option<CommandChild>>);
|
||||
const DEFAULT_PORT: u16 = 3000;
|
||||
async fn find_available_port(start: u16) -> u16 { }
|
||||
|
||||
// ❌ 避免
|
||||
struct sidecar_process { }
|
||||
const defaultPort: u16 = 3000;
|
||||
```
|
||||
|
||||
### 类型注解
|
||||
|
||||
- 函数参数必须有类型注解
|
||||
- 函数返回值必须明确声明 (除非返回 `()`)
|
||||
- 优先使用具体类型而非 `impl Trait` (除非必要)
|
||||
- 使用 `&str` 而非 `String` 作为只读字符串参数
|
||||
|
||||
```rust
|
||||
// ✅ 推荐
|
||||
#[tauri::command]
|
||||
fn greet(name: &str) -> String {
|
||||
format!("Hello, {}!", name)
|
||||
}
|
||||
|
||||
async fn is_port_available(port: u16) -> bool {
|
||||
tokio::net::TcpListener::bind(format!("127.0.0.1:{}", port))
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
```
|
||||
|
||||
### 错误处理
|
||||
|
||||
- 使用 `Result<T, E>` 返回可能失败的操作
|
||||
- 使用 `expect()` 时提供有意义的错误消息 (中文)
|
||||
- 避免 `unwrap()` 在生产代码中,除非逻辑上保证不会 panic
|
||||
- 使用 `?` 操作符传播错误
|
||||
- 记录关键错误信息到控制台
|
||||
|
||||
```rust
|
||||
// ✅ 推荐
|
||||
let sidecar = app_handle
|
||||
.shell()
|
||||
.sidecar("app")
|
||||
.expect("无法找到 app sidecar");
|
||||
|
||||
let (mut rx, child) = sidecar.spawn().expect("启动 sidecar 失败");
|
||||
|
||||
// 日志记录
|
||||
eprintln!("✗ Sidecar App 启动失败");
|
||||
println!("✓ Sidecar App 启动成功!");
|
||||
|
||||
// ❌ 避免
|
||||
let data = read_file().unwrap(); // 无上下文信息
|
||||
```
|
||||
|
||||
### 异步代码
|
||||
|
||||
- 使用 `async/await` 而非手动创建 Future
|
||||
- Tauri 内部使用 `tauri::async_runtime::spawn` 启动异步任务
|
||||
- 使用 Tokio 的异步 API (如 `tokio::net::TcpListener`)
|
||||
- 避免阻塞异步运行时 (使用 `tokio::task::spawn_blocking`)
|
||||
|
||||
```rust
|
||||
// ✅ 推荐
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let port = find_available_port(3000).await;
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
### 格式化
|
||||
|
||||
- 使用 `cargo fmt` 自动格式化
|
||||
- 缩进: 4 空格
|
||||
- 行宽: 100 字符 (rustfmt 默认)
|
||||
- 结构体和枚举的字段每行一个 (如果超过一定长度)
|
||||
- 链式调用适当换行提高可读性
|
||||
|
||||
### 注释
|
||||
|
||||
- 使用中文注释说明复杂逻辑
|
||||
- 代码块前添加简短说明注释
|
||||
- 避免显而易见的注释
|
||||
|
||||
```rust
|
||||
// ✅ 推荐
|
||||
// 全局状态:存储 Sidecar App 进程句柄
|
||||
struct SidecarProcess(Mutex<Option<CommandChild>>);
|
||||
|
||||
// 检查端口是否可用
|
||||
async fn is_port_available(port: u16) -> bool { }
|
||||
```
|
||||
|
||||
## Tauri 特定规范
|
||||
|
||||
### 模块组织
|
||||
|
||||
- **`lib.rs`**: 主入口,负责注册插件、命令、状态管理
|
||||
- **`commands/mod.rs`**: 所有 Tauri 命令集中定义,命令必须是 `pub fn`
|
||||
- **`sidecar.rs`**: Sidecar 进程管理逻辑,导出公共 API(`spawn_sidecar`, `cleanup_sidecar_process`)
|
||||
|
||||
```rust
|
||||
// lib.rs - 模块声明
|
||||
mod commands;
|
||||
mod sidecar;
|
||||
|
||||
use sidecar::SidecarProcess;
|
||||
|
||||
// 注册命令时使用模块路径
|
||||
.invoke_handler(tauri::generate_handler![commands::greet])
|
||||
```
|
||||
|
||||
### 命令定义
|
||||
|
||||
- 使用 `#[tauri::command]` 宏标记命令
|
||||
- 命令函数必须是公开的或在 `invoke_handler` 中注册
|
||||
- 参数类型必须实现 `serde::Deserialize`
|
||||
- 返回类型必须实现 `serde::Serialize`
|
||||
|
||||
```rust
|
||||
#[tauri::command]
|
||||
fn greet(name: &str) -> String {
|
||||
format!("Hello, {}!", name)
|
||||
}
|
||||
|
||||
// 在 Builder 中注册
|
||||
.invoke_handler(tauri::generate_handler![greet])
|
||||
```
|
||||
|
||||
### 状态管理
|
||||
|
||||
- 使用 `app.manage()` 注册全局状态
|
||||
- 状态必须实现 `Send + Sync`
|
||||
- 使用 `Mutex` 或 `RwLock` 保证线程安全
|
||||
|
||||
```rust
|
||||
struct SidecarProcess(Mutex<Option<CommandChild>>);
|
||||
|
||||
// 注册状态
|
||||
app.manage(SidecarProcess(Mutex::new(None)));
|
||||
|
||||
// 访问状态
|
||||
if let Some(state) = app_handle.try_state::<SidecarProcess>() {
|
||||
*state.0.lock().unwrap() = Some(child);
|
||||
}
|
||||
```
|
||||
|
||||
### Sidecar 进程管理
|
||||
|
||||
- Sidecar 二进制必须在 `tauri.conf.json` 的 `bundle.externalBin` 中声明
|
||||
- 使用 `app.shell().sidecar()` 启动 sidecar
|
||||
- 在应用退出时清理子进程 (监听 `RunEvent::ExitRequested`)
|
||||
|
||||
```rust
|
||||
// 启动 sidecar
|
||||
let sidecar = app_handle
|
||||
.shell()
|
||||
.sidecar("app")
|
||||
.expect("无法找到 app sidecar")
|
||||
.env("PORT", port.to_string());
|
||||
|
||||
// 清理进程
|
||||
match event {
|
||||
tauri::RunEvent::ExitRequested { .. } | tauri::RunEvent::Exit => {
|
||||
if let Some(child) = process.take() {
|
||||
let _ = child.kill();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
```
|
||||
|
||||
## 依赖管理
|
||||
|
||||
- 在 `Cargo.toml` 中明确声明依赖版本
|
||||
- 使用语义化版本 (如 `"2"` 表示兼容 2.x.x)
|
||||
- 仅启用需要的 feature 以减少编译时间和二进制大小
|
||||
|
||||
```toml
|
||||
tauri = { version = "2", features = [] }
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-shell = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
tokio = { version = "1", features = ["net"] }
|
||||
```
|
||||
|
||||
## 开发工具
|
||||
|
||||
推荐安装以下 VSCode 扩展:
|
||||
- `tauri-apps.tauri-vscode` - Tauri 官方支持
|
||||
- `rust-lang.rust-analyzer` - Rust 语言服务器
|
||||
|
||||
## 最佳实践
|
||||
|
||||
1. **开发环境配置**:
|
||||
- 开发模式下需先启动前端开发服务器(`bun run dev`),再启动 Tauri(`tauri dev`)
|
||||
- 生产构建自动打包 sidecar 二进制,无需额外配置
|
||||
2. **进程生命周期**: 始终在应用退出时清理子进程和资源
|
||||
3. **端口管理**:
|
||||
- 开发模式固定使用 3000 端口(与开发服务器匹配)
|
||||
- 生产模式使用端口扫描避免硬编码端口冲突
|
||||
4. **超时处理**: 异步操作设置合理的超时时间 (如 5 秒)
|
||||
5. **日志**: 使用表情符号 (✓/✗/🔧/🚀) 和中文消息提供清晰的状态反馈
|
||||
6. **错误退出**: 关键错误时调用 `std::process::exit(1)`
|
||||
7. **窗口配置**: 使用 `WebviewWindowBuilder` 动态创建窗口
|
||||
|
||||
## 提交代码前检查清单
|
||||
|
||||
- [ ] `cargo fmt` 格式化通过
|
||||
- [ ] `cargo clippy` 无警告
|
||||
- [ ] `cargo check` 编译通过
|
||||
- [ ] `cargo test` 测试通过
|
||||
- [ ] 更新相关注释和文档
|
||||
- [ ] 检查是否有 `unwrap()` 需要替换为 `expect()`
|
||||
- [ ] 验证 Tauri 应用正常启动和退出
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "app-desktop"
|
||||
version = "0.1.0"
|
||||
description = "A Tauri App"
|
||||
authors = ["imbytecat"]
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[lib]
|
||||
# The `_lib` suffix may seem redundant but it is necessary
|
||||
# to make the lib name unique and wouldn't conflict with the bin name.
|
||||
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
|
||||
name = "app_desktop_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2", features = [] }
|
||||
tauri-plugin-shell = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
tokio = { version = "1", features = ["net"] }
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Capability for the main window",
|
||||
"windows": ["main"],
|
||||
"local": true,
|
||||
"remote": {
|
||||
"urls": [
|
||||
"http://localhost:*",
|
||||
"http://127.0.0.1:*",
|
||||
"http{s}?://localhost(:\\d+)?/*"
|
||||
]
|
||||
},
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-set-title",
|
||||
{
|
||||
"identifier": "shell:allow-execute",
|
||||
"allow": [
|
||||
{
|
||||
"name": "binaries/app",
|
||||
"sidecar": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 6.8 KiB |
|
After Width: | Height: | Size: 974 B |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 7.6 KiB |
|
After Width: | Height: | Size: 903 B |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,8 @@
|
||||
// 原生桌面功能命令
|
||||
// 未来可能包含: 文件对话框、系统通知、剪贴板等
|
||||
|
||||
// 示例命令 (可根据需要删除或替换)
|
||||
#[tauri::command]
|
||||
pub fn greet(name: &str) -> String {
|
||||
format!("Hello, {}! You've been greeted from Rust!", name)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use tauri::Manager;
|
||||
|
||||
// 模块声明
|
||||
mod commands;
|
||||
mod sidecar;
|
||||
|
||||
use sidecar::SidecarProcess;
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.setup(|app| {
|
||||
// 注册全局状态
|
||||
app.manage(SidecarProcess(std::sync::Mutex::new(None)));
|
||||
|
||||
// 启动 Sidecar 进程
|
||||
let app_handle = app.handle().clone();
|
||||
sidecar::spawn_sidecar(app_handle);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![commands::greet])
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while building tauri application")
|
||||
.run(|app_handle, event| {
|
||||
// 监听应用退出事件,清理 Sidecar 进程
|
||||
if let tauri::RunEvent::Exit = event {
|
||||
// 只在 Exit 事件时清理,避免重复执行
|
||||
sidecar::cleanup_sidecar_process(app_handle);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
app_desktop_lib::run()
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use tauri::Manager;
|
||||
use tauri_plugin_shell::process::{CommandChild, CommandEvent};
|
||||
use tauri_plugin_shell::ShellExt;
|
||||
|
||||
// ===== 配置常量 =====
|
||||
|
||||
/// Sidecar App 启动超时时间(秒)
|
||||
const STARTUP_TIMEOUT_SECS: u64 = 5;
|
||||
|
||||
/// 默认起始端口
|
||||
const DEFAULT_PORT: u16 = 3000;
|
||||
|
||||
/// 端口扫描范围(从起始端口开始扫描的端口数量)
|
||||
const PORT_SCAN_RANGE: u16 = 100;
|
||||
|
||||
/// 窗口默认宽度
|
||||
const DEFAULT_WINDOW_WIDTH: f64 = 1200.0;
|
||||
|
||||
/// 窗口默认高度
|
||||
const DEFAULT_WINDOW_HEIGHT: f64 = 800.0;
|
||||
|
||||
/// 窗口标题
|
||||
const WINDOW_TITLE: &str = "Tauri App";
|
||||
|
||||
// ===== 数据结构 =====
|
||||
|
||||
/// 全局状态:存储 Sidecar 进程句柄
|
||||
pub struct SidecarProcess(pub Mutex<Option<CommandChild>>);
|
||||
|
||||
// 检查端口是否可用(未被占用)
|
||||
async fn is_port_available(port: u16) -> bool {
|
||||
tokio::net::TcpListener::bind(format!("127.0.0.1:{}", port))
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
// 查找可用端口
|
||||
async fn find_available_port(start: u16) -> u16 {
|
||||
for port in start..start + PORT_SCAN_RANGE {
|
||||
if is_port_available(port).await {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
start // 回退到起始端口
|
||||
}
|
||||
|
||||
/// 启动 Sidecar 进程并创建主窗口
|
||||
pub fn spawn_sidecar(app_handle: tauri::AppHandle) {
|
||||
// 检测是否为开发模式
|
||||
let is_dev = cfg!(debug_assertions);
|
||||
|
||||
if is_dev {
|
||||
// 开发模式:直接创建窗口连接到 Vite 开发服务器
|
||||
println!("🔧 开发模式");
|
||||
|
||||
match tauri::WebviewWindowBuilder::new(
|
||||
&app_handle,
|
||||
"main",
|
||||
tauri::WebviewUrl::External("http://localhost:3000".parse().unwrap()),
|
||||
)
|
||||
.title(WINDOW_TITLE)
|
||||
.inner_size(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT)
|
||||
.center()
|
||||
.build()
|
||||
{
|
||||
Ok(_) => println!("✓ 开发窗口创建成功"),
|
||||
Err(e) => {
|
||||
eprintln!("✗ 窗口创建失败: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// 生产模式:启动 sidecar 二进制
|
||||
tauri::async_runtime::spawn(async move {
|
||||
println!("🚀 生产模式");
|
||||
|
||||
// 查找可用端口
|
||||
let port = find_available_port(DEFAULT_PORT).await;
|
||||
println!("使用端口: {}", port);
|
||||
|
||||
// 启动 sidecar
|
||||
let sidecar = app_handle
|
||||
.shell()
|
||||
.sidecar("app")
|
||||
.expect("无法找到 app")
|
||||
.env("PORT", port.to_string());
|
||||
|
||||
let (mut rx, child) = sidecar.spawn().expect("启动 sidecar 失败");
|
||||
|
||||
// 保存进程句柄到全局状态
|
||||
if let Some(state) = app_handle.try_state::<SidecarProcess>() {
|
||||
*state.0.lock().unwrap() = Some(child);
|
||||
}
|
||||
|
||||
// 监听 stdout,等待服务器就绪信号
|
||||
let start_time = std::time::Instant::now();
|
||||
let timeout = Duration::from_secs(STARTUP_TIMEOUT_SECS);
|
||||
let mut app_ready = false;
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
if let CommandEvent::Stdout(line) = event {
|
||||
let output = String::from_utf8_lossy(&line);
|
||||
println!("App: {}", output);
|
||||
|
||||
// 检测 App 启动成功的标志
|
||||
if output.contains("Listening on:") || output.contains("localhost") {
|
||||
app_ready = true;
|
||||
println!("✓ App 启动成功!");
|
||||
|
||||
// 创建主窗口
|
||||
let url = format!("http://localhost:{}", port);
|
||||
tauri::WebviewWindowBuilder::new(
|
||||
&app_handle,
|
||||
"main",
|
||||
tauri::WebviewUrl::External(url.parse().unwrap()),
|
||||
)
|
||||
.title(WINDOW_TITLE)
|
||||
.inner_size(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT)
|
||||
.center()
|
||||
.build()
|
||||
.expect("创建窗口失败");
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 超时检查
|
||||
if start_time.elapsed() > timeout {
|
||||
eprintln!("✗ 启动超时: App 未能在 {} 秒内启动", STARTUP_TIMEOUT_SECS);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if !app_ready {
|
||||
eprintln!("✗ App 启动失败");
|
||||
std::process::exit(1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 清理 Sidecar 进程 (在应用退出时调用)
|
||||
pub fn cleanup_sidecar_process(app_handle: &tauri::AppHandle) {
|
||||
let is_dev = cfg!(debug_assertions);
|
||||
|
||||
if is_dev {
|
||||
// 开发模式:退出时发送异常信号(exit 1),让 Turbo 停止 Vite 服务器
|
||||
println!("🔧 开发模式退出,终止所有依赖任务...");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
// 生产模式:正常清理 sidecar 进程
|
||||
println!("应用退出,正在清理 Sidecar 进程...");
|
||||
if let Some(state) = app_handle.try_state::<SidecarProcess>() {
|
||||
if let Ok(mut process) = state.0.lock() {
|
||||
if let Some(child) = process.take() {
|
||||
let _ = child.kill();
|
||||
println!("✓ Sidecar 进程已终止");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "app-desktop",
|
||||
"version": "0.1.0",
|
||||
"identifier": "com.imbytecat.app-desktop",
|
||||
"app": {
|
||||
"withGlobalTauri": true,
|
||||
"windows": [],
|
||||
"security": {
|
||||
"csp": null
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"externalBin": ["binaries/app"]
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { defineCommand, runMain } from 'citty'
|
||||
import { name, version } from '#package'
|
||||
|
||||
// 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)',
|
||||
},
|
||||
default: 'serve',
|
||||
subCommands: {
|
||||
serve: () => import('@/cli/serve').then((m) => m.default),
|
||||
migrate: () => import('@/cli/migrate').then((m) => m.default),
|
||||
},
|
||||
})
|
||||
|
||||
runMain(main)
|
||||
@@ -1 +0,0 @@
|
||||
export default function startNitroServer(): Promise<void>
|
||||
@@ -1,3 +0,0 @@
|
||||
export default async function startNitroServer() {
|
||||
await import('#server')
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
import { defineCommand } from 'citty'
|
||||
|
||||
export default defineCommand({
|
||||
meta: {
|
||||
name: 'migrate',
|
||||
description: 'Apply pending database migrations',
|
||||
},
|
||||
async run() {
|
||||
const [{ env }, { drizzle }, { sql }, { embeddedMigrations }, { getLogger }] = await Promise.all([
|
||||
import('@/env'),
|
||||
import('drizzle-orm/postgres-js'),
|
||||
import('drizzle-orm'),
|
||||
import('@/server/db/migrations.gen'),
|
||||
import('@/server/logger'),
|
||||
])
|
||||
|
||||
const logger = getLogger(['cli', 'migrate'])
|
||||
|
||||
if (embeddedMigrations.length === 0) {
|
||||
logger.info('No migrations bundled into this binary.')
|
||||
return
|
||||
}
|
||||
|
||||
const sha256 = (s: string) => Bun.CryptoHasher.hash('sha256', s, 'hex')
|
||||
|
||||
const db = drizzle({
|
||||
connection: {
|
||||
url: env.DATABASE_URL,
|
||||
max: 1,
|
||||
onnotice: (n) => logger.debug('pg notice', { notice: n.message }),
|
||||
},
|
||||
})
|
||||
try {
|
||||
await db.execute(sql`CREATE SCHEMA IF NOT EXISTS "drizzle"`)
|
||||
await db.execute(sql`
|
||||
CREATE TABLE IF NOT EXISTS "drizzle"."__drizzle_migrations" (
|
||||
id SERIAL PRIMARY KEY,
|
||||
hash text NOT NULL,
|
||||
created_at bigint
|
||||
)
|
||||
`)
|
||||
|
||||
const applied = await db.execute<{ hash: string; created_at: string | null }>(
|
||||
sql`SELECT hash, created_at FROM "drizzle"."__drizzle_migrations" ORDER BY created_at ASC`,
|
||||
)
|
||||
|
||||
// Reject schema drift: any applied migration whose embedded SQL has changed (or is missing) is fatal.
|
||||
for (const row of applied) {
|
||||
const when = Number(row.created_at)
|
||||
const m = embeddedMigrations.find((e) => e.when === when)
|
||||
if (!m) {
|
||||
throw new Error(`Applied migration when=${when} is not in this binary; do not roll back applied migrations.`)
|
||||
}
|
||||
if (sha256(m.sql) !== row.hash) {
|
||||
throw new Error(`Migration hash mismatch at when=${when}; do not edit migrations after they are applied.`)
|
||||
}
|
||||
}
|
||||
|
||||
const appliedWhens = new Set(applied.map((r) => Number(r.created_at)))
|
||||
const pending = embeddedMigrations.filter((m) => !appliedWhens.has(m.when))
|
||||
if (pending.length === 0) {
|
||||
logger.info('Database is up to date.')
|
||||
return
|
||||
}
|
||||
|
||||
logger.info('Applying {count} migration(s)...', { count: pending.length })
|
||||
await db.transaction(async (tx) => {
|
||||
for (const m of pending) {
|
||||
for (const rawStmt of m.sql.split('--> statement-breakpoint')) {
|
||||
const stmt = rawStmt.trim()
|
||||
if (!stmt) continue
|
||||
await tx.execute(sql.raw(stmt))
|
||||
}
|
||||
await tx.execute(
|
||||
sql`INSERT INTO "drizzle"."__drizzle_migrations" ("hash", "created_at") VALUES (${sha256(m.sql)}, ${m.when})`,
|
||||
)
|
||||
}
|
||||
})
|
||||
logger.info('Migrations applied.')
|
||||
} finally {
|
||||
await db.$client.end()
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -1,12 +0,0 @@
|
||||
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,27 +0,0 @@
|
||||
import { createORPCClient } from '@orpc/client'
|
||||
import { RPCLink } from '@orpc/client/fetch'
|
||||
import { createRouterClient } from '@orpc/server'
|
||||
import { createTanstackQueryUtils } from '@orpc/tanstack-query'
|
||||
import { createIsomorphicFn } from '@tanstack/react-start'
|
||||
import { getRequestHeaders } from '@tanstack/react-start/server'
|
||||
import { router } from '@/server/api/routers'
|
||||
import type { RouterClient } from '@/server/api/types'
|
||||
|
||||
const getORPCClient = createIsomorphicFn()
|
||||
.server(() =>
|
||||
createRouterClient(router, {
|
||||
context: () => ({
|
||||
headers: getRequestHeaders(),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
.client(() => {
|
||||
const link = new RPCLink({
|
||||
url: `${window.location.origin}/api/rpc`,
|
||||
})
|
||||
return createORPCClient<RouterClient>(link)
|
||||
})
|
||||
|
||||
const client: RouterClient = getORPCClient()
|
||||
|
||||
export const orpc = createTanstackQueryUtils(client)
|
||||
@@ -1,7 +0,0 @@
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { orpc } from '@/client/orpc'
|
||||
|
||||
export const useInvalidateTodos = () => {
|
||||
const queryClient = useQueryClient()
|
||||
return () => queryClient.invalidateQueries({ queryKey: orpc.todo.list.key() })
|
||||
}
|
||||
@@ -1,40 +1,3 @@
|
||||
export const ErrorComponent = ({ error, reset }: { error: Error; reset: () => void }) => {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-50 px-4">
|
||||
<div className="max-w-md w-full text-center space-y-6">
|
||||
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-red-100">
|
||||
<svg
|
||||
className="w-8 h-8 text-red-500"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-900">出错了</h1>
|
||||
<p className="text-slate-500 mt-2">{import.meta.env.DEV ? error.message : '请求失败,请稍后重试'}</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-center gap-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={reset}
|
||||
className="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-medium transition-colors"
|
||||
>
|
||||
重试
|
||||
</button>
|
||||
<a href="/" className="px-6 py-2.5 text-slate-600 hover:text-slate-900 font-medium transition-colors">
|
||||
返回首页
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
export function ErrorComponent() {
|
||||
return <div>An unhandled error happened!</div>
|
||||
}
|
||||
|
||||
@@ -1,23 +1,3 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
|
||||
export const NotFoundComponent = () => {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-50 px-4">
|
||||
<div className="max-w-md w-full text-center space-y-6">
|
||||
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-slate-100">
|
||||
<span className="text-3xl font-bold text-slate-400">404</span>
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-900">页面不存在</h1>
|
||||
<p className="text-slate-500 mt-2">您访问的页面可能已被移除或地址有误</p>
|
||||
</div>
|
||||
<Link
|
||||
to="/"
|
||||
className="inline-block px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-medium transition-colors"
|
||||
>
|
||||
返回首页
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
export function NotFoundComponent() {
|
||||
return <div>404 - Not Found</div>
|
||||
}
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
import type { SubmitEventHandler } from 'react'
|
||||
import { useState } from 'react'
|
||||
|
||||
interface TodoFormProps {
|
||||
onSubmit: (title: string) => void
|
||||
isPending: boolean
|
||||
}
|
||||
|
||||
export const TodoForm = ({ onSubmit, isPending }: TodoFormProps) => {
|
||||
const [title, setTitle] = useState('')
|
||||
|
||||
const handleSubmit: SubmitEventHandler<HTMLFormElement> = (e) => {
|
||||
e.preventDefault()
|
||||
if (title.trim()) {
|
||||
onSubmit(title.trim())
|
||||
setTitle('')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="relative group z-10">
|
||||
<div className="relative transform transition-all duration-200 focus-within:-translate-y-1">
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="添加新任务..."
|
||||
className="w-full pl-6 pr-32 py-5 bg-white rounded-2xl shadow-[0_8px_30px_rgb(0,0,0,0.04)] border-0 ring-1 ring-slate-100 focus:ring-2 focus:ring-indigo-500/50 outline-none transition-all placeholder:text-slate-400 text-lg text-slate-700"
|
||||
disabled={isPending}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isPending || !title.trim()}
|
||||
className="absolute right-3 top-3 bottom-3 px-6 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-medium transition-all shadow-md shadow-indigo-200 disabled:opacity-50 disabled:shadow-none hover:shadow-lg hover:shadow-indigo-300 active:scale-95"
|
||||
>
|
||||
{isPending ? '添加中' : '添加'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import type { RouterOutputs } from '@/server/api/types'
|
||||
|
||||
type Todo = RouterOutputs['todo']['list'][number]
|
||||
|
||||
interface TodoItemProps {
|
||||
todo: Todo
|
||||
onToggle: (id: string, completed: boolean) => void
|
||||
onDelete: (id: string) => void
|
||||
}
|
||||
|
||||
export const TodoItem = ({ todo, onToggle, onDelete }: TodoItemProps) => {
|
||||
return (
|
||||
<div
|
||||
className={`group relative flex items-center p-4 bg-white rounded-xl border border-slate-100 shadow-sm transition-all duration-200 hover:shadow-md hover:border-slate-200 ${
|
||||
todo.completed ? 'bg-slate-50/50' : ''
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onToggle(todo.id, todo.completed)}
|
||||
className={`shrink-0 w-6 h-6 rounded-full border-2 transition-all duration-200 flex items-center justify-center mr-4 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${
|
||||
todo.completed ? 'bg-indigo-500 border-indigo-500' : 'border-slate-300 hover:border-indigo-500 bg-white'
|
||||
}`}
|
||||
>
|
||||
{todo.completed && (
|
||||
<svg
|
||||
className="w-3.5 h-3.5 text-white"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={3}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<p
|
||||
className={`text-lg transition-all duration-200 truncate ${
|
||||
todo.completed ? 'text-slate-400 line-through decoration-slate-300 decoration-2' : 'text-slate-700'
|
||||
}`}
|
||||
>
|
||||
{todo.title}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center opacity-0 group-hover:opacity-100 transition-opacity duration-200 absolute right-4 pl-4 bg-linear-to-l from-white via-white to-transparent sm:static sm:bg-none">
|
||||
<span className="text-xs text-slate-400 mr-3 hidden sm:inline-block">
|
||||
{new Date(todo.createdAt).toLocaleDateString('zh-CN')}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onDelete(todo.id)}
|
||||
className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors focus:outline-none"
|
||||
title="删除"
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { drizzle } from 'drizzle-orm/postgres-js'
|
||||
import * as schema from '@/db/schema'
|
||||
import { env } from '@/env'
|
||||
|
||||
export function createDb() {
|
||||
return drizzle({
|
||||
connection: {
|
||||
url: env.DATABASE_URL,
|
||||
prepare: true,
|
||||
},
|
||||
schema,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { sql } from 'drizzle-orm'
|
||||
import { boolean, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core'
|
||||
|
||||
export const todoTable = pgTable('todo', {
|
||||
id: uuid('id').primaryKey().default(sql`uuidv7()`),
|
||||
title: text('title').notNull(),
|
||||
completed: boolean('completed').notNull().default(false),
|
||||
createdAt: timestamp('created_at', { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdateFn(() => new Date()),
|
||||
})
|
||||
@@ -3,13 +3,12 @@ import { z } from 'zod'
|
||||
|
||||
export const env = createEnv({
|
||||
server: {
|
||||
DATABASE_URL: z.url({ protocol: /^postgres(ql)?$/ }),
|
||||
LOG_DB: z.stringbool().default(false),
|
||||
LOG_FORMAT: z.enum(['pretty', 'json']).optional(),
|
||||
LOG_LEVEL: z.enum(['trace', 'debug', 'info', 'warning', 'error', 'fatal']).default('info'),
|
||||
DATABASE_URL: z.url(),
|
||||
},
|
||||
clientPrefix: 'VITE_',
|
||||
client: {},
|
||||
client: {
|
||||
VITE_APP_TITLE: z.string().min(1).optional(),
|
||||
},
|
||||
runtimeEnv: process.env,
|
||||
emptyStringAsUndefined: true,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { TanStackDevtoolsReactPlugin } from '@tanstack/react-devtools'
|
||||
import { ReactQueryDevtoolsPanel } from '@tanstack/react-query-devtools'
|
||||
|
||||
export const devtools = {
|
||||
name: 'TanStack Query',
|
||||
render: <ReactQueryDevtoolsPanel />,
|
||||
} satisfies TanStackDevtoolsReactPlugin
|
||||
@@ -0,0 +1 @@
|
||||
export * from './devtools'
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { TanStackDevtoolsReactPlugin } from '@tanstack/react-devtools'
|
||||
import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
|
||||
|
||||
export const devtools = {
|
||||
name: 'TanStack Router',
|
||||
render: <TanStackRouterDevtoolsPanel />,
|
||||
} satisfies TanStackDevtoolsReactPlugin
|
||||
@@ -0,0 +1 @@
|
||||
export * from './devtools'
|
||||
@@ -0,0 +1,53 @@
|
||||
import { createORPCClient } from '@orpc/client'
|
||||
import { RPCLink } from '@orpc/client/fetch'
|
||||
import { createRouterClient } from '@orpc/server'
|
||||
import { createTanstackQueryUtils } from '@orpc/tanstack-query'
|
||||
import { createIsomorphicFn } from '@tanstack/react-start'
|
||||
import { getRequestHeaders } from '@tanstack/react-start/server'
|
||||
import { router } from './router'
|
||||
import type { RouterClient } from './types'
|
||||
|
||||
const getORPCClient = createIsomorphicFn()
|
||||
.server(() =>
|
||||
createRouterClient(router, {
|
||||
context: () => ({
|
||||
headers: getRequestHeaders(),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
.client(() => {
|
||||
const link = new RPCLink({
|
||||
url: `${window.location.origin}/api/rpc`,
|
||||
})
|
||||
return createORPCClient<RouterClient>(link)
|
||||
})
|
||||
|
||||
const client: RouterClient = getORPCClient()
|
||||
|
||||
export const orpc = createTanstackQueryUtils(client, {
|
||||
experimental_defaults: {
|
||||
todo: {
|
||||
create: {
|
||||
mutationOptions: {
|
||||
onSuccess: (_, __, ___, ctx) => {
|
||||
ctx.client.invalidateQueries({ queryKey: orpc.todo.list.key() })
|
||||
},
|
||||
},
|
||||
},
|
||||
update: {
|
||||
mutationOptions: {
|
||||
onSuccess: (_, __, ___, ctx) => {
|
||||
ctx.client.invalidateQueries({ queryKey: orpc.todo.list.key() })
|
||||
},
|
||||
},
|
||||
},
|
||||
remove: {
|
||||
mutationOptions: {
|
||||
onSuccess: (_, __, ___, ctx) => {
|
||||
ctx.client.invalidateQueries({ queryKey: orpc.todo.list.key() })
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,5 @@
|
||||
import * as todo from './contracts/todo'
|
||||
|
||||
export const contract = {
|
||||
todo,
|
||||
}
|
||||
@@ -1,16 +1,25 @@
|
||||
import { oc } from '@orpc/contract'
|
||||
import { createInsertSchema, createSelectSchema, createUpdateSchema } from 'drizzle-zod'
|
||||
import {
|
||||
createInsertSchema,
|
||||
createSelectSchema,
|
||||
createUpdateSchema,
|
||||
} from 'drizzle-zod'
|
||||
import { z } from 'zod'
|
||||
import { generatedFieldKeys } from '@/server/db/fields'
|
||||
import { todoTable } from '@/server/db/schema'
|
||||
import { todoTable } from '@/db/schema'
|
||||
|
||||
const selectSchema = createSelectSchema(todoTable)
|
||||
|
||||
const insertSchema = createInsertSchema(todoTable).omit(generatedFieldKeys)
|
||||
const insertSchema = createInsertSchema(todoTable).omit({
|
||||
id: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
})
|
||||
|
||||
const updateSchema = createUpdateSchema(todoTable)
|
||||
.omit(generatedFieldKeys)
|
||||
.refine((data) => Object.keys(data).length > 0, { message: 'At least one field is required' })
|
||||
const updateSchema = createUpdateSchema(todoTable).omit({
|
||||
id: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
})
|
||||
|
||||
export const list = oc.input(z.void()).output(z.array(selectSchema))
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { ORPCError } from '@orpc/server'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { todoTable } from '@/db/schema'
|
||||
import { baseProcedure } from '@/orpc/procedures'
|
||||
|
||||
export const list = baseProcedure.todo.list.handler(async ({ context }) => {
|
||||
const todos = await context.db.query.todoTable.findMany({
|
||||
orderBy: (todos, { desc }) => [desc(todos.createdAt)],
|
||||
})
|
||||
return todos
|
||||
})
|
||||
|
||||
export const create = baseProcedure.todo.create.handler(
|
||||
async ({ context, input }) => {
|
||||
const [newTodo] = await context.db
|
||||
.insert(todoTable)
|
||||
.values(input)
|
||||
.returning()
|
||||
|
||||
if (!newTodo) {
|
||||
throw new ORPCError('NOT_FOUND')
|
||||
}
|
||||
|
||||
return newTodo
|
||||
},
|
||||
)
|
||||
|
||||
export const update = baseProcedure.todo.update.handler(
|
||||
async ({ context, input }) => {
|
||||
const [updatedTodo] = await context.db
|
||||
.update(todoTable)
|
||||
.set(input.data)
|
||||
.where(eq(todoTable.id, input.id))
|
||||
.returning()
|
||||
|
||||
if (!updatedTodo) {
|
||||
throw new ORPCError('NOT_FOUND')
|
||||
}
|
||||
|
||||
return updatedTodo
|
||||
},
|
||||
)
|
||||
|
||||
export const remove = baseProcedure.todo.remove.handler(
|
||||
async ({ context, input }) => {
|
||||
await context.db.delete(todoTable).where(eq(todoTable.id, input.id))
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
export { orpc } from './client'
|
||||
export * from './types'
|
||||
@@ -0,0 +1,17 @@
|
||||
import { createDb } from '@/db'
|
||||
import { os } from '@/orpc/server'
|
||||
|
||||
export type Database = ReturnType<typeof createDb>
|
||||
|
||||
const globalForDb = globalThis as { __db?: Database }
|
||||
|
||||
function getDb(): Database {
|
||||
globalForDb.__db ??= createDb()
|
||||
return globalForDb.__db
|
||||
}
|
||||
|
||||
export const dbProvider = os.middleware(async ({ context, next }) => {
|
||||
return next({
|
||||
context: { ...context, db: getDb() },
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1 @@
|
||||
export * from './db'
|
||||
@@ -0,0 +1,4 @@
|
||||
import { dbProvider } from './middlewares/db'
|
||||
import { os } from './server'
|
||||
|
||||
export const baseProcedure = os.use(dbProvider)
|
||||
@@ -0,0 +1,6 @@
|
||||
import * as todo from './handlers/todo'
|
||||
import { os } from './server'
|
||||
|
||||
export const router = os.router({
|
||||
todo,
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
import { implement } from '@orpc/server'
|
||||
import { contract } from './contract'
|
||||
|
||||
export type ORPCContext = {
|
||||
headers?: Headers
|
||||
}
|
||||
|
||||
export const os = implement(contract).$context<ORPCContext>()
|
||||
@@ -0,0 +1,11 @@
|
||||
import type {
|
||||
ContractRouterClient,
|
||||
InferContractRouterInputs,
|
||||
InferContractRouterOutputs,
|
||||
} from '@orpc/contract'
|
||||
import type { contract } from './contract'
|
||||
|
||||
export type Contract = typeof contract
|
||||
export type RouterClient = ContractRouterClient<Contract>
|
||||
export type RouterInputs = InferContractRouterInputs<Contract>
|
||||
export type RouterOutputs = InferContractRouterOutputs<Contract>
|
||||
@@ -9,26 +9,14 @@
|
||||
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as HealthRouteImport } from './routes/health'
|
||||
import { Route as IndexRouteImport } from './routes/index'
|
||||
import { Route as ApiSplatRouteImport } from './routes/api/$'
|
||||
import { Route as ApiRpcSplatRouteImport } from './routes/api/rpc.$'
|
||||
|
||||
const HealthRoute = HealthRouteImport.update({
|
||||
id: '/health',
|
||||
path: '/health',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const IndexRoute = IndexRouteImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const ApiSplatRoute = ApiSplatRouteImport.update({
|
||||
id: '/api/$',
|
||||
path: '/api/$',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const ApiRpcSplatRoute = ApiRpcSplatRouteImport.update({
|
||||
id: '/api/rpc/$',
|
||||
path: '/api/rpc/$',
|
||||
@@ -37,47 +25,32 @@ const ApiRpcSplatRoute = ApiRpcSplatRouteImport.update({
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof IndexRoute
|
||||
'/health': typeof HealthRoute
|
||||
'/api/$': typeof ApiSplatRoute
|
||||
'/api/rpc/$': typeof ApiRpcSplatRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof IndexRoute
|
||||
'/health': typeof HealthRoute
|
||||
'/api/$': typeof ApiSplatRoute
|
||||
'/api/rpc/$': typeof ApiRpcSplatRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/': typeof IndexRoute
|
||||
'/health': typeof HealthRoute
|
||||
'/api/$': typeof ApiSplatRoute
|
||||
'/api/rpc/$': typeof ApiRpcSplatRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths: '/' | '/health' | '/api/$' | '/api/rpc/$'
|
||||
fullPaths: '/' | '/api/rpc/$'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to: '/' | '/health' | '/api/$' | '/api/rpc/$'
|
||||
id: '__root__' | '/' | '/health' | '/api/$' | '/api/rpc/$'
|
||||
to: '/' | '/api/rpc/$'
|
||||
id: '__root__' | '/' | '/api/rpc/$'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
IndexRoute: typeof IndexRoute
|
||||
HealthRoute: typeof HealthRoute
|
||||
ApiSplatRoute: typeof ApiSplatRoute
|
||||
ApiRpcSplatRoute: typeof ApiRpcSplatRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface FileRoutesByPath {
|
||||
'/health': {
|
||||
id: '/health'
|
||||
path: '/health'
|
||||
fullPath: '/health'
|
||||
preLoaderRoute: typeof HealthRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/': {
|
||||
id: '/'
|
||||
path: '/'
|
||||
@@ -85,13 +58,6 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof IndexRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/api/$': {
|
||||
id: '/api/$'
|
||||
path: '/api/$'
|
||||
fullPath: '/api/$'
|
||||
preLoaderRoute: typeof ApiSplatRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/api/rpc/$': {
|
||||
id: '/api/rpc/$'
|
||||
path: '/api/rpc/$'
|
||||
@@ -104,8 +70,6 @@ declare module '@tanstack/react-router' {
|
||||
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
IndexRoute: IndexRoute,
|
||||
HealthRoute: HealthRoute,
|
||||
ApiSplatRoute: ApiSplatRoute,
|
||||
ApiRpcSplatRoute: ApiRpcSplatRoute,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
|
||||
@@ -5,14 +5,7 @@ import type { RouterContext } from './routes/__root'
|
||||
import { routeTree } from './routeTree.gen'
|
||||
|
||||
export const getRouter = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 30 * 1000,
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
const queryClient = new QueryClient()
|
||||
|
||||
const router = createRouter({
|
||||
routeTree,
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import { TanStackDevtools } from '@tanstack/react-devtools'
|
||||
import type { QueryClient } from '@tanstack/react-query'
|
||||
import { ReactQueryDevtoolsPanel } from '@tanstack/react-query-devtools'
|
||||
import { createRootRouteWithContext, HeadContent, Scripts } from '@tanstack/react-router'
|
||||
import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
|
||||
import {
|
||||
createRootRouteWithContext,
|
||||
HeadContent,
|
||||
Scripts,
|
||||
} from '@tanstack/react-router'
|
||||
import type { ReactNode } from 'react'
|
||||
import { name } from '#package'
|
||||
import { ErrorComponent } from '@/components/Error'
|
||||
import { NotFoundComponent } from '@/components/NotFound'
|
||||
import { devtools as queryDevtools } from '@/integrations/tanstack-query'
|
||||
import { devtools as routerDevtools } from '@/integrations/tanstack-router'
|
||||
import appCss from '@/styles.css?url'
|
||||
|
||||
export interface RouterContext {
|
||||
@@ -24,7 +27,7 @@ export const Route = createRootRouteWithContext<RouterContext>()({
|
||||
content: 'width=device-width, initial-scale=1',
|
||||
},
|
||||
{
|
||||
title: name,
|
||||
title: 'Fullstack Starter',
|
||||
},
|
||||
],
|
||||
links: [
|
||||
@@ -35,8 +38,8 @@ export const Route = createRootRouteWithContext<RouterContext>()({
|
||||
],
|
||||
}),
|
||||
shellComponent: RootDocument,
|
||||
errorComponent: ErrorComponent,
|
||||
notFoundComponent: NotFoundComponent,
|
||||
errorComponent: () => <ErrorComponent />,
|
||||
notFoundComponent: () => <NotFoundComponent />,
|
||||
})
|
||||
|
||||
function RootDocument({ children }: Readonly<{ children: ReactNode }>) {
|
||||
@@ -47,23 +50,12 @@ function RootDocument({ children }: Readonly<{ children: ReactNode }>) {
|
||||
</head>
|
||||
<body>
|
||||
{children}
|
||||
{import.meta.env.DEV && (
|
||||
<TanStackDevtools
|
||||
config={{
|
||||
position: 'bottom-right',
|
||||
}}
|
||||
plugins={[
|
||||
{
|
||||
name: 'TanStack Router',
|
||||
render: <TanStackRouterDevtoolsPanel />,
|
||||
},
|
||||
{
|
||||
name: 'TanStack Query',
|
||||
render: <ReactQueryDevtoolsPanel />,
|
||||
},
|
||||
]}
|
||||
plugins={[routerDevtools, queryDevtools]}
|
||||
/>
|
||||
)}
|
||||
<Scripts />
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import { OpenAPIHandler } from '@orpc/openapi/fetch'
|
||||
import { OpenAPIReferencePlugin } from '@orpc/openapi/plugins'
|
||||
import { onError } from '@orpc/server'
|
||||
import { ZodToJsonSchemaConverter } from '@orpc/zod/zod4'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { name, version } from '#package'
|
||||
import { handleValidationError, logError } from '@/server/api/interceptors'
|
||||
import { router } from '@/server/api/routers'
|
||||
|
||||
const handler = new OpenAPIHandler(router, {
|
||||
plugins: [
|
||||
new OpenAPIReferencePlugin({
|
||||
docsProvider: 'scalar',
|
||||
schemaConverters: [new ZodToJsonSchemaConverter()],
|
||||
specGenerateOptions: {
|
||||
info: {
|
||||
title: name,
|
||||
version,
|
||||
},
|
||||
},
|
||||
docsPath: '/docs',
|
||||
specPath: '/spec.json',
|
||||
}),
|
||||
],
|
||||
interceptors: [onError(logError)],
|
||||
clientInterceptors: [onError(handleValidationError)],
|
||||
})
|
||||
|
||||
export const Route = createFileRoute('/api/$')({
|
||||
server: {
|
||||
handlers: {
|
||||
ANY: async ({ request }) => {
|
||||
const { response } = await handler.handle(request, {
|
||||
prefix: '/api',
|
||||
context: {
|
||||
headers: request.headers,
|
||||
},
|
||||
})
|
||||
|
||||
return response ?? new Response('Not Found', { status: 404 })
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -1,12 +1,46 @@
|
||||
import { onError } from '@orpc/server'
|
||||
import { ORPCError, onError, ValidationError } from '@orpc/server'
|
||||
import { RPCHandler } from '@orpc/server/fetch'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { handleValidationError, logError } from '@/server/api/interceptors'
|
||||
import { router } from '@/server/api/routers'
|
||||
import { z } from 'zod'
|
||||
import { router } from '@/orpc/router'
|
||||
|
||||
const handler = new RPCHandler(router, {
|
||||
interceptors: [onError(logError)],
|
||||
clientInterceptors: [onError(handleValidationError)],
|
||||
interceptors: [
|
||||
onError((error) => {
|
||||
console.error(error)
|
||||
}),
|
||||
],
|
||||
clientInterceptors: [
|
||||
onError((error) => {
|
||||
if (
|
||||
error instanceof ORPCError &&
|
||||
error.code === 'BAD_REQUEST' &&
|
||||
error.cause instanceof ValidationError
|
||||
) {
|
||||
// If you only use Zod you can safely cast to ZodIssue[]
|
||||
const zodError = new z.ZodError(
|
||||
error.cause.issues as z.core.$ZodIssue[],
|
||||
)
|
||||
|
||||
throw new ORPCError('INPUT_VALIDATION_FAILED', {
|
||||
status: 422,
|
||||
message: z.prettifyError(zodError),
|
||||
data: z.flattenError(zodError),
|
||||
cause: error.cause,
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
error instanceof ORPCError &&
|
||||
error.code === 'INTERNAL_SERVER_ERROR' &&
|
||||
error.cause instanceof ValidationError
|
||||
) {
|
||||
throw new ORPCError('OUTPUT_VALIDATION_FAILED', {
|
||||
cause: error.cause,
|
||||
})
|
||||
}
|
||||
}),
|
||||
],
|
||||
})
|
||||
|
||||
export const Route = createFileRoute('/api/rpc/$')({
|
||||
@@ -15,9 +49,7 @@ export const Route = createFileRoute('/api/rpc/$')({
|
||||
ANY: async ({ request }) => {
|
||||
const { response } = await handler.handle(request, {
|
||||
prefix: '/api/rpc',
|
||||
context: {
|
||||
headers: request.headers,
|
||||
},
|
||||
context: {},
|
||||
})
|
||||
|
||||
return response ?? new Response('Not Found', { status: 404 })
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
export const Route = createFileRoute('/health')({
|
||||
server: {
|
||||
handlers: {
|
||||
GET: () => new Response('ok', { status: 200, headers: { 'content-type': 'text/plain' } }),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useMutation, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { orpc } from '@/client/orpc'
|
||||
import { useInvalidateTodos } from '@/client/queries/todo'
|
||||
import { TodoForm } from '@/components/TodoForm'
|
||||
import { TodoItem } from '@/components/TodoItem'
|
||||
import { isTauri } from '@tauri-apps/api/core'
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window'
|
||||
import type { ChangeEventHandler, FormEventHandler } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { orpc } from '@/orpc'
|
||||
|
||||
export const Route = createFileRoute('/')({
|
||||
component: Todos,
|
||||
@@ -13,12 +14,40 @@ export const Route = createFileRoute('/')({
|
||||
})
|
||||
|
||||
function Todos() {
|
||||
const listQuery = useSuspenseQuery(orpc.todo.list.queryOptions())
|
||||
const invalidateTodos = useInvalidateTodos()
|
||||
const [newTodoTitle, setNewTodoTitle] = useState('')
|
||||
|
||||
const createMutation = useMutation(orpc.todo.create.mutationOptions({ onSuccess: invalidateTodos }))
|
||||
const updateMutation = useMutation(orpc.todo.update.mutationOptions({ onSuccess: invalidateTodos }))
|
||||
const deleteMutation = useMutation(orpc.todo.remove.mutationOptions({ onSuccess: invalidateTodos }))
|
||||
const listQuery = useSuspenseQuery(orpc.todo.list.queryOptions())
|
||||
const createMutation = useMutation(orpc.todo.create.mutationOptions())
|
||||
const updateMutation = useMutation(orpc.todo.update.mutationOptions())
|
||||
const deleteMutation = useMutation(orpc.todo.remove.mutationOptions())
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTauri()) return
|
||||
getCurrentWindow().setTitle('待办事项')
|
||||
}, [])
|
||||
|
||||
const handleCreateTodo: FormEventHandler<HTMLFormElement> = (e) => {
|
||||
e.preventDefault()
|
||||
if (newTodoTitle.trim()) {
|
||||
createMutation.mutate({ title: newTodoTitle.trim() })
|
||||
setNewTodoTitle('')
|
||||
}
|
||||
}
|
||||
|
||||
const handleInputChange: ChangeEventHandler<HTMLInputElement> = (e) => {
|
||||
setNewTodoTitle(e.target.value)
|
||||
}
|
||||
|
||||
const handleToggleTodo = (id: string, currentCompleted: boolean) => {
|
||||
updateMutation.mutate({
|
||||
id,
|
||||
data: { completed: !currentCompleted },
|
||||
})
|
||||
}
|
||||
|
||||
const handleDeleteTodo = (id: string) => {
|
||||
deleteMutation.mutate({ id })
|
||||
}
|
||||
|
||||
const todos = listQuery.data
|
||||
const completedCount = todos.filter((todo) => todo.completed).length
|
||||
@@ -28,9 +57,12 @@ function Todos() {
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 py-12 px-4 sm:px-6 font-sans">
|
||||
<div className="max-w-2xl mx-auto space-y-8">
|
||||
{/* Header */}
|
||||
<div className="flex items-end justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-slate-900 tracking-tight">我的待办</h1>
|
||||
<h1 className="text-3xl font-bold text-slate-900 tracking-tight">
|
||||
我的待办
|
||||
</h1>
|
||||
<p className="text-slate-500 mt-1">保持专注,逐个击破</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
@@ -38,12 +70,34 @@ function Todos() {
|
||||
{completedCount}
|
||||
<span className="text-slate-400 text-lg">/{totalCount}</span>
|
||||
</div>
|
||||
<div className="text-xs font-medium text-slate-400 uppercase tracking-wider">已完成</div>
|
||||
<div className="text-xs font-medium text-slate-400 uppercase tracking-wider">
|
||||
已完成
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TodoForm onSubmit={(title) => createMutation.mutate({ title })} isPending={createMutation.isPending} />
|
||||
{/* Add Todo Form */}
|
||||
<form onSubmit={handleCreateTodo} className="relative group z-10">
|
||||
<div className="relative transform transition-all duration-200 focus-within:-translate-y-1">
|
||||
<input
|
||||
type="text"
|
||||
value={newTodoTitle}
|
||||
onChange={handleInputChange}
|
||||
placeholder="添加新任务..."
|
||||
className="w-full pl-6 pr-32 py-5 bg-white rounded-2xl shadow-[0_8px_30px_rgb(0,0,0,0.04)] border-0 ring-1 ring-slate-100 focus:ring-2 focus:ring-indigo-500/50 outline-none transition-all placeholder:text-slate-400 text-lg text-slate-700"
|
||||
disabled={createMutation.isPending}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={createMutation.isPending || !newTodoTitle.trim()}
|
||||
className="absolute right-3 top-3 bottom-3 px-6 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-medium transition-all shadow-md shadow-indigo-200 disabled:opacity-50 disabled:shadow-none hover:shadow-lg hover:shadow-indigo-300 active:scale-95"
|
||||
>
|
||||
{createMutation.isPending ? '添加中' : '添加'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{/* Progress Bar (Only visible when there are tasks) */}
|
||||
{totalCount > 0 && (
|
||||
<div className="h-1.5 w-full bg-slate-200 rounded-full overflow-hidden">
|
||||
<div
|
||||
@@ -53,6 +107,7 @@ function Todos() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Todo List */}
|
||||
<div className="space-y-3">
|
||||
{todos.length === 0 ? (
|
||||
<div className="py-20 text-center">
|
||||
@@ -64,20 +119,93 @@ function Todos() {
|
||||
stroke="currentColor"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.5}
|
||||
d="M12 6v6m0 0v6m0-6h6m-6 0H6"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-slate-500 text-lg font-medium">没有待办事项</p>
|
||||
<p className="text-slate-400 text-sm mt-1">输入上方内容添加您的第一个任务</p>
|
||||
<p className="text-slate-400 text-sm mt-1">
|
||||
输入上方内容添加您的第一个任务
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
todos.map((todo) => (
|
||||
<TodoItem
|
||||
<div
|
||||
key={todo.id}
|
||||
todo={todo}
|
||||
onToggle={(id, completed) => updateMutation.mutate({ id, data: { completed: !completed } })}
|
||||
onDelete={(id) => deleteMutation.mutate({ id })}
|
||||
className={`group relative flex items-center p-4 bg-white rounded-xl border border-slate-100 shadow-sm transition-all duration-200 hover:shadow-md hover:border-slate-200 ${
|
||||
todo.completed ? 'bg-slate-50/50' : ''
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleToggleTodo(todo.id, todo.completed)}
|
||||
className={`flex-shrink-0 w-6 h-6 rounded-full border-2 transition-all duration-200 flex items-center justify-center mr-4 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${
|
||||
todo.completed
|
||||
? 'bg-indigo-500 border-indigo-500'
|
||||
: 'border-slate-300 hover:border-indigo-500 bg-white'
|
||||
}`}
|
||||
>
|
||||
{todo.completed && (
|
||||
<svg
|
||||
className="w-3.5 h-3.5 text-white"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={3}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M5 13l4 4L19 7"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<p
|
||||
className={`text-lg transition-all duration-200 truncate ${
|
||||
todo.completed
|
||||
? 'text-slate-400 line-through decoration-slate-300 decoration-2'
|
||||
: 'text-slate-700'
|
||||
}`}
|
||||
>
|
||||
{todo.title}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center opacity-0 group-hover:opacity-100 transition-opacity duration-200 absolute right-4 pl-4 bg-gradient-to-l from-white via-white to-transparent sm:static sm:bg-none">
|
||||
<span className="text-xs text-slate-400 mr-3 hidden sm:inline-block">
|
||||
{new Date(todo.createdAt).toLocaleDateString('zh-CN')}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleDeleteTodo(todo.id)}
|
||||
className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors focus:outline-none"
|
||||
title="删除"
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
export interface BaseContext {
|
||||
headers: Headers
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import * as todo from './todo.contract'
|
||||
|
||||
export const contract = {
|
||||
todo,
|
||||
}
|
||||
|
||||
export type Contract = typeof contract
|
||||
@@ -1,20 +0,0 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
import { createInsertSchema } from 'drizzle-zod'
|
||||
import { generatedFieldKeys } from '@/server/db/fields'
|
||||
import { todoTable } from '@/server/db/schema'
|
||||
|
||||
describe('todo insert schema', () => {
|
||||
const insertSchema = createInsertSchema(todoTable).omit(generatedFieldKeys)
|
||||
|
||||
test('accepts a minimal valid input', () => {
|
||||
expect(insertSchema.safeParse({ title: 'buy milk' }).success).toBe(true)
|
||||
})
|
||||
|
||||
test('rejects missing title', () => {
|
||||
expect(insertSchema.safeParse({}).success).toBe(false)
|
||||
})
|
||||
|
||||
test('rejects non-string title', () => {
|
||||
expect(insertSchema.safeParse({ title: 42 }).success).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,32 +0,0 @@
|
||||
import { ORPCError, ValidationError } from '@orpc/server'
|
||||
import { z } from 'zod'
|
||||
import { getLogger } from '@/server/logger'
|
||||
|
||||
const logger = getLogger(['api'])
|
||||
|
||||
export const logError = (error: unknown) => {
|
||||
logger.error('Unhandled error in ORPC handler', { error })
|
||||
}
|
||||
|
||||
export const handleValidationError = (error: unknown) => {
|
||||
if (!(error instanceof ORPCError) || !(error.cause instanceof ValidationError)) return
|
||||
|
||||
if (error.code === 'BAD_REQUEST') {
|
||||
// ORPC widens issues to the Standard Schema shape; every contract here is built from Zod/drizzle-zod,
|
||||
// so the runtime objects are Zod issues. Rehydrate to reuse z.prettifyError / z.flattenError.
|
||||
const zodError = new z.ZodError(error.cause.issues as z.core.$ZodIssue[])
|
||||
|
||||
throw new ORPCError('INPUT_VALIDATION_FAILED', {
|
||||
status: 422,
|
||||
message: z.prettifyError(zodError),
|
||||
data: z.flattenError(zodError),
|
||||
cause: error.cause,
|
||||
})
|
||||
}
|
||||
|
||||
if (error.code === 'INTERNAL_SERVER_ERROR') {
|
||||
throw new ORPCError('OUTPUT_VALIDATION_FAILED', {
|
||||
cause: error.cause,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import { os } from '@/server/api/server'
|
||||
import * as todo from './todo.router'
|
||||
|
||||
export const router = os.router({
|
||||
todo,
|
||||
})
|
||||
@@ -1,39 +0,0 @@
|
||||
import { ORPCError } from '@orpc/server'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { os } from '@/server/api/server'
|
||||
import { db } from '@/server/db'
|
||||
import { todoTable } from '@/server/db/schema'
|
||||
|
||||
export const list = os.todo.list.handler(async () => {
|
||||
return db.query.todoTable.findMany({
|
||||
orderBy: (table, { desc }) => desc(table.createdAt),
|
||||
})
|
||||
})
|
||||
|
||||
export const create = os.todo.create.handler(async ({ input }) => {
|
||||
const [newTodo] = await db.insert(todoTable).values(input).returning()
|
||||
|
||||
if (!newTodo) {
|
||||
throw new ORPCError('INTERNAL_SERVER_ERROR', { message: 'Failed to create todo' })
|
||||
}
|
||||
|
||||
return newTodo
|
||||
})
|
||||
|
||||
export const update = os.todo.update.handler(async ({ input }) => {
|
||||
const [updatedTodo] = await db.update(todoTable).set(input.data).where(eq(todoTable.id, input.id)).returning()
|
||||
|
||||
if (!updatedTodo) {
|
||||
throw new ORPCError('NOT_FOUND')
|
||||
}
|
||||
|
||||
return updatedTodo
|
||||
})
|
||||
|
||||
export const remove = os.todo.remove.handler(async ({ input }) => {
|
||||
const [deleted] = await db.delete(todoTable).where(eq(todoTable.id, input.id)).returning({ id: todoTable.id })
|
||||
|
||||
if (!deleted) {
|
||||
throw new ORPCError('NOT_FOUND')
|
||||
}
|
||||
})
|
||||
@@ -1,5 +0,0 @@
|
||||
import { implement } from '@orpc/server'
|
||||
import type { BaseContext } from './context'
|
||||
import { contract } from './contracts'
|
||||
|
||||
export const os = implement(contract).$context<BaseContext>()
|
||||
@@ -1,5 +0,0 @@
|
||||
import type { ContractRouterClient, InferContractRouterOutputs } from '@orpc/contract'
|
||||
import type { Contract } from './contracts'
|
||||
|
||||
export type RouterClient = ContractRouterClient<Contract>
|
||||
export type RouterOutputs = InferContractRouterOutputs<Contract>
|
||||
@@ -1,19 +0,0 @@
|
||||
import { sql } from 'drizzle-orm'
|
||||
import { timestamp, uuid } from 'drizzle-orm/pg-core'
|
||||
|
||||
export const generatedFields = {
|
||||
id: uuid('id').primaryKey().default(sql`uuidv7()`),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdateFn(() => new Date()),
|
||||
}
|
||||
|
||||
type GeneratedFieldKey = keyof typeof generatedFields
|
||||
|
||||
export const generatedFieldKeys = {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
} satisfies Record<GeneratedFieldKey, true>
|
||||
@@ -1,11 +0,0 @@
|
||||
import { DrizzleLogger } from '@logtape/drizzle-orm'
|
||||
import { drizzle } from 'drizzle-orm/postgres-js'
|
||||
import { env } from '@/env'
|
||||
import * as schema from '@/server/db/schema'
|
||||
import { getLogger } from '@/server/logger'
|
||||
|
||||
export const db = drizzle({
|
||||
connection: env.DATABASE_URL,
|
||||
schema,
|
||||
logger: env.LOG_DB ? new DrizzleLogger(getLogger(['db']), 'info') : false,
|
||||
})
|
||||
@@ -1,8 +0,0 @@
|
||||
// AUTO-GENERATED by `bun run db:embed`. Do not edit.
|
||||
import sql_0 from '#drizzle/0000_loving_thunderbird.sql' with { type: 'text' }
|
||||
|
||||
export type EmbeddedMigration = { tag: string; sql: string; when: number; breakpoints: boolean }
|
||||
|
||||
export const embeddedMigrations: readonly EmbeddedMigration[] = [
|
||||
{ tag: '0000_loving_thunderbird', sql: sql_0, when: 1777096386609, breakpoints: true },
|
||||
]
|
||||
@@ -1,8 +0,0 @@
|
||||
import { boolean, pgTable, text } from 'drizzle-orm/pg-core'
|
||||
import { generatedFields } from '../fields'
|
||||
|
||||
export const todoTable = pgTable('todo', {
|
||||
...generatedFields,
|
||||
title: text('title').notNull(),
|
||||
completed: boolean('completed').notNull().default(false),
|
||||
})
|
||||