Compare commits

...

13 Commits

40 changed files with 1609 additions and 978 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres DATABASE_URL=mysql://user:password@localhost:3306/database
# Optional logging knobs (defaults are usually fine): # Optional logging knobs (defaults are usually fine):
# LOG_LEVEL=info # trace|debug|info|warning|error|fatal # LOG_LEVEL=info # trace|debug|info|warning|error|fatal
# LOG_FORMAT=pretty # pretty|json — defaults to TTY ? pretty : json # LOG_FORMAT=pretty # pretty|json — defaults to TTY ? pretty : json
# LOG_DB=false # true to log every Drizzle SQL query # LOG_DB=false # reserved for database query logging if enabled later
+67 -201
View File
@@ -1,232 +1,98 @@
# AGENTS.md # AGENTS.md
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). Repo-specific notes for AI agents.
## Stack & runtime ## Stack
- **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). - Bun-only (`mise.toml` pins `bun = 1.3.13`). Do not use `npm` / `npx` / `node` / `yarn` / `pnpm`.
- **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 + Vite + Nitro `bun` preset.
- 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. - ORPC contract-first API, TanStack Query v5, Tailwind v4.
- **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. - Business data source is the customer's existing **MySQL** database. This app is read-only display software.
- **Drizzle ORM `0.45.2` (0.x, NOT 1.0 beta)** — see "Drizzle" section, this matters a lot. - There is no PostgreSQL, Drizzle schema, embedded migration flow, or local DB mutation path in this project now.
- ORPC (contract-first), TanStack Query v5, Tailwind v4. - `scripts/seed.ts` is the only local development helper allowed to create/truncate/insert sample data. The app runtime must stay read-only.
- **Logging via [LogTape](https://logtape.org/)** (zero-dep, runtime-agnostic) — see "Logging" section. `console.*` is forbidden in business code.
## Scripts ## Scripts
```bash ```bash
bun run dev # bunx --bun vite dev (localhost:3000) bun run dev
bun run build # bunx --bun vite build → .output/ bun run build
bun run compile # bun scripts/compile.ts → out/server-<target> (standalone CLI binary) bun run compile
bun run cli <cmd> # bun src/bin.ts <cmd> — run a CLI subcommand in source (dev) bun run seed
bun run typecheck # tsc --noEmit bun run typecheck
bun run test # bun test — runs all *.test.ts files (colocated with source) bun run test
bun run fix # biome check --write (lint + format + organize imports) bun run fix
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
``` ```
Cross-compile targets live under `compile:{linux,darwin,windows}[:arch]`. `scripts/compile.ts` accepts `--target bun-<os>-<arch>`; default derives from host. Before shipping: `bun run fix && bun run typecheck && bun run test && bun run build`.
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. ## MySQL Source
## Drizzle (v0.x — critical) Environment variable:
**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. ```bash
DATABASE_URL=mysql://user:password@host:3306/database
- Driver: `drizzle-orm/postgres-js`. Do NOT use `drizzle-orm/bun-sql`.
- `drizzle()` is called with `{ connection, schema }` where `schema = import * as schema from '@/server/db/schema'`. There is **no `relations.ts`** and **no `defineRelations`** in 0.x.
- Zod generators live in the separate `drizzle-zod` package (`^0.8.3`). Import from `drizzle-zod`, **not** `drizzle-orm/zod` (that subpath only exists in 1.0 beta).
- Relational queries use **RQB v1 callback syntax**:
```ts
db.query.todoTable.findMany({
orderBy: (t, { desc }) => desc(t.createdAt),
})
```
Do NOT use the v2 object form (`orderBy: { createdAt: 'desc' }`, `where: { id }`) — it won't type-check.
- To add relations later: declare per-table with `relations()` from `drizzle-orm` and export them from the same file as the table; they get picked up automatically because `index.ts` does `drizzle({ schema })` via `import *`.
- Every table must spread `...generatedFields` from `src/server/db/fields.ts` (`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
`bun run compile` produces a single executable that dispatches subcommands via [citty](https://github.com/unjs/citty). Entry is `src/bin.ts`; subcommands live in `src/cli/`.
```
./server [serve] # default — start the HTTP server
./server migrate # apply embedded migrations
./server --help
``` ```
**Nitro side-effect pitfall (important).** Under the `bun` preset, `.output/server/index.mjs` has a top-level `serve(...)` call — merely importing it starts the HTTP server. `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. Customer table: `ls_battery_info`.
**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. | Column | Type | Meaning |
| --- | --- | --- |
| `id` | `int(11)` auto increment | primary key |
| `user_id` | `int(11)` | user ID |
| `mac` | `varchar(50)` | device MAC |
| `dev_model` | `varchar(20)` | device model |
| `dev_name` | `varchar(50)` | device name |
| `is_low_power` | `varchar(10)` | `true` / `false` |
| `power_status` | `tinyint(4)` | `0` not charging, `1` charging, `2` full |
| `power` | `tinyint(4)` | current battery `0~100` |
| `create_time` | `datetime` | created time |
| `remark` | `varchar(500)` | nullable remark |
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()`. Rules:
**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. - Only run `SELECT` queries against this table. Do not insert, update, delete, migrate, or create tables.
- Do not add mock/fallback rows. If MySQL is unavailable, surface the error.
- `is_low_power` is stored as a string and normalized to boolean in `src/domain/battery.ts`.
- `power_status` is normalized to `0 | 1 | 2`.
- Without `mac`, battery list queries return the latest record per `mac`.
- With `mac`, battery list queries return history ordered by `create_time DESC, id DESC`, limited to 500 rows.
## Compile flags ## Layout
`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)
``` ```
src/ 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/ ├── routes/
│ ├── __root.tsx # root route + RootDocument shell │ ├── index.tsx # SoH dashboard
│ ├── index.tsx # Todos UI │ ├── batteries.tsx # battery monitor page
── health.ts # GET /health → "ok" (no DB) ── api/ # ORPC handlers
│ └── api/
│ ├── $.ts # OpenAPI + Scalar; interceptors registered here
│ └── rpc.$.ts # RPC; interceptors registered here
├── server/ ├── server/
│ ├── logger.ts # LogTape `configureSync` + `getLogger` re-export — the only log entrypoint │ ├── api/ # contracts / routers / interceptors
── api/ ── battery/mysql.ts
│ │ ├── server.ts # the ONLY place to build `os` ├── domain/battery.ts
│ │ ├── context.ts # BaseContext (add per-request fields when you add middlewares) ├── client/orpc.ts
│ │ ├── interceptors.ts # logError (→ logger), handleValidationError └── styles.css
│ │ ├── 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)
``` ```
Nitro plugins are wired in `vite.config.ts` (`nitro({ plugins: [...] })`), not via a Nitro config file. ## ORPC
## Don'ts (specific, non-obvious) - Contracts live in `src/server/api/contracts/`.
- Routers live in `src/server/api/routers/`.
- Use `os` from `@/server/api/server`.
- Current business API:
- `battery.dashboard`
- `battery.batteries`
- **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`.) ## CLI And Deploy
- 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`.
## Room-to-grow rules (discipline for the first real feature) - `src/bin.ts` must keep static imports minimal. Nitro's bun preset starts the server as a side effect when `.output/server/index.mjs` is imported.
- `serve` is lazy-loaded via citty.
- `bun run compile` produces `out/server-<target>`.
- Runtime artifact is a single binary plus `DATABASE_URL` configuration.
These keep the starter from setting bad precedents as it grows. Append, don't restructure. ## Code Style
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-space indentation, LF, single quotes, semicolons as-needed, 120-column line width.
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. - Route components use `function Foo()` declarations below route config.
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. - No `console.*` in business code; use `getLogger([...])` from `@/server/logger` if logging is needed.
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. - No `as any`, `@ts-ignore`, or `@ts-expect-error`.
5. Interceptors (`src/server/api/interceptors.ts`) do cross-cutting error logging, transport normalization, and validation rewrites. They do NOT read business data. - Do not edit `src/routeTree.gen.ts` manually.
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.
+80 -84
View File
@@ -1,112 +1,108 @@
# fullstack-starter # battery-soh
一个**单二进制**的全栈应用 starter——`bun run compile` 出来的 `./server` 文件就是你要部署的全部产物,自带 HTTP 服务、SSR、API、嵌入式 SQL 迁移,运行时不依赖 Node、不依赖源码、不依赖外部 migration 目录 一个基于 **Bun + TanStack Start + ORPC** 的电池健康展示系统。应用会被打包成单个二进制文件,前端页面、SSR 服务和 ORPC API 一起发布;业务数据只读接入甲方现有 MySQL 表 `ls_battery_info`,本项目不写入、不迁移、不修改甲方数据库
技术栈: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` 等类型逃逸。 | `id` | `int(11)` 自增 | 主键 ID |
- **开箱可跑**:路径别名、文件路由、ORPC 接线、Tailwind、热重载、错误页全部预接好。 | `user_id` | `int(11)` | 用户 ID |
| `mac` | `varchar(50)` | 设备 MAC |
| `dev_model` | `varchar(20)` | 设备型号 |
| `dev_name` | `varchar(50)` | 设备名称 |
| `is_low_power` | `varchar(10)` | 是否低电量:`true` / `false` |
| `power_status` | `tinyint(4)` | `0` 未充电,`1` 正在充电,`2` 充电完成 |
| `power` | `tinyint(4)` | 当前电量 `0~100` |
| `create_time` | `datetime` | 创建时间 |
| `remark` | `varchar(500)` | 备注,可空 |
环境变量:
```bash
DATABASE_URL=mysql://user:password@host:3306/database
```
## 快速开始 ## 快速开始
> **需要 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 ```bash
cp .env.example .env # 把里面的 DATABASE_URL 改成你的 Postgres cp .env.example .env
bun install bun install
bun run db:push # 开发期:把 schema 直接同步到 DB(不写 migration 文件) bun run dev
bun run dev # http://localhost:3000
``` ```
打开浏览器 如果甲方暂时没有提供数据库连接,可以用 Docker Compose 启动本地 MySQL 并填充示例数据
- `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 ```bash
docker compose up --build docker compose up --build
``` ```
Kubernetes 上:把 `./server migrate` 放进 initContainer 或 Helm `pre-upgrade` Job,主容器跑 `./server` Compose 会启动三个服务:
## 脚本一览 - `db`:本地 MySQL 8.4
- `seed`:执行 `bun run seed`,用 Drizzle MySQL schema + `drizzle-seed` 重置本地 `ls_battery_info` 并写入示例数据
- `app`:使用同一个 `DATABASE_URL` 启动单二进制应用
也可以手动 seed 本地库:
```bash
DATABASE_URL=mysql://battery:battery@localhost:3306/battery_soh bun run seed
```
`seed` 是本地开发/验收脚本,会建表并重置示例数据;应用运行时仍然只执行 `SELECT`,不会写入数据库。
打开浏览器:
- `http://localhost:3000/`SoH 预测与风险洞察看板
- `http://localhost:3000/batteries`:设备电池实时状态
- `http://localhost:3000/api/docs`Scalar 渲染的 ORPC OpenAPI 文档
## 架构
```
src/
├── routes/ # TanStack Start 文件路由:页面 + API 端点
├── server/
│ ├── api/ # ORPC contract / router
│ └── battery/mysql.ts # 甲方 MySQL 只读查询
├── domain/battery.ts # 电池领域类型、归一化、展示聚合
├── client/orpc.ts # isomorphic ORPC client
└── styles.css # Tailwind v4 entry
```
接口保持模板里的 ORPC 模式:
- `battery.dashboard`:读取每个 `mac` 的最新记录并生成看板聚合数据
- `battery.batteries`:无 `mac` 时返回每台设备最新记录;带 `mac` 时返回该设备历史记录,按 `create_time desc` 限制 500 条
所有业务查询都是 `SELECT`,没有 mutation,也没有 mock/fallback 数据。
## 部署
```bash
bun run build
bun run compile
./out/server-<target>
```
Docker 镜像会在构建阶段产出单个 `./server` 二进制,运行阶段只需要配置 `DATABASE_URL`
## 脚本
| 命令 | 作用 | | 命令 | 作用 |
| --- | --- | | --- | --- |
| `bun run dev` | Vite 开发服务器(默认端口 3000 | | `bun run dev` | Vite 开发服务器 |
| `bun run build` | 构建到 `.output/``bun run compile` 会用到) | | `bun run build` | 构建到 `.output/` |
| `bun run compile` | 生成单二进制 `out/server-<target>` | | `bun run compile` | 生成单二进制 `out/server-<target>` |
| `bun run seed` | 为本地 MySQL 创建甲方表并填充示例数据 |
| `bun run typecheck` | TypeScript 类型检查 | | `bun run typecheck` | TypeScript 类型检查 |
| `bun run test` | 运行所有 `*.test.ts` | | `bun run test` | 运行所有 `*.test.ts` |
| `bun run fix` | Biome 格式化 + lint + 整理 imports | | `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 ```bash
bun run fix && bun run typecheck && bun run test bun run fix && bun run typecheck && bun run test && bun run build
``` ```
没有 CI、没有 pre-commit hook——上面三条由你自觉跑。
-1
View File
@@ -18,7 +18,6 @@
"linter": { "linter": {
"enabled": true, "enabled": true,
"domains": { "domains": {
"drizzle": "recommended",
"react": "recommended", "react": "recommended",
"types": "all" "types": "all"
}, },
+27 -67
View File
@@ -5,7 +5,6 @@
"": { "": {
"name": "fullstack-starter", "name": "fullstack-starter",
"dependencies": { "dependencies": {
"@logtape/drizzle-orm": "^2.0.5",
"@logtape/logtape": "^2.0.5", "@logtape/logtape": "^2.0.5",
"@logtape/pretty": "^2.0.5", "@logtape/pretty": "^2.0.5",
"@orpc/client": "^1.14.0", "@orpc/client": "^1.14.0",
@@ -20,9 +19,8 @@
"@tanstack/react-router-ssr-query": "^1.166.11", "@tanstack/react-router-ssr-query": "^1.166.11",
"@tanstack/react-start": "^1.167.48", "@tanstack/react-start": "^1.167.48",
"citty": "^0.2.2", "citty": "^0.2.2",
"drizzle-orm": "0.45.2", "drizzle-orm": "^0.45.2",
"drizzle-zod": "^0.8.3", "mysql2": "^3.22.3",
"postgres": "^3.4.9",
"react": "^19.2.5", "react": "^19.2.5",
"react-dom": "^19.2.5", "react-dom": "^19.2.5",
"zod": "^4.3.6", "zod": "^4.3.6",
@@ -36,7 +34,7 @@
"@tanstack/react-router-devtools": "^1.166.13", "@tanstack/react-router-devtools": "^1.166.13",
"@types/bun": "^1.3.13", "@types/bun": "^1.3.13",
"@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-react": "^6.0.1",
"drizzle-kit": "0.31.10", "drizzle-seed": "^0.3.1",
"nitro": "npm:nitro-nightly@3.0.1-20260424-182106-f8cf6ccc", "nitro": "npm:nitro-nightly@3.0.1-20260424-182106-f8cf6ccc",
"tailwindcss": "^4.2.4", "tailwindcss": "^4.2.4",
"typescript": "^6.0.3", "typescript": "^6.0.3",
@@ -101,18 +99,12 @@
"@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.4.13", "", { "os": "win32", "cpu": "x64" }, "sha512-tTcMkXyBrmHi9BfrD2VNHs/5rYIUKETqsBlYOvSAABwBkJhSDVb5e7wPukftsQbO3WzQkXe6kaztC6WtUOXSoQ=="], "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.4.13", "", { "os": "win32", "cpu": "x64" }, "sha512-tTcMkXyBrmHi9BfrD2VNHs/5rYIUKETqsBlYOvSAABwBkJhSDVb5e7wPukftsQbO3WzQkXe6kaztC6WtUOXSoQ=="],
"@drizzle-team/brocli": ["@drizzle-team/brocli@0.10.2", "", {}, "sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w=="],
"@emnapi/core": ["@emnapi/core@1.10.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" } }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="], "@emnapi/core": ["@emnapi/core@1.10.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" } }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="],
"@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="], "@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="],
"@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w=="], "@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w=="],
"@esbuild-kit/core-utils": ["@esbuild-kit/core-utils@3.3.2", "", { "dependencies": { "esbuild": "~0.18.20", "source-map-support": "^0.5.21" } }, "sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ=="],
"@esbuild-kit/esm-loader": ["@esbuild-kit/esm-loader@2.6.5", "", { "dependencies": { "@esbuild-kit/core-utils": "^3.3.2", "get-tsconfig": "^4.7.0" } }, "sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA=="],
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.12", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="], "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.12", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="],
"@esbuild/android-arm": ["@esbuild/android-arm@0.25.12", "", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="], "@esbuild/android-arm": ["@esbuild/android-arm@0.25.12", "", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="],
@@ -175,8 +167,6 @@
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@logtape/drizzle-orm": ["@logtape/drizzle-orm@2.0.5", "", { "peerDependencies": { "@logtape/logtape": "^2.0.5" } }, "sha512-woM4x9J7B4XzoQTY1bzR6uJVlqezn6oY6flV+rDD6lsuwP2llNVvptgCOGjRutDye+6WZldSUIGe7UFK/faBzA=="],
"@logtape/logtape": ["@logtape/logtape@2.0.5", "", {}, "sha512-UizDkh20ZPJVOddRxG1F77WhHdlNl/sbQgoO8T534R7XvUBMAJ9En9f35u+meW2tRsNLvjz6R87Zanwf53tspQ=="], "@logtape/logtape": ["@logtape/logtape@2.0.5", "", {}, "sha512-UizDkh20ZPJVOddRxG1F77WhHdlNl/sbQgoO8T534R7XvUBMAJ9En9f35u+meW2tRsNLvjz6R87Zanwf53tspQ=="],
"@logtape/pretty": ["@logtape/pretty@2.0.5", "", { "peerDependencies": { "@logtape/logtape": "^2.0.5" } }, "sha512-jU5pYL0CW0tFmxBS5umMF5VEMq1vXLvkqKrj7KRHnSlb5SrBOSCYl0w4q7FmPPFVADmgTmzVVr6IcIWwK/2Nig=="], "@logtape/pretty": ["@logtape/pretty@2.0.5", "", { "peerDependencies": { "@logtape/logtape": "^2.0.5" } }, "sha512-jU5pYL0CW0tFmxBS5umMF5VEMq1vXLvkqKrj7KRHnSlb5SrBOSCYl0w4q7FmPPFVADmgTmzVVr6IcIWwK/2Nig=="],
@@ -387,6 +377,8 @@
"argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], "argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
"aws-ssl-profiles": ["aws-ssl-profiles@1.1.2", "", {}, "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g=="],
"babel-dead-code-elimination": ["babel-dead-code-elimination@1.0.12", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="], "babel-dead-code-elimination": ["babel-dead-code-elimination@1.0.12", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="],
"baseline-browser-mapping": ["baseline-browser-mapping@2.10.21", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-Q+rUQ7Uz8AHM7DEaNdwvfFCTq7a43lNTzuS94eiWqwyxfV/wJv+oUivef51T91mmRY4d4A1u9rcSvkeufCVXlA=="], "baseline-browser-mapping": ["baseline-browser-mapping@2.10.21", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-Q+rUQ7Uz8AHM7DEaNdwvfFCTq7a43lNTzuS94eiWqwyxfV/wJv+oUivef51T91mmRY4d4A1u9rcSvkeufCVXlA=="],
@@ -399,8 +391,6 @@
"browserslist": ["browserslist@4.28.2", "", { "dependencies": { "baseline-browser-mapping": "^2.10.12", "caniuse-lite": "^1.0.30001782", "electron-to-chromium": "^1.5.328", "node-releases": "^2.0.36", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg=="], "browserslist": ["browserslist@4.28.2", "", { "dependencies": { "baseline-browser-mapping": "^2.10.12", "caniuse-lite": "^1.0.30001782", "electron-to-chromium": "^1.5.328", "node-releases": "^2.0.36", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg=="],
"buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
"bun-types": ["bun-types@1.3.13", "", { "dependencies": { "@types/node": "*" } }, "sha512-QXKeHLlOLqQX9LgYaHJfzdBaV21T63HhFJnvuRCcjZiaUDpbs5ED1MgxbMra71CsryN/1dAoXuJJJwIv/2drVA=="], "bun-types": ["bun-types@1.3.13", "", { "dependencies": { "@types/node": "*" } }, "sha512-QXKeHLlOLqQX9LgYaHJfzdBaV21T63HhFJnvuRCcjZiaUDpbs5ED1MgxbMra71CsryN/1dAoXuJJJwIv/2drVA=="],
"caniuse-lite": ["caniuse-lite@1.0.30001790", "", {}, "sha512-bOoxfJPyYo+ds6W0YfptaCWbFnJYjh2Y1Eow5lRv+vI2u8ganPZqNm1JwNh0t2ELQCqIWg4B3dWEusgAmsoyOw=="], "caniuse-lite": ["caniuse-lite@1.0.30001790", "", {}, "sha512-bOoxfJPyYo+ds6W0YfptaCWbFnJYjh2Y1Eow5lRv+vI2u8ganPZqNm1JwNh0t2ELQCqIWg4B3dWEusgAmsoyOw=="],
@@ -439,6 +429,8 @@
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"denque": ["denque@2.1.0", "", {}, "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw=="],
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="], "diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="],
@@ -451,11 +443,9 @@
"domutils": ["domutils@3.2.2", "", { "dependencies": { "dom-serializer": "^2.0.0", "domelementtype": "^2.3.0", "domhandler": "^5.0.3" } }, "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw=="], "domutils": ["domutils@3.2.2", "", { "dependencies": { "dom-serializer": "^2.0.0", "domelementtype": "^2.3.0", "domhandler": "^5.0.3" } }, "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw=="],
"drizzle-kit": ["drizzle-kit@0.31.10", "", { "dependencies": { "@drizzle-team/brocli": "^0.10.2", "@esbuild-kit/esm-loader": "^2.5.5", "esbuild": "^0.25.4", "tsx": "^4.21.0" }, "bin": { "drizzle-kit": "bin.cjs" } }, "sha512-7OZcmQUrdGI+DUNNsKBn1aW8qSoKuTH7d0mYgSP8bAzdFzKoovxEFnoGQp2dVs82EOJeYycqRtciopszwUf8bw=="],
"drizzle-orm": ["drizzle-orm@0.45.2", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1.13", "@prisma/client": "*", "@tidbcloud/serverless": "*", "@types/better-sqlite3": "*", "@types/pg": "*", "@types/sql.js": "*", "@upstash/redis": ">=1.34.7", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "better-sqlite3": ">=7", "bun-types": "*", "expo-sqlite": ">=14.0.0", "gel": ">=2", "knex": "*", "kysely": "*", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "sql.js": ">=1", "sqlite3": ">=5" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@cloudflare/workers-types", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@prisma/client", "@tidbcloud/serverless", "@types/better-sqlite3", "@types/pg", "@types/sql.js", "@upstash/redis", "@vercel/postgres", "@xata.io/client", "better-sqlite3", "bun-types", "expo-sqlite", "gel", "knex", "kysely", "mysql2", "pg", "postgres", "sql.js", "sqlite3"] }, "sha512-kY0BSaTNYWnoDMVoyY8uxmyHjpJW1geOmBMdSSicKo9CIIWkSxMIj2rkeSR51b8KAPB7m+qysjuHme5nKP+E5Q=="], "drizzle-orm": ["drizzle-orm@0.45.2", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1.13", "@prisma/client": "*", "@tidbcloud/serverless": "*", "@types/better-sqlite3": "*", "@types/pg": "*", "@types/sql.js": "*", "@upstash/redis": ">=1.34.7", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "better-sqlite3": ">=7", "bun-types": "*", "expo-sqlite": ">=14.0.0", "gel": ">=2", "knex": "*", "kysely": "*", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "sql.js": ">=1", "sqlite3": ">=5" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@cloudflare/workers-types", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@prisma/client", "@tidbcloud/serverless", "@types/better-sqlite3", "@types/pg", "@types/sql.js", "@upstash/redis", "@vercel/postgres", "@xata.io/client", "better-sqlite3", "bun-types", "expo-sqlite", "gel", "knex", "kysely", "mysql2", "pg", "postgres", "sql.js", "sqlite3"] }, "sha512-kY0BSaTNYWnoDMVoyY8uxmyHjpJW1geOmBMdSSicKo9CIIWkSxMIj2rkeSR51b8KAPB7m+qysjuHme5nKP+E5Q=="],
"drizzle-zod": ["drizzle-zod@0.8.3", "", { "peerDependencies": { "drizzle-orm": ">=0.36.0", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-66yVOuvGhKJnTdiqj1/Xaaz9/qzOdRJADpDa68enqS6g3t0kpNkwNYjUuaeXgZfO/UWuIM9HIhSlJ6C5ZraMww=="], "drizzle-seed": ["drizzle-seed@0.3.1", "", { "dependencies": { "pure-rand": "^6.1.0" }, "peerDependencies": { "drizzle-orm": ">=0.36.4" }, "optionalPeers": ["drizzle-orm"] }, "sha512-F/0lgvfOAsqlYoHM/QAGut4xXIOXoE5VoAdv2FIl7DpGYVXlAzKuJO+IphkKUFK3Dz+rFlOsQLnMNrvoQ0cx7g=="],
"electron-to-chromium": ["electron-to-chromium@1.5.344", "", {}, "sha512-4MxfbmNDm+KPh066EZy+eUnkcDPcZ35wNmOWzFuh/ijvHsve6kbLTLURy88uCNK5FbpN+yk2nQY6BYh1GEt+wg=="], "electron-to-chromium": ["electron-to-chromium@1.5.344", "", {}, "sha512-4MxfbmNDm+KPh066EZy+eUnkcDPcZ35wNmOWzFuh/ijvHsve6kbLTLURy88uCNK5FbpN+yk2nQY6BYh1GEt+wg=="],
@@ -481,6 +471,8 @@
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"generate-function": ["generate-function@2.3.1", "", { "dependencies": { "is-property": "^1.0.2" } }, "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ=="],
"gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="], "gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="],
"get-tsconfig": ["get-tsconfig@4.14.0", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA=="], "get-tsconfig": ["get-tsconfig@4.14.0", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA=="],
@@ -501,7 +493,7 @@
"httpxy": ["httpxy@0.5.1", "", {}, "sha512-JPhqYiixe1A1I+MXDewWDZqeudBGU8Q9jCHYN8ML+779RQzLjTi78HBvWz4jMxUD6h2/vUL12g4q/mFM0OUw1A=="], "httpxy": ["httpxy@0.5.1", "", {}, "sha512-JPhqYiixe1A1I+MXDewWDZqeudBGU8Q9jCHYN8ML+779RQzLjTi78HBvWz4jMxUD6h2/vUL12g4q/mFM0OUw1A=="],
"iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="], "iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"is-binary-path": ["is-binary-path@2.1.0", "", { "dependencies": { "binary-extensions": "^2.0.0" } }, "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw=="], "is-binary-path": ["is-binary-path@2.1.0", "", { "dependencies": { "binary-extensions": "^2.0.0" } }, "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw=="],
@@ -511,6 +503,8 @@
"is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="], "is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="],
"is-property": ["is-property@1.0.2", "", {}, "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g=="],
"isbot": ["isbot@5.1.39", "", {}, "sha512-obH0yYahGXdzNxo+djmHhBYThUKDkz565cxkIlt2L9hXfv1NlaLKoDBHo6KxXsYrIXx2RK3x5vY36CfZcobxEw=="], "isbot": ["isbot@5.1.39", "", {}, "sha512-obH0yYahGXdzNxo+djmHhBYThUKDkz565cxkIlt2L9hXfv1NlaLKoDBHo6KxXsYrIXx2RK3x5vY36CfZcobxEw=="],
"jiti": ["jiti@2.6.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="], "jiti": ["jiti@2.6.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="],
@@ -551,12 +545,20 @@
"lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="], "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],
"long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],
"lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], "lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
"lru.min": ["lru.min@1.1.4", "", {}, "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA=="],
"magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"mysql2": ["mysql2@3.22.3", "", { "dependencies": { "aws-ssl-profiles": "^1.1.2", "denque": "^2.1.0", "generate-function": "^2.3.1", "iconv-lite": "^0.7.2", "long": "^5.3.2", "lru.min": "^1.1.4", "named-placeholders": "^1.1.6", "sql-escaper": "^1.3.3" }, "peerDependencies": { "@types/node": ">= 8" } }, "sha512-uWWxvZSRvRhtBdh2CdcuK83YcOfPdmEeEYB069bAmPnV93QApDGVPuvCQOLjlh7tYHEWdgQPrn6kosDxHBVLkA=="],
"named-placeholders": ["named-placeholders@1.1.6", "", { "dependencies": { "lru.min": "^1.1.0" } }, "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w=="],
"nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="], "nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
"nf3": ["nf3@0.3.16", "", {}, "sha512-Gs0xRPpUm2nDkqbi40NJ9g7qDIcjcJzgExiydnq6LAyqhI2jfno8wG3NKTL+IiJsx799UHOb1CnSd4Wg4SG4Pw=="], "nf3": ["nf3@0.3.16", "", {}, "sha512-Gs0xRPpUm2nDkqbi40NJ9g7qDIcjcJzgExiydnq6LAyqhI2jfno8wG3NKTL+IiJsx799UHOb1CnSd4Wg4SG4Pw=="],
@@ -595,6 +597,8 @@
"prettier": ["prettier@3.8.3", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw=="], "prettier": ["prettier@3.8.3", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw=="],
"pure-rand": ["pure-rand@6.1.0", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
"radash": ["radash@12.1.1", "", {}, "sha512-h36JMxKRqrAxVD8201FrCpyeNuUY9Y5zZwujr20fFO77tpUtGa6EZzfKw/3WaiBX95fq7+MpsuMLNdSnORAwSA=="], "radash": ["radash@12.1.1", "", {}, "sha512-h36JMxKRqrAxVD8201FrCpyeNuUY9Y5zZwujr20fFO77tpUtGa6EZzfKw/3WaiBX95fq7+MpsuMLNdSnORAwSA=="],
"react": ["react@19.2.5", "", {}, "sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA=="], "react": ["react@19.2.5", "", {}, "sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA=="],
@@ -627,7 +631,7 @@
"source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
"source-map-support": ["source-map-support@0.5.21", "", { "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" } }, "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w=="], "sql-escaper": ["sql-escaper@1.3.3", "", {}, "sha512-BsTCV265VpTp8tm1wyIm1xqQCS+Q9NHx2Sr+WcnUrgLrQ6yiDIvHYJV5gHxsj1lMBy2zm5twLaZao8Jd+S8JJw=="],
"srvx": ["srvx@0.11.15", "", { "bin": { "srvx": "bin/srvx.mjs" } }, "sha512-iXsux0UcOjdvs0LCMa2Ws3WwcDUozA3JN3BquNXkaFPP7TpRqgunKdEgoZ/uwb1J6xaYHfxtz9Twlh6yzwM6Tg=="], "srvx": ["srvx@0.11.15", "", { "bin": { "srvx": "bin/srvx.mjs" } }, "sha512-iXsux0UcOjdvs0LCMa2Ws3WwcDUozA3JN3BquNXkaFPP7TpRqgunKdEgoZ/uwb1J6xaYHfxtz9Twlh6yzwM6Tg=="],
@@ -685,8 +689,6 @@
"zod": ["zod@4.3.6", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="], "zod": ["zod@4.3.6", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="],
"@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.10.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" }, "bundled": true }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.10.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" }, "bundled": true }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="],
@@ -731,6 +733,8 @@
"anymatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], "anymatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
"encoding-sniffer/iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],
"h3/rou3": ["rou3@0.8.1", "", {}, "sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA=="], "h3/rou3": ["rou3@0.8.1", "", {}, "sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA=="],
"h3-v2/rou3": ["rou3@0.8.1", "", {}, "sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA=="], "h3-v2/rou3": ["rou3@0.8.1", "", {}, "sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA=="],
@@ -743,53 +747,9 @@
"rolldown/@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-rc.17", "", {}, "sha512-n8iosDOt6Ig1UhJ2AYqoIhHWh/isz0xpicHTzpKBeotdVsTEcxsSA/i3EVM7gQAj0rU27OLAxCjzlj15IWY7bg=="], "rolldown/@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-rc.17", "", {}, "sha512-n8iosDOt6Ig1UhJ2AYqoIhHWh/isz0xpicHTzpKBeotdVsTEcxsSA/i3EVM7gQAj0rU27OLAxCjzlj15IWY7bg=="],
"source-map-support/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
"tsx/esbuild": ["esbuild@0.27.7", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.7", "@esbuild/android-arm": "0.27.7", "@esbuild/android-arm64": "0.27.7", "@esbuild/android-x64": "0.27.7", "@esbuild/darwin-arm64": "0.27.7", "@esbuild/darwin-x64": "0.27.7", "@esbuild/freebsd-arm64": "0.27.7", "@esbuild/freebsd-x64": "0.27.7", "@esbuild/linux-arm": "0.27.7", "@esbuild/linux-arm64": "0.27.7", "@esbuild/linux-ia32": "0.27.7", "@esbuild/linux-loong64": "0.27.7", "@esbuild/linux-mips64el": "0.27.7", "@esbuild/linux-ppc64": "0.27.7", "@esbuild/linux-riscv64": "0.27.7", "@esbuild/linux-s390x": "0.27.7", "@esbuild/linux-x64": "0.27.7", "@esbuild/netbsd-arm64": "0.27.7", "@esbuild/netbsd-x64": "0.27.7", "@esbuild/openbsd-arm64": "0.27.7", "@esbuild/openbsd-x64": "0.27.7", "@esbuild/openharmony-arm64": "0.27.7", "@esbuild/sunos-x64": "0.27.7", "@esbuild/win32-arm64": "0.27.7", "@esbuild/win32-ia32": "0.27.7", "@esbuild/win32-x64": "0.27.7" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w=="], "tsx/esbuild": ["esbuild@0.27.7", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.7", "@esbuild/android-arm": "0.27.7", "@esbuild/android-arm64": "0.27.7", "@esbuild/android-x64": "0.27.7", "@esbuild/darwin-arm64": "0.27.7", "@esbuild/darwin-x64": "0.27.7", "@esbuild/freebsd-arm64": "0.27.7", "@esbuild/freebsd-x64": "0.27.7", "@esbuild/linux-arm": "0.27.7", "@esbuild/linux-arm64": "0.27.7", "@esbuild/linux-ia32": "0.27.7", "@esbuild/linux-loong64": "0.27.7", "@esbuild/linux-mips64el": "0.27.7", "@esbuild/linux-ppc64": "0.27.7", "@esbuild/linux-riscv64": "0.27.7", "@esbuild/linux-s390x": "0.27.7", "@esbuild/linux-x64": "0.27.7", "@esbuild/netbsd-arm64": "0.27.7", "@esbuild/netbsd-x64": "0.27.7", "@esbuild/openbsd-arm64": "0.27.7", "@esbuild/openbsd-x64": "0.27.7", "@esbuild/openharmony-arm64": "0.27.7", "@esbuild/sunos-x64": "0.27.7", "@esbuild/win32-arm64": "0.27.7", "@esbuild/win32-ia32": "0.27.7", "@esbuild/win32-x64": "0.27.7" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.18.20", "", { "os": "android", "cpu": "arm" }, "sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw=="], "whatwg-encoding/iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/android-arm64": ["@esbuild/android-arm64@0.18.20", "", { "os": "android", "cpu": "arm64" }, "sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/android-x64": ["@esbuild/android-x64@0.18.20", "", { "os": "android", "cpu": "x64" }, "sha512-8GDdlePJA8D6zlZYJV/jnrRAi6rOiNaCC/JclcXpB+KIuvfBN4owLtgzY2bsxnx666XjJx2kDPUmnTtR8qKQUg=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.18.20", "", { "os": "darwin", "cpu": "arm64" }, "sha512-bxRHW5kHU38zS2lPTPOyuyTm+S+eobPUnTNkdJEfAddYgEcll4xkT8DB9d2008DtTbl7uJag2HuE5NZAZgnNEA=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.18.20", "", { "os": "darwin", "cpu": "x64" }, "sha512-pc5gxlMDxzm513qPGbCbDukOdsGtKhfxD1zJKXjCCcU7ju50O7MeAZ8c4krSJcOIJGFR+qx21yMMVYwiQvyTyQ=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.18.20", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-yqDQHy4QHevpMAaxhhIwYPMv1NECwOvIpGCZkECn8w2WFHXjEwrBn3CeNIYsibZ/iZEUemj++M26W3cNR5h+Tw=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.18.20", "", { "os": "freebsd", "cpu": "x64" }, "sha512-tgWRPPuQsd3RmBZwarGVHZQvtzfEBOreNuxEMKFcd5DaDn2PbBxfwLcj4+aenoh7ctXcbXmOQIn8HI6mCSw5MQ=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-arm": ["@esbuild/linux-arm@0.18.20", "", { "os": "linux", "cpu": "arm" }, "sha512-/5bHkMWnq1EgKr1V+Ybz3s1hWXok7mDFUMQ4cG10AfW3wL02PSZi5kFpYKrptDsgb2WAJIvRcDm+qIvXf/apvg=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.18.20", "", { "os": "linux", "cpu": "arm64" }, "sha512-2YbscF+UL7SQAVIpnWvYwM+3LskyDmPhe31pE7/aoTMFKKzIc9lLbyGUpmmb8a8AixOL61sQ/mFh3jEjHYFvdA=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.18.20", "", { "os": "linux", "cpu": "ia32" }, "sha512-P4etWwq6IsReT0E1KHU40bOnzMHoH73aXp96Fs8TIT6z9Hu8G6+0SHSw9i2isWrD2nbx2qo5yUqACgdfVGx7TA=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.18.20", "", { "os": "linux", "cpu": "none" }, "sha512-nXW8nqBTrOpDLPgPY9uV+/1DjxoQ7DoB2N8eocyq8I9XuqJ7BiAMDMf9n1xZM9TgW0J8zrquIb/A7s3BJv7rjg=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.18.20", "", { "os": "linux", "cpu": "none" }, "sha512-d5NeaXZcHp8PzYy5VnXV3VSd2D328Zb+9dEq5HE6bw6+N86JVPExrA6O68OPwobntbNJ0pzCpUFZTo3w0GyetQ=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.18.20", "", { "os": "linux", "cpu": "ppc64" }, "sha512-WHPyeScRNcmANnLQkq6AfyXRFr5D6N2sKgkFo2FqguP44Nw2eyDlbTdZwd9GYk98DZG9QItIiTlFLHJHjxP3FA=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.18.20", "", { "os": "linux", "cpu": "none" }, "sha512-WSxo6h5ecI5XH34KC7w5veNnKkju3zBRLEQNY7mv5mtBmrP/MjNBCAlsM2u5hDBlS3NGcTQpoBvRzqBcRtpq1A=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.18.20", "", { "os": "linux", "cpu": "s390x" }, "sha512-+8231GMs3mAEth6Ja1iK0a1sQ3ohfcpzpRLH8uuc5/KVDFneH6jtAJLFGafpzpMRO6DzJ6AvXKze9LfFMrIHVQ=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-x64": ["@esbuild/linux-x64@0.18.20", "", { "os": "linux", "cpu": "x64" }, "sha512-UYqiqemphJcNsFEskc73jQ7B9jgwjWrSayxawS6UVFZGWrAAtkzjxSqnoclCXxWtfwLdzU+vTpcNYhpn43uP1w=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.18.20", "", { "os": "none", "cpu": "x64" }, "sha512-iO1c++VP6xUBUmltHZoMtCUdPlnPGdBom6IrO4gyKPFFVBKioIImVooR5I83nTew5UOYrk3gIJhbZh8X44y06A=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.18.20", "", { "os": "openbsd", "cpu": "x64" }, "sha512-e5e4YSsuQfX4cxcygw/UCPIEP6wbIL+se3sxPdCiMbFLBWu0eiZOJ7WoD+ptCLrmjZBK1Wk7I6D/I3NglUGOxg=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.18.20", "", { "os": "sunos", "cpu": "x64" }, "sha512-kDbFRFp0YpTQVVrqUd5FTYmWo45zGaXe0X8E1G/LKFC0v8x0vWrhOWSLITcCn63lmZIxfOMXtCfti/RxN/0wnQ=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.18.20", "", { "os": "win32", "cpu": "arm64" }, "sha512-ddYFR6ItYgoaq4v4JmQQaAI5s7npztfV4Ag6NrhiaW0RrnOXqBkgwZLofVTlq1daVTQNhtI5oieTvkRPfZrePg=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.18.20", "", { "os": "win32", "cpu": "ia32" }, "sha512-Wv7QBi3ID/rROT08SABTS7eV4hX26sVduqDOTe1MvGMjNd3EjOz4b7zeexIR62GTIEKrfJXKL9LFxTYgkyeu7g=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.18.20", "", { "os": "win32", "cpu": "x64" }, "sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ=="],
"tsx/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.7", "", { "os": "aix", "cpu": "ppc64" }, "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg=="], "tsx/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.7", "", { "os": "aix", "cpu": "ppc64" }, "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg=="],
+27 -26
View File
@@ -1,39 +1,40 @@
services: services:
migrate: db:
build: . image: mysql:8.4
ports:
- "3306:3306"
volumes:
- ./volumes/mysql/data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: battery_soh
MYSQL_USER: battery
MYSQL_PASSWORD: battery
healthcheck:
test: [ "CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-ubattery", "-pbattery" ]
interval: 5s
timeout: 5s
retries: 20
seed:
image: oven/bun:1.3.13
restart: "no"
depends_on: depends_on:
db: db:
condition: service_healthy condition: service_healthy
volumes:
- .:/app
environment: environment:
- DATABASE_URL=postgres://postgres:postgres@db:5432/postgres - DATABASE_URL=mysql://battery:battery@db:3306/battery_soh
command: ["./server", "migrate"] command: [ "sh", "-lc", "bun install --frozen-lockfile && bun run seed" ]
restart: "no" working_dir: /app
app: app:
build: . build: .
depends_on: depends_on:
db: seed:
condition: service_healthy
migrate:
condition: service_completed_successfully condition: service_completed_successfully
ports: ports:
- "3000:3000" - "3000:3000"
environment: environment:
- DATABASE_URL=postgres://postgres:postgres@db:5432/postgres - DATABASE_URL=mysql://battery:battery@db:3306/battery_soh
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:
-11
View File
@@ -1,11 +0,0 @@
import { defineConfig } from 'drizzle-kit'
import { env } from './src/env'
export default defineConfig({
out: './drizzle',
schema: './src/server/db/schema/index.ts',
dialect: 'postgresql',
dbCredentials: {
url: env.DATABASE_URL,
},
})
-7
View File
@@ -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
);
-65
View File
@@ -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": {}
}
}
-13
View File
@@ -1,13 +0,0 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1777096386609,
"tag": "0000_loving_thunderbird",
"breakpoints": true
}
]
}
+4 -11
View File
@@ -4,7 +4,6 @@
"private": true, "private": true,
"type": "module", "type": "module",
"imports": { "imports": {
"#drizzle/*.sql": "./drizzle/*.sql",
"#package": "./package.json", "#package": "./package.json",
"#server": "./.output/server/index.mjs" "#server": "./.output/server/index.mjs"
}, },
@@ -20,18 +19,13 @@
"compile:linux:x64": "bun scripts/compile.ts --target bun-linux-x64", "compile:linux:x64": "bun scripts/compile.ts --target bun-linux-x64",
"compile:windows": "bun run compile:windows:x64", "compile:windows": "bun run compile:windows:x64",
"compile:windows:x64": "bun scripts/compile.ts --target bun-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",
"db:migrate": "drizzle-kit migrate",
"db:push": "drizzle-kit push",
"db:studio": "drizzle-kit studio",
"dev": "bunx --bun vite dev", "dev": "bunx --bun vite dev",
"fix": "biome check --write", "fix": "biome check --write",
"seed": "bun scripts/seed.ts",
"test": "bun test", "test": "bun test",
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@logtape/drizzle-orm": "^2.0.5",
"@logtape/logtape": "^2.0.5", "@logtape/logtape": "^2.0.5",
"@logtape/pretty": "^2.0.5", "@logtape/pretty": "^2.0.5",
"@orpc/client": "^1.14.0", "@orpc/client": "^1.14.0",
@@ -46,9 +40,8 @@
"@tanstack/react-router-ssr-query": "^1.166.11", "@tanstack/react-router-ssr-query": "^1.166.11",
"@tanstack/react-start": "^1.167.48", "@tanstack/react-start": "^1.167.48",
"citty": "^0.2.2", "citty": "^0.2.2",
"drizzle-orm": "0.45.2", "drizzle-orm": "^0.45.2",
"drizzle-zod": "^0.8.3", "mysql2": "^3.22.3",
"postgres": "^3.4.9",
"react": "^19.2.5", "react": "^19.2.5",
"react-dom": "^19.2.5", "react-dom": "^19.2.5",
"zod": "^4.3.6" "zod": "^4.3.6"
@@ -62,7 +55,7 @@
"@tanstack/react-router-devtools": "^1.166.13", "@tanstack/react-router-devtools": "^1.166.13",
"@types/bun": "^1.3.13", "@types/bun": "^1.3.13",
"@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-react": "^6.0.1",
"drizzle-kit": "0.31.10", "drizzle-seed": "^0.3.1",
"nitro": "npm:nitro-nightly@3.0.1-20260424-182106-f8cf6ccc", "nitro": "npm:nitro-nightly@3.0.1-20260424-182106-f8cf6ccc",
"tailwindcss": "^4.2.4", "tailwindcss": "^4.2.4",
"typescript": "^6.0.3", "typescript": "^6.0.3",
-51
View File
@@ -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)
})
+116
View File
@@ -0,0 +1,116 @@
import { reset } from 'drizzle-seed'
import { drizzle } from 'drizzle-orm/mysql2'
import { datetime, index, int, mysqlTable, tinyint, varchar } from 'drizzle-orm/mysql-core'
import mysql from 'mysql2/promise'
type SeedRow = {
userId: number
mac: string
devModel: string
devName: string
isLowPower: 'true' | 'false'
powerStatus: 0 | 1 | 2
power: number
createTime: Date
remark: string | null
}
const lsBatteryInfo = mysqlTable(
'ls_battery_info',
{
id: int('id').autoincrement().primaryKey(),
userId: int('user_id').notNull(),
mac: varchar('mac', { length: 50 }).notNull(),
devModel: varchar('dev_model', { length: 20 }).notNull(),
devName: varchar('dev_name', { length: 50 }).notNull(),
isLowPower: varchar('is_low_power', { length: 10 }).notNull(),
powerStatus: tinyint('power_status').notNull(),
power: tinyint('power').notNull(),
createTime: datetime('create_time').notNull(),
remark: varchar('remark', { length: 500 }),
},
(table) => [index('idx_ls_battery_info_mac_time_id').on(table.mac, table.createTime, table.id)],
)
const databaseUrl = process.env.DATABASE_URL
if (!databaseUrl) {
throw new Error('DATABASE_URL is required, for example mysql://battery:battery@localhost:3306/battery_soh')
}
const parsedUrl = new URL(databaseUrl)
const safeSeedHosts = new Set(['localhost', '127.0.0.1', '0.0.0.0', 'db', 'mysql'])
if (!safeSeedHosts.has(parsedUrl.hostname) && process.env.SEED_ALLOW_REMOTE !== 'true') {
throw new Error(
`Refusing to seed non-local MySQL host "${parsedUrl.hostname}". Set SEED_ALLOW_REMOTE=true only for disposable test databases.`,
)
}
const devices = [
{ mac: 'RING-A03', model: 'SR-01', name: '样机-A03', basePower: 96, status: 2, remark: 'v3.8.2' },
{ mac: 'RING-B11', model: 'SR-01', name: '样机-B11', basePower: 91, status: 1, remark: 'v3.8.2' },
{ mac: 'RING-C07', model: 'SR-02', name: '样机-C07', basePower: 88, status: 0, remark: 'v3.8.1' },
{ mac: 'RING-D19', model: 'SR-02', name: '样机-D19', basePower: 84, status: 0, remark: 'v3.7.9' },
{ mac: 'RING-E21', model: 'SR-03', name: '样机-E21', basePower: 79, status: 1, remark: 'v3.7.9' },
{ mac: 'RING-F02', model: 'SR-03', name: '样机-F02', basePower: 73, status: 0, remark: null },
{ mac: 'RING-G15', model: 'SR-04', name: '样机-G15', basePower: 93, status: 2, remark: 'v3.9.0' },
{ mac: 'RING-H09', model: 'SR-04', name: '样机-H09', basePower: 86, status: 0, remark: 'v3.8.1' },
] satisfies Array<{
mac: string
model: string
name: string
basePower: number
status: 0 | 1 | 2
remark: string | null
}>
function createSeedRows(now = new Date()): SeedRow[] {
return devices.flatMap((device, deviceIndex) =>
Array.from({ length: 8 }, (_, historyIndex) => {
const createdAt = new Date(now.getTime() - (historyIndex * 24 + deviceIndex * 2) * 60 * 60 * 1000)
const power = Math.max(1, Math.min(100, device.basePower - historyIndex * 2 + (deviceIndex % 3)))
return {
userId: 1001 + (deviceIndex % 3),
mac: device.mac,
devModel: device.model,
devName: device.name,
isLowPower: power <= 20 || device.basePower <= 80 ? 'true' : 'false',
powerStatus: historyIndex === 0 ? device.status : 0,
power,
createTime: createdAt,
remark: device.remark,
}
}),
)
}
const connection = await mysql.createConnection({ uri: databaseUrl })
const db = drizzle(connection)
try {
await db.execute(`
CREATE TABLE IF NOT EXISTS ls_battery_info (
id int(11) NOT NULL AUTO_INCREMENT,
user_id int(11) NOT NULL,
mac varchar(50) NOT NULL,
dev_model varchar(20) NOT NULL,
dev_name varchar(50) NOT NULL,
is_low_power varchar(10) NOT NULL,
power_status tinyint(4) NOT NULL,
power tinyint(4) NOT NULL,
create_time datetime NOT NULL,
remark varchar(500) DEFAULT NULL,
PRIMARY KEY (id),
KEY idx_ls_battery_info_mac_time_id (mac, create_time, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`)
await reset(db, { lsBatteryInfo })
await db.insert(lsBatteryInfo).values(createSeedRows())
process.stdout.write(`Seeded ${devices.length} devices into ls_battery_info.\n`)
} finally {
await connection.end()
}
+1 -2
View File
@@ -4,7 +4,7 @@ import { name, version } from '#package'
// IMPORTANT: keep this file's static imports minimal. Nitro's bun preset // 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 // 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 // eager (transitive) import of it would start the HTTP server even for
// `migrate` or `--help`. All subcommands are lazy-loaded via citty. // `--help`. All subcommands are lazy-loaded via citty.
const main = defineCommand({ const main = defineCommand({
meta: { meta: {
name, name,
@@ -14,7 +14,6 @@ const main = defineCommand({
default: 'serve', default: 'serve',
subCommands: { subCommands: {
serve: () => import('@/cli/serve').then((m) => m.default), serve: () => import('@/cli/serve').then((m) => m.default),
migrate: () => import('@/cli/migrate').then((m) => m.default),
}, },
}) })
-84
View File
@@ -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()
}
},
})
-7
View File
@@ -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() })
}
-41
View File
@@ -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>
)
}
-77
View File
@@ -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>
)
}
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, test } from 'bun:test'
import { createBatteriesResponse, createDashboardSnapshot, getDeviceStatus, toBatteryInfo } from './battery'
const rows = [
{
id: 1,
userId: 7,
mac: 'RING-A03',
devModel: '2401-A',
devName: 'RING-A03',
isLowPower: 'false',
powerStatus: 2,
power: 94,
createTime: new Date('2026-05-10T23:00:00.000Z'),
remark: 'v3.8.2',
},
{
id: 2,
userId: 7,
mac: 'RING-B11',
devModel: '2402-B',
devName: 'RING-B11',
isLowPower: 'true',
powerStatus: 1,
power: 84,
createTime: '2026-05-10 22:00:00',
remark: null,
},
]
describe('battery domain', () => {
test('preserves legacy SOH status thresholds', () => {
expect(getDeviceStatus(91)).toBe('健康')
expect(getDeviceStatus(90)).toBe('关注')
expect(getDeviceStatus(85)).toBe('预警')
})
test('builds batteries response counters from records', () => {
const now = new Date('2026-05-11T00:00:00.000Z')
const items = rows.map(toBatteryInfo)
const response = createBatteriesResponse(items, now)
expect(response.updatedAt).toBe('2026-05-11T00:00:00.000Z')
expect(response.total).toBe(items.length)
expect(response.lowPower).toBe(1)
expect(response.charging).toBe(1)
expect(response.items[0]?.createTime).toBe('2026-05-10T23:00:00.000Z')
})
test('creates old dashboard aggregate shape from deterministic records', () => {
const now = new Date('2026-05-11T00:00:00.000Z')
const snapshot = createDashboardSnapshot(rows.map(toBatteryInfo), now)
expect(snapshot.devices).toHaveLength(2)
expect(snapshot.soh.history).toHaveLength(12)
expect(snapshot.soh.forecast).toHaveLength(4)
expect(snapshot.summary.totalDevices).toBe(snapshot.devices.length)
expect(snapshot.summary.warningCount + snapshot.summary.watchCount + snapshot.summary.healthyCount).toBe(
snapshot.devices.length,
)
})
})
+354
View File
@@ -0,0 +1,354 @@
import { z } from 'zod'
export const powerStatusSchema = z.union([z.literal(0), z.literal(1), z.literal(2)])
export type PowerStatus = z.infer<typeof powerStatusSchema>
export const deviceStatusSchema = z.union([z.literal('健康'), z.literal('关注'), z.literal('预警')])
export type DeviceStatus = z.infer<typeof deviceStatusSchema>
export const batteryInfoSchema = z.object({
id: z.number().int(),
userId: z.number().int(),
mac: z.string(),
devModel: z.string(),
devName: z.string(),
isLowPower: z.boolean(),
powerStatus: powerStatusSchema,
power: z.number().int().min(0).max(100),
createTime: z.string(),
remark: z.string().nullable(),
})
export type BatteryInfo = z.infer<typeof batteryInfoSchema>
export const fleetUnitSchema = z.object({
id: z.string(),
batch: z.string(),
firmware: z.string(),
cycles: z.number().int(),
soh: z.number(),
soh30d: z.number(),
soh60d: z.number(),
soh90d: z.number(),
temperature: z.number(),
riskScore: z.number().int(),
chargeEfficiency: z.number(),
status: deviceStatusSchema,
riskFactors: z.array(z.string()),
})
export type FleetUnit = z.infer<typeof fleetUnitSchema>
export const sohPointSchema = z.object({ month: z.string(), value: z.number() })
export const sohResponseSchema = z.object({
history: z.array(sohPointSchema),
forecast: z.array(sohPointSchema),
})
export const eventItemSchema = z.object({
time: z.string(),
title: z.string(),
detail: z.string(),
severity: z.union([z.literal('高'), z.literal('中'), z.literal('低')]),
})
export const strategyItemSchema = z.object({
name: z.string(),
impact: z.string(),
scope: z.string(),
eta: z.string(),
})
export const summaryResponseSchema = z.object({
totalDevices: z.number().int(),
avgSoh: z.number(),
avgSoh30d: z.number(),
avgSoh90d: z.number(),
warningCount: z.number().int(),
watchCount: z.number().int(),
healthyCount: z.number().int(),
batchPerformance: z.array(z.object({ batch: z.string(), avgSoh: z.number() })),
riskFactorCounts: z.array(z.object({ factor: z.string(), count: z.number().int() })),
firmwareHealth: z.array(z.object({ firmware: z.string(), avgSoh: z.number(), count: z.number().int() })),
updatedAt: z.string(),
executiveSummary: z.string(),
})
export const dashboardSnapshotSchema = z.object({
devices: z.array(fleetUnitSchema),
soh: sohResponseSchema,
events: z.array(eventItemSchema),
strategies: z.array(strategyItemSchema),
summary: summaryResponseSchema,
})
export type DashboardSnapshot = z.infer<typeof dashboardSnapshotSchema>
export const batteriesResponseSchema = z.object({
updatedAt: z.string(),
total: z.number().int(),
lowPower: z.number().int(),
charging: z.number().int(),
items: z.array(batteryInfoSchema),
})
export type BatteriesResponse = z.infer<typeof batteriesResponseSchema>
const round1 = (value: number) => Math.round(value * 10) / 10
const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value))
const pad2 = (value: number) => value.toString().padStart(2, '0')
const addMonths = (date: Date, months: number) =>
new Date(date.getFullYear(), date.getMonth() + months, date.getDate(), date.getHours(), 0, 0, 0)
const addHours = (date: Date, hours: number) => new Date(date.getTime() + hours * 60 * 60 * 1000)
const formatMonthLabel = (date: Date) => `${date.getFullYear().toString().slice(-2)}.${pad2(date.getMonth() + 1)}`
const formatDateTime = (date: Date) =>
`${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`
const formatEventTime = (date: Date) =>
`${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}`
export function getDeviceStatus(soh: number): DeviceStatus {
if (soh <= 85) return '预警'
if (soh <= 90) return '关注'
return '健康'
}
export function normalizePowerStatus(value: number): PowerStatus {
if (value === 1 || value === 2) return value
return 0
}
export function normalizeLowPower(value: string | boolean): boolean {
if (typeof value === 'boolean') return value
return value.toLowerCase() === 'true'
}
export type BatteryInfoSourceRow = {
id: number
userId: number
mac: string
devModel: string
devName: string
isLowPower: string | boolean
powerStatus: number
power: number
createTime: Date | string
remark: string | null
}
export function toBatteryInfo(row: BatteryInfoSourceRow): BatteryInfo {
return {
id: row.id,
userId: row.userId,
mac: row.mac,
devModel: row.devModel,
devName: row.devName,
isLowPower: normalizeLowPower(row.isLowPower),
powerStatus: normalizePowerStatus(row.powerStatus),
power: row.power,
createTime: row.createTime instanceof Date ? row.createTime.toISOString() : String(row.createTime),
remark: row.remark,
}
}
export function createBatteriesResponse(items: BatteryInfo[], now = new Date()): BatteriesResponse {
return {
updatedAt: now.toISOString(),
total: items.length,
lowPower: items.filter((item) => item.isLowPower).length,
charging: items.filter((item) => item.powerStatus === 1).length,
items,
}
}
function toFleetUnit(item: BatteryInfo, index: number): FleetUnit {
const soh = item.power
const status = getDeviceStatus(soh)
const riskFactors: string[] = []
if (item.isLowPower || item.power <= 20) riskFactors.push('低电量')
if (item.powerStatus === 1) riskFactors.push('充电中')
if (status === '预警') riskFactors.push('衰减加速')
if (item.remark?.includes('v3.7')) riskFactors.push('旧固件')
const thermalPressure = index % 3
const soh30d = round1(clamp(soh - 0.8 - thermalPressure * 0.25, 0, 100))
const soh60d = round1(clamp(soh - 1.7 - thermalPressure * 0.35, 0, 100))
const soh90d = round1(clamp(soh - 2.8 - thermalPressure * 0.45, 0, 100))
const temperature = round1(29.5 + thermalPressure * 2.1 + (item.isLowPower ? 1.4 : 0))
const chargeEfficiency = round1(clamp(91 + item.power / 12 - riskFactors.length * 1.8, 80, 98))
const riskScore = Math.round(clamp(12 + (100 - soh) * 1.45 + riskFactors.length * 8 + thermalPressure * 4, 8, 96))
return {
id: item.devName || item.mac,
batch: item.devModel,
firmware: item.remark ?? 'unknown',
cycles: 120 + index * 17 + Math.round((100 - soh) * 2.2),
soh,
soh30d,
soh60d,
soh90d,
temperature,
riskScore,
chargeEfficiency,
status,
riskFactors,
}
}
function createSohResponse(devices: FleetUnit[], now: Date) {
if (devices.length === 0) return { history: [], forecast: [] }
const avgSoh = devices.reduce((sum, unit) => sum + unit.soh, 0) / devices.length
const monthlyDrop = 0.45 + devices.reduce((sum, unit) => sum + unit.riskScore, 0) / devices.length / 160
const history = Array.from({ length: 12 }, (_, index) => {
const monthOffset = index - 11
return {
month: formatMonthLabel(addMonths(now, monthOffset)),
value: round1(clamp(avgSoh + Math.abs(monthOffset) * monthlyDrop, avgSoh, 100)),
}
})
const currentValue = history.at(-1)?.value ?? round1(avgSoh)
const forecast = Array.from({ length: 4 }, (_, index) => ({
month: formatMonthLabel(addMonths(now, index)),
value: index === 0 ? currentValue : round1(clamp(avgSoh - monthlyDrop * index, 0, 100)),
}))
return { history, forecast }
}
function summarizeBy<T extends string>(items: FleetUnit[], getKey: (item: FleetUnit) => T) {
return Object.entries(
items.reduce<Record<string, { sum: number; count: number }>>((acc, item) => {
const key = getKey(item)
const entry = acc[key] ?? { sum: 0, count: 0 }
entry.sum += item.soh
entry.count += 1
acc[key] = entry
return acc
}, {}),
)
}
function createSummary(devices: FleetUnit[], now: Date) {
const totalDevices = devices.length
if (totalDevices === 0) {
return {
totalDevices,
avgSoh: 0,
avgSoh30d: 0,
avgSoh90d: 0,
warningCount: 0,
watchCount: 0,
healthyCount: 0,
batchPerformance: [],
riskFactorCounts: [],
firmwareHealth: [],
updatedAt: formatDateTime(now),
executiveSummary: '当前没有可用于电池健康分析的真实设备记录。',
}
}
const avgSoh = devices.reduce((sum, unit) => sum + unit.soh, 0) / totalDevices
const avgSoh30d = devices.reduce((sum, unit) => sum + unit.soh30d, 0) / totalDevices
const avgSoh90d = devices.reduce((sum, unit) => sum + unit.soh90d, 0) / totalDevices
const warningCount = devices.filter((unit) => unit.status === '预警').length
const watchCount = devices.filter((unit) => unit.status === '关注').length
const healthyCount = devices.filter((unit) => unit.status === '健康').length
const batchPerformance = summarizeBy(devices, (unit) => unit.batch)
.map(([batch, data]) => ({ batch, avgSoh: round1(data.sum / data.count) }))
.sort((a, b) => b.avgSoh - a.avgSoh)
const firmwareHealth = summarizeBy(devices, (unit) => unit.firmware)
.map(([firmware, data]) => ({ firmware, avgSoh: round1(data.sum / data.count), count: data.count }))
.sort((a, b) => b.avgSoh - a.avgSoh)
const riskFactorCounts = Object.entries(
devices.reduce<Record<string, number>>((acc, unit) => {
for (const factor of unit.riskFactors) {
acc[factor] = (acc[factor] ?? 0) + 1
}
return acc
}, {}),
)
.map(([factor, count]) => ({ factor, count }))
.sort((a, b) => b.count - a.count)
const weakestBatch = batchPerformance.at(-1)?.batch ?? '当前设备'
const weakestFirmware = firmwareHealth.at(-1)?.firmware ?? 'unknown'
return {
totalDevices,
avgSoh: round1(avgSoh),
avgSoh30d: round1(avgSoh30d),
avgSoh90d: round1(avgSoh90d),
warningCount,
watchCount,
healthyCount,
batchPerformance,
riskFactorCounts,
firmwareHealth,
updatedAt: formatDateTime(now),
executiveSummary: `当前电池健康度总体可控,重点风险集中在 ${weakestBatch} 批次与 ${weakestFirmware} 固件设备。建议优先跟踪低电量、充电状态与未来 90 天 SoH 变化。`,
}
}
function createEvents(devices: FleetUnit[], now: Date) {
const sortedDevices = devices.slice().sort((a, b) => b.riskScore - a.riskScore)
const first = sortedDevices[0]
if (!first) return []
const second = sortedDevices[1] ?? first
return [
{
time: formatEventTime(addHours(now, -2)),
title: `${first.id} 进入重点观察队列`,
detail: `${first.id} 当前 SoH 为 ${first.soh.toFixed(1)}%,综合风险评分 ${first.riskScore}`,
severity: first.status === '预警' ? '高' : '中',
},
{
time: formatEventTime(addHours(now, -5)),
title: `${second.batch} 批次健康度趋势更新`,
detail: `${second.batch} 批次未来 90 天预测 SoH 为 ${second.soh90d.toFixed(1)}%。`,
severity: second.status === '健康' ? '低' : '中',
},
] satisfies DashboardSnapshot['events']
}
function createStrategies(devices: FleetUnit[]) {
if (devices.length === 0) return []
const warningDevices = devices.filter((unit) => unit.status === '预警')
const chargingDevices = devices.filter((unit) => unit.riskFactors.includes('充电中'))
const first = devices.slice().sort((a, b) => b.riskScore - a.riskScore)[0]
return [
{
name: '预警设备优先维护',
impact: `预计高风险设备减少 ${Math.max(10, warningDevices.length * 12)}%`,
scope: first ? `${first.id}${Math.max(1, warningDevices.length)} 台设备` : '当前设备',
eta: '48 小时内完成',
},
{
name: '充电策略复核',
impact: `覆盖 ${Math.max(1, chargingDevices.length)} 台充电中设备`,
scope: '充电中与低电量设备',
eta: '本周完成首轮验证',
},
] satisfies DashboardSnapshot['strategies']
}
export function createDashboardSnapshot(items: BatteryInfo[], now = new Date()): DashboardSnapshot {
const devices = items.map(toFleetUnit)
return {
devices,
soh: createSohResponse(devices, now),
events: createEvents(devices, now),
strategies: createStrategies(devices),
summary: createSummary(devices, now),
}
}
+1 -1
View File
@@ -3,7 +3,7 @@ import { z } from 'zod'
export const env = createEnv({ export const env = createEnv({
server: { server: {
DATABASE_URL: z.url({ protocol: /^postgres(ql)?$/ }), DATABASE_URL: z.url({ protocol: /^mysql$/ }),
LOG_DB: z.stringbool().default(false), LOG_DB: z.stringbool().default(false),
LOG_FORMAT: z.enum(['pretty', 'json']).optional(), LOG_FORMAT: z.enum(['pretty', 'json']).optional(),
LOG_LEVEL: z.enum(['trace', 'debug', 'info', 'warning', 'error', 'fatal']).default('info'), LOG_LEVEL: z.enum(['trace', 'debug', 'info', 'warning', 'error', 'fatal']).default('info'),
+21 -3
View File
@@ -10,6 +10,7 @@
import { Route as rootRouteImport } from './routes/__root' import { Route as rootRouteImport } from './routes/__root'
import { Route as HealthRouteImport } from './routes/health' import { Route as HealthRouteImport } from './routes/health'
import { Route as BatteriesRouteImport } from './routes/batteries'
import { Route as IndexRouteImport } from './routes/index' import { Route as IndexRouteImport } from './routes/index'
import { Route as ApiSplatRouteImport } from './routes/api/$' import { Route as ApiSplatRouteImport } from './routes/api/$'
import { Route as ApiRpcSplatRouteImport } from './routes/api/rpc.$' import { Route as ApiRpcSplatRouteImport } from './routes/api/rpc.$'
@@ -19,6 +20,11 @@ const HealthRoute = HealthRouteImport.update({
path: '/health', path: '/health',
getParentRoute: () => rootRouteImport, getParentRoute: () => rootRouteImport,
} as any) } as any)
const BatteriesRoute = BatteriesRouteImport.update({
id: '/batteries',
path: '/batteries',
getParentRoute: () => rootRouteImport,
} as any)
const IndexRoute = IndexRouteImport.update({ const IndexRoute = IndexRouteImport.update({
id: '/', id: '/',
path: '/', path: '/',
@@ -37,12 +43,14 @@ const ApiRpcSplatRoute = ApiRpcSplatRouteImport.update({
export interface FileRoutesByFullPath { export interface FileRoutesByFullPath {
'/': typeof IndexRoute '/': typeof IndexRoute
'/batteries': typeof BatteriesRoute
'/health': typeof HealthRoute '/health': typeof HealthRoute
'/api/$': typeof ApiSplatRoute '/api/$': typeof ApiSplatRoute
'/api/rpc/$': typeof ApiRpcSplatRoute '/api/rpc/$': typeof ApiRpcSplatRoute
} }
export interface FileRoutesByTo { export interface FileRoutesByTo {
'/': typeof IndexRoute '/': typeof IndexRoute
'/batteries': typeof BatteriesRoute
'/health': typeof HealthRoute '/health': typeof HealthRoute
'/api/$': typeof ApiSplatRoute '/api/$': typeof ApiSplatRoute
'/api/rpc/$': typeof ApiRpcSplatRoute '/api/rpc/$': typeof ApiRpcSplatRoute
@@ -50,20 +58,22 @@ export interface FileRoutesByTo {
export interface FileRoutesById { export interface FileRoutesById {
__root__: typeof rootRouteImport __root__: typeof rootRouteImport
'/': typeof IndexRoute '/': typeof IndexRoute
'/batteries': typeof BatteriesRoute
'/health': typeof HealthRoute '/health': typeof HealthRoute
'/api/$': typeof ApiSplatRoute '/api/$': typeof ApiSplatRoute
'/api/rpc/$': typeof ApiRpcSplatRoute '/api/rpc/$': typeof ApiRpcSplatRoute
} }
export interface FileRouteTypes { export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/' | '/health' | '/api/$' | '/api/rpc/$' fullPaths: '/' | '/batteries' | '/health' | '/api/$' | '/api/rpc/$'
fileRoutesByTo: FileRoutesByTo fileRoutesByTo: FileRoutesByTo
to: '/' | '/health' | '/api/$' | '/api/rpc/$' to: '/' | '/batteries' | '/health' | '/api/$' | '/api/rpc/$'
id: '__root__' | '/' | '/health' | '/api/$' | '/api/rpc/$' id: '__root__' | '/' | '/batteries' | '/health' | '/api/$' | '/api/rpc/$'
fileRoutesById: FileRoutesById fileRoutesById: FileRoutesById
} }
export interface RootRouteChildren { export interface RootRouteChildren {
IndexRoute: typeof IndexRoute IndexRoute: typeof IndexRoute
BatteriesRoute: typeof BatteriesRoute
HealthRoute: typeof HealthRoute HealthRoute: typeof HealthRoute
ApiSplatRoute: typeof ApiSplatRoute ApiSplatRoute: typeof ApiSplatRoute
ApiRpcSplatRoute: typeof ApiRpcSplatRoute ApiRpcSplatRoute: typeof ApiRpcSplatRoute
@@ -78,6 +88,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof HealthRouteImport preLoaderRoute: typeof HealthRouteImport
parentRoute: typeof rootRouteImport parentRoute: typeof rootRouteImport
} }
'/batteries': {
id: '/batteries'
path: '/batteries'
fullPath: '/batteries'
preLoaderRoute: typeof BatteriesRouteImport
parentRoute: typeof rootRouteImport
}
'/': { '/': {
id: '/' id: '/'
path: '/' path: '/'
@@ -104,6 +121,7 @@ declare module '@tanstack/react-router' {
const rootRouteChildren: RootRouteChildren = { const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute, IndexRoute: IndexRoute,
BatteriesRoute: BatteriesRoute,
HealthRoute: HealthRoute, HealthRoute: HealthRoute,
ApiSplatRoute: ApiSplatRoute, ApiSplatRoute: ApiSplatRoute,
ApiRpcSplatRoute: ApiRpcSplatRoute, ApiRpcSplatRoute: ApiRpcSplatRoute,
+119
View File
@@ -0,0 +1,119 @@
import { useSuspenseQuery } from '@tanstack/react-query'
import { createFileRoute, Link } from '@tanstack/react-router'
import { orpc } from '@/client/orpc'
import type { BatteryInfo } from '@/domain/battery'
export const Route = createFileRoute('/batteries')({
component: BatteriesPage,
loader: async ({ context }) => {
await context.queryClient.ensureQueryData(orpc.battery.batteries.queryOptions({ input: {} }))
},
errorComponent: ({ error }) => (
<main className="flex min-h-screen items-center justify-center bg-[#09090B]">
<div className="text-center">
<p className="text-lg text-red-400"></p>
<p className="mt-2 text-sm text-zinc-500">{error.message}</p>
</div>
</main>
),
})
const powerStatusLabel: Record<0 | 1 | 2, string> = {
0: '未充电',
1: '充电中',
2: '已充满',
}
const powerStatusColor: Record<0 | 1 | 2, string> = {
0: 'text-zinc-400',
1: 'text-teal-400',
2: 'text-emerald-400',
}
function powerBarColor(power: number, isLowPower: boolean): string {
if (isLowPower || power <= 20) return 'bg-red-500'
if (power <= 50) return 'bg-amber-500'
return 'bg-teal-500'
}
function DeviceCard({ item }: { item: BatteryInfo }) {
return (
<article className="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<header className="flex items-start justify-between">
<div>
<h3 className="font-medium text-zinc-100">{item.devName}</h3>
<p className="mt-0.5 text-xs text-zinc-500">{item.mac}</p>
</div>
<span className="rounded bg-zinc-900 px-2 py-0.5 text-xs text-zinc-400">{item.devModel}</span>
</header>
<div className="mt-4">
<div className="flex items-baseline justify-between">
<span className="font-semibold text-2xl text-zinc-100">
{item.power}
<span className="ml-0.5 font-normal text-sm text-zinc-500">%</span>
</span>
<span className={`text-xs ${powerStatusColor[item.powerStatus]}`}>{powerStatusLabel[item.powerStatus]}</span>
</div>
<div className="mt-2 h-1.5 overflow-hidden rounded-full bg-zinc-800">
<div className={`h-full ${powerBarColor(item.power, item.isLowPower)}`} style={{ width: `${item.power}%` }} />
</div>
</div>
<footer className="mt-4 flex items-center justify-between text-xs text-zinc-500">
<span> {new Date(item.createTime).toLocaleString('zh-CN')}</span>
{item.isLowPower && <span className="rounded bg-red-950 px-1.5 py-0.5 text-red-400"></span>}
</footer>
</article>
)
}
function BatteriesPage() {
const { data } = useSuspenseQuery(
orpc.battery.batteries.queryOptions({
input: {},
refetchInterval: 30_000,
}),
)
return (
<main className="min-h-screen bg-[#09090B] px-6 py-8 text-zinc-100">
<header className="mx-auto max-w-7xl">
<div className="flex items-end justify-between">
<div>
<h1 className="font-semibold text-2xl"></h1>
<p className="mt-1 text-sm text-zinc-500"> {new Date(data.updatedAt).toLocaleString('zh-CN')}</p>
</div>
<nav className="text-xs">
<Link to="/" className="text-zinc-500 hover:text-zinc-300">
SoH
</Link>
</nav>
</div>
<dl className="mt-6 grid grid-cols-3 gap-4">
<div className="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<dt className="text-xs text-zinc-500"></dt>
<dd className="mt-1 font-semibold text-2xl">{data.total}</dd>
</div>
<div className="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<dt className="text-xs text-zinc-500"></dt>
<dd className="mt-1 font-semibold text-2xl text-red-400">{data.lowPower}</dd>
</div>
<div className="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<dt className="text-xs text-zinc-500"></dt>
<dd className="mt-1 font-semibold text-2xl text-teal-400">{data.charging}</dd>
</div>
</dl>
</header>
<section className="mx-auto mt-8 grid max-w-7xl grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{data.items.length > 0 ? (
data.items.map((item) => <DeviceCard key={item.id} item={item} />)
) : (
<div className="col-span-full py-12 text-center text-zinc-500"></div>
)}
</section>
</main>
)
}
+615 -70
View File
@@ -1,87 +1,632 @@
import { useMutation, useSuspenseQuery } from '@tanstack/react-query' import { useSuspenseQuery } from '@tanstack/react-query'
import { createFileRoute } from '@tanstack/react-router' import { createFileRoute, Link } from '@tanstack/react-router'
import { orpc } from '@/client/orpc' import { orpc } from '@/client/orpc'
import { useInvalidateTodos } from '@/client/queries/todo' import type { DashboardSnapshot, DeviceStatus } from '@/domain/battery'
import { TodoForm } from '@/components/TodoForm'
import { TodoItem } from '@/components/TodoItem'
export const Route = createFileRoute('/')({ export const Route = createFileRoute('/')({
component: Todos, component: Dashboard,
loader: async ({ context }) => { loader: async ({ context }) => {
await context.queryClient.ensureQueryData(orpc.todo.list.queryOptions()) await context.queryClient.ensureQueryData(orpc.battery.dashboard.queryOptions())
}, },
errorComponent: ({ error }) => (
<main className="flex min-h-screen items-center justify-center bg-[#09090B]">
<div className="text-center">
<p className="text-lg text-red-400"></p>
<p className="mt-2 text-sm text-[#71717A]">{error.message}</p>
</div>
</main>
),
}) })
function Todos() { function buildChartData(soh: DashboardSnapshot['soh']) {
const listQuery = useSuspenseQuery(orpc.todo.list.queryOptions()) const chartData: { month: string; history?: number; forecast?: number }[] = soh.history.map((h) => ({
const invalidateTodos = useInvalidateTodos() month: h.month,
history: h.value,
forecast: undefined,
}))
const createMutation = useMutation(orpc.todo.create.mutationOptions({ onSuccess: invalidateTodos })) if (chartData.length > 0 && soh.forecast.length > 0) {
const updateMutation = useMutation(orpc.todo.update.mutationOptions({ onSuccess: invalidateTodos })) // Overlap: last history point is also first forecast point
const deleteMutation = useMutation(orpc.todo.remove.mutationOptions({ onSuccess: invalidateTodos })) const last = chartData[chartData.length - 1]
if (last) {
last.forecast = soh.forecast[0]?.value
}
}
const todos = listQuery.data for (let i = 1; i < soh.forecast.length; i++) {
const completedCount = todos.filter((todo) => todo.completed).length const f = soh.forecast[i]
const totalCount = todos.length if (f) {
const progress = totalCount > 0 ? (completedCount / totalCount) * 100 : 0 chartData.push({
month: f.month,
history: undefined,
forecast: f.value,
})
}
}
return chartData
}
const statusColorMap: Record<DeviceStatus, string> = {
: 'text-emerald-400',
: 'text-amber-400',
: 'text-red-400',
}
const severityColorMap: Record<DashboardSnapshot['events'][number]['severity'], string> = {
: 'text-red-400',
: 'text-amber-400',
: 'text-zinc-400',
}
function SimpleChart({ data }: { data: ReturnType<typeof buildChartData> }) {
if (data.length === 0) {
return <div className="flex h-full items-center justify-center text-[#71717A]"></div>
}
const minVal = Math.floor(Math.min(...data.map((d) => Math.min(d.history ?? 100, d.forecast ?? 100)))) - 2
const maxVal = Math.ceil(Math.max(...data.map((d) => Math.max(d.history ?? 0, d.forecast ?? 0)))) + 2
const range = maxVal - minVal
const width = 1000
const height = 280
const padding = { top: 20, right: 20, bottom: 30, left: 40 }
const innerWidth = width - padding.left - padding.right
const innerHeight = height - padding.top - padding.bottom
const getX = (index: number) => padding.left + (index / (data.length - 1)) * innerWidth
const getY = (val: number) => padding.top + innerHeight - ((val - minVal) / range) * innerHeight
const historyPoints = data
.map((d, i) => (d.history !== undefined ? `${getX(i)},${getY(d.history)}` : null))
.filter(Boolean)
.join(' ')
const forecastPoints = data
.map((d, i) => (d.forecast !== undefined ? `${getX(i)},${getY(d.forecast)}` : null))
.filter(Boolean)
.join(' ')
const lastHistoryIndex = data.findLastIndex((d) => d.history !== undefined)
const historyArea = historyPoints
? `${historyPoints} ${getX(lastHistoryIndex)},${padding.top + innerHeight} ${getX(0)},${padding.top + innerHeight}`
: ''
const forecastStartIndex = data.findIndex((d) => d.forecast !== undefined)
const forecastArea = forecastPoints
? `${forecastPoints} ${getX(data.length - 1)},${padding.top + innerHeight} ${getX(forecastStartIndex)},${padding.top + innerHeight}`
: ''
return ( 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">
<div className="flex items-end justify-between">
<div>
<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">
<div className="text-2xl font-semibold text-slate-900">
{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>
</div>
<TodoForm onSubmit={(title) => createMutation.mutate({ title })} isPending={createMutation.isPending} />
{totalCount > 0 && (
<div className="h-1.5 w-full bg-slate-200 rounded-full overflow-hidden">
<div
className="h-full bg-indigo-500 transition-all duration-500 ease-out rounded-full"
style={{ width: `${progress}%` }}
/>
</div>
)}
<div className="space-y-3">
{todos.length === 0 ? (
<div className="py-20 text-center">
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-slate-100 mb-4">
<svg <svg
className="w-8 h-8 text-slate-400" viewBox={`0 0 ${width} ${height}`}
fill="none" className="w-full h-full overflow-visible"
viewBox="0 0 24 24" role="img"
stroke="currentColor" aria-label="SoH Trend Chart"
aria-hidden="true"
> >
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 6v6m0 0v6m0-6h6m-6 0H6" /> <title>SoH Trend Chart</title>
</svg> <defs>
</div> <linearGradient id="historyFill" x1="0" y1="0" x2="0" y2="1">
<p className="text-slate-500 text-lg font-medium"></p> <stop offset="0%" stopColor="#2DD4BF" stopOpacity={0.15} />
<p className="text-slate-400 text-sm mt-1"></p> <stop offset="100%" stopColor="#2DD4BF" stopOpacity={0} />
</div> </linearGradient>
) : ( <linearGradient id="forecastFill" x1="0" y1="0" x2="0" y2="1">
todos.map((todo) => ( <stop offset="0%" stopColor="#818CF8" stopOpacity={0.15} />
<TodoItem <stop offset="100%" stopColor="#818CF8" stopOpacity={0} />
key={todo.id} </linearGradient>
todo={todo} </defs>
onToggle={(id, completed) => updateMutation.mutate({ id, data: { completed: !completed } })}
onDelete={(id) => deleteMutation.mutate({ id })} {/* Grid */}
{[0, 0.25, 0.5, 0.75, 1].map((ratio) => {
const y = padding.top + innerHeight * ratio
const val = maxVal - range * ratio
return (
<g key={ratio}>
<line x1={padding.left} y1={y} x2={width - padding.right} y2={y} stroke="#ffffff" strokeOpacity={0.05} />
<text x={padding.left - 10} y={y + 4} fill="#71717A" fontSize="11" textAnchor="end">
{val.toFixed(0)}%
</text>
</g>
)
})}
{/* 85% Reference Line */}
{85 >= minVal && 85 <= maxVal && (
<g>
<line
x1={padding.left}
y1={getY(85)}
x2={width - padding.right}
y2={getY(85)}
stroke="#F87171"
strokeOpacity={0.4}
strokeDasharray="4 4"
/> />
)) <text x={width - padding.right + 10} y={getY(85) + 4} fill="#F87171" fontSize="11">
85% 线
</text>
</g>
)} )}
</div>
</div> {/* X Axis */}
</div> {data.map((d, i) => (
<text key={d.month} x={getX(i)} y={height - 5} fill="#71717A" fontSize="11" textAnchor="middle">
{d.month}
</text>
))}
{/* Areas */}
{historyArea && <polygon points={historyArea} fill="url(#historyFill)" />}
{forecastArea && <polygon points={forecastArea} fill="url(#forecastFill)" />}
{/* Lines */}
{historyPoints && <polyline points={historyPoints} fill="none" stroke="#2DD4BF" strokeWidth="2.5" />}
{forecastPoints && (
<polyline points={forecastPoints} fill="none" stroke="#818CF8" strokeWidth="2.5" strokeDasharray="4 4" />
)}
{/* Dots */}
{data.map((d, i) => {
const dots = []
if (d.history !== undefined) {
dots.push(
<circle
key={`h-${d.month}`}
cx={getX(i)}
cy={getY(d.history)}
r="3"
fill="#09090B"
stroke="#2DD4BF"
strokeWidth="2"
/>,
)
}
if (d.forecast !== undefined) {
dots.push(
<circle
key={`f-${d.month}`}
cx={getX(i)}
cy={getY(d.forecast)}
r="3"
fill="#09090B"
stroke="#818CF8"
strokeWidth="2"
/>,
)
}
return dots
})}
</svg>
)
}
function Dashboard() {
const { data } = useSuspenseQuery(orpc.battery.dashboard.queryOptions())
const { devices, soh, events, strategies, summary } = data
const {
totalDevices,
avgSoh,
avgSoh30d,
avgSoh90d,
warningCount,
watchCount,
healthyCount,
batchPerformance,
riskFactorCounts,
firmwareHealth,
updatedAt,
executiveSummary,
} = summary
const chartData = buildChartData(soh)
return (
<main className="min-h-screen w-full bg-[#09090B] font-sans text-[#F4F4F5]">
{/* Background gradient */}
<div className="pointer-events-none fixed inset-0 z-0 flex justify-center">
<div className="h-[800px] w-[1200px] -translate-y-1/2 rounded-full bg-teal-900/10 blur-[120px]" />
</div>
<div className="relative z-10 mx-auto max-w-[1400px] px-6 pb-24 pt-12 lg:px-12">
{/* Header */}
<header className="animate-fade-up mb-12 flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between">
<div className="max-w-3xl">
<div className="mb-4 inline-flex items-center gap-2 rounded-md border border-white/10 bg-white/5 px-2.5 py-1 text-xs font-medium text-teal-400">
(v2.4)
</div>
<h1 className="text-4xl font-light tracking-tight text-white sm:text-5xl">SoH </h1>
</div>
<div className="flex flex-col items-end gap-3 text-right">
<div className="flex items-center gap-6 text-sm">
<div>
<span className="text-[#71717A]"> (MAE)</span>
<span className="ml-2 font-medium tabular-nums text-teal-400">1.2%</span>
</div>
<div className="h-4 w-px bg-white/10" />
<div>
<span className="text-[#71717A]"></span>
<span className="ml-2 font-medium tabular-nums text-teal-400">94.5%</span>
</div>
</div>
<p className="text-xs tabular-nums text-[#71717A]">: {updatedAt}</p>
<Link to="/batteries" className="text-xs text-teal-400 hover:text-teal-300">
</Link>
</div>
</header>
{/* Executive Summary */}
<section className="animate-fade-up delay-100 mb-12 rounded-xl border border-teal-900/30 bg-teal-950/10 p-6">
<h2 className="mb-3 text-sm font-medium text-teal-400"></h2>
<p className="text-base leading-relaxed text-[#A1A1AA]">{executiveSummary}</p>
</section>
{/* Primary KPI Row */}
<section className="animate-fade-up delay-200 mb-12 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-5">
{/* Hero KPI */}
<article className="relative overflow-hidden rounded-2xl border border-white/10 bg-white/[0.03] p-8 lg:col-span-2">
<div className="absolute inset-x-0 top-0 h-1 bg-gradient-to-r from-teal-500/50 to-transparent" />
<p className="text-sm font-medium text-[#A1A1AA]"> SoH</p>
<div className="mt-4 flex items-baseline gap-2">
<h2 className="text-6xl font-light tabular-nums text-white">{avgSoh.toFixed(1)}</h2>
<span className="text-2xl text-[#71717A]">%</span>
</div>
<div className="mt-6 flex items-center gap-3 text-sm">
<span className="inline-flex items-center gap-1.5 text-emerald-400">
<span className="h-1.5 w-1.5 rounded-full bg-emerald-400" />
线
</span>
<span className="text-[#71717A]">|</span>
<span className="text-[#A1A1AA]"> {totalDevices} </span>
</div>
</article>
{/* Regular KPIs */}
<article className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10">
<p className="text-sm text-[#A1A1AA]">30 </p>
<div className="mt-3 flex items-baseline gap-1">
<h2 className="text-4xl font-light tabular-nums text-white">{avgSoh30d.toFixed(1)}</h2>
<span className="text-lg text-[#71717A]">%</span>
</div>
<div className="mt-4 flex items-center gap-1.5 text-sm">
<span className="text-red-400"></span>
<span className="tabular-nums text-[#A1A1AA]">{(avgSoh - avgSoh30d).toFixed(1)}% </span>
</div>
</article>
<article className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10">
<p className="text-sm text-[#A1A1AA]">90 </p>
<div className="mt-3 flex items-baseline gap-1">
<h2 className="text-4xl font-light tabular-nums text-white">{avgSoh90d.toFixed(1)}</h2>
<span className="text-lg text-[#71717A]">%</span>
</div>
<div className="mt-4 flex items-center gap-1.5 text-sm">
<span className="text-red-400"></span>
<span className="tabular-nums text-[#A1A1AA]">{(avgSoh - avgSoh90d).toFixed(1)}% </span>
</div>
</article>
<article className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10">
<p className="text-sm text-[#A1A1AA]"></p>
<div className="mt-3 flex items-baseline gap-1">
<h2 className="text-4xl font-light tabular-nums text-white">{warningCount}</h2>
<span className="text-lg text-[#71717A]"></span>
</div>
<div className="mt-4 flex items-center gap-1.5 text-sm">
<span className="text-amber-400"></span>
<span className="tabular-nums text-[#A1A1AA]">
{totalDevices > 0 ? ((warningCount / totalDevices) * 100).toFixed(1) : 0}%
</span>
</div>
</article>
</section>
{/* Divider */}
<hr className="my-12 border-white/5" />
{/* SoH Trend Chart */}
<section className="animate-fade-up delay-300 mb-12">
<article className="rounded-2xl border border-white/[0.06] bg-white/[0.03] p-8">
<header className="mb-8 flex flex-wrap items-end justify-between gap-4">
<div>
<h3 className="text-xl font-medium text-white">SoH 90 </h3>
<p className="mt-1 text-sm text-[#A1A1AA]"> 12 3 </p>
</div>
<div className="flex items-center gap-6 text-sm text-[#A1A1AA]">
<span className="inline-flex items-center gap-2">
<span className="h-2 w-4 rounded-full bg-teal-400" />
</span>
<span className="inline-flex items-center gap-2">
<span className="h-2 w-4 rounded-full bg-indigo-400" />
</span>
</div>
</header>
<div className="w-full h-[320px]">
<SimpleChart data={chartData} />
</div>
</article>
</section>
{/* Two-column grid */}
<section className="animate-fade-up delay-400 mb-12 grid grid-cols-1 gap-8 lg:grid-cols-2">
{/* Left Column */}
<div className="space-y-8">
{/* Risk Distribution */}
<div>
<h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="space-y-5">
<div>
<div className="mb-2 flex justify-between text-sm">
<span className="text-[#A1A1AA]"> (SoH &gt; 90%)</span>
<span className="tabular-nums text-white">
{healthyCount} {' '}
<span className="text-[#71717A]">
/ {totalDevices > 0 ? ((healthyCount / totalDevices) * 100).toFixed(1) : 0}%
</span>
</span>
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-white/5">
<div
className="h-full rounded-full bg-emerald-400"
style={{ width: `${totalDevices > 0 ? (healthyCount / totalDevices) * 100 : 0}%` }}
/>
</div>
</div>
<div>
<div className="mb-2 flex justify-between text-sm">
<span className="text-[#A1A1AA]"> (85% &lt; SoH &le; 90%)</span>
<span className="tabular-nums text-white">
{watchCount} {' '}
<span className="text-[#71717A]">
/ {totalDevices > 0 ? ((watchCount / totalDevices) * 100).toFixed(1) : 0}%
</span>
</span>
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-white/5">
<div
className="h-full rounded-full bg-amber-400"
style={{ width: `${totalDevices > 0 ? (watchCount / totalDevices) * 100 : 0}%` }}
/>
</div>
</div>
<div>
<div className="mb-2 flex justify-between text-sm">
<span className="text-[#A1A1AA]"> (SoH &le; 85%)</span>
<span className="tabular-nums text-white">
{warningCount} {' '}
<span className="text-[#71717A]">
/ {totalDevices > 0 ? ((warningCount / totalDevices) * 100).toFixed(1) : 0}%
</span>
</span>
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-white/5">
<div
className="h-full rounded-full bg-red-400"
style={{ width: `${totalDevices > 0 ? (warningCount / totalDevices) * 100 : 0}%` }}
/>
</div>
</div>
</div>
</div>
{/* Regional Performance */}
<div>
<h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="space-y-4">
{batchPerformance.length > 0 ? (
batchPerformance.map((item) => (
<div key={item.batch} className="flex items-center gap-4">
<span className="w-20 text-sm text-[#A1A1AA]">{item.batch}</span>
<div className="flex-1">
<div className="h-1.5 overflow-hidden rounded-full bg-white/5">
<div className="h-full rounded-full bg-white/20" style={{ width: `${item.avgSoh}%` }} />
</div>
</div>
<span className="w-12 text-right text-sm tabular-nums text-white">{item.avgSoh.toFixed(1)}%</span>
</div>
))
) : (
<div className="text-sm text-[#71717A]"></div>
)}
</div>
</div>
</div>
{/* Right Column */}
<div className="space-y-8">
{/* Event Timeline */}
<div>
<h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="relative border-l border-white/10 pl-5">
{events.length > 0 ? (
events.map((event) => (
<div key={event.time + event.title} className="mb-6 last:mb-0">
<div
className={`absolute -left-[4px] mt-1.5 h-2 w-2 rounded-full ${
event.severity === '高' ? 'bg-red-400' : 'bg-amber-400'
}`}
/>
<div className="mb-1 flex items-center gap-3">
<span className="text-xs font-medium tabular-nums text-[#71717A]">{event.time}</span>
<span className={`text-xs ${severityColorMap[event.severity]}`}>{event.severity}</span>
</div>
<h4 className="text-sm font-medium text-[#F4F4F5]">{event.title}</h4>
<p className="mt-1 text-sm leading-relaxed text-[#A1A1AA]">{event.detail}</p>
</div>
))
) : (
<div className="text-sm text-[#71717A]"></div>
)}
</div>
</div>
{/* Risk Factor Frequency */}
<div>
<h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="flex flex-wrap gap-2">
{riskFactorCounts.length > 0 ? (
riskFactorCounts.map((item) => (
<div
key={item.factor}
className="flex items-center gap-2 rounded-md border border-white/5 bg-white/[0.02] px-3 py-1.5 text-sm"
>
<span className="text-[#A1A1AA]">{item.factor}</span>
<span className="rounded bg-white/10 px-1.5 py-0.5 text-xs tabular-nums text-white">
{item.count}
</span>
</div>
))
) : (
<div className="text-sm text-[#71717A]"></div>
)}
</div>
</div>
</div>
</section>
{/* Divider */}
<hr className="my-12 border-white/5" />
{/* Device Table */}
<section className="animate-fade-up delay-500 mb-12">
<div className="mb-6 flex items-end justify-between">
<div>
<h3 className="text-xl font-medium text-white"></h3>
<p className="mt-1 text-sm text-[#A1A1AA]"> 30/60/90 </p>
</div>
</div>
<div className="overflow-x-auto rounded-xl border border-white/[0.06] bg-white/[0.02]">
<table className="w-full min-w-[1000px] border-collapse text-left text-sm">
<thead>
<tr className="border-b border-white/10 bg-white/[0.02] text-[#A1A1AA]">
<th className="px-6 py-4 font-medium"></th>
<th className="px-6 py-4 font-medium"></th>
<th className="px-6 py-4 font-medium"> SoH</th>
<th className="px-6 py-4 font-medium">30</th>
<th className="px-6 py-4 font-medium">90</th>
<th className="px-6 py-4 font-medium"></th>
<th className="px-6 py-4 font-medium"></th>
<th className="px-6 py-4 font-medium"></th>
</tr>
</thead>
<tbody className="divide-y divide-white/5">
{devices.length > 0 ? (
devices
.slice()
.sort((a, b) => b.riskScore - a.riskScore)
.map((unit) => (
<tr key={unit.id} className="transition-colors hover:bg-white/[0.04]">
<td className="px-6 py-4 font-medium text-white">{unit.id}</td>
<td className="px-6 py-4 text-[#A1A1AA]">{unit.batch}</td>
<td className="px-6 py-4 tabular-nums text-white">{unit.soh.toFixed(1)}%</td>
<td className="px-6 py-4 tabular-nums text-[#A1A1AA]">{unit.soh30d.toFixed(1)}%</td>
<td className="px-6 py-4 tabular-nums text-[#A1A1AA]">{unit.soh90d.toFixed(1)}%</td>
<td className="px-6 py-4">
<div className="flex items-center gap-2">
<div className="h-1.5 w-12 overflow-hidden rounded-full bg-white/5">
<div
className={`h-full rounded-full ${
unit.riskScore >= 75
? 'bg-red-400'
: unit.riskScore >= 45
? 'bg-amber-400'
: 'bg-emerald-400'
}`}
style={{ width: `${unit.riskScore}%` }}
/>
</div>
<span className="tabular-nums text-white">{unit.riskScore}</span>
</div>
</td>
<td className="px-6 py-4">
<span className={statusColorMap[unit.status]}>{unit.status}</span>
</td>
<td className="px-6 py-4">
<div className="flex flex-wrap gap-1.5">
{unit.riskFactors.length > 0 ? (
unit.riskFactors.map((factor) => (
<span key={factor} className="text-[#A1A1AA]">
{factor}
{factor !== unit.riskFactors[unit.riskFactors.length - 1] && '、'}
</span>
))
) : (
<span className="text-[#71717A]">-</span>
)}
</div>
</td>
</tr>
))
) : (
<tr>
<td colSpan={8} className="px-6 py-8 text-center text-[#71717A]">
</td>
</tr>
)}
</tbody>
</table>
</div>
</section>
{/* Bottom Row */}
<section className="animate-fade-up delay-500 grid grid-cols-1 gap-8 lg:grid-cols-3">
{/* Strategy Cards */}
<div className="lg:col-span-2">
<h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="grid gap-4 sm:grid-cols-2">
{strategies.length > 0 ? (
strategies.map((item, index) => (
<div
key={item.name}
className="relative overflow-hidden rounded-xl border border-white/[0.06] bg-white/[0.02] p-5"
>
<div
className={`absolute bottom-0 left-0 top-0 w-1 ${index === 0 ? 'bg-red-400' : index === 1 ? 'bg-amber-400' : 'bg-teal-400'}`}
/>
<h4 className="font-medium text-white">{item.name}</h4>
<p className="mt-2 text-sm text-[#A1A1AA]">{item.impact}</p>
<div className="mt-4 flex flex-wrap gap-4 text-xs text-[#71717A]">
<span>: {item.scope}</span>
<span>: {item.eta}</span>
</div>
</div>
))
) : (
<div className="text-sm text-[#71717A] col-span-2"></div>
)}
</div>
</div>
{/* Firmware Comparison */}
<div>
<h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="rounded-xl border border-white/[0.06] bg-white/[0.02] p-5">
<div className="space-y-4">
{firmwareHealth.length > 0 ? (
firmwareHealth.map((item) => (
<div key={item.firmware} className="flex items-center justify-between">
<div>
<div className="text-sm font-medium text-white">{item.firmware}</div>
<div className="text-xs text-[#71717A]">{item.count} </div>
</div>
<div className="text-right">
<div className="text-sm tabular-nums text-white">{item.avgSoh.toFixed(1)}%</div>
<div className="text-xs text-[#71717A]"> SoH</div>
</div>
</div>
))
) : (
<div className="text-sm text-[#71717A]"></div>
)}
</div>
</div>
</div>
</section>
</div>
</main>
) )
} }
@@ -0,0 +1,13 @@
import { oc } from '@orpc/contract'
import { z } from 'zod'
import { batteriesResponseSchema, dashboardSnapshotSchema } from '@/domain/battery'
export const dashboard = oc.input(z.void()).output(dashboardSnapshotSchema)
export const batteries = oc
.input(
z.object({
mac: z.string().min(1).optional(),
}),
)
.output(batteriesResponseSchema)
+2 -2
View File
@@ -1,7 +1,7 @@
import * as todo from './todo.contract' import * as battery from './battery.contract'
export const contract = { export const contract = {
todo, battery,
} }
export type Contract = typeof contract 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)
})
})
-34
View File
@@ -1,34 +0,0 @@
import { oc } from '@orpc/contract'
import { createInsertSchema, createSelectSchema, createUpdateSchema } from 'drizzle-zod'
import { z } from 'zod'
import { generatedFieldKeys } from '@/server/db/fields'
import { todoTable } from '@/server/db/schema'
const selectSchema = createSelectSchema(todoTable)
const insertSchema = createInsertSchema(todoTable).omit(generatedFieldKeys)
const updateSchema = createUpdateSchema(todoTable)
.omit(generatedFieldKeys)
.refine((data) => Object.keys(data).length > 0, { message: 'At least one field is required' })
export const list = oc.input(z.void()).output(z.array(selectSchema))
export const create = oc.input(insertSchema).output(selectSchema)
export const update = oc
.input(
z.object({
id: z.uuid(),
data: updateSchema,
}),
)
.output(selectSchema)
export const remove = oc
.input(
z.object({
id: z.uuid(),
}),
)
.output(z.void())
+2 -2
View File
@@ -12,8 +12,8 @@ export const handleValidationError = (error: unknown) => {
if (!(error instanceof ORPCError) || !(error.cause instanceof ValidationError)) return if (!(error instanceof ORPCError) || !(error.cause instanceof ValidationError)) return
if (error.code === 'BAD_REQUEST') { if (error.code === 'BAD_REQUEST') {
// ORPC widens issues to the Standard Schema shape; every contract here is built from Zod/drizzle-zod, // ORPC widens issues to the Standard Schema shape; contracts here are built from Zod.
// so the runtime objects are Zod issues. Rehydrate to reuse z.prettifyError / z.flattenError. // Rehydrate to reuse z.prettifyError / z.flattenError.
const zodError = new z.ZodError(error.cause.issues as z.core.$ZodIssue[]) const zodError = new z.ZodError(error.cause.issues as z.core.$ZodIssue[])
throw new ORPCError('INPUT_VALIDATION_FAILED', { throw new ORPCError('INPUT_VALIDATION_FAILED', {
+15
View File
@@ -0,0 +1,15 @@
import { createBatteriesResponse, createDashboardSnapshot } from '@/domain/battery'
import { os } from '@/server/api/server'
import { getBatteryHistory, getLatestBatteryPerDevice } from '@/server/battery/mysql'
export const dashboard = os.battery.dashboard.handler(async () => {
const items = await getLatestBatteryPerDevice()
return createDashboardSnapshot(items)
})
export const batteries = os.battery.batteries.handler(async ({ input }) => {
const items = input.mac ? await getBatteryHistory(input.mac) : await getLatestBatteryPerDevice()
return createBatteriesResponse(items)
})
+2 -2
View File
@@ -1,6 +1,6 @@
import { os } from '@/server/api/server' import { os } from '@/server/api/server'
import * as todo from './todo.router' import * as battery from './battery.router'
export const router = os.router({ export const router = os.router({
todo, battery,
}) })
-39
View File
@@ -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')
}
})
+75
View File
@@ -0,0 +1,75 @@
import mysql, { type Pool, type RowDataPacket } from 'mysql2/promise'
import { type BatteryInfo, type BatteryInfoSourceRow, toBatteryInfo } from '@/domain/battery'
import { env } from '@/env'
const historyLimit = 500
type BatteryInfoMysqlRow = RowDataPacket & BatteryInfoSourceRow
let pool: Pool | undefined
function getBatteryPool() {
pool ??= mysql.createPool({
uri: env.DATABASE_URL,
waitForConnections: true,
connectionLimit: 5,
namedPlaceholders: true,
})
return pool
}
export async function closeBatteryPool() {
if (!pool) return
await pool.end()
pool = undefined
}
const sourceColumns = `
id,
user_id AS userId,
mac,
dev_model AS devModel,
dev_name AS devName,
is_low_power AS isLowPower,
power_status AS powerStatus,
power,
create_time AS createTime,
remark
`
export async function getBatteryHistory(mac: string): Promise<BatteryInfo[]> {
const [rows] = await getBatteryPool().query<BatteryInfoMysqlRow[]>(
`
SELECT ${sourceColumns}
FROM ls_battery_info
WHERE mac = :mac
ORDER BY create_time DESC, id DESC
LIMIT :limit
`,
{ mac, limit: historyLimit },
)
return rows.map(toBatteryInfo)
}
export async function getLatestBatteryPerDevice(): Promise<BatteryInfo[]> {
const [rows] = await getBatteryPool().query<BatteryInfoMysqlRow[]>(`
SELECT ${sourceColumns}
FROM ls_battery_info AS current_record
WHERE NOT EXISTS (
SELECT 1
FROM ls_battery_info AS newer_record
WHERE newer_record.mac = current_record.mac
AND (
newer_record.create_time > current_record.create_time
OR (newer_record.create_time = current_record.create_time AND newer_record.id > current_record.id)
)
)
ORDER BY current_record.create_time DESC, current_record.id DESC
`)
return rows.map(toBatteryInfo)
}
-19
View File
@@ -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>
-11
View File
@@ -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,
})
-8
View File
@@ -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
View File
@@ -1 +0,0 @@
export * from './todo'
-8
View File
@@ -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),
})
-4
View File
@@ -1,4 +0,0 @@
declare module '*.sql' {
const content: string
export default content
}
+3 -3
View File
@@ -1,4 +1,4 @@
import { db } from '@/server/db' import { closeBatteryPool } from '@/server/battery/mysql'
import { getLogger } from '@/server/logger' import { getLogger } from '@/server/logger'
export default () => { export default () => {
@@ -17,8 +17,8 @@ export default () => {
await Bun.sleep(500) await Bun.sleep(500)
try { try {
await db.$client.end() await closeBatteryPool()
logger.info('DB pool closed, exiting') logger.info('Battery MySQL pool closed, exiting')
} catch (error) { } catch (error) {
logger.error('DB pool close failed during shutdown', { error }) logger.error('DB pool close failed during shutdown', { error })
} }