@umituz/web-hono 1.14.0 → 1.15.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,7 +1,7 @@
1
1
  {
2
2
  "name": "@umituz/web-hono",
3
- "version": "1.14.0",
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), better-auth server integration (tables/getter/mount/session helpers), weak-compare If-None-Match matcher (matchesEtag), and db lifecycle scripts (reset / snapshot / seed)",
3
+ "version": "1.15.0",
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), 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",
7
7
  "types": "./src/index.ts",
@@ -18,6 +18,10 @@
18
18
  "./auth": "./src/auth.ts",
19
19
  "./mail": "./src/mail.ts",
20
20
  "./etag": "./src/etag.ts",
21
+ "./cookies": "./src/cookies.ts",
22
+ "./http": "./src/http.ts",
23
+ "./r2": "./src/r2.ts",
24
+ "./resource": "./src/resource.ts",
21
25
  "./package.json": "./package.json"
22
26
  },
23
27
  "scripts": {
package/src/auth.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { betterAuth } from 'better-auth';
2
+ import { bearer } from 'better-auth/plugins';
2
3
  import { drizzleAdapter } from 'better-auth/adapters/drizzle';
3
4
  import { eq } from 'drizzle-orm';
4
5
  import { Hono } from 'hono';
@@ -123,6 +124,7 @@ function initAuth(env: AuthEnv, opts: AuthOptions<AuthEnv>) {
123
124
  },
124
125
  session: { expiresIn: SESSION_SECONDS, updateAge: UPDATE_AGE_SECONDS },
125
126
  trustedOrigins: opts.trustedOrigins ?? [],
127
+ plugins: [bearer()],
126
128
  });
127
129
  }
128
130
 
package/src/cookies.ts ADDED
@@ -0,0 +1,41 @@
1
+ export type CookieSameSite = 'lax' | 'strict' | 'none';
2
+
3
+ export interface CookieChannelConfig {
4
+ /** Wire name of the cookie (`prefs_theme`…). */
5
+ key: string;
6
+ /** max-age in seconds — long-lived preferences pass a year. */
7
+ maxAgeSeconds: number;
8
+ sameSite: CookieSameSite;
9
+ }
10
+
11
+ export interface CookieChannel {
12
+ /** Current value, or null when the cookie is absent/empty. */
13
+ read(): string | null;
14
+ write(value: string): void;
15
+ clear(): void;
16
+ }
17
+
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
+ export function createCookieChannel(config: CookieChannelConfig): CookieChannel {
24
+ const prefix = `${config.key}=`;
25
+ return {
26
+ read() {
27
+ const entry = document.cookie
28
+ .split('; ')
29
+ .find((part) => part.startsWith(prefix));
30
+ const value = entry === undefined ? null : entry.slice(prefix.length);
31
+ if (value === null || value.length === 0) return null;
32
+ return value;
33
+ },
34
+ write(value) {
35
+ document.cookie = `${config.key}=${value}; path=/; max-age=${config.maxAgeSeconds}; samesite=${config.sameSite}`;
36
+ },
37
+ clear() {
38
+ document.cookie = `${config.key}=; path=/; max-age=0; samesite=${config.sameSite}`;
39
+ },
40
+ };
41
+ }
package/src/http.ts ADDED
@@ -0,0 +1,63 @@
1
+ import type { Context } from 'hono';
2
+ import { getCookie } from 'hono/cookie';
3
+ import { matchesEtag } from './etag';
4
+
5
+ /** Cache-Control catalog for auth-private responses. */
6
+ export const CACHE_CONTROLS = {
7
+ /** Revalidate every time (audio/video streams, mutable payloads). */
8
+ privateRevalidate: 'private, max-age=0, must-revalidate',
9
+ /** Browser-fresh for a day (cover art and other immutable-ish assets). */
10
+ privateDay: 'private, max-age=86400',
11
+ /** ETag-carried payloads: cache allowed, revalidate on every use. */
12
+ etagRevalidate: 'no-cache',
13
+ } as const;
14
+
15
+ export interface RequestScopeConfig {
16
+ /** Query parameter that carries the scope explicitly (`?lang=ko`). */
17
+ queryParam: string;
18
+ /** Cookie consulted when the query parameter is absent. */
19
+ cookieKey: string;
20
+ }
21
+
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
+ export function requestScopeOf(c: Context, config: RequestScopeConfig): string | null {
29
+ const fromQuery = c.req.query(config.queryParam);
30
+ if (fromQuery !== undefined && fromQuery.length > 0) return fromQuery;
31
+ const fromCookie = getCookie(c, config.cookieKey);
32
+ if (fromCookie !== undefined && fromCookie.length > 0) return fromCookie;
33
+ return null;
34
+ }
35
+
36
+ /**
37
+ * The If-None-Match dance in one call: weak-compares the request's
38
+ * If-None-Match against `etag` and answers 304 (ETag + no-cache headers,
39
+ * empty body) or 200 (same headers plus the JSON payload). Payload types
40
+ * stay the caller's — only the transport is shared.
41
+ */
42
+ export function respondWithEtag(c: Context, etag: string, payload: unknown) {
43
+ if (matchesEtag(c.req.header('If-None-Match'), etag)) {
44
+ return c.body(null, 304, { ETag: etag, 'Cache-Control': CACHE_CONTROLS.etagRevalidate });
45
+ }
46
+ c.header('ETag', etag);
47
+ c.header('Cache-Control', CACHE_CONTROLS.etagRevalidate);
48
+ return c.json(payload);
49
+ }
50
+
51
+ /**
52
+ * `500 { error, details }` for caught errors in hand-rolled routes —
53
+ * the envelope's last resort outside the global onError.
54
+ */
55
+ export function internalError(c: Context, message: string, err?: unknown) {
56
+ return c.json(
57
+ {
58
+ error: message,
59
+ details: err instanceof Error ? err.name : 'error',
60
+ },
61
+ 500,
62
+ );
63
+ }
package/src/index.ts CHANGED
@@ -19,6 +19,10 @@
19
19
  * `/store` createStore — the fetch-backed reactive store
20
20
  * `/store/react` makeStoreHooks — useQuery/useDbValue/useCollection/useHydration
21
21
  * `/lifecycle` reset / snapshot / seed — the shared-Neon db lifecycle
22
+ * `/cookies` createCookieChannel — one named browser cookie, read/write/clear
23
+ * `/http` requestScopeOf / respondWithEtag / internalError / CACHE_CONTROLS
24
+ * `/r2` streamFromBucket / parseRange — ranged R2 streaming
25
+ * `/resource` createResource — TTL-cached async value with subscribe
22
26
  */
23
27
  export { createApi } from './api';
24
28
  export type { ApiConfig } from './api';
@@ -29,7 +33,7 @@ export type { CrudSpec, CrudTable, CrudDb, CrudDbFactory, CreateSpec, ListSpec }
29
33
  export { docStore, canTransition, epoch, WorkflowError, UnknownCollectionError } from './docstore';
30
34
  export type { Doc, DocInput, DocTable, DocCollectionSpec, DocStoreSpec, DocValidateFn, DocAfterWriteFn, DocScopeSpec } from './docstore';
31
35
  export { getDb } from './db';
32
- export { uid, pickPatch, patchTypeErrors, normalizeRow, stampUpdate, trio, actor } from './lib';
36
+ export { uid, pickPatch, patchTypeErrors, normalizeRow, stampUpdate, trio, actor, mapLimit, withRetry } from './lib';
33
37
  export { isoNow, isoAt, todayISO, addDaysISO } from './dates';
34
38
  export type { IsoPrecision } from './dates';
35
39
  export { resolveOrg, orgHasMode, nextNumber } from './org';
package/src/lib.ts CHANGED
@@ -139,3 +139,26 @@ export function normalizeRow(table: PgTable, input: Record<string, unknown>): Re
139
139
  }
140
140
  return out;
141
141
  }
142
+
143
+ /** Run `fn` over items in `limit`-sized waves — bounded DB subrequest fan-out. */
144
+ export async function mapLimit<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
145
+ const out: R[] = [];
146
+ for (let i = 0; i < items.length; i += limit) {
147
+ out.push(...(await Promise.all(items.slice(i, i + limit).map(fn))));
148
+ }
149
+ return out;
150
+ }
151
+
152
+ /** Retry transient Neon/HTTP blips: up to `attempts` tries, backoff 250ms·n. */
153
+ export async function withRetry<T>(fn: () => Promise<T>, attempts = 3): Promise<T> {
154
+ let lastErr: unknown;
155
+ for (let i = 0; i < attempts; i++) {
156
+ try {
157
+ return await fn();
158
+ } catch (err) {
159
+ lastErr = err;
160
+ await new Promise((r) => setTimeout(r, 250 * (i + 1)));
161
+ }
162
+ }
163
+ throw lastErr;
164
+ }
package/src/mail.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export interface MailEnv {
2
- RESEND_API_KEY: string;
2
+ RESEND_API_KEY?: string;
3
3
  }
4
4
 
5
5
  export interface SendEmailInput {
package/src/r2.ts ADDED
@@ -0,0 +1,110 @@
1
+ import type { Context } from 'hono';
2
+
3
+ /** The R2 surface streamFromBucket needs — Cloudflare's binding satisfies
4
+ * it structurally, tests satisfy it with an in-memory fake. */
5
+ export interface R2StreamBucket {
6
+ head(key: string): Promise<{
7
+ size: number;
8
+ httpEtag: string;
9
+ httpMetadata?: { contentType?: string } | undefined;
10
+ } | null>;
11
+ get(key: string, options?: { range?: { offset: number; length: number } }): Promise<{ body: ReadableStream } | null>;
12
+ }
13
+
14
+ export interface RangedRequest {
15
+ offset: number;
16
+ length: number;
17
+ }
18
+
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
+ export function parseRange(header: string | undefined, size: number): RangedRequest | 'invalid' | null {
24
+ if (!header) return null;
25
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
26
+ if (!match) return 'invalid';
27
+ const [, startRaw, endRaw] = match;
28
+ if (startRaw === '' && endRaw === '') return 'invalid';
29
+ if (startRaw === '') {
30
+ const suffix = Number(endRaw);
31
+ if (!Number.isFinite(suffix) || suffix <= 0) return 'invalid';
32
+ const length = Math.min(suffix, size);
33
+ return { offset: size - length, length };
34
+ }
35
+ const start = Number(startRaw);
36
+ if (!Number.isFinite(start) || start < 0) return 'invalid';
37
+ if (start >= size) return 'invalid';
38
+ let end = size - 1;
39
+ if (endRaw !== '') {
40
+ const parsed = Number(endRaw);
41
+ if (!Number.isFinite(parsed) || parsed < start) return 'invalid';
42
+ end = Math.min(parsed, size - 1);
43
+ }
44
+ return { offset: start, length: end - start + 1 };
45
+ }
46
+
47
+ export interface StreamOptions {
48
+ /** Cache-Control value — CACHE_CONTROLS.privateRevalidate / privateDay. */
49
+ cacheControl: string;
50
+ /** e.g. `attachment; filename="report.pdf"`. */
51
+ contentDisposition?: string;
52
+ }
53
+
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
+ export async function streamFromBucket(
61
+ c: Context,
62
+ bucket: R2StreamBucket,
63
+ key: string,
64
+ options: StreamOptions,
65
+ ) {
66
+ if (!key) return c.json({ error: 'not found' }, 404);
67
+ const head = await bucket.head(key);
68
+ if (!head) return c.json({ error: 'not found' }, 404);
69
+ const size = head.size;
70
+ const contentType = head.httpMetadata?.contentType ?? 'application/octet-stream';
71
+ const range = parseRange(c.req.header('Range'), size);
72
+
73
+ if (range === 'invalid') {
74
+ return c.body(null, 416, {
75
+ 'Content-Range': `bytes */${size}`,
76
+ 'Accept-Ranges': 'bytes',
77
+ });
78
+ }
79
+
80
+ const headers: Record<string, string> = {
81
+ 'Content-Type': contentType,
82
+ 'Accept-Ranges': 'bytes',
83
+ 'Cache-Control': options.cacheControl,
84
+ ETag: head.httpEtag,
85
+ };
86
+ if (options.contentDisposition !== undefined) headers['Content-Disposition'] = options.contentDisposition;
87
+
88
+ if (c.req.method === 'HEAD') {
89
+ if (range) {
90
+ headers['Content-Length'] = String(range.length);
91
+ headers['Content-Range'] = `bytes ${range.offset}-${range.offset + range.length - 1}/${size}`;
92
+ } else {
93
+ headers['Content-Length'] = String(size);
94
+ }
95
+ return c.body(null, 200, headers);
96
+ }
97
+
98
+ if (range) {
99
+ const obj = await bucket.get(key, { range: { offset: range.offset, length: range.length } });
100
+ if (!obj) return c.json({ error: 'not found' }, 404);
101
+ headers['Content-Length'] = String(range.length);
102
+ headers['Content-Range'] = `bytes ${range.offset}-${range.offset + range.length - 1}/${size}`;
103
+ return c.body(obj.body, 206, headers);
104
+ }
105
+
106
+ const obj = await bucket.get(key);
107
+ if (!obj) return c.json({ error: 'not found' }, 404);
108
+ headers['Content-Length'] = String(size);
109
+ return c.body(obj.body, 200, headers);
110
+ }
@@ -0,0 +1,129 @@
1
+ /** Default TTL for cached resources — one minute of warm navigations. */
2
+ export const RESOURCE_TTL_MS = 60_000;
3
+
4
+ export interface Resource<T> {
5
+ /** Cached value without loading; null when nothing valid was loaded. */
6
+ read(): T | null;
7
+ write(value: T): void;
8
+ subscribe(listener: () => void): () => void;
9
+ ensure(): Promise<T | null>;
10
+ refresh(): Promise<T | null>;
11
+ clear(): void;
12
+ }
13
+
14
+ export interface ResourceConfig<T> {
15
+ /** Network (or other async) source of truth. */
16
+ load: () => Promise<T>;
17
+ /** localStorage persistence key, or null for memory-only. */
18
+ storageKey: string | null;
19
+ /** Validates stored JSON; a null return ignores the persisted value. */
20
+ decode?: (stored: unknown) => T | null;
21
+ ttlMs: number;
22
+ }
23
+
24
+ const memoryStore = new Map<string, string>();
25
+
26
+ function readStored(key: string): unknown {
27
+ let raw: string | null = null;
28
+ try {
29
+ raw = localStorage.getItem(key);
30
+ } catch {
31
+ raw = memoryStore.get(key) ?? null;
32
+ }
33
+ if (raw === null || raw.length === 0) return null;
34
+ try {
35
+ return JSON.parse(raw);
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ function writeStored(key: string, value: unknown): void {
42
+ const raw = JSON.stringify(value);
43
+ try {
44
+ localStorage.setItem(key, raw);
45
+ } catch {
46
+ memoryStore.set(key, raw);
47
+ }
48
+ }
49
+
50
+ function dropStored(key: string): void {
51
+ try {
52
+ localStorage.removeItem(key);
53
+ } catch {}
54
+ memoryStore.delete(key);
55
+ }
56
+
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
+ export function createResource<T>(config: ResourceConfig<T>): Resource<T> {
65
+ const stored = config.storageKey === null ? null : readStored(config.storageKey);
66
+ let value: T | null = stored === null || config.decode === undefined ? null : config.decode(stored);
67
+ let expiresAt = 0;
68
+ let inflight: Promise<T | null> | null = null;
69
+ const listeners = new Set<() => void>();
70
+
71
+ function notify(): void {
72
+ for (const listener of listeners) {
73
+ try {
74
+ listener();
75
+ } catch {}
76
+ }
77
+ }
78
+
79
+ function fetch(): Promise<T | null> {
80
+ const run = (async () => {
81
+ try {
82
+ const next = await config.load();
83
+ value = next;
84
+ expiresAt = Date.now() + config.ttlMs;
85
+ if (config.storageKey !== null) writeStored(config.storageKey, next);
86
+ notify();
87
+ return next;
88
+ } catch {
89
+ return value;
90
+ } finally {
91
+ inflight = null;
92
+ }
93
+ })();
94
+ inflight = run;
95
+ return run;
96
+ }
97
+
98
+ return {
99
+ read: () => value,
100
+ write: (next: T) => {
101
+ value = next;
102
+ expiresAt = Date.now() + config.ttlMs;
103
+ if (config.storageKey !== null) writeStored(config.storageKey, next);
104
+ notify();
105
+ },
106
+ subscribe: (listener: () => void) => {
107
+ listeners.add(listener);
108
+ return () => {
109
+ listeners.delete(listener);
110
+ };
111
+ },
112
+ ensure: () => {
113
+ if (inflight !== null) return inflight;
114
+ if (value !== null && Date.now() < expiresAt) return Promise.resolve(value);
115
+ return fetch();
116
+ },
117
+ refresh: () => {
118
+ if (inflight !== null) return inflight;
119
+ return fetch();
120
+ },
121
+ clear: () => {
122
+ value = null;
123
+ expiresAt = 0;
124
+ inflight = null;
125
+ if (config.storageKey !== null) dropStored(config.storageKey);
126
+ notify();
127
+ },
128
+ };
129
+ }