@umituz/web-hono 1.3.0 → 1.5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/web-hono",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
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), and db lifecycle scripts (reset / snapshot / seed)",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -0,0 +1,39 @@
1
+ import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
2
+ import { uid } from './lib';
3
+ import type { CrudDb } from './crud';
4
+
5
+ export type ActivityTable = PgTable & { id: PgColumn };
6
+
7
+ export interface AuditWrite {
8
+ actorId: string;
9
+ actorName: string;
10
+ action: string;
11
+ entityType: string;
12
+ entityId: string;
13
+ entityLabel: string;
14
+ changes?: { field: string; from: string; to: string }[];
15
+ [extra: string]: unknown;
16
+ }
17
+
18
+ export interface NotificationWrite {
19
+ type: string;
20
+ severity: string;
21
+ title: string;
22
+ body: string;
23
+ entityType?: string;
24
+ entityId?: string;
25
+ [extra: string]: unknown;
26
+ }
27
+
28
+ export async function writeAudit(db: CrudDb, table: ActivityTable, entry: AuditWrite, prefix = 'aud'): Promise<void> {
29
+ await db.insert(table).values({ id: uid(prefix), at: new Date(), changes: entry.changes ?? [], ...entry } as never);
30
+ }
31
+
32
+ export async function writeNotification(
33
+ db: CrudDb,
34
+ table: ActivityTable,
35
+ n: NotificationWrite,
36
+ prefix = 'ntf',
37
+ ): Promise<void> {
38
+ await db.insert(table).values({ id: uid(prefix), at: new Date(), read: false, ...n } as never);
39
+ }
package/src/crud.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Hono } from 'hono';
2
2
  import { and, asc, desc, eq, getTableColumns, isNull } from 'drizzle-orm';
3
3
  import { drizzle } from 'drizzle-orm/neon-http';
4
+ import type { NeonHttpDatabase } from 'drizzle-orm/neon-http';
4
5
  import { neon } from '@neondatabase/serverless';
5
6
  import type { Context } from 'hono';
6
7
  import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
@@ -27,10 +28,6 @@ import type { ApiEnv } from './env';
27
28
  * the factory is for plain settings/catalog rows only.
28
29
  */
29
30
 
30
- /** Anything the factory can select/insert/update against — the return type
31
- * of the default neon-http construction. Injected instances from other
32
- * drivers (pglite, node-postgres) differ only at the type level; injection
33
- * sites bypass with `as unknown as CrudDb`. */
34
31
  type RequestContext = Context<{ Bindings: ApiEnv }>;
35
32
  function defaultDb(c: RequestContext) {
36
33
  // Schema-less drizzle: the factory only runs select/insert/update, which
@@ -38,7 +35,7 @@ function defaultDb(c: RequestContext) {
38
35
  // its own instance from the request's binding instead of requiring one.
39
36
  return drizzle(neon(c.env.DATABASE_URL));
40
37
  }
41
- export type CrudDb = ReturnType<typeof defaultDb>;
38
+ export type CrudDb = Pick<NeonHttpDatabase<Record<string, never>>, 'select' | 'insert' | 'update'>;
42
39
  export type CrudDbFactory = (c: RequestContext) => CrudDb;
43
40
 
44
41
  export type CrudTable = PgTable & { id: PgColumn; deletedAt: PgColumn };
package/src/errors.ts CHANGED
@@ -32,6 +32,14 @@ export class ApiError extends Error {
32
32
  static badRequest(message: string, details?: unknown): ApiError {
33
33
  return new ApiError(400, message, details);
34
34
  }
35
+
36
+ static forbidden(message: string): ApiError {
37
+ return new ApiError(403, message);
38
+ }
39
+
40
+ static conflict(message: string): ApiError {
41
+ return new ApiError(409, message);
42
+ }
35
43
  }
36
44
 
37
45
  /**
package/src/index.ts CHANGED
@@ -5,8 +5,10 @@
5
5
  * Apps keep their schema (with TABLE_PREFIX), domain routers, zod schemas,
6
6
  * and business rules — this package owns the cross-cutting skeleton:
7
7
  * the createApi app factory, the error envelope layer, the full-CRUD
8
- * resource factory, getDb, the uid/pickPatch/stampUpdate/trio helpers,
9
- * the JSON-404 and SPA-fallback handlers, and the ApiEnv binding types.
8
+ * resource factory, getDb, the uid/pickPatch/stampUpdate/trio/actor
9
+ * helpers, the org-scoped lookups (resolveOrg/orgHasMode/nextNumber),
10
+ * the audit and notification writes, findRow/softDelete, the JSON-404
11
+ * and SPA-fallback handlers, and the ApiEnv binding types.
10
12
  *
11
13
  * Entry points:
12
14
  * `.` server core (this file)
@@ -24,6 +26,12 @@ export { ApiError, apiOnError } from './errors';
24
26
  export { crudRoutes, listRoutes } from './crud';
25
27
  export type { CrudSpec, CrudTable, CrudDb, CrudDbFactory, CreateSpec, ListSpec } from './crud';
26
28
  export { getDb } from './db';
27
- export { uid, pickPatch, stampUpdate, trio } from './lib';
29
+ export { uid, pickPatch, stampUpdate, trio, actor } from './lib';
30
+ export { resolveOrg, orgHasMode, nextNumber } from './org';
31
+ export type { UsersLike, OrgsLike, NumberedTable } from './org';
32
+ export { writeAudit, writeNotification } from './activity';
33
+ export type { ActivityTable, AuditWrite, NotificationWrite } from './activity';
34
+ export { findRow, softDelete } from './rows';
35
+ export type { AliveTable } from './rows';
28
36
  export { apiNotFound, spaFallback } from './handlers';
29
37
  export type { ApiEnv } from './env';
package/src/lib.ts CHANGED
@@ -9,6 +9,11 @@ export function uid(prefix: string): string {
9
9
  return `${prefix}_${Date.now().toString(36)}${idCounter.toString(36)}`;
10
10
  }
11
11
 
12
+ /** Write-schema actor pair with the fleet defaults. */
13
+ export function actor(input: { actorId?: string; actorName?: string }, name = 'Back office'): { actorId: string; actorName: string } {
14
+ return { actorId: input.actorId ?? 'api', actorName: input.actorName ?? name };
15
+ }
16
+
12
17
  /**
13
18
  * Fleet time-trio columns for timestamptz tables — spread into a pgTable
14
19
  * definition: `{ id: text('id').primaryKey(), name: text('name'), ...trio() }`.
package/src/org.ts ADDED
@@ -0,0 +1,47 @@
1
+ import { eq } from 'drizzle-orm';
2
+ import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
3
+ import type { CrudDb } from './crud';
4
+
5
+ export type UsersLike = PgTable & { id: PgColumn; organizationId: PgColumn };
6
+ export type OrgsLike = PgTable & { id: PgColumn; modes: PgColumn };
7
+ export type NumberedTable = PgTable & { number: PgColumn; organizationId: PgColumn };
8
+
9
+ /** Organization of the acting user; missing actor → fallback. */
10
+ export async function resolveOrg(
11
+ db: CrudDb,
12
+ users: UsersLike,
13
+ actorId: string | undefined,
14
+ fallback: string,
15
+ ): Promise<string> {
16
+ if (actorId) {
17
+ const [row] = await db
18
+ .select({ organizationId: users.organizationId })
19
+ .from(users)
20
+ .where(eq(users.id, actorId))
21
+ .limit(1);
22
+ if (row) return row.organizationId as string;
23
+ }
24
+ return fallback;
25
+ }
26
+
27
+ export async function orgHasMode(db: CrudDb, orgs: OrgsLike, orgId: string, mode: string): Promise<boolean> {
28
+ const [org] = await db.select({ modes: orgs.modes }).from(orgs).where(eq(orgs.id, orgId)).limit(1);
29
+ return Array.isArray(org?.modes) && (org.modes as string[]).includes(mode);
30
+ }
31
+
32
+ /** Next `PREFIX-n` document number: max numeric suffix +1. Not a
33
+ * reservation — the partial-unique on number turns races into a 409. */
34
+ export async function nextNumber(
35
+ db: CrudDb,
36
+ table: NumberedTable,
37
+ prefix: string,
38
+ opts: { orgId?: string; base?: number } = {},
39
+ ): Promise<string> {
40
+ const q = db.select({ number: table.number }).from(table);
41
+ const rows = opts.orgId ? await q.where(eq(table.organizationId, opts.orgId)) : await q;
42
+ const max = rows.reduce((m, r) => {
43
+ const n = new RegExp(`^${prefix}-(\\d+)$`).exec(String(r.number ?? ''))?.[1];
44
+ return n ? Math.max(m, Number(n)) : m;
45
+ }, opts.base ?? 2000);
46
+ return `${prefix}-${max + 1}`;
47
+ }
package/src/rows.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { and, eq, isNull } from 'drizzle-orm';
2
+ import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
3
+ import { ApiError } from './errors';
4
+ import { stampUpdate } from './lib';
5
+ import type { CrudDb, CrudTable } from './crud';
6
+
7
+ export type AliveTable = PgTable & { id: PgColumn; deletedAt: PgColumn };
8
+ type RowOf<T> = T extends { $inferSelect: infer R } ? R : never;
9
+
10
+ /** Live row by id — a miss throws ApiError.notFound (the envelope's 404). */
11
+ export async function findRow<T extends AliveTable>(db: CrudDb, table: T, id: string, label: string): Promise<RowOf<T>> {
12
+ const rows = (await db.select().from(table as CrudTable).where(and(eq(table.id, id), isNull(table.deletedAt)))) as RowOf<T>[];
13
+ const row = rows[0];
14
+ if (!row) throw ApiError.notFound(label);
15
+ return row;
16
+ }
17
+
18
+ /** Soft delete (deletedAt + updatedAt stamps) — a miss throws notFound. */
19
+ export async function softDelete<T extends AliveTable>(db: CrudDb, table: T, id: string, label: string): Promise<RowOf<T>> {
20
+ const rows = (await db
21
+ .update(table as CrudTable)
22
+ .set({ deletedAt: new Date(), ...stampUpdate(table) } as never)
23
+ .where(and(eq(table.id, id), isNull(table.deletedAt)))
24
+ .returning()) as RowOf<T>[];
25
+ const row = rows[0];
26
+ if (!row) throw ApiError.notFound(label);
27
+ return row;
28
+ }