@umituz/web-hono 1.19.0 → 1.19.2
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/package.json +1 -1
- package/src/activity.ts +0 -4
- package/src/api.ts +0 -31
- package/src/client.ts +0 -11
- package/src/cookies.ts +0 -8
- package/src/crud.ts +4 -51
- package/src/db.ts +0 -8
- package/src/docstore.ts +33 -63
- package/src/env.ts +0 -7
- package/src/errors.ts +0 -21
- package/src/handlers.ts +0 -12
- package/src/health.ts +0 -6
- package/src/http.ts +0 -28
- package/src/index.ts +0 -27
- package/src/lib.ts +1 -40
- package/src/lifecycle.ts +0 -37
- package/src/org.ts +0 -9
- package/src/r2.ts +0 -14
- package/src/resource-react.ts +0 -7
- package/src/resource.ts +0 -12
- package/src/rows.ts +0 -2
- package/src/store-react.ts +0 -17
- package/src/types.ts +0 -19
- package/src/validator.ts +0 -13
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@umituz/web-hono",
|
|
3
|
-
"version": "1.19.
|
|
3
|
+
"version": "1.19.2",
|
|
4
4
|
"description": "API backend platform for Cloudflare Workers + Neon Postgres: createApi skeleton + error envelope layer, full-CRUD resource factory (opt-in create/remove, list params), schema→client type bridge (ClientRow), apiFetch/apiWrite client, reactive fetch-backed store (+React hooks), doc-sync diff/snapshot/push machine (snapshotDocs/diffOps/pushOps), better-auth server integration (tables/getter/mount/session helpers), weak-compare If-None-Match matcher (matchesEtag), cookie channels + request scope/ETag/R2-stream server helpers, TTL resource cache, and db lifecycle scripts (reset / snapshot / seed)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.ts",
|
package/src/activity.ts
CHANGED
|
@@ -34,10 +34,6 @@ export interface NotificationOpts {
|
|
|
34
34
|
type ColumnMeta = { columnType?: string };
|
|
35
35
|
type Columns = Record<string, ColumnMeta>;
|
|
36
36
|
|
|
37
|
-
/** Stamps the first present time column — the fleet's `at` plain tables and
|
|
38
|
-
* the trio-convention (`createdAt`) tables are both served; tables with
|
|
39
|
-
* neither rely on their column defaults. Text time columns receive the ISO
|
|
40
|
-
* string form, timestamp columns the Date object. */
|
|
41
37
|
function timeStamp(table: ActivityTable, candidates: string[]): Record<string, Date | string> {
|
|
42
38
|
const columns = getTableColumns(table) as unknown as Columns;
|
|
43
39
|
for (const name of candidates) {
|
package/src/api.ts
CHANGED
|
@@ -6,37 +6,13 @@ import { apiOnError } from './errors';
|
|
|
6
6
|
import { healthRouter } from './health';
|
|
7
7
|
import type { ApiEnv } from './env';
|
|
8
8
|
|
|
9
|
-
/**
|
|
10
|
-
* The one-call API skeleton — everything the 1.x apps hand-copied into
|
|
11
|
-
* api/index.ts, routes/health.ts and env wiring, composed once:
|
|
12
|
-
*
|
|
13
|
-
* export default createApi({
|
|
14
|
-
* service: 'storyora',
|
|
15
|
-
* build: BUILD_MARKER,
|
|
16
|
-
* routers: [['/projects', projectsRouter], ['/', orgRouter]],
|
|
17
|
-
* });
|
|
18
|
-
*
|
|
19
|
-
* The chain, in order: /api/health (canary — deliberately BEFORE middleware
|
|
20
|
-
* so uptime probes stay unauthenticated) → your middleware (auth, logging —
|
|
21
|
-
* /api only) → your routers → onError (the `{ error }` envelope) →
|
|
22
|
-
* unmatched /api/* stays JSON 404 → everything else resolves via the ASSETS
|
|
23
|
-
* binding (SPA). Apps needing a different chain keep hand-mounting the
|
|
24
|
-
* same pieces — this factory is the fleet default, not a cage.
|
|
25
|
-
*/
|
|
26
9
|
export interface ApiConfig<E extends ApiEnv = ApiEnv> {
|
|
27
|
-
/** Service name surfaced by /api/health. */
|
|
28
10
|
service: string;
|
|
29
|
-
/** CI-injected build marker for the deploy canary; omitted → null. */
|
|
30
11
|
build?: string;
|
|
31
|
-
/** Routers mounted under /api: ['/stories', storiesRouter]. */
|
|
32
12
|
routers?: ReadonlyArray<readonly [string, Hono<{ Bindings: E }>]>;
|
|
33
|
-
/** Middleware applied to the /api sub-app in order (auth, logging…). */
|
|
34
13
|
middleware?: ReadonlyArray<MiddlewareHandler<{ Bindings: E }>>;
|
|
35
14
|
}
|
|
36
15
|
|
|
37
|
-
/** Cap on replayed paths per bootstrap call — keeps one Worker request
|
|
38
|
-
* inside the free-tier subrequest budget even when a replayed route runs
|
|
39
|
-
* a couple of queries of its own. */
|
|
40
16
|
const BOOTSTRAP_MAX_PATHS = 40;
|
|
41
17
|
|
|
42
18
|
export function createApi<E extends ApiEnv = ApiEnv>(config: ApiConfig<E>): Hono<{ Bindings: E }> {
|
|
@@ -48,15 +24,8 @@ export function createApi<E extends ApiEnv = ApiEnv>(config: ApiConfig<E>): Hono
|
|
|
48
24
|
|
|
49
25
|
const app = new Hono<{ Bindings: E }>();
|
|
50
26
|
app.route('/api', api);
|
|
51
|
-
// Widening ApiEnv→E is safe at runtime (c.env: E ⊇ ApiEnv); hono's Context
|
|
52
|
-
// invariance just refuses the direct cast.
|
|
53
27
|
app.onError(apiOnError as unknown as ErrorHandler<{ Bindings: E }>);
|
|
54
28
|
|
|
55
|
-
// GET /api/bootstrap?paths=/api/a,/api/b — replays the app's own list
|
|
56
|
-
// routes in-process (no network) and bundles their JSON bodies under one
|
|
57
|
-
// response, so a hydrating client pays one round trip per chunk instead
|
|
58
|
-
// of one per collection. Only /api paths are replayed; anything else the
|
|
59
|
-
// router would have answered stays answerable only the normal way.
|
|
60
29
|
app.get('/api/bootstrap', async (c) => {
|
|
61
30
|
const raw = c.req.query('paths') ?? '';
|
|
62
31
|
const paths = [...new Set(raw.split(',').map((p) => p.trim()).filter((p) => p.startsWith('/api/') && p !== '/api/bootstrap'))]
|
package/src/client.ts
CHANGED
|
@@ -27,21 +27,10 @@ export async function apiFetch<T>(path: string, init: { method?: 'POST' | 'PATCH
|
|
|
27
27
|
const body = (await res.json().catch(() => null)) as { error?: string } | null;
|
|
28
28
|
throw new ApiClientError(body?.error ?? `API ${path} responded ${res.status}`, res.status, body);
|
|
29
29
|
}
|
|
30
|
-
// Void endpoints (204 / empty body) resolve to undefined — res.json()
|
|
31
|
-
// would throw a SyntaxError on the empty stream.
|
|
32
30
|
const text = await res.text();
|
|
33
31
|
return (text.length > 0 ? JSON.parse(text) : undefined) as T;
|
|
34
32
|
}
|
|
35
33
|
|
|
36
|
-
/**
|
|
37
|
-
* The repository write idiom in one call: mutate through the API, then
|
|
38
|
-
* refresh the collections the write touched. Refresh only runs when the
|
|
39
|
-
* write succeeded — failures leave the cache untouched.
|
|
40
|
-
*
|
|
41
|
-
* Hosts with a store/cache layer pass their own `refresh` (and usually wrap
|
|
42
|
-
* this in a typed helper binding their collection keys); `keys` stay plain
|
|
43
|
-
* strings here so the package stays store-agnostic.
|
|
44
|
-
*/
|
|
45
34
|
export async function apiWrite<T = void>(
|
|
46
35
|
path: string,
|
|
47
36
|
init: { method: 'POST' | 'PATCH' | 'PUT' | 'DELETE'; json?: unknown },
|
package/src/cookies.ts
CHANGED
|
@@ -1,25 +1,17 @@
|
|
|
1
1
|
export type CookieSameSite = 'lax' | 'strict' | 'none';
|
|
2
2
|
|
|
3
3
|
export interface CookieChannelConfig {
|
|
4
|
-
/** Wire name of the cookie (`prefs_theme`…). */
|
|
5
4
|
key: string;
|
|
6
|
-
/** max-age in seconds — long-lived preferences pass a year. */
|
|
7
5
|
maxAgeSeconds: number;
|
|
8
6
|
sameSite: CookieSameSite;
|
|
9
7
|
}
|
|
10
8
|
|
|
11
9
|
export interface CookieChannel {
|
|
12
|
-
/** Current value, or null when the cookie is absent/empty. */
|
|
13
10
|
read(): string | null;
|
|
14
11
|
write(value: string): void;
|
|
15
12
|
clear(): void;
|
|
16
13
|
}
|
|
17
14
|
|
|
18
|
-
/**
|
|
19
|
-
* One named browser cookie, read/write/clear — the only cookie surface apps
|
|
20
|
-
* should hand-roll. Serializes exactly `key=value; path=/; max-age=N;
|
|
21
|
-
* samesite=X` and parses back defensively (values never contain `;`).
|
|
22
|
-
*/
|
|
23
15
|
export function createCookieChannel(config: CookieChannelConfig): CookieChannel {
|
|
24
16
|
const prefix = `${config.key}=`;
|
|
25
17
|
return {
|
package/src/crud.ts
CHANGED
|
@@ -9,77 +9,42 @@ import { z } from 'zod';
|
|
|
9
9
|
import { normalizeRow, patchTypeErrors, pickPatch, stampUpdate, uid } from './lib';
|
|
10
10
|
import type { ApiEnv } from './env';
|
|
11
11
|
|
|
12
|
-
/**
|
|
13
|
-
* The standard entity resource factory: GET list (soft-deleted hidden,
|
|
14
|
-
* ordered, optional ?limit/&offset/&order) + PATCH /:id (pickPatch-filtered
|
|
15
|
-
* body, updatedAt stamp, 404 on miss) — plus OPT-IN POST create (zod schema,
|
|
16
|
-
* uid prefix, server-side defaults) and DELETE /:id (soft delete). Mount it
|
|
17
|
-
* onto an area router with `.route('/', crudRoutes({ ... }))`.
|
|
18
|
-
*
|
|
19
|
-
* Omitting `create`/`remove` registers exactly GET + PATCH — the 1.x
|
|
20
|
-
* surface, byte-identical. `db` is injectable (tests, Hyperdrive variants);
|
|
21
|
-
* the default builds a per-request neon-http instance as before.
|
|
22
|
-
*
|
|
23
|
-
* listRoutes is the GET-only sibling for append-only collections (event
|
|
24
|
-
* logs, activities, users) whose rows are written server-side only.
|
|
25
|
-
*
|
|
26
|
-
* Entities with business rules (role immutability guards, goods-receipt
|
|
27
|
-
* restock, order transitions…) stay hand-written in their area router —
|
|
28
|
-
* the factory is for plain settings/catalog rows only.
|
|
29
|
-
*/
|
|
30
|
-
|
|
31
12
|
type RequestContext = Context<{ Bindings: ApiEnv }>;
|
|
32
13
|
function defaultDb(c: RequestContext) {
|
|
33
|
-
// Schema-less drizzle: the factory only runs select/insert/update, which
|
|
34
|
-
// never touch the schema registry (only `db.query.*` does) — so it builds
|
|
35
|
-
// its own instance from the request's binding instead of requiring one.
|
|
36
14
|
return drizzle(neon(c.env.DATABASE_URL));
|
|
37
15
|
}
|
|
38
|
-
export type CrudDb = Pick<NeonHttpDatabase<Record<string, never>>, 'select' | 'insert' | 'update'
|
|
16
|
+
export type CrudDb = Pick<NeonHttpDatabase<Record<string, never>>, 'select' | 'insert' | 'update'> & {
|
|
17
|
+
/** Present on neon-http (production Workers); absent on some local drivers (pglite). */
|
|
18
|
+
batch?: NeonHttpDatabase<Record<string, never>>['batch'];
|
|
19
|
+
};
|
|
39
20
|
export type CrudDbFactory = (c: RequestContext) => CrudDb;
|
|
40
21
|
|
|
41
22
|
export type CrudTable = PgTable & { id: PgColumn; deletedAt: PgColumn };
|
|
42
23
|
|
|
43
24
|
export type OrderSpec = { col: PgColumn; dir?: 'asc' | 'desc' };
|
|
44
25
|
|
|
45
|
-
/** Opt-in POST create: zod-validated body, server-generated uid, optional
|
|
46
|
-
* request-scoped stamps (organizationId, createdBy…). */
|
|
47
26
|
export interface CreateSpec {
|
|
48
|
-
/** zod schema for the request body (`.strict()` per fleet convention). */
|
|
49
27
|
schema: z.ZodType;
|
|
50
|
-
/** uid prefix: 'prd' → prd_<base36 ts><counter>. */
|
|
51
28
|
prefix: string;
|
|
52
|
-
/** Server-side stamps merged UNDER the parsed body — body values win. */
|
|
53
29
|
defaults?: (c: RequestContext) => Record<string, unknown>;
|
|
54
30
|
}
|
|
55
31
|
|
|
56
32
|
export interface ListSpec {
|
|
57
|
-
/** Path under /api, e.g. '/activities'. */
|
|
58
33
|
path: string;
|
|
59
34
|
table: PgTable & { deletedAt: PgColumn };
|
|
60
|
-
/** List order; defaults to insertion order. Array = multi-key
|
|
61
|
-
* (primary first, ties broken by the next key). */
|
|
62
35
|
orderBy?: OrderSpec | ReadonlyArray<OrderSpec>;
|
|
63
|
-
/** Injectable db factory (tests, Hyperdrive). Default: per-request
|
|
64
|
-
* drizzle(neon(c.env.DATABASE_URL)) — the 1.x behavior. */
|
|
65
36
|
db?: CrudDbFactory;
|
|
66
37
|
}
|
|
67
38
|
|
|
68
39
|
export interface CrudSpec extends ListSpec {
|
|
69
40
|
table: CrudTable;
|
|
70
|
-
/** Human label for 404s — 'Product' → 'Product not found'. */
|
|
71
41
|
label: string;
|
|
72
|
-
/** Opt-in POST create. Absent ⇒ no POST route (404), as in 1.x. */
|
|
73
42
|
create?: CreateSpec;
|
|
74
|
-
/** Opt-in soft-delete DELETE. Absent ⇒ no DELETE route (404), as in 1.x. */
|
|
75
43
|
remove?: boolean;
|
|
76
44
|
}
|
|
77
45
|
|
|
78
|
-
/** ?limit cap — protects the hydrate-everything thin-read doctrine. */
|
|
79
46
|
const MAX_LIST_LIMIT = 500;
|
|
80
47
|
|
|
81
|
-
/** GET-only list (soft-deleted hidden) for append-only collections — event
|
|
82
|
-
* logs, activities, users. No PATCH: these rows are written server-side. */
|
|
83
48
|
export function listRoutes(spec: ListSpec): Hono<{ Bindings: ApiEnv }> {
|
|
84
49
|
const { path, table, orderBy } = spec;
|
|
85
50
|
const getDb = spec.db ?? defaultDb;
|
|
@@ -105,8 +70,6 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
|
|
|
105
70
|
const db = getDb(c);
|
|
106
71
|
const q = db.select().from(table).where(isNull(table.deletedAt)).$dynamic();
|
|
107
72
|
|
|
108
|
-
// ?order=col | -col (leading '-' = desc) — whitelisted against the
|
|
109
|
-
// table's own property columns; an explicit order overrides spec.orderBy.
|
|
110
73
|
const orderParam = c.req.query('order');
|
|
111
74
|
if (orderParam !== undefined) {
|
|
112
75
|
const wantDesc = orderParam.startsWith('-');
|
|
@@ -119,9 +82,6 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
|
|
|
119
82
|
q.orderBy(...orders.map((o) => (o.dir === 'desc' ? desc(o.col) : asc(o.col))));
|
|
120
83
|
}
|
|
121
84
|
|
|
122
|
-
// ?limit/&offset= — absent params add no clauses: the 1.x query exactly.
|
|
123
|
-
// offset without order follows the spec/default insertion order (the
|
|
124
|
-
// same caveat 1.x lists always had).
|
|
125
85
|
const limitParam = c.req.query('limit');
|
|
126
86
|
if (limitParam !== undefined) {
|
|
127
87
|
const n = Number(limitParam);
|
|
@@ -148,9 +108,6 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
|
|
|
148
108
|
const db = getDb(c);
|
|
149
109
|
const [row] = await db
|
|
150
110
|
.update(table)
|
|
151
|
-
// Generic tables can't carry per-table set types — values are already
|
|
152
|
-
// column-filtered by pickPatch, so the cast is purely type-level. The
|
|
153
|
-
// updatedAt stamp matches the table's column type (date vs timestamp).
|
|
154
111
|
.set({ ...patch, ...stampUpdate(table) } as never)
|
|
155
112
|
.where(and(eq(table.id, c.req.param('id')), isNull(table.deletedAt)))
|
|
156
113
|
.returning();
|
|
@@ -172,8 +129,6 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
|
|
|
172
129
|
const db = getDb(c);
|
|
173
130
|
const [row] = await db
|
|
174
131
|
.insert(table)
|
|
175
|
-
// id LAST: server-generated, never client-supplied. createdAt/
|
|
176
|
-
// updatedAt come from the DB column defaults (fleet convention).
|
|
177
132
|
.values({ ...defaults?.(c), ...body, id: uid(prefix) } as never)
|
|
178
133
|
.returning();
|
|
179
134
|
return c.json(row, 201);
|
|
@@ -185,8 +140,6 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
|
|
|
185
140
|
const db = getDb(c);
|
|
186
141
|
const [row] = await db
|
|
187
142
|
.update(table)
|
|
188
|
-
// Soft delete: every read filters isNull(deletedAt), so the row
|
|
189
|
-
// vanishes from lists without losing history.
|
|
190
143
|
.set({ deletedAt: new Date(), ...stampUpdate(table) } as never)
|
|
191
144
|
.where(and(eq(table.id, c.req.param('id')), isNull(table.deletedAt)))
|
|
192
145
|
.returning({ id: table.id });
|
package/src/db.ts
CHANGED
|
@@ -1,14 +1,6 @@
|
|
|
1
1
|
import { drizzle } from 'drizzle-orm/neon-http';
|
|
2
2
|
import { neon } from '@neondatabase/serverless';
|
|
3
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
4
|
export function getDb<TSchema extends Record<string, unknown>>(env: { DATABASE_URL: string }, schema: TSchema) {
|
|
13
5
|
const sql = neon(env.DATABASE_URL);
|
|
14
6
|
return drizzle(sql, { schema });
|
package/src/docstore.ts
CHANGED
|
@@ -10,28 +10,6 @@ import { validateJson } from './validator';
|
|
|
10
10
|
import type { CrudDb } from './crud';
|
|
11
11
|
import type { ApiEnv } from './env';
|
|
12
12
|
|
|
13
|
-
/**
|
|
14
|
-
* The doc-store resource factory for jsonb-wire-faithful architectures:
|
|
15
|
-
* the client owns whole documents (nested shapes, client-generated ids,
|
|
16
|
-
* ISO date strings inside the doc) and the table stores them verbatim in
|
|
17
|
-
* one `data jsonb` column beside the epoch-ms bookkeeping trio. The row
|
|
18
|
-
* never leaks — the wire speaks docs only.
|
|
19
|
-
*
|
|
20
|
-
* One call returns the router (GET list / GET-PUT-PATCH-DELETE by id /
|
|
21
|
-
* POST /batch) AND the motor functions (putDoc/patchDoc/softDeleteDoc/
|
|
22
|
-
* listDocs/getDoc) that seed scripts and server-side workflows call
|
|
23
|
-
* directly. Status machines ride along as declarative `transitions` maps and
|
|
24
|
-
* write guards as `validate` hooks; violations surface as WorkflowError → 400.
|
|
25
|
-
*
|
|
26
|
-
* Router config scales it from open admin surfaces to authenticated user
|
|
27
|
-
* sync APIs: `scopeOf` derives the scope per request from the session (401
|
|
28
|
-
* when it resolves null, replacing the `?scope=` query), `routeKeys`
|
|
29
|
-
* allowlists which collections the router serves (others 404 as unknown,
|
|
30
|
-
* staying motor-only), `onPut`/`onPatch` shape writes (server-owned fields,
|
|
31
|
-
* deep merges), and `bulkBatch` runs the batch as grouped bulk writes that
|
|
32
|
-
* keep large syncs inside the Workers subrequest budget.
|
|
33
|
-
*/
|
|
34
|
-
|
|
35
13
|
export type Doc = Record<string, unknown> & { id: string };
|
|
36
14
|
export type DocInput = Record<string, unknown>;
|
|
37
15
|
|
|
@@ -42,31 +20,17 @@ export interface DocScopeSpec {
|
|
|
42
20
|
field: string;
|
|
43
21
|
}
|
|
44
22
|
|
|
45
|
-
/**
|
|
46
|
-
* Cross-cutting write guard: runs inside putDoc before the write, covering
|
|
47
|
-
* every path that funnels through it (PUT, PATCH-merged, batch puts,
|
|
48
|
-
* server-side calls) but never putDocs seeds. Receives the incoming doc,
|
|
49
|
-
* the current row when one exists, and the db for cross-collection reads
|
|
50
|
-
* (booking-conflict style rules). Throw WorkflowError (or ApiError) to
|
|
51
|
-
* reject the write.
|
|
52
|
-
*/
|
|
53
23
|
export type DocValidateFn = (args: { db: CrudDb; doc: DocInput; existing?: DocInput }) => void | Promise<void>;
|
|
54
24
|
|
|
55
25
|
export type DocAfterWriteFn = (args: { db: CrudDb; key: string; id: string; doc: Doc; op: 'put' | 'delete' }) => void | Promise<void>;
|
|
56
26
|
|
|
57
27
|
export interface DocCollectionSpec {
|
|
58
|
-
/** Wire collection name — the URL segment and the batch op key. */
|
|
59
28
|
key: string;
|
|
60
29
|
table: DocTable;
|
|
61
|
-
/** Extra typed columns derived from the doc (users: email/name/flags). */
|
|
62
30
|
columns?: (doc: DocInput) => Record<string, unknown>;
|
|
63
|
-
/** Collections that must always write the one fixed id. */
|
|
64
31
|
singletonId?: string;
|
|
65
|
-
/** Status state machine: allowed targets per current status. */
|
|
66
32
|
transitions?: Readonly<Record<string, readonly string[]>>;
|
|
67
|
-
/** Doc field the transitions guard reads. Default 'status'. */
|
|
68
33
|
statusKey?: string;
|
|
69
|
-
/** Write guard — see DocValidateFn. */
|
|
70
34
|
validate?: DocValidateFn;
|
|
71
35
|
idField?: string;
|
|
72
36
|
scope?: DocScopeSpec;
|
|
@@ -75,17 +39,13 @@ export interface DocCollectionSpec {
|
|
|
75
39
|
|
|
76
40
|
export interface DocWriteHookArgs {
|
|
77
41
|
key: string;
|
|
78
|
-
/** Incoming document — hooks may rewrite server-owned fields in place. */
|
|
79
42
|
doc: Record<string, unknown>;
|
|
80
|
-
/** Current stored doc, or null when the write creates. */
|
|
81
43
|
existing: Record<string, unknown> | null;
|
|
82
|
-
/** Session scope when `scopeOf` resolved one (else undefined). */
|
|
83
44
|
scope: string | undefined;
|
|
84
45
|
}
|
|
85
46
|
|
|
86
47
|
export interface DocPatchHookArgs {
|
|
87
48
|
key: string;
|
|
88
|
-
/** Incoming patch — hooks may rewrite it in place. */
|
|
89
49
|
patch: Record<string, unknown>;
|
|
90
50
|
existing: Doc | null;
|
|
91
51
|
scope: string | undefined;
|
|
@@ -93,40 +53,22 @@ export interface DocPatchHookArgs {
|
|
|
93
53
|
|
|
94
54
|
export interface DocStoreSpec<E extends ApiEnv = ApiEnv> {
|
|
95
55
|
collections: readonly DocCollectionSpec[];
|
|
96
|
-
/** Injectable db factory (tests, Hyperdrive). Default: per-request neon-http. */
|
|
97
56
|
db?: (c: Context<{ Bindings: E }>) => CrudDb;
|
|
98
|
-
/** POST /batch op cap. Default 2000. */
|
|
99
57
|
maxBatch?: number;
|
|
100
|
-
/** Restrict the generated ROUTER to these keys (authz allowlist — admin
|
|
101
|
-
* collections stay motor-only). Others answer 404 as if unknown.
|
|
102
|
-
* Default: every collection is routed. */
|
|
103
58
|
routeKeys?: readonly string[];
|
|
104
|
-
/** Session-derived scope for the router: resolves per request (better-auth
|
|
105
|
-
* user id, tenant id…). Null answers 401. When set it replaces the
|
|
106
|
-
* `?scope=` query: scoped collections are filtered by it and puts get it
|
|
107
|
-
* stamped, so clients cannot read or write another scope's rows. */
|
|
108
59
|
scopeOf?: (c: Context<{ Bindings: E }>) => Promise<string | null>;
|
|
109
|
-
/** Router-level put shaping (server-owned fields) before the write. */
|
|
110
60
|
onPut?: (args: DocWriteHookArgs) => void | Promise<void>;
|
|
111
|
-
/** Router-level patch shaping (deep merges, server-owned fields). */
|
|
112
61
|
onPatch?: (args: DocPatchHookArgs) => void | Promise<void>;
|
|
113
|
-
/** Batch runs as grouped bulk writes — one guard read + chunked upserts
|
|
114
|
-
* per collection instead of per-op putDoc — keeping large sync batches
|
|
115
|
-
* inside the Workers subrequest budget. Default: per-op. */
|
|
116
62
|
bulkBatch?: boolean;
|
|
117
63
|
}
|
|
118
64
|
|
|
119
65
|
export class WorkflowError extends Error {}
|
|
120
66
|
export class UnknownCollectionError extends Error {}
|
|
121
67
|
|
|
122
|
-
/** Status machine check: staying put is always allowed. */
|
|
123
68
|
export function canTransition(map: Readonly<Record<string, readonly string[]>>, from: string, to: string): boolean {
|
|
124
69
|
return from === to || (map[from] ?? []).includes(to);
|
|
125
70
|
}
|
|
126
71
|
|
|
127
|
-
/** ISO string → epoch ms; anything unparsable falls back to now. The
|
|
128
|
-
* epoch-0 instant (1970-01-01T00:00:00Z) parses to 0 and must stay 0 —
|
|
129
|
-
* a truthiness check would silently rewrite it to "now". */
|
|
130
72
|
export function epoch(iso: unknown): number {
|
|
131
73
|
if (typeof iso !== 'string') return Date.now();
|
|
132
74
|
const ms = Date.parse(iso);
|
|
@@ -203,8 +145,6 @@ export function docStore<E extends ApiEnv = ApiEnv>(spec: DocStoreSpec<E>) {
|
|
|
203
145
|
const id = docIdOf(col, doc);
|
|
204
146
|
const values: Record<string, unknown> = {
|
|
205
147
|
id,
|
|
206
|
-
// epoch() already falls back to now for unparsable input; the extra
|
|
207
|
-
// `|| now` would rewrite a legitimate 0 (epoch-0 instant) to now.
|
|
208
148
|
createdAt: epoch(doc.createdAt),
|
|
209
149
|
updatedAt: epoch(doc.updatedAt),
|
|
210
150
|
deletedAt: null as number | null,
|
|
@@ -252,9 +192,6 @@ export function docStore<E extends ApiEnv = ApiEnv>(spec: DocStoreSpec<E>) {
|
|
|
252
192
|
if (col.afterWrite) await col.afterWrite({ db, key, id, doc: doc as Doc, op: 'put' });
|
|
253
193
|
}
|
|
254
194
|
|
|
255
|
-
/** Trusted bulk load for seed scripts: chunked multi-row upsert with the
|
|
256
|
-
* same revive semantics as putDoc, without per-row workflow/singleton
|
|
257
|
-
* guards (seeds write fresh, consistent datasets by construction). */
|
|
258
195
|
async function putDocs(db: CrudDb, key: string, docs: readonly DocInput[], chunkSize = 200): Promise<number> {
|
|
259
196
|
const col = requireSpec(key);
|
|
260
197
|
let count = 0;
|
|
@@ -321,6 +258,38 @@ export function docStore<E extends ApiEnv = ApiEnv>(spec: DocStoreSpec<E>) {
|
|
|
321
258
|
return rows.map((r) => r.data as Doc);
|
|
322
259
|
}
|
|
323
260
|
|
|
261
|
+
/**
|
|
262
|
+
* List many collections in ONE Neon HTTP round trip when the driver
|
|
263
|
+
* supports db.batch (neon-http on Workers). Workers plans cap subrequests
|
|
264
|
+
* per invocation (50 on the free tier), so hydrating dozens of collections
|
|
265
|
+
* with parallel listDocs calls trips the cap — this sidesteps it. Drivers
|
|
266
|
+
* without batch (local pglite) fall back to sequential selects.
|
|
267
|
+
*/
|
|
268
|
+
async function listDocsBatch(db: CrudDb, keys: readonly string[], scope?: string): Promise<Record<string, Doc[]>> {
|
|
269
|
+
const cols = keys.map((key) => requireSpec(key));
|
|
270
|
+
const queries = cols.map((col) => {
|
|
271
|
+
const conds = [isNull(col.table.deletedAt)];
|
|
272
|
+
if (col.scope && scope !== undefined) conds.push(eq(col.scope.column, scope));
|
|
273
|
+
return db
|
|
274
|
+
.select({ data: col.table.data })
|
|
275
|
+
.from(col.table)
|
|
276
|
+
.where(and(...conds))
|
|
277
|
+
.orderBy(col.table.id);
|
|
278
|
+
});
|
|
279
|
+
const out: Record<string, Doc[]> = {};
|
|
280
|
+
if (typeof db.batch === 'function') {
|
|
281
|
+
const results = await db.batch(queries as never);
|
|
282
|
+
cols.forEach((col, i) => {
|
|
283
|
+
out[col.key] = (results[i] as { data: unknown }[]).map((r) => r.data as Doc);
|
|
284
|
+
});
|
|
285
|
+
return out;
|
|
286
|
+
}
|
|
287
|
+
for (let i = 0; i < cols.length; i += 1) {
|
|
288
|
+
out[cols[i].key] = (await queries[i]).map((r) => r.data as Doc);
|
|
289
|
+
}
|
|
290
|
+
return out;
|
|
291
|
+
}
|
|
292
|
+
|
|
324
293
|
async function getDoc(db: CrudDb, key: string, id: string, scope?: string): Promise<Doc | undefined> {
|
|
325
294
|
const col = requireSpec(key);
|
|
326
295
|
const [row] = await db
|
|
@@ -578,6 +547,7 @@ export function docStore<E extends ApiEnv = ApiEnv>(spec: DocStoreSpec<E>) {
|
|
|
578
547
|
patchDoc,
|
|
579
548
|
softDeleteDoc,
|
|
580
549
|
listDocs,
|
|
550
|
+
listDocsBatch,
|
|
581
551
|
getDoc,
|
|
582
552
|
};
|
|
583
553
|
}
|
package/src/env.ts
CHANGED
|
@@ -1,12 +1,5 @@
|
|
|
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
1
|
export interface ApiEnv {
|
|
7
|
-
/** Neon Postgres connection string (wrangler secret / .dev.vars). */
|
|
8
2
|
DATABASE_URL: string;
|
|
9
|
-
/** Static assets binding (Workers Static Assets) for SPA fallback. */
|
|
10
3
|
ASSETS: {
|
|
11
4
|
fetch(input: Request | string, init?: RequestInit): Promise<Response>;
|
|
12
5
|
};
|
package/src/errors.ts
CHANGED
|
@@ -4,28 +4,16 @@ import { HTTPException } from 'hono/http-exception';
|
|
|
4
4
|
import { ZodError } from 'zod';
|
|
5
5
|
import type { ApiEnv } from './env';
|
|
6
6
|
|
|
7
|
-
/**
|
|
8
|
-
* The error layer of the `{ error, details? }` envelope. Routes throw
|
|
9
|
-
* `ApiError` (or let drizzle/postgres errors bubble) and `apiOnError` —
|
|
10
|
-
* installed by `createApi`, or by hand via `app.onError(apiOnError)` —
|
|
11
|
-
* maps everything to the envelope. Unexpected errors never leak internals:
|
|
12
|
-
* they answer a generic 500 and log server-side.
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
/** A deliberate 4xx: the route's own words, the envelope's shape. */
|
|
16
7
|
export class ApiError extends Error {
|
|
17
8
|
constructor(
|
|
18
|
-
/** Literal status this error answers with (404, 400, 409…). */
|
|
19
9
|
public readonly status: ContentfulStatusCode,
|
|
20
10
|
message: string,
|
|
21
|
-
/** Optional details (zod fieldErrors, ids, …). */
|
|
22
11
|
public readonly details?: unknown,
|
|
23
12
|
) {
|
|
24
13
|
super(message);
|
|
25
14
|
this.name = 'ApiError';
|
|
26
15
|
}
|
|
27
16
|
|
|
28
|
-
/** `404 { error: '${label} not found' }` — the fleet's miss shape. */
|
|
29
17
|
static notFound(label: string): ApiError {
|
|
30
18
|
return new ApiError(404, `${label} not found`);
|
|
31
19
|
}
|
|
@@ -43,11 +31,6 @@ export class ApiError extends Error {
|
|
|
43
31
|
}
|
|
44
32
|
}
|
|
45
33
|
|
|
46
|
-
/**
|
|
47
|
-
* Postgres unique_violation — the code sits on the error itself (pglite,
|
|
48
|
-
* node-postgres) or nested in a driver cause-chain (neon-http). Depth-capped
|
|
49
|
-
* walk so malformed causes can't loop.
|
|
50
|
-
*/
|
|
51
34
|
export function isUniqueViolation(err: unknown): boolean {
|
|
52
35
|
let e: unknown = err;
|
|
53
36
|
for (let depth = 0; e !== null && typeof e === 'object' && depth < 3; depth += 1) {
|
|
@@ -57,7 +40,6 @@ export function isUniqueViolation(err: unknown): boolean {
|
|
|
57
40
|
return false;
|
|
58
41
|
}
|
|
59
42
|
|
|
60
|
-
/** The standard onError: every failure speaks the envelope. */
|
|
61
43
|
export const apiOnError: ErrorHandler<{ Bindings: ApiEnv }> = (err, c) => {
|
|
62
44
|
if (err instanceof ApiError) {
|
|
63
45
|
return c.json(
|
|
@@ -69,14 +51,11 @@ export const apiOnError: ErrorHandler<{ Bindings: ApiEnv }> = (err, c) => {
|
|
|
69
51
|
return c.json({ error: err.message }, err.status);
|
|
70
52
|
}
|
|
71
53
|
if (err instanceof ZodError) {
|
|
72
|
-
// Safety net: validateJson normally answers inline, but a hand-rolled
|
|
73
|
-
// safeParse that throws lands here with the same contract.
|
|
74
54
|
return c.json({ error: 'Invalid request body', details: err.flatten().fieldErrors }, 400);
|
|
75
55
|
}
|
|
76
56
|
if (isUniqueViolation(err)) {
|
|
77
57
|
return c.json({ error: 'Already exists' }, 409);
|
|
78
58
|
}
|
|
79
|
-
// Unexpected: log server-side, answer generic — never leak internals.
|
|
80
59
|
console.error(`[api] ${c.req.method} ${c.req.path}:`, err);
|
|
81
60
|
return c.json({ error: 'Internal server error' }, 500);
|
|
82
61
|
};
|
package/src/handlers.ts
CHANGED
|
@@ -1,18 +1,6 @@
|
|
|
1
1
|
import type { Handler } from 'hono';
|
|
2
2
|
import type { ApiEnv } from './env';
|
|
3
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
4
|
export const apiNotFound: Handler<{ Bindings: ApiEnv }> = (c) => c.json({ error: 'Not found' }, 404);
|
|
10
5
|
|
|
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
6
|
export const spaFallback: Handler<{ Bindings: ApiEnv }> = (c) => c.env.ASSETS.fetch(c.req.raw);
|
package/src/health.ts
CHANGED
|
@@ -1,12 +1,6 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
2
|
import type { ApiEnv } from './env';
|
|
3
3
|
|
|
4
|
-
/**
|
|
5
|
-
* The deploy canary: `GET /api/health` → `{ ok, service, build, time }`.
|
|
6
|
-
* `build` is the CI-injected marker (missing → null) — bump it so the E2E
|
|
7
|
-
* canary can prove the new Worker is the one answering. Replaces the
|
|
8
|
-
* per-app routes/health.ts that 1.x apps copied around verbatim.
|
|
9
|
-
*/
|
|
10
4
|
export function healthRouter<E extends ApiEnv = ApiEnv>(opts: { service: string; build?: string }): Hono<{ Bindings: E }> {
|
|
11
5
|
const router = new Hono<{ Bindings: E }>();
|
|
12
6
|
router.get('/', (c) =>
|
package/src/http.ts
CHANGED
|
@@ -2,29 +2,17 @@ import type { Context } from 'hono';
|
|
|
2
2
|
import { getCookie } from 'hono/cookie';
|
|
3
3
|
import { matchesEtag } from './etag';
|
|
4
4
|
|
|
5
|
-
/** Cache-Control catalog for auth-private responses. */
|
|
6
5
|
export const CACHE_CONTROLS = {
|
|
7
|
-
/** Revalidate every time (audio/video streams, mutable payloads). */
|
|
8
6
|
privateRevalidate: 'private, max-age=0, must-revalidate',
|
|
9
|
-
/** Browser-fresh for a day (cover art and other immutable-ish assets). */
|
|
10
7
|
privateDay: 'private, max-age=86400',
|
|
11
|
-
/** ETag-carried payloads: cache allowed, revalidate on every use. */
|
|
12
8
|
etagRevalidate: 'no-cache',
|
|
13
9
|
} as const;
|
|
14
10
|
|
|
15
11
|
export interface RequestScopeConfig {
|
|
16
|
-
/** Query parameter that carries the scope explicitly (`?lang=ko`). */
|
|
17
12
|
queryParam: string;
|
|
18
|
-
/** Cookie consulted when the query parameter is absent. */
|
|
19
13
|
cookieKey: string;
|
|
20
14
|
}
|
|
21
15
|
|
|
22
|
-
/**
|
|
23
|
-
* Resolve a request-scoped value — a language, a tenant, a workspace —
|
|
24
|
-
* from the explicit query parameter first, then the ambient cookie, or
|
|
25
|
-
* null when the request carries neither. Routes answer a 400 on null
|
|
26
|
-
* instead of guessing a default.
|
|
27
|
-
*/
|
|
28
16
|
export function requestScopeOf(c: Context, config: RequestScopeConfig): string | null {
|
|
29
17
|
const fromQuery = c.req.query(config.queryParam);
|
|
30
18
|
if (fromQuery !== undefined && fromQuery.length > 0) return fromQuery;
|
|
@@ -33,23 +21,11 @@ export function requestScopeOf(c: Context, config: RequestScopeConfig): string |
|
|
|
33
21
|
return null;
|
|
34
22
|
}
|
|
35
23
|
|
|
36
|
-
/**
|
|
37
|
-
* The 304 half of the If-None-Match dance on its own: returns the empty
|
|
38
|
-
* Not-Modified response when the request's If-None-Match weak-compares
|
|
39
|
-
* against `etag`, or null when the caller must build and send the full
|
|
40
|
-
* payload — so routes can skip the expensive work before committing to it.
|
|
41
|
-
*/
|
|
42
24
|
export function notModifiedResponse(c: Context, etag: string): Response | null {
|
|
43
25
|
if (!matchesEtag(c.req.header('If-None-Match'), etag)) return null;
|
|
44
26
|
return c.body(null, 304, { ETag: etag, 'Cache-Control': CACHE_CONTROLS.etagRevalidate });
|
|
45
27
|
}
|
|
46
28
|
|
|
47
|
-
/**
|
|
48
|
-
* The If-None-Match dance in one call: weak-compares the request's
|
|
49
|
-
* If-None-Match against `etag` and answers 304 (ETag + no-cache headers,
|
|
50
|
-
* empty body) or 200 (same headers plus the JSON payload). Payload types
|
|
51
|
-
* stay the caller's — only the transport is shared.
|
|
52
|
-
*/
|
|
53
29
|
export function respondWithEtag(c: Context, etag: string, payload: unknown) {
|
|
54
30
|
const notModified = notModifiedResponse(c, etag);
|
|
55
31
|
if (notModified) return notModified;
|
|
@@ -58,10 +34,6 @@ export function respondWithEtag(c: Context, etag: string, payload: unknown) {
|
|
|
58
34
|
return c.json(payload);
|
|
59
35
|
}
|
|
60
36
|
|
|
61
|
-
/**
|
|
62
|
-
* `500 { error, details }` for caught errors in hand-rolled routes —
|
|
63
|
-
* the envelope's last resort outside the global onError.
|
|
64
|
-
*/
|
|
65
37
|
export function internalError(c: Context, message: string, err?: unknown) {
|
|
66
38
|
return c.json(
|
|
67
39
|
{
|
package/src/index.ts
CHANGED
|
@@ -1,30 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @umituz/web-hono — the API backend platform for single-Worker apps on
|
|
3
|
-
* Cloudflare (SPA assets + `/api/*` Hono) with Neon Postgres via drizzle.
|
|
4
|
-
*
|
|
5
|
-
* Apps keep their schema (with TABLE_PREFIX), domain routers, zod schemas,
|
|
6
|
-
* and business rules — this package owns the cross-cutting skeleton:
|
|
7
|
-
* the createApi app factory, the error envelope layer, the full-CRUD
|
|
8
|
-
* resource factory, getDb, the uid/pickPatch/stampUpdate/trio/actor
|
|
9
|
-
* helpers, the ISO date-string primitives (isoNow/todayISO/addDaysISO),
|
|
10
|
-
* the org-scoped lookups (resolveOrg/orgHasMode/nextNumber),
|
|
11
|
-
* the audit and notification writes, findRow/softDelete, the JSON-404
|
|
12
|
-
* and SPA-fallback handlers, and the ApiEnv binding types.
|
|
13
|
-
*
|
|
14
|
-
* Entry points:
|
|
15
|
-
* `.` server core (this file) — includes docStore (jsonb doc factories)
|
|
16
|
-
* `/types` Row/NewRow/Serialized/ClientRow — the schema→client type bridge
|
|
17
|
-
* `/validator` validateJson — the zod `{ error, details }` body contract
|
|
18
|
-
* `/client` apiFetch / apiWrite — the same-origin API client
|
|
19
|
-
* `/store` createStore — the fetch-backed reactive store
|
|
20
|
-
* `/store/react` makeStoreHooks — useQuery/useDbValue/useCollection/useHydration
|
|
21
|
-
* `/sync` snapshotDocs / diffOps / pushOps — the doc-sync diff machine
|
|
22
|
-
* `/lifecycle` reset / snapshot / seed — the shared-Neon db lifecycle
|
|
23
|
-
* `/cookies` createCookieChannel — one named browser cookie, read/write/clear
|
|
24
|
-
* `/http` requestScopeOf / respondWithEtag / internalError / CACHE_CONTROLS
|
|
25
|
-
* `/r2` streamFromBucket / parseRange — ranged R2 streaming
|
|
26
|
-
* `/resource` createResource — TTL-cached async value with subscribe
|
|
27
|
-
*/
|
|
28
1
|
export { createApi } from './api';
|
|
29
2
|
export type { ApiConfig } from './api';
|
|
30
3
|
export { healthRouter } from './health';
|
package/src/lib.ts
CHANGED
|
@@ -2,24 +2,16 @@ import { getTableColumns } from 'drizzle-orm';
|
|
|
2
2
|
import { timestamp } from 'drizzle-orm/pg-core';
|
|
3
3
|
import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
|
|
4
4
|
|
|
5
|
-
/** Server-side id generation: `${prefix}_${base36 timestamp}${base36 counter}`. */
|
|
6
5
|
let idCounter = 0;
|
|
7
6
|
export function uid(prefix: string): string {
|
|
8
7
|
idCounter += 1;
|
|
9
8
|
return `${prefix}_${Date.now().toString(36)}${idCounter.toString(36)}`;
|
|
10
9
|
}
|
|
11
10
|
|
|
12
|
-
/** Write-schema actor pair with the fleet defaults. */
|
|
13
11
|
export function actor(input: { actorId?: string; actorName?: string }, name = 'Back office'): { actorId: string; actorName: string } {
|
|
14
12
|
return { actorId: input.actorId ?? 'api', actorName: input.actorName ?? name };
|
|
15
13
|
}
|
|
16
14
|
|
|
17
|
-
/**
|
|
18
|
-
* Fleet time-trio columns for timestamptz tables — spread into a pgTable
|
|
19
|
-
* definition: `{ id: text('id').primaryKey(), name: text('name'), ...trio() }`.
|
|
20
|
-
* One encoding of the fleet standard instead of the three (inline columns,
|
|
21
|
-
* factory functions, spread objects) the 1.x apps each hand-rolled.
|
|
22
|
-
*/
|
|
23
15
|
export function trio() {
|
|
24
16
|
return {
|
|
25
17
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
|
@@ -28,10 +20,8 @@ export function trio() {
|
|
|
28
20
|
};
|
|
29
21
|
}
|
|
30
22
|
|
|
31
|
-
/** Fields no client may ever patch. */
|
|
32
23
|
const PROTECTED_KEYS = new Set(['id', 'createdAt', 'updatedAt', 'deletedAt']);
|
|
33
24
|
|
|
34
|
-
/** Local calendar day as 'YYYY-MM-DD' — the stamp for date-string columns. */
|
|
35
25
|
function localDateStamp(): string {
|
|
36
26
|
const d = new Date();
|
|
37
27
|
const mm = String(d.getMonth() + 1).padStart(2, '0');
|
|
@@ -39,28 +29,13 @@ function localDateStamp(): string {
|
|
|
39
29
|
return `${d.getFullYear()}-${mm}-${dd}`;
|
|
40
30
|
}
|
|
41
31
|
|
|
42
|
-
/**
|
|
43
|
-
* updatedAt stamp matching the table's column type. Fleet-standard tables
|
|
44
|
-
* (timestamp withTimezone) get a Date — unchanged from previous versions.
|
|
45
|
-
* Domains that model updatedAt as a calendar date column (date string,
|
|
46
|
-
* date-string) get today's local 'YYYY-MM-DD' instead of a Date that the
|
|
47
|
-
* column cannot carry.
|
|
48
|
-
*/
|
|
49
32
|
export function stampUpdate(table: PgTable): Record<string, unknown> {
|
|
50
33
|
const columns = getTableColumns(table) as unknown as Record<string, { columnType: string }>;
|
|
51
34
|
const updatedAt = columns.updatedAt;
|
|
52
|
-
// No updatedAt column → stamp nothing; stamping a nonexistent column would
|
|
53
|
-
// fail the drizzle update at runtime.
|
|
54
35
|
if (!updatedAt) return {};
|
|
55
36
|
return updatedAt.columnType.includes('Timestamp') ? { updatedAt: new Date() } : { updatedAt: localDateStamp() };
|
|
56
37
|
}
|
|
57
38
|
|
|
58
|
-
/**
|
|
59
|
-
* Filters a JSON patch body down to the table's own columns (drizzle speaks
|
|
60
|
-
* the camelCase schema PROPERTY names — which are the domain field names).
|
|
61
|
-
* ISO-datetime strings destined for timestamptz columns become Date objects.
|
|
62
|
-
* Returns null when nothing updatable remains.
|
|
63
|
-
*/
|
|
64
39
|
export function pickPatch(table: PgTable, body: unknown): Record<string, unknown> | null {
|
|
65
40
|
if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;
|
|
66
41
|
const columns = getTableColumns(table) as unknown as Record<string, { columnType: string }>;
|
|
@@ -71,7 +46,7 @@ export function pickPatch(table: PgTable, body: unknown): Record<string, unknown
|
|
|
71
46
|
if (!col || value === undefined) continue;
|
|
72
47
|
if (typeof value === 'string' && col.columnType.includes('Timestamp')) {
|
|
73
48
|
const d = new Date(value);
|
|
74
|
-
if (Number.isNaN(d.getTime())) continue;
|
|
49
|
+
if (Number.isNaN(d.getTime())) continue;
|
|
75
50
|
out[key] = d;
|
|
76
51
|
} else {
|
|
77
52
|
out[key] = value;
|
|
@@ -80,12 +55,6 @@ export function pickPatch(table: PgTable, body: unknown): Record<string, unknown
|
|
|
80
55
|
return Object.keys(out).length > 0 ? out : null;
|
|
81
56
|
}
|
|
82
57
|
|
|
83
|
-
/**
|
|
84
|
-
* Column-type check for schema-less patches (the crudRoutes PATCH path):
|
|
85
|
-
* a JSON value whose primitive type contradicts the column's drizzle
|
|
86
|
-
* dataType would otherwise surface as a driver 500. Returns the details
|
|
87
|
-
* object for the 400 envelope, or null when every value fits.
|
|
88
|
-
*/
|
|
89
58
|
export function patchTypeErrors(table: PgTable, patch: Record<string, unknown>): Record<string, string[]> | null {
|
|
90
59
|
const columns = getTableColumns(table) as unknown as Record<string, PgColumn>;
|
|
91
60
|
const errors: Record<string, string[]> = {};
|
|
@@ -114,12 +83,6 @@ export function patchTypeErrors(table: PgTable, patch: Record<string, unknown>):
|
|
|
114
83
|
return Object.keys(errors).length > 0 ? errors : null;
|
|
115
84
|
}
|
|
116
85
|
|
|
117
|
-
/**
|
|
118
|
-
* Normalizes a create payload against the table before insert: drops keys
|
|
119
|
-
* that are not table columns, turns ISO-datetime strings destined for
|
|
120
|
-
* timestamptz columns into Dates, and maps '' to NULL on nullable columns
|
|
121
|
-
* (empty form fields). The insert-side twin of pickPatch.
|
|
122
|
-
*/
|
|
123
86
|
export function normalizeRow(table: PgTable, input: Record<string, unknown>): Record<string, unknown> {
|
|
124
87
|
const columns = getTableColumns(table) as unknown as Record<string, { columnType: string; notNull: boolean }>;
|
|
125
88
|
const out: Record<string, unknown> = {};
|
|
@@ -140,7 +103,6 @@ export function normalizeRow(table: PgTable, input: Record<string, unknown>): Re
|
|
|
140
103
|
return out;
|
|
141
104
|
}
|
|
142
105
|
|
|
143
|
-
/** Run `fn` over items in `limit`-sized waves — bounded DB subrequest fan-out. */
|
|
144
106
|
export async function mapLimit<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
|
|
145
107
|
const out: R[] = [];
|
|
146
108
|
for (let i = 0; i < items.length; i += limit) {
|
|
@@ -149,7 +111,6 @@ export async function mapLimit<T, R>(items: T[], limit: number, fn: (item: T) =>
|
|
|
149
111
|
return out;
|
|
150
112
|
}
|
|
151
113
|
|
|
152
|
-
/** Retry transient Neon/HTTP blips: up to `attempts` tries, backoff 250ms·n. */
|
|
153
114
|
export async function withRetry<T>(fn: () => Promise<T>, attempts = 3): Promise<T> {
|
|
154
115
|
let lastErr: unknown;
|
|
155
116
|
for (let i = 0; i < attempts; i++) {
|
package/src/lifecycle.ts
CHANGED
|
@@ -5,36 +5,16 @@ import type { PgTable } from 'drizzle-orm/pg-core';
|
|
|
5
5
|
import { readFileSync, writeFileSync } from 'node:fs';
|
|
6
6
|
import { gzipSync, gunzipSync } from 'node:zlib';
|
|
7
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 (the
|
|
12
|
-
* `scripts/tables.ts` shape) shared by all three operations so snapshot
|
|
13
|
-
* and seed can never diverge.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
8
|
export interface TableSpec {
|
|
17
|
-
/** Snapshot/seed key AND the SQL table name — e.g. 'users' for `prefix_users`. */
|
|
18
9
|
name: string;
|
|
19
10
|
table: PgTable;
|
|
20
11
|
}
|
|
21
12
|
|
|
22
|
-
/** The on-disk shape of a seed snapshot (`seed-data.json.gz`). */
|
|
23
13
|
export interface SeedSnapshot {
|
|
24
14
|
generatedAt: string;
|
|
25
15
|
tables: Record<string, Record<string, unknown>[]>;
|
|
26
16
|
}
|
|
27
17
|
|
|
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
18
|
export async function resetTables(opts: { specs: TableSpec[]; prefix: string; url: string }): Promise<string[]> {
|
|
39
19
|
const sql = neon(opts.url);
|
|
40
20
|
|
|
@@ -52,13 +32,6 @@ export async function resetTables(opts: { specs: TableSpec[]; prefix: string; ur
|
|
|
52
32
|
return dropped;
|
|
53
33
|
}
|
|
54
34
|
|
|
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
35
|
export async function snapshotToSeed(opts: { specs: TableSpec[]; url: string; outPath: string | URL }): Promise<{ total: number; rawBytes: number }> {
|
|
63
36
|
const db = drizzle(neon(opts.url));
|
|
64
37
|
|
|
@@ -79,7 +52,6 @@ export async function snapshotToSeed(opts: { specs: TableSpec[]; url: string; ou
|
|
|
79
52
|
|
|
80
53
|
type Row = Record<string, unknown>;
|
|
81
54
|
|
|
82
|
-
/** ISO string → Date for timestamptz columns; trim to YYYY-MM-DD for date columns. */
|
|
83
55
|
function reviveRow(table: PgTable, row: Row): Row {
|
|
84
56
|
const out: Row = { ...row };
|
|
85
57
|
for (const [key, col] of Object.entries(getTableColumns(table))) {
|
|
@@ -91,13 +63,6 @@ function reviveRow(table: PgTable, row: Row): Row {
|
|
|
91
63
|
return out;
|
|
92
64
|
}
|
|
93
65
|
|
|
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
66
|
export async function seedFromSnapshot(opts: { specs: TableSpec[]; url: string; inPath: string | URL }): Promise<number> {
|
|
102
67
|
const db = drizzle(neon(opts.url));
|
|
103
68
|
|
|
@@ -109,8 +74,6 @@ export async function seedFromSnapshot(opts: { specs: TableSpec[]; url: string;
|
|
|
109
74
|
const rows = (snapshot.tables[name] ?? []).map((r) => reviveRow(table, r));
|
|
110
75
|
for (let i = 0; i < rows.length; i += 200) {
|
|
111
76
|
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
77
|
const res = (await db.insert(table).values(chunk as never).onConflictDoNothing().returning()) as unknown[];
|
|
115
78
|
inserted += res.length;
|
|
116
79
|
}
|
package/src/org.ts
CHANGED
|
@@ -6,7 +6,6 @@ export type UsersLike = PgTable & { id: PgColumn; organizationId: PgColumn };
|
|
|
6
6
|
export type OrgsLike = PgTable & { id: PgColumn; modes: PgColumn };
|
|
7
7
|
export type NumberedTable = PgTable & { number?: PgColumn; organizationId?: PgColumn; deletedAt?: PgColumn };
|
|
8
8
|
|
|
9
|
-
/** Organization of the acting user; missing actor → fallback. */
|
|
10
9
|
export async function resolveOrg(
|
|
11
10
|
db: CrudDb,
|
|
12
11
|
users: UsersLike,
|
|
@@ -29,14 +28,6 @@ export async function orgHasMode(db: CrudDb, orgs: OrgsLike, orgId: string, mode
|
|
|
29
28
|
return Array.isArray(org?.modes) && (org.modes as string[]).includes(mode);
|
|
30
29
|
}
|
|
31
30
|
|
|
32
|
-
/** Next `PREFIX-n` (or `PREFIX-YYYY-NNNN` with year: true) document number:
|
|
33
|
-
* max numeric suffix +1 among the current year's live rows. Not a
|
|
34
|
-
* reservation — the partial-unique on number turns races into a 409.
|
|
35
|
-
* pad applies in EVERY mode — plain `pad: 4` yields `PRD-0001` and reads
|
|
36
|
-
* padded/legacy rows alike (`PRD-9` still counts as 9). digitsOnly: true
|
|
37
|
-
* serves prefix-less columns that store the bare integer ("101") — prefix
|
|
38
|
-
* is ignored, non-numeric rows don't count. scope: numbers per an arbitrary
|
|
39
|
-
* FK column (workspaceId…) — orgId is the common instance of the same form. */
|
|
40
31
|
export async function nextNumber(
|
|
41
32
|
db: CrudDb,
|
|
42
33
|
table: NumberedTable,
|
package/src/r2.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import type { Context } from 'hono';
|
|
2
2
|
|
|
3
|
-
/** The R2 surface streamFromBucket needs — Cloudflare's binding satisfies
|
|
4
|
-
* it structurally, tests satisfy it with an in-memory fake. */
|
|
5
3
|
export interface R2StreamBucket {
|
|
6
4
|
head(key: string): Promise<{
|
|
7
5
|
size: number;
|
|
@@ -16,10 +14,6 @@ export interface RangedRequest {
|
|
|
16
14
|
length: number;
|
|
17
15
|
}
|
|
18
16
|
|
|
19
|
-
/**
|
|
20
|
-
* Parse a single-range `bytes=` header against a known size: a valid window,
|
|
21
|
-
* 'invalid' (answer 416), or null (no Range header → full body).
|
|
22
|
-
*/
|
|
23
17
|
export function parseRange(header: string | undefined, size: number): RangedRequest | 'invalid' | null {
|
|
24
18
|
if (!header) return null;
|
|
25
19
|
const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
|
|
@@ -45,18 +39,10 @@ export function parseRange(header: string | undefined, size: number): RangedRequ
|
|
|
45
39
|
}
|
|
46
40
|
|
|
47
41
|
export interface StreamOptions {
|
|
48
|
-
/** Cache-Control value — CACHE_CONTROLS.privateRevalidate / privateDay. */
|
|
49
42
|
cacheControl: string;
|
|
50
|
-
/** e.g. `attachment; filename="report.pdf"`. */
|
|
51
43
|
contentDisposition?: string;
|
|
52
44
|
}
|
|
53
45
|
|
|
54
|
-
/**
|
|
55
|
-
* Serve an R2 object as a Workers response: HEAD support, single-range
|
|
56
|
-
* requests (206 + Content-Range), malformed ranges (416), R2's own ETag
|
|
57
|
-
* and content type. Missing key or empty key answers 404 — callers pass
|
|
58
|
-
* `''` for docs without media.
|
|
59
|
-
*/
|
|
60
46
|
export async function streamFromBucket(
|
|
61
47
|
c: Context,
|
|
62
48
|
bucket: R2StreamBucket,
|
package/src/resource-react.ts
CHANGED
|
@@ -1,10 +1,3 @@
|
|
|
1
|
-
/* React binding for a createResource instance. The resource is
|
|
2
|
-
framework-free; apps that don't use React never import this entry.
|
|
3
|
-
Binding pattern:
|
|
4
|
-
|
|
5
|
-
const plans = createResource({ load, storageKey: null, ttlMs: RESOURCE_TTL_MS });
|
|
6
|
-
const { value, loading } = useResource(plans); */
|
|
7
|
-
|
|
8
1
|
import { useEffect, useState, useSyncExternalStore } from 'react';
|
|
9
2
|
import type { Resource } from './resource';
|
|
10
3
|
|
package/src/resource.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
/** Default TTL for cached resources — one minute of warm navigations. */
|
|
2
1
|
export const RESOURCE_TTL_MS = 60_000;
|
|
3
2
|
|
|
4
3
|
export interface Resource<T> {
|
|
5
|
-
/** Cached value without loading; null when nothing valid was loaded. */
|
|
6
4
|
read(): T | null;
|
|
7
5
|
write(value: T): void;
|
|
8
6
|
subscribe(listener: () => void): () => void;
|
|
@@ -12,11 +10,8 @@ export interface Resource<T> {
|
|
|
12
10
|
}
|
|
13
11
|
|
|
14
12
|
export interface ResourceConfig<T> {
|
|
15
|
-
/** Network (or other async) source of truth. */
|
|
16
13
|
load: () => Promise<T>;
|
|
17
|
-
/** localStorage persistence key, or null for memory-only. */
|
|
18
14
|
storageKey: string | null;
|
|
19
|
-
/** Validates stored JSON; a null return ignores the persisted value. */
|
|
20
15
|
decode?: (stored: unknown) => T | null;
|
|
21
16
|
ttlMs: number;
|
|
22
17
|
}
|
|
@@ -54,13 +49,6 @@ function dropStored(key: string): void {
|
|
|
54
49
|
memoryStore.delete(key);
|
|
55
50
|
}
|
|
56
51
|
|
|
57
|
-
/**
|
|
58
|
-
* A TTL-cached async value: read() synchronously, ensure() (deduped,
|
|
59
|
-
* in-flight shared) or refresh() from the network, subscribe() for
|
|
60
|
-
* React re-renders, optional localStorage persistence behind decode().
|
|
61
|
-
* Loads swallow errors and keep the last good value — a failed refresh
|
|
62
|
-
* never blanks a warm cache.
|
|
63
|
-
*/
|
|
64
52
|
export function createResource<T>(config: ResourceConfig<T>): Resource<T> {
|
|
65
53
|
const stored = config.storageKey === null ? null : readStored(config.storageKey);
|
|
66
54
|
let value: T | null = stored === null || config.decode === undefined ? null : config.decode(stored);
|
package/src/rows.ts
CHANGED
|
@@ -7,7 +7,6 @@ import type { CrudDb, CrudTable } from './crud';
|
|
|
7
7
|
export type AliveTable = PgTable & { id: PgColumn; deletedAt: PgColumn };
|
|
8
8
|
type RowOf<T> = T extends { $inferSelect: infer R } ? R : never;
|
|
9
9
|
|
|
10
|
-
/** Live row by id — a miss throws ApiError.notFound (the envelope's 404). */
|
|
11
10
|
export async function findRow<T extends AliveTable>(db: CrudDb, table: T, id: string, label: string): Promise<RowOf<T>> {
|
|
12
11
|
const rows = (await db.select().from(table as CrudTable).where(and(eq(table.id, id), isNull(table.deletedAt)))) as RowOf<T>[];
|
|
13
12
|
const row = rows[0];
|
|
@@ -15,7 +14,6 @@ export async function findRow<T extends AliveTable>(db: CrudDb, table: T, id: st
|
|
|
15
14
|
return row;
|
|
16
15
|
}
|
|
17
16
|
|
|
18
|
-
/** Soft delete (deletedAt + updatedAt stamps) — a miss throws notFound. */
|
|
19
17
|
export async function softDelete<T extends AliveTable>(db: CrudDb, table: T, id: string, label: string): Promise<RowOf<T>> {
|
|
20
18
|
const rows = (await db
|
|
21
19
|
.update(table as CrudTable)
|
package/src/store-react.ts
CHANGED
|
@@ -1,9 +1,3 @@
|
|
|
1
|
-
/* React bindings for a createStore instance. The store is framework-free;
|
|
2
|
-
apps that don't use React never import this entry. Binding pattern:
|
|
3
|
-
|
|
4
|
-
const store = createStore(config);
|
|
5
|
-
export const { useQuery, useDbValue } = makeStoreHooks(store); */
|
|
6
|
-
|
|
7
1
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
8
2
|
import { REFETCH_ALL, type createStore } from './store';
|
|
9
3
|
|
|
@@ -17,8 +11,6 @@ export interface QueryResult<T> {
|
|
|
17
11
|
export type Store<Database extends object> = ReturnType<typeof createStore<Database>>;
|
|
18
12
|
|
|
19
13
|
export function makeStoreHooks<Database extends object>(store: Store<Database>) {
|
|
20
|
-
/** Async queries with loading/error states; re-runs when the underlying
|
|
21
|
-
* collections change (via the store's pub/sub) or when the key changes. */
|
|
22
14
|
function useQuery<T>(key: unknown[], fetcher: () => Promise<T>, enabled = true): QueryResult<T> {
|
|
23
15
|
const keyStr = JSON.stringify(key);
|
|
24
16
|
const fetcherRef = useRef(fetcher);
|
|
@@ -58,30 +50,22 @@ export function makeStoreHooks<Database extends object>(store: Store<Database>)
|
|
|
58
50
|
return { data: state.data, status: state.status, error: state.error, refetch };
|
|
59
51
|
}
|
|
60
52
|
|
|
61
|
-
/** Non-promise variant for synchronous derived reads that should still
|
|
62
|
-
* refresh when collections change. */
|
|
63
53
|
function useDbValue<T>(compute: () => T, keys: string[]): T {
|
|
64
54
|
const [, force] = useState(0);
|
|
65
55
|
const computeRef = useRef(compute);
|
|
66
56
|
computeRef.current = compute;
|
|
67
57
|
const valueRef = useRef<T>(compute());
|
|
68
58
|
valueRef.current = computeRef.current();
|
|
69
|
-
// deps: the joined key string — the subscription only changes when it does
|
|
70
59
|
useEffect(() => store.subscribe(keys, () => force((v) => v + 1)), [keys.join(',')]);
|
|
71
60
|
return valueRef.current;
|
|
72
61
|
}
|
|
73
62
|
|
|
74
|
-
/** Typed synchronous collection read that re-renders on that collection's
|
|
75
|
-
* channel: `const items = useCollection('items');` — Database['items']. */
|
|
76
63
|
function useCollection<K extends keyof Database & string>(key: K): Database[K] {
|
|
77
64
|
const [, force] = useState(0);
|
|
78
65
|
useEffect(() => store.subscribe([key], () => force((v) => v + 1)), [key]);
|
|
79
66
|
return store.getDb()[key];
|
|
80
67
|
}
|
|
81
68
|
|
|
82
|
-
/** The app boot gate: loading while the first hydration runs, error +
|
|
83
|
-
* retry on failure. Replaces the per-app boot-gate providers 1.x apps
|
|
84
|
-
* hand-rolled around ensureHydrated. */
|
|
85
69
|
function useHydration(): { status: 'loading' | 'ready' | 'error'; error?: string; retry: () => void } {
|
|
86
70
|
const [state, setState] = useState<{ status: 'loading' | 'ready' | 'error'; error?: string }>({ status: 'loading' });
|
|
87
71
|
const [attempt, setAttempt] = useState(0);
|
|
@@ -94,7 +78,6 @@ export function makeStoreHooks<Database extends object>(store: Store<Database>)
|
|
|
94
78
|
if (alive) setState({ status: 'ready' });
|
|
95
79
|
},
|
|
96
80
|
(err) => {
|
|
97
|
-
// ensureHydrated already reset itself — the next call (retry) refetches.
|
|
98
81
|
if (alive) setState({ status: 'error', error: err instanceof Error ? err.message : 'Hydration failed' });
|
|
99
82
|
},
|
|
100
83
|
);
|
package/src/types.ts
CHANGED
|
@@ -1,31 +1,12 @@
|
|
|
1
1
|
import type { InferInsertModel, InferSelectModel } from 'drizzle-orm';
|
|
2
2
|
import type { PgTable } from 'drizzle-orm/pg-core';
|
|
3
3
|
|
|
4
|
-
/**
|
|
5
|
-
* The server↔client type bridge. The drizzle schema is the single source of
|
|
6
|
-
* truth: the server row, the wire shape, and the store cache all DERIVE from
|
|
7
|
-
* it — no hand-mirrored interface files that silently drift (the 1.x fleet
|
|
8
|
-
* maintained those by convention only).
|
|
9
|
-
*
|
|
10
|
-
* // app schema: export const products = pgTable(...)
|
|
11
|
-
* type Product = ClientRow<typeof products>; // what src/data/store.ts caches
|
|
12
|
-
* type NewProduct = NewRow<typeof products>; // what a POST body becomes
|
|
13
|
-
*
|
|
14
|
-
* This entry is type-only — client code importing it pulls no server runtime.
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
/** The server-side row straight from the drizzle schema (Date objects for
|
|
18
|
-
* timestamptz columns — what drizzle returns, what handlers pass to c.json). */
|
|
19
4
|
export type Row<T extends PgTable> = InferSelectModel<T>;
|
|
20
5
|
|
|
21
|
-
/** The insert shape (POST bodies after zod) — defaults/optional per schema. */
|
|
22
6
|
export type NewRow<T extends PgTable> = InferInsertModel<T>;
|
|
23
7
|
|
|
24
|
-
/** What JSON.stringify delivers over the wire: Date → ISO string, everything
|
|
25
|
-
* else (jsonb, enums, date mode:'string' columns — already strings) as-is. */
|
|
26
8
|
export type Serialized<T> = {
|
|
27
9
|
[K in keyof T]: T[K] extends Date ? string : T[K] extends Date | null ? string | null : T[K];
|
|
28
10
|
};
|
|
29
11
|
|
|
30
|
-
/** The client-cached row type: what apiFetch/store hold after c.json(). */
|
|
31
12
|
export type ClientRow<T extends PgTable> = Serialized<Row<T>>;
|
package/src/validator.ts
CHANGED
|
@@ -1,19 +1,6 @@
|
|
|
1
1
|
import type { Context } from 'hono';
|
|
2
2
|
import { z } from 'zod';
|
|
3
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
4
|
export function validateJson<S extends z.ZodType>(schema: S, message = 'Invalid request body') {
|
|
18
5
|
return (value: unknown, c: Context) => {
|
|
19
6
|
const parsed = schema.safeParse(value);
|