@umituz/web-hono 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 umituz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,131 @@
1
- # Temporary Holding Version
1
+ # @umituz/web-hono
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Hono backend contract for single-Worker apps on Cloudflare (SPA assets + `/api/*` Hono) with Neon Postgres via drizzle. It packages the cross-cutting API skeleton proven in production by the pilot app [foodora](https://foodora.umituz998.workers.dev): the `crudRoutes` factory, `pickPatch`/`uid`, `getDb`, the JSON-404 and SPA-fallback handlers, the zod body-validation contract, the same-origin API client, and the shared-Neon database lifecycle scripts.
4
+
5
+ The package is **source-distributed** (published as raw TypeScript in `src/`). Wrangler, Vite, and tsc all compile it alongside your app; no prebuilt bundle ships.
6
+
7
+ ## Design philosophy
8
+
9
+ - **Contract, not framework.** The package owns cross-cutting conventions only — the error envelope (`{ error, details? }`), the soft-delete list read, the setting-patch idiom, literal status codes. Your schema, `TABLE_PREFIX`, zod schemas, domain routers, and business rules stay in your app.
10
+ - **The factory has a hard scope.** `crudRoutes` covers list + setting-patch ONLY: "does this PATCH merely change a column value?" Entities with business rules (transitions, restock, overlap guards) stay hand-written in their area router — writing factory-covered code by hand and stuffing out-of-scope behavior into the factory are both contract violations.
11
+ - **Store-agnostic client.** `apiFetch`/`apiWrite` never import your store; hosts pass their own typed `refresh` (usually via a 3-line wrapper that binds their collection keys).
12
+ - **Shared-Neon safety.** The lifecycle scripts drop only tables carrying your project's `TABLE_PREFIX` and refuse to run the moment they see a prefix-less table — one Neon project hosts a whole fleet of products.
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @umituz/web-hono
18
+ ```
19
+
20
+ Peer dependencies (install alongside): `hono ^4`, `drizzle-orm ^0.45`, `@neondatabase/serverless ^1`, `zod ^4`.
21
+
22
+ ## Entry points
23
+
24
+ | Entry point | Exports | Used by |
25
+ |---|---|---|
26
+ | `@umituz/web-hono` | `crudRoutes`, `CrudSpec`/`CrudTable`, `getDb`, `uid`, `pickPatch`, `apiNotFound`, `spaFallback`, `ApiEnv` | `api/index.ts`, area routers, `api/db.ts` |
27
+ | `@umituz/web-hono/validator` | `validateJson(schema, message?)` | every hand-written POST/PATCH route |
28
+ | `@umituz/web-hono/client` | `apiFetch<T>`, `apiWrite<T>` | `src/data/http.ts`, repositories |
29
+ | `@umituz/web-hono/lifecycle` | `resetTables`, `snapshotToSeed`, `seedFromSnapshot`, `TableSpec`, `SeedSnapshot` | `scripts/reset.ts` / `snapshot.ts` / `seed.ts` wrappers |
30
+
31
+ ## Quick start
32
+
33
+ **1. Worker entry** (`api/index.ts`) — mount list, then close the chain:
34
+
35
+ ```ts
36
+ import { Hono } from 'hono';
37
+ import { apiNotFound, spaFallback } from '@umituz/web-hono';
38
+ import type { ApiEnv } from '@umituz/web-hono';
39
+ import { healthRouter } from './routes/health';
40
+ import { orgRouter } from './routes/org';
41
+
42
+ const app = new Hono<{ Bindings: ApiEnv }>();
43
+
44
+ app.route('/api/health', healthRouter);
45
+ app.route('/api', orgRouter);
46
+
47
+ app.all('/api/*', apiNotFound); // unmatched API stays JSON — never the SPA's index.html
48
+ app.get('*', spaFallback); // client-side routes resolve via the ASSETS binding
49
+
50
+ export default app;
51
+ ```
52
+
53
+ **2. Factory mounts** (area routers) — plain settings/catalog entities:
54
+
55
+ ```ts
56
+ import { crudRoutes } from '@umituz/web-hono';
57
+
58
+ orgRouter.route('/', crudRoutes({ path: '/branches', table: branches, label: 'Branch', orderBy: { col: branches.name } }));
59
+ ```
60
+
61
+ Generates `GET /api/branches` (visible rows, ordered) + `PATCH /api/branches/:id` (pickPatch-filtered body, `updatedAt` stamp, `404 'Branch not found'`).
62
+
63
+ **3. Validated writes** — the single definition of the body contract:
64
+
65
+ ```ts
66
+ import { validator } from 'hono/validator';
67
+ import { validateJson } from '@umituz/web-hono/validator';
68
+
69
+ app.post(
70
+ '/products',
71
+ validator('json', validateJson(CreateProductSchema, 'Invalid product payload')),
72
+ (c) => { /* c.req.valid('json') is the parsed zod output */ },
73
+ );
74
+ ```
75
+
76
+ Failures answer `400 { error: <message>, details: <fieldErrors> }` — the envelope every client toast surfaces.
77
+
78
+ **4. App db wrapper** (`api/db.ts`) — bind your schema once:
79
+
80
+ ```ts
81
+ import { getDb } from '@umituz/web-hono';
82
+ import * as schema from './schema';
83
+
84
+ export const getDbBound = (env: { DATABASE_URL: string }) => getDb(env, schema);
85
+ ```
86
+
87
+ **5. Frontend client** (`src/data/http.ts`):
88
+
89
+ ```ts
90
+ import { apiFetch, apiWrite as write } from '@umituz/web-hono/client';
91
+ import { refresh, type CollectionKey } from './store';
92
+
93
+ export { apiFetch };
94
+ export const apiWrite = <T = void>(path: string, init: Parameters<typeof write>[1], keys: CollectionKey[] = []) =>
95
+ write<T>(path, init, keys, (k) => refresh(k));
96
+ ```
97
+
98
+ **6. Lifecycle scripts** (`scripts/`) — keep only your `TABLE_SPECS` registry and thin wrappers:
99
+
100
+ ```ts
101
+ // scripts/snapshot.ts
102
+ import 'dotenv/config';
103
+ import { snapshotToSeed } from '@umituz/web-hono/lifecycle';
104
+ import { TABLE_SPECS } from './tables';
105
+
106
+ const url = process.env.DATABASE_URL;
107
+ if (!url) throw new Error('DATABASE_URL is required (.env)');
108
+ await snapshotToSeed({ specs: TABLE_SPECS, url, outPath: new URL('./seed-data.json.gz', import.meta.url) });
109
+ ```
110
+
111
+ `resetTables({ specs, prefix, url })` drops only `prefix*` tables (in reverse registry order, CASCADE); `seedFromSnapshot({ specs, url, inPath })` replays idempotently (ON CONFLICT DO NOTHING, 200-row chunks, per-column-type revival of timestamps/dates).
112
+
113
+ ## What stays in the app
114
+
115
+ - `api/schema.ts` — every table, the project's `TABLE_PREFIX`, fleet column standards (time trio, soft delete, jsonb nesting)
116
+ - Domain routers with business rules (order transitions, reservation overlap guards, restock side effects)
117
+ - Zod schemas and per-route error messages
118
+ - Audit/notification/entitlement helpers (they insert into YOUR tables)
119
+ - `api/routes/health.ts` — the `BUILD_MARKER` deploy canary is per-project
120
+
121
+ ## Testing
122
+
123
+ ```bash
124
+ npm test
125
+ ```
126
+
127
+ 21 vitest cases cover the pure logic and DB-free short-circuit paths (pickPatch filters, uid shape, the 400/404 envelopes, validator contract, client error mapping, reset safety stop). Live-DB paths (list/PATCH success, snapshot/seed) are proven by the consuming app's E2E — the pilot is foodora.
128
+
129
+ ## License
130
+
131
+ MIT
package/package.json CHANGED
@@ -1,6 +1,84 @@
1
1
  {
2
2
  "name": "@umituz/web-hono",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Hono backend contract for Cloudflare Workers + Neon Postgres: crudRoutes factory, pickPatch, validateJson, apiFetch/apiWrite client, and db lifecycle scripts (reset / snapshot / seed)",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.ts",
8
+ "sideEffects": false,
9
+ "exports": {
10
+ ".": "./src/index.ts",
11
+ "./validator": "./src/validator.ts",
12
+ "./client": "./src/client.ts",
13
+ "./lifecycle": "./src/lifecycle.ts",
14
+ "./package.json": "./package.json"
15
+ },
16
+ "scripts": {
17
+ "typecheck": "tsc --noEmit",
18
+ "lint": "eslint .",
19
+ "test": "vitest run",
20
+ "test:watch": "vitest",
21
+ "prepublishOnly": "npm run typecheck && npm run lint && npm test",
22
+ "version:patch": "npm version patch -m 'chore: release v%s'",
23
+ "version:minor": "npm version minor -m 'chore: release v%s'",
24
+ "version:major": "npm version major -m 'chore: release v%s'"
25
+ },
26
+ "keywords": [
27
+ "hono",
28
+ "hono-api",
29
+ "cloudflare-workers",
30
+ "workers",
31
+ "neon",
32
+ "postgres",
33
+ "drizzle",
34
+ "drizzle-orm",
35
+ "crud",
36
+ "crud-factory",
37
+ "rest-api",
38
+ "spa-fallback",
39
+ "zod",
40
+ "validation",
41
+ "api-client",
42
+ "seed",
43
+ "snapshot",
44
+ "database-lifecycle",
45
+ "serverless",
46
+ "typescript",
47
+ "edge"
48
+ ],
49
+ "author": "umituz",
50
+ "license": "MIT",
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "https://github.com/umituz/web-hono"
54
+ },
55
+ "peerDependencies": {
56
+ "@neondatabase/serverless": "^1.0.0",
57
+ "drizzle-orm": "^0.45.4",
58
+ "hono": "^4.0.0",
59
+ "zod": "^4.0.0"
60
+ },
61
+ "devDependencies": {
62
+ "@eslint/js": "^9.32.0",
63
+ "@neondatabase/serverless": "^1.2.0",
64
+ "@types/node": "~22.13.10",
65
+ "drizzle-orm": "^0.45.4",
66
+ "eslint": "^9.32.0",
67
+ "hono": "^4.13.13",
68
+ "typescript": "~5.9.2",
69
+ "typescript-eslint": "^8.58.0",
70
+ "vitest": "3.2.4",
71
+ "zod": "^4.6.5"
72
+ },
73
+ "engines": {
74
+ "node": ">=18"
75
+ },
76
+ "publishConfig": {
77
+ "access": "public"
78
+ },
79
+ "files": [
80
+ "src",
81
+ "README.md",
82
+ "LICENSE"
83
+ ]
84
+ }
package/src/client.ts ADDED
@@ -0,0 +1,36 @@
1
+ /* Minimal JSON client for a same-origin Hono API. Throws an Error carrying
2
+ the server's message (zod/404/400 bodies are `{ error }`) so UI toast
3
+ handlers can surface it directly. */
4
+
5
+ export async function apiFetch<T>(path: string, init: { method?: 'POST' | 'PATCH' | 'PUT' | 'DELETE'; json?: unknown } = {}): Promise<T> {
6
+ const res = await fetch(path, {
7
+ method: init.method ?? 'GET',
8
+ headers: init.json !== undefined ? { 'content-type': 'application/json', accept: 'application/json' } : { accept: 'application/json' },
9
+ body: init.json !== undefined ? JSON.stringify(init.json) : undefined,
10
+ });
11
+ if (!res.ok) {
12
+ const body = (await res.json().catch(() => null)) as { error?: string } | null;
13
+ throw new Error(body?.error ?? `API ${path} responded ${res.status}`);
14
+ }
15
+ return (await res.json()) as T;
16
+ }
17
+
18
+ /**
19
+ * The repository write idiom in one call: mutate through the API, then
20
+ * refresh the collections the write touched. Refresh only runs when the
21
+ * write succeeded — failures leave the cache untouched.
22
+ *
23
+ * Hosts with a store/cache layer pass their own `refresh` (and usually wrap
24
+ * this in a typed helper binding their collection keys); `keys` stay plain
25
+ * strings here so the package stays store-agnostic.
26
+ */
27
+ export async function apiWrite<T = void>(
28
+ path: string,
29
+ init: { method: 'POST' | 'PATCH' | 'PUT' | 'DELETE'; json?: unknown },
30
+ keys: string[] = [],
31
+ refresh: (keys: string[]) => Promise<void> = async () => {},
32
+ ): Promise<T> {
33
+ const result = await apiFetch<T>(path, init);
34
+ if (keys.length) await refresh(keys);
35
+ return result;
36
+ }
package/src/crud.ts ADDED
@@ -0,0 +1,60 @@
1
+ import { Hono } from 'hono';
2
+ import { and, asc, desc, eq, isNull } from 'drizzle-orm';
3
+ import { drizzle } from 'drizzle-orm/neon-http';
4
+ import { neon } from '@neondatabase/serverless';
5
+ import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
6
+ import { pickPatch } from './lib';
7
+ import type { ApiEnv } from './env';
8
+
9
+ /**
10
+ * The standard entity resource: GET list (soft-deleted hidden, ordered) +
11
+ * PATCH /:id (pickPatch-filtered body, updatedAt stamp, 404 on miss).
12
+ * Mount it onto an area router with `.route('/', crudRoutes({ ... }))`.
13
+ *
14
+ * Entities with business rules (role immutability guards, goods-receipt
15
+ * restock, order transitions…) stay hand-written in their area router —
16
+ * the factory is for plain settings/catalog rows only.
17
+ */
18
+
19
+ export type CrudTable = PgTable & { id: PgColumn; deletedAt: PgColumn };
20
+
21
+ export interface CrudSpec {
22
+ /** Path under /api, e.g. '/products'. */
23
+ path: string;
24
+ table: CrudTable;
25
+ /** Human label for 404s — 'Product' → 'Product not found'. */
26
+ label: string;
27
+ /** List order; defaults to insertion order. */
28
+ orderBy?: { col: PgColumn; dir?: 'asc' | 'desc' };
29
+ }
30
+
31
+ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
32
+ const { path, table, label, orderBy } = spec;
33
+ const router = new Hono<{ Bindings: ApiEnv }>();
34
+
35
+ router.get(path, async (c) => {
36
+ // Schema-less drizzle: the factory only runs select/update, which never
37
+ // touch the schema registry (only `db.query.*` does) — so it builds its
38
+ // own instance from the request's binding instead of requiring one.
39
+ const db = drizzle(neon(c.env.DATABASE_URL));
40
+ const q = db.select().from(table).where(isNull(table.deletedAt)).$dynamic();
41
+ if (orderBy) q.orderBy(orderBy.dir === 'desc' ? desc(orderBy.col) : asc(orderBy.col));
42
+ return c.json(await q);
43
+ });
44
+
45
+ router.patch(`${path}/:id`, async (c) => {
46
+ const patch = pickPatch(table, await c.req.json().catch(() => null));
47
+ if (!patch) return c.json({ error: 'No updatable fields' }, 400);
48
+ const db = drizzle(neon(c.env.DATABASE_URL));
49
+ const [row] = await db
50
+ .update(table)
51
+ // Generic tables can't carry per-table set types — values are already
52
+ // column-filtered by pickPatch, so the cast is purely type-level.
53
+ .set({ ...patch, updatedAt: new Date() } as never)
54
+ .where(and(eq(table.id, c.req.param('id')), isNull(table.deletedAt)))
55
+ .returning();
56
+ return row ? c.json(row) : c.json({ error: `${label} not found` }, 404);
57
+ });
58
+
59
+ return router;
60
+ }
package/src/db.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { drizzle } from 'drizzle-orm/neon-http';
2
+ import { neon } from '@neondatabase/serverless';
3
+
4
+ /**
5
+ * neon-http driver: fetch-based, serverless-friendly — no connection pool,
6
+ * no Hyperdrive needed. Each request gets its own HTTP call to Neon.
7
+ *
8
+ * `schema` is the app's drizzle schema (`import * as schema from './schema'`)
9
+ * and enables relational `db.query.*` access; plain select/insert/update
10
+ * paths work regardless.
11
+ */
12
+ export function getDb<TSchema extends Record<string, unknown>>(env: { DATABASE_URL: string }, schema: TSchema) {
13
+ const sql = neon(env.DATABASE_URL);
14
+ return drizzle(sql, { schema });
15
+ }
package/src/env.ts ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Worker bindings — self-contained types (no @cloudflare/workers-types dep).
3
+ * Apps with extra bindings extend this interface; the package's helpers
4
+ * only ever need these two.
5
+ */
6
+ export interface ApiEnv {
7
+ /** Neon Postgres connection string (wrangler secret / .dev.vars). */
8
+ DATABASE_URL: string;
9
+ /** Static assets binding (Workers Static Assets) for SPA fallback. */
10
+ ASSETS: {
11
+ fetch(input: Request | string, init?: RequestInit): Promise<Response>;
12
+ };
13
+ }
@@ -0,0 +1,18 @@
1
+ import type { Handler } from 'hono';
2
+ import type { ApiEnv } from './env';
3
+
4
+ /**
5
+ * Unmatched API paths must stay JSON — without this they'd fall into the
6
+ * SPA fallback and return index.html with a 200.
7
+ * Usage: `app.all('/api/*', apiNotFound)`.
8
+ */
9
+ export const apiNotFound: Handler<{ Bindings: ApiEnv }> = (c) => c.json({ error: 'Not found' }, 404);
10
+
11
+ /**
12
+ * SPA fallback: client-side routes (e.g. /suppliers) have no asset file.
13
+ * Pass the ORIGINAL request to the assets binding — with
14
+ * `not_found_handling: "single-page-application"` it resolves to index.html
15
+ * in place (no redirect). Fetching "/index.html" explicitly would 307 to "/".
16
+ * Usage: `app.get('*', spaFallback)`.
17
+ */
18
+ export const spaFallback: Handler<{ Bindings: ApiEnv }> = (c) => c.env.ASSETS.fetch(c.req.raw);
package/src/index.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @umituz/web-hono — the Hono backend contract for single-Worker apps on
3
+ * Cloudflare (SPA assets + `/api/*` Hono) with Neon Postgres via drizzle:
4
+ * the crudRoutes factory, pickPatch/uid helpers, getDb, the JSON-404 and
5
+ * SPA-fallback handlers, and the ApiEnv binding types.
6
+ *
7
+ * Apps keep their schema (with TABLE_PREFIX), domain routers, zod schemas,
8
+ * and business rules — this package owns the cross-cutting API skeleton
9
+ * only.
10
+ *
11
+ * Entry points:
12
+ * `.` server core (this file)
13
+ * `/validator` validateJson — the zod `{ error, details }` body contract
14
+ * `/client` apiFetch / apiWrite — the same-origin API client
15
+ * `/lifecycle` reset / snapshot / seed — the shared-Neon db lifecycle
16
+ */
17
+ export { crudRoutes } from './crud';
18
+ export type { CrudSpec, CrudTable } from './crud';
19
+ export { getDb } from './db';
20
+ export { uid, pickPatch } from './lib';
21
+ export { apiNotFound, spaFallback } from './handlers';
22
+ export type { ApiEnv } from './env';
package/src/lib.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { getTableColumns } from 'drizzle-orm';
2
+ import type { PgTable } from 'drizzle-orm/pg-core';
3
+
4
+ /** Server-side id generation: `${prefix}_${base36 timestamp}${base36 counter}`. */
5
+ let idCounter = 0;
6
+ export function uid(prefix: string): string {
7
+ idCounter += 1;
8
+ return `${prefix}_${Date.now().toString(36)}${idCounter.toString(36)}`;
9
+ }
10
+
11
+ /** Fields no client may ever patch. */
12
+ const PROTECTED_KEYS = new Set(['id', 'createdAt', 'updatedAt', 'deletedAt']);
13
+
14
+ /**
15
+ * Filters a JSON patch body down to the table's own columns (drizzle speaks
16
+ * the camelCase schema PROPERTY names — which are the domain field names).
17
+ * ISO-datetime strings destined for timestamptz columns become Date objects.
18
+ * Returns null when nothing updatable remains.
19
+ */
20
+ export function pickPatch(table: PgTable, body: unknown): Record<string, unknown> | null {
21
+ if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;
22
+ const columns = getTableColumns(table) as unknown as Record<string, { columnType: string }>;
23
+ const out: Record<string, unknown> = {};
24
+ for (const [key, value] of Object.entries(body as Record<string, unknown>)) {
25
+ if (PROTECTED_KEYS.has(key)) continue;
26
+ const col = columns[key];
27
+ if (!col || value === undefined) continue;
28
+ if (typeof value === 'string' && col.columnType.includes('Timestamp')) {
29
+ const d = new Date(value);
30
+ if (Number.isNaN(d.getTime())) continue; // '' and junk → skip, not 500
31
+ out[key] = d;
32
+ } else {
33
+ out[key] = value;
34
+ }
35
+ }
36
+ return Object.keys(out).length > 0 ? out : null;
37
+ }
@@ -0,0 +1,121 @@
1
+ import { getTableName, getTableColumns } from 'drizzle-orm';
2
+ import { neon } from '@neondatabase/serverless';
3
+ import { drizzle } from 'drizzle-orm/neon-http';
4
+ import type { PgTable } from 'drizzle-orm/pg-core';
5
+ import { readFileSync, writeFileSync } from 'node:fs';
6
+ import { gzipSync, gunzipSync } from 'node:zlib';
7
+
8
+ /**
9
+ * Database lifecycle for the shared-Neon-project fleet model: one Neon
10
+ * project hosts many products, each living in its own `TABLE_PREFIX*`
11
+ * tables. `specs` is the app's single table registry (foodora's
12
+ * `scripts/tables.ts` shape) shared by all three operations so snapshot
13
+ * and seed can never diverge.
14
+ */
15
+
16
+ export interface TableSpec {
17
+ /** Snapshot/seed key AND the SQL table name — e.g. 'users' for `foodora_users`. */
18
+ name: string;
19
+ table: PgTable;
20
+ }
21
+
22
+ /** The on-disk shape of a seed snapshot (`seed-data.json.gz`). */
23
+ export interface SeedSnapshot {
24
+ generatedAt: string;
25
+ tables: Record<string, Record<string, unknown>[]>;
26
+ }
27
+
28
+ /**
29
+ * db:reset step 1 — drops THIS product's prefixed tables (the npm script
30
+ * chain then recreates them with `drizzle-kit push` and replays `db:seed`).
31
+ * Clean-slate lifecycle for a shared Neon project: when a product is paused,
32
+ * reset it; when work resumes, the same command brings it fully back.
33
+ *
34
+ * SAFETY: only tables whose SQL name carries the prefix are dropped — other
35
+ * products sharing the Neon project are never touched. A spec without the
36
+ * prefix stops everything before a single DROP runs.
37
+ */
38
+ export async function resetTables(opts: { specs: TableSpec[]; prefix: string; url: string }): Promise<string[]> {
39
+ const sql = neon(opts.url);
40
+
41
+ const names = opts.specs.map((spec) => getTableName(spec.table));
42
+ const unsafe = names.find((n) => !n.startsWith(opts.prefix));
43
+ if (unsafe !== undefined) throw new Error(`Safety stop: '${unsafe}' does not carry prefix '${opts.prefix}' — refusing to drop.`);
44
+
45
+ const dropped: string[] = [];
46
+ for (const name of [...names].reverse()) {
47
+ await sql`DROP TABLE IF EXISTS ${sql.unsafe(`"${name}"`)} CASCADE`;
48
+ dropped.push(name);
49
+ console.log(`dropped: ${name}`);
50
+ }
51
+ console.log(`\n${names.length} '${opts.prefix}*' tables dropped.`);
52
+ return dropped;
53
+ }
54
+
55
+ /**
56
+ * db:snapshot — reads EVERY row of every table (soft-deleted included) and
57
+ * writes the gzipped seed file. Run after meaningful data changes; the
58
+ * snapshot is what `seedFromSnapshot` replays into an empty database.
59
+ * Rows are stored with drizzle PROPERTY names (camelCase), which is exactly
60
+ * what `.values()` speaks — no key mapping on the way back in.
61
+ */
62
+ export async function snapshotToSeed(opts: { specs: TableSpec[]; url: string; outPath: string | URL }): Promise<{ total: number; rawBytes: number }> {
63
+ const db = drizzle(neon(opts.url));
64
+
65
+ const tables: Record<string, unknown[]> = {};
66
+ let total = 0;
67
+ for (const { name, table } of opts.specs) {
68
+ const rows = (await db.select().from(table)) as unknown[];
69
+ tables[name] = rows;
70
+ total += rows.length;
71
+ console.log(`${name.padEnd(20)} ${rows.length}`);
72
+ }
73
+
74
+ const payload = JSON.stringify({ generatedAt: new Date().toISOString(), tables });
75
+ writeFileSync(opts.outPath, gzipSync(Buffer.from(payload, 'utf8')));
76
+ console.log(`\nSnapshot: ${total} rows → ${opts.outPath} (${(payload.length / 1024).toFixed(0)} KiB raw)`);
77
+ return { total, rawBytes: payload.length };
78
+ }
79
+
80
+ type Row = Record<string, unknown>;
81
+
82
+ /** ISO string → Date for timestamptz columns; trim to YYYY-MM-DD for date columns. */
83
+ function reviveRow(table: PgTable, row: Row): Row {
84
+ const out: Row = { ...row };
85
+ for (const [key, col] of Object.entries(getTableColumns(table))) {
86
+ const v = out[key];
87
+ if (v === null || v === undefined) continue;
88
+ if (col.columnType.includes('Timestamp')) out[key] = new Date(v as string);
89
+ else if (col.columnType.toLowerCase().includes('date')) out[key] = String(v).slice(0, 10);
90
+ }
91
+ return out;
92
+ }
93
+
94
+ /**
95
+ * db:seed — replays the snapshot into the database. Idempotent:
96
+ * ON CONFLICT DO NOTHING — first run wins, existing ids skip. JSON
97
+ * round-trip notes: timestamps come back as ISO strings and dates as
98
+ * 'YYYY-MM-DD'; both are converted back per column type (derived from the
99
+ * drizzle schema — no per-table field lists to maintain).
100
+ */
101
+ export async function seedFromSnapshot(opts: { specs: TableSpec[]; url: string; inPath: string | URL }): Promise<number> {
102
+ const db = drizzle(neon(opts.url));
103
+
104
+ const snapshot = JSON.parse(gunzipSync(readFileSync(opts.inPath)).toString('utf8')) as SeedSnapshot;
105
+ console.log(`Snapshot generated at ${snapshot.generatedAt}`);
106
+
107
+ let inserted = 0;
108
+ for (const { name, table } of opts.specs) {
109
+ const rows = (snapshot.tables[name] ?? []).map((r) => reviveRow(table, r));
110
+ for (let i = 0; i < rows.length; i += 200) {
111
+ const chunk = rows.slice(i, i + 200);
112
+ // `.returning()` (full rows) instead of `returning({ id })`: some tables
113
+ // are singletons keyed by organization_id without an id column.
114
+ const res = (await db.insert(table).values(chunk as never).onConflictDoNothing().returning()) as unknown[];
115
+ inserted += res.length;
116
+ }
117
+ console.log(`${name.padEnd(20)} ${rows.length} offered`);
118
+ }
119
+ console.log(`\nSeed complete: ${inserted} rows inserted (existing ids skipped).`);
120
+ return inserted;
121
+ }
@@ -0,0 +1,25 @@
1
+ import type { Context } from 'hono';
2
+ import { z } from 'zod';
3
+
4
+ /**
5
+ * The single definition of the API's JSON-body validation contract:
6
+ * zod safeParse behind hono's `validator('json', …)` — failures answer
7
+ * `400 { error, details: fieldErrors }`, successes flow the parsed (and
8
+ * `.strict()`, `.trim()`-ed) data into the handler via `c.req.valid('json')`.
9
+ *
10
+ * Usage:
11
+ * app.post(
12
+ * '/widgets',
13
+ * validator('json', validateJson(CreateWidgetSchema, 'Invalid widget payload')),
14
+ * (c) => { const input = c.req.valid('json'); … },
15
+ * );
16
+ */
17
+ export function validateJson<S extends z.ZodType>(schema: S, message = 'Invalid request body') {
18
+ return (value: unknown, c: Context) => {
19
+ const parsed = schema.safeParse(value);
20
+ if (!parsed.success) {
21
+ return c.json({ error: message, details: parsed.error.flatten().fieldErrors }, 400);
22
+ }
23
+ return parsed.data as z.output<S>;
24
+ };
25
+ }