@umituz/web-hono 1.15.0 → 1.17.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.15.0",
3
+ "version": "1.17.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), 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",
@@ -22,6 +22,7 @@
22
22
  "./http": "./src/http.ts",
23
23
  "./r2": "./src/r2.ts",
24
24
  "./resource": "./src/resource.ts",
25
+ "./resource/react": "./src/resource-react.ts",
25
26
  "./package.json": "./package.json"
26
27
  },
27
28
  "scripts": {
package/src/docstore.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Hono } from 'hono';
2
- import { and, eq, getTableColumns, isNull, sql } from 'drizzle-orm';
2
+ import { and, eq, getTableColumns, inArray, isNull, sql } from 'drizzle-orm';
3
3
  import { drizzle } from 'drizzle-orm/neon-http';
4
4
  import { neon } from '@neondatabase/serverless';
5
5
  import { validator } from 'hono/validator';
@@ -22,10 +22,16 @@ import type { ApiEnv } from './env';
22
22
  * listDocs/getDoc) that seed scripts and server-side workflows call
23
23
  * directly. Status machines ride along as declarative `transitions` maps and
24
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.
25
33
  */
26
34
 
27
- type RequestContext = Context<{ Bindings: ApiEnv }>;
28
-
29
35
  export type Doc = Record<string, unknown> & { id: string };
30
36
  export type DocInput = Record<string, unknown>;
31
37
 
@@ -57,7 +63,7 @@ export interface DocCollectionSpec {
57
63
  /** Collections that must always write the one fixed id. */
58
64
  singletonId?: string;
59
65
  /** Status state machine: allowed targets per current status. */
60
- transitions?: Record<string, string[]>;
66
+ transitions?: Readonly<Record<string, readonly string[]>>;
61
67
  /** Doc field the transitions guard reads. Default 'status'. */
62
68
  statusKey?: string;
63
69
  /** Write guard — see DocValidateFn. */
@@ -67,19 +73,54 @@ export interface DocCollectionSpec {
67
73
  afterWrite?: DocAfterWriteFn;
68
74
  }
69
75
 
70
- export interface DocStoreSpec {
76
+ export interface DocWriteHookArgs {
77
+ key: string;
78
+ /** Incoming document — hooks may rewrite server-owned fields in place. */
79
+ doc: Record<string, unknown>;
80
+ /** Current stored doc, or null when the write creates. */
81
+ existing: Record<string, unknown> | null;
82
+ /** Session scope when `scopeOf` resolved one (else undefined). */
83
+ scope: string | undefined;
84
+ }
85
+
86
+ export interface DocPatchHookArgs {
87
+ key: string;
88
+ /** Incoming patch — hooks may rewrite it in place. */
89
+ patch: Record<string, unknown>;
90
+ existing: Doc | null;
91
+ scope: string | undefined;
92
+ }
93
+
94
+ export interface DocStoreSpec<E extends ApiEnv = ApiEnv> {
71
95
  collections: readonly DocCollectionSpec[];
72
96
  /** Injectable db factory (tests, Hyperdrive). Default: per-request neon-http. */
73
- db?: (c: RequestContext) => CrudDb;
97
+ db?: (c: Context<{ Bindings: E }>) => CrudDb;
74
98
  /** POST /batch op cap. Default 2000. */
75
99
  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
+ 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
+ scopeOf?: (c: Context<{ Bindings: E }>) => Promise<string | null>;
109
+ /** Router-level put shaping (server-owned fields) before the write. */
110
+ onPut?: (args: DocWriteHookArgs) => void | Promise<void>;
111
+ /** Router-level patch shaping (deep merges, server-owned fields). */
112
+ 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
+ bulkBatch?: boolean;
76
117
  }
77
118
 
78
119
  export class WorkflowError extends Error {}
79
120
  export class UnknownCollectionError extends Error {}
80
121
 
81
122
  /** Status machine check: staying put is always allowed. */
82
- export function canTransition(map: Record<string, string[]>, from: string, to: string): boolean {
123
+ export function canTransition(map: Readonly<Record<string, readonly string[]>>, from: string, to: string): boolean {
83
124
  return from === to || (map[from] ?? []).includes(to);
84
125
  }
85
126
 
@@ -92,14 +133,15 @@ export function epoch(iso: unknown): number {
92
133
  return Number.isNaN(ms) ? Date.now() : ms;
93
134
  }
94
135
 
95
- function defaultDb(c: RequestContext): CrudDb {
136
+ function defaultDb<E extends ApiEnv>(c: Context<{ Bindings: E }>): CrudDb {
96
137
  return drizzle(neon(c.env.DATABASE_URL));
97
138
  }
98
139
 
99
- export function docStore(spec: DocStoreSpec) {
140
+ export function docStore<E extends ApiEnv = ApiEnv>(spec: DocStoreSpec<E>) {
100
141
  const byKey = new Map(spec.collections.map((col) => [col.key, col]));
101
- const getDb = spec.db ?? defaultDb;
142
+ const getDb = spec.db ?? defaultDb<E>;
102
143
  const maxBatch = spec.maxBatch ?? 2000;
144
+ const routeSet = spec.routeKeys === undefined ? null : new Set(spec.routeKeys);
103
145
 
104
146
  function collectionOf(key: string): DocCollectionSpec | undefined {
105
147
  return byKey.get(key);
@@ -111,6 +153,14 @@ export function docStore(spec: DocStoreSpec) {
111
153
  return col;
112
154
  }
113
155
 
156
+ function requireRoute(key: string): DocCollectionSpec {
157
+ const col = requireSpec(key);
158
+ if (routeSet !== null && !routeSet.has(key)) {
159
+ throw new UnknownCollectionError(`Unknown collection '${key}'`);
160
+ }
161
+ return col;
162
+ }
163
+
114
164
  function idFieldOf(col: DocCollectionSpec): string {
115
165
  return col.idField ?? 'id';
116
166
  }
@@ -295,138 +345,229 @@ export function docStore(spec: DocStoreSpec) {
295
345
  .max(maxBatch),
296
346
  }).strict();
297
347
 
298
- function requireScopeQuery(c: RequestContext, col: DocCollectionSpec): string | undefined {
348
+ function requireScopeQuery(c: Context, col: DocCollectionSpec): string | undefined {
299
349
  if (!col.scope) return undefined;
300
350
  const q = c.req.query('scope');
301
351
  if (!q) throw new WorkflowError(`Scoped collection '${col.key}' requires a scope query`);
302
352
  return q;
303
353
  }
304
354
 
305
- const router = new Hono<{ Bindings: ApiEnv }>();
355
+ function routeErrorResponse(c: Context, err: unknown): Response {
356
+ if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
357
+ if (err instanceof UnknownCollectionError) return c.json({ error: err.message }, 404);
358
+ throw err;
359
+ }
360
+
361
+ async function resolveScope(c: Context): Promise<string | null | undefined> {
362
+ if (spec.scopeOf === undefined) return undefined;
363
+ return spec.scopeOf(c as unknown as Context<{ Bindings: E }>);
364
+ }
365
+
366
+ function dbOf(c: Context): CrudDb {
367
+ return getDb(c as unknown as Context<{ Bindings: E }>);
368
+ }
369
+
370
+ const router = new Hono<{ Bindings: E }>();
306
371
 
307
372
  router.get('/:collection', async (c) => {
308
373
  try {
309
- requireSpec(c.req.param('collection'));
310
- } catch {
311
- return c.json({ error: 'Unknown collection', collection: c.req.param('collection') }, 404);
374
+ const col = requireRoute(c.req.param('collection'));
375
+ const scope = spec.scopeOf === undefined ? c.req.query('scope') : await resolveScope(c);
376
+ if (scope === null) return c.json({ error: 'Authentication required' }, 401);
377
+ return c.json(await listDocs(dbOf(c), col.key, scope));
378
+ } catch (err) {
379
+ return routeErrorResponse(c, err);
312
380
  }
313
- return c.json(await listDocs(getDb(c), c.req.param('collection'), c.req.query('scope')));
314
381
  });
315
382
 
316
383
  router.get('/:collection/:id', async (c) => {
317
- let col: DocCollectionSpec;
318
384
  try {
319
- col = requireSpec(c.req.param('collection'));
320
- } catch {
321
- return c.json({ error: 'Unknown collection', collection: c.req.param('collection') }, 404);
322
- }
323
- let scope: string | undefined;
324
- try {
325
- scope = requireScopeQuery(c, col);
385
+ const col = requireRoute(c.req.param('collection'));
386
+ const scope = spec.scopeOf === undefined ? requireScopeQuery(c, col) : await resolveScope(c);
387
+ if (scope === null) return c.json({ error: 'Authentication required' }, 401);
388
+ const doc = await getDoc(dbOf(c), col.key, c.req.param('id'), scope);
389
+ return doc ? c.json(doc) : c.json({ error: 'Document not found' }, 404);
326
390
  } catch (err) {
327
- if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
328
- throw err;
391
+ return routeErrorResponse(c, err);
329
392
  }
330
- const doc = await getDoc(getDb(c), col.key, c.req.param('id'), scope);
331
- return doc ? c.json(doc) : c.json({ error: 'Document not found' }, 404);
332
393
  });
333
394
 
334
395
  router.put('/:collection/:id', validator('json', validateJson(docSchema, 'Invalid document payload')), async (c) => {
335
- const key = c.req.param('collection');
336
- let col: DocCollectionSpec;
337
396
  try {
338
- col = requireSpec(key);
339
- } catch {
340
- return c.json({ error: 'Unknown collection', collection: key }, 404);
341
- }
342
- const doc = c.req.valid('json') as unknown as DocInput;
343
- const fld = idFieldOf(col);
344
- if (typeof doc[fld] !== 'string' || (doc[fld] as string).length === 0) {
345
- return c.json({ error: 'Invalid document payload', details: { [fld]: ['Required'] } }, 400);
346
- }
347
- if (doc[fld] !== c.req.param('id')) {
348
- return c.json({ error: 'Body id does not match the URL' }, 400);
349
- }
350
- if (col.scope && typeof doc[col.scope.field] !== 'string') {
351
- const q = c.req.query('scope');
352
- if (!q) return c.json({ error: `Scoped collection '${key}' requires a scope query` }, 400);
353
- doc[col.scope.field] = q;
354
- }
355
- try {
356
- await putDoc(getDb(c), key, doc);
397
+ const col = requireRoute(c.req.param('collection'));
398
+ const doc = c.req.valid('json') as unknown as DocInput;
399
+ const fld = idFieldOf(col);
400
+ if (typeof doc[fld] !== 'string' || (doc[fld] as string).length === 0) {
401
+ return c.json({ error: 'Invalid document payload', details: { [fld]: ['Required'] } }, 400);
402
+ }
403
+ if (doc[fld] !== c.req.param('id')) {
404
+ return c.json({ error: 'Body id does not match the URL' }, 400);
405
+ }
406
+ const queryMode = spec.scopeOf === undefined;
407
+ if (queryMode && col.scope && typeof doc[col.scope.field] !== 'string') {
408
+ const q = c.req.query('scope');
409
+ if (!q) return c.json({ error: `Scoped collection '${col.key}' requires a scope query` }, 400);
410
+ doc[col.scope.field] = q;
411
+ }
412
+ const scope = queryMode ? undefined : await resolveScope(c);
413
+ if (scope === null) return c.json({ error: 'Authentication required' }, 401);
414
+ if (col.scope && scope !== undefined) doc[col.scope.field] = scope;
415
+ const existing =
416
+ spec.onPut === undefined
417
+ ? undefined
418
+ : await getDoc(dbOf(c), col.key, doc[fld] as string, col.scope ? scope : undefined);
419
+ if (spec.onPut !== undefined) {
420
+ await spec.onPut({ key: col.key, doc, existing: existing ?? null, scope: scope ?? undefined });
421
+ }
422
+ await putDoc(dbOf(c), col.key, doc);
423
+ return c.json(doc as Doc, existing ? 200 : 201);
357
424
  } catch (err) {
358
- if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
359
- throw err;
425
+ return routeErrorResponse(c, err);
360
426
  }
361
- return c.json(doc, 201);
362
427
  });
363
428
 
364
429
  router.patch('/:collection/:id', validator('json', validateJson(patchSchema, 'Invalid patch payload')), async (c) => {
365
- const key = c.req.param('collection');
366
- let col: DocCollectionSpec;
367
430
  try {
368
- col = requireSpec(key);
369
- } catch {
370
- return c.json({ error: 'Unknown collection', collection: key }, 404);
371
- }
372
- let scope: string | undefined;
373
- try {
374
- scope = requireScopeQuery(c, col);
375
- } catch (err) {
376
- if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
377
- throw err;
378
- }
379
- try {
380
- const merged = await patchDoc(getDb(c), key, c.req.param('id'), c.req.valid('json') as unknown as DocInput, scope);
431
+ const col = requireRoute(c.req.param('collection'));
432
+ const scope = spec.scopeOf === undefined ? requireScopeQuery(c, col) : await resolveScope(c);
433
+ if (scope === null) return c.json({ error: 'Authentication required' }, 401);
434
+ const patch = c.req.valid('json') as unknown as DocInput;
435
+ if (spec.onPatch !== undefined) {
436
+ const existing = await getDoc(dbOf(c), col.key, c.req.param('id'), col.scope ? scope : undefined);
437
+ await spec.onPatch({ key: col.key, patch, existing: existing ?? null, scope: scope ?? undefined });
438
+ }
439
+ const merged = await patchDoc(dbOf(c), col.key, c.req.param('id'), patch, col.scope ? scope : undefined);
381
440
  return c.json(merged ?? {});
382
441
  } catch (err) {
383
- if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
384
- throw err;
442
+ return routeErrorResponse(c, err);
385
443
  }
386
444
  });
387
445
 
388
446
  router.delete('/:collection/:id', async (c) => {
389
- let col: DocCollectionSpec;
390
- try {
391
- col = requireSpec(c.req.param('collection'));
392
- } catch {
393
- return c.json({ error: 'Unknown collection', collection: c.req.param('collection') }, 404);
394
- }
395
- let scope: string | undefined;
396
447
  try {
397
- scope = requireScopeQuery(c, col);
398
- } catch (err) {
399
- if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
400
- throw err;
401
- }
402
- try {
403
- const gone = await softDeleteDoc(getDb(c), col.key, c.req.param('id'), scope);
448
+ const col = requireRoute(c.req.param('collection'));
449
+ const scope = spec.scopeOf === undefined ? requireScopeQuery(c, col) : await resolveScope(c);
450
+ if (scope === null) return c.json({ error: 'Authentication required' }, 401);
451
+ const gone = await softDeleteDoc(dbOf(c), col.key, c.req.param('id'), col.scope ? scope : undefined);
404
452
  return gone ? c.json({ ok: true }) : c.json({ error: 'Document not found' }, 404);
405
453
  } catch (err) {
406
- if (err instanceof WorkflowError) return c.json({ error: err.message }, 400);
407
- throw err;
454
+ return routeErrorResponse(c, err);
408
455
  }
409
456
  });
410
457
 
411
458
  router.post('/batch', validator('json', validateJson(batchSchema, 'Invalid batch payload')), async (c) => {
412
- const applied: { collection: string; id: string }[] = [];
459
+ const batchError = (err: unknown, extra: Record<string, unknown> = {}): Response | null => {
460
+ if (err instanceof WorkflowError) return c.json({ error: err.message, ...extra }, 400);
461
+ if (err instanceof UnknownCollectionError) return c.json({ error: err.message, ...extra }, 404);
462
+ return null;
463
+ };
464
+
465
+ const scope = await resolveScope(c);
466
+ if (scope === null) return c.json({ error: 'Authentication required' }, 401);
467
+
468
+ if (!spec.bulkBatch) {
469
+ const applied: { collection: string; id: string }[] = [];
470
+ try {
471
+ for (const op of c.req.valid('json').ops) {
472
+ const col = requireRoute(op.collection);
473
+ if (op.op === 'put') {
474
+ const doc = op.doc as DocInput;
475
+ if (col.scope && scope !== undefined) doc[col.scope.field] = scope;
476
+ await putDoc(dbOf(c), op.collection, doc);
477
+ applied.push({ collection: op.collection, id: docIdOf(col, doc) });
478
+ } else {
479
+ const delScope = col.scope && scope === undefined ? op.scope : col.scope ? scope : op.scope;
480
+ await softDeleteDoc(dbOf(c), op.collection, op.id, delScope);
481
+ applied.push({ collection: op.collection, id: op.id });
482
+ }
483
+ }
484
+ } catch (err) {
485
+ const mapped = batchError(err, { applied: applied.length });
486
+ if (mapped !== null) return mapped;
487
+ throw err;
488
+ }
489
+ return c.json({ ok: true, applied: applied.length });
490
+ }
491
+
492
+ const db = dbOf(c);
493
+ const putsByCollection = new Map<string, Map<string, DocInput>>();
494
+ const delsByCollection = new Map<string, Set<string>>();
413
495
  try {
414
496
  for (const op of c.req.valid('json').ops) {
415
- requireSpec(op.collection);
416
- if (op.op === 'put') {
417
- await putDoc(getDb(c), op.collection, op.doc as DocInput);
418
- applied.push({ collection: op.collection, id: docIdOf(requireSpec(op.collection), op.doc as DocInput) });
419
- } else {
420
- await softDeleteDoc(getDb(c), op.collection, op.id, op.scope);
421
- applied.push({ collection: op.collection, id: op.id });
497
+ const col = requireRoute(op.collection);
498
+ if (op.op === 'del') {
499
+ const dels = delsByCollection.get(op.collection) ?? new Set<string>();
500
+ dels.add(op.id);
501
+ delsByCollection.set(op.collection, dels);
502
+ continue;
503
+ }
504
+ const doc = op.doc as DocInput;
505
+ const id = docIdOf(col, doc);
506
+ if (col.singletonId && id !== col.singletonId) {
507
+ throw new WorkflowError(`Collection '${op.collection}' only accepts document id '${col.singletonId}'`);
422
508
  }
509
+ if (col.scope && scope !== undefined) doc[col.scope.field] = scope;
510
+ const puts = putsByCollection.get(op.collection) ?? new Map<string, DocInput>();
511
+ puts.set(id, doc);
512
+ putsByCollection.set(op.collection, puts);
513
+ }
514
+ } catch (err) {
515
+ const mapped = batchError(err);
516
+ if (mapped !== null) return mapped;
517
+ throw err;
518
+ }
519
+
520
+ try {
521
+ let applied = 0;
522
+ for (const [key, docs] of putsByCollection) {
523
+ const col = requireSpec(key);
524
+ const existingById = new Map<string, DocInput>();
525
+ if (col.scope !== undefined && col.scope !== null) {
526
+ const needsExisting = col.transitions !== undefined || spec.onPut !== undefined;
527
+ if (needsExisting && scope !== undefined) {
528
+ const rows = await db
529
+ .select({ id: col.table.id, data: col.table.data })
530
+ .from(col.table)
531
+ .where(and(eq(col.scope.column, scope), inArray(col.table.id, [...docs.keys()])));
532
+ for (const row of rows) existingById.set(String(row.id), (row.data ?? {}) as DocInput);
533
+ }
534
+ } else if (spec.onPut !== undefined) {
535
+ for (const id of docs.keys()) {
536
+ const doc = await getDoc(db, key, id);
537
+ if (doc !== undefined) existingById.set(id, doc);
538
+ }
539
+ }
540
+ for (const doc of docs.values()) {
541
+ const id = String(doc[idFieldOf(col)]);
542
+ const existing = existingById.get(id) ?? null;
543
+ if (spec.onPut !== undefined) await spec.onPut({ key, doc, existing, scope });
544
+ if (col.transitions !== undefined && existing !== null) {
545
+ const statusKey = col.statusKey ?? 'status';
546
+ const from = existing[statusKey];
547
+ const to = doc[statusKey];
548
+ if (typeof from === 'string' && typeof to === 'string' && !canTransition(col.transitions, from, to)) {
549
+ throw new WorkflowError(`Invalid ${key} transition ${from} → ${to}`);
550
+ }
551
+ }
552
+ }
553
+ applied += await putDocs(db, key, [...docs.values()]);
554
+ }
555
+ for (const [key, ids] of delsByCollection) {
556
+ const col = requireSpec(key);
557
+ const conds = [inArray(col.table.id, [...ids])];
558
+ if (col.scope && scope !== undefined) conds.unshift(eq(col.scope.column, scope));
559
+ await db
560
+ .update(col.table)
561
+ .set({ deletedAt: Date.now() } as never)
562
+ .where(and(...conds));
563
+ applied += ids.size;
423
564
  }
565
+ return c.json({ ok: true, applied });
424
566
  } catch (err) {
425
- if (err instanceof WorkflowError) return c.json({ error: err.message, applied: applied.length }, 400);
426
- if (err instanceof UnknownCollectionError) return c.json({ error: err.message, applied: applied.length }, 404);
567
+ const mapped = batchError(err);
568
+ if (mapped !== null) return mapped;
427
569
  throw err;
428
570
  }
429
- return c.json({ ok: true, applied: applied.length });
430
571
  });
431
572
 
432
573
  return {
package/src/index.ts CHANGED
@@ -31,7 +31,7 @@ export { ApiError, apiOnError, isUniqueViolation } from './errors';
31
31
  export { crudRoutes, listRoutes } from './crud';
32
32
  export type { CrudSpec, CrudTable, CrudDb, CrudDbFactory, CreateSpec, ListSpec } from './crud';
33
33
  export { docStore, canTransition, epoch, WorkflowError, UnknownCollectionError } from './docstore';
34
- export type { Doc, DocInput, DocTable, DocCollectionSpec, DocStoreSpec, DocValidateFn, DocAfterWriteFn, DocScopeSpec } from './docstore';
34
+ export type { Doc, DocInput, DocTable, DocCollectionSpec, DocStoreSpec, DocValidateFn, DocAfterWriteFn, DocScopeSpec, DocWriteHookArgs, DocPatchHookArgs } from './docstore';
35
35
  export { getDb } from './db';
36
36
  export { uid, pickPatch, patchTypeErrors, normalizeRow, stampUpdate, trio, actor, mapLimit, withRetry } from './lib';
37
37
  export { isoNow, isoAt, todayISO, addDaysISO } from './dates';
@@ -0,0 +1,39 @@
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
+ import { useEffect, useState, useSyncExternalStore } from 'react';
9
+ import type { Resource } from './resource';
10
+
11
+ export interface ResourceResult<T> {
12
+ value: T | null;
13
+ loading: boolean;
14
+ }
15
+
16
+ export function useResource<T>(resource: Resource<T>): ResourceResult<T> {
17
+ const value = useSyncExternalStore(
18
+ (onChange) => resource.subscribe(onChange),
19
+ () => resource.read(),
20
+ () => resource.read(),
21
+ );
22
+ const [loading, setLoading] = useState(resource.read() === null);
23
+
24
+ useEffect(() => {
25
+ if (resource.read() !== null) setLoading(false);
26
+ let alive = true;
27
+ resource
28
+ .ensure()
29
+ .catch(() => null)
30
+ .finally(() => {
31
+ if (alive) setLoading(false);
32
+ });
33
+ return () => {
34
+ alive = false;
35
+ };
36
+ }, [resource]);
37
+
38
+ return { value, loading };
39
+ }