@spooky-sync/client-react 0.0.0-stage → 0.0.1-canary.384

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/dist/index.cjs ADDED
@@ -0,0 +1,1351 @@
1
+ 'use client';
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3
+ let surrealdb = require("surrealdb");
4
+ let _spooky_sync_core = require("@spooky-sync/core");
5
+ let react = require("react");
6
+ let react_jsx_runtime = require("react/jsx-runtime");
7
+
8
+ //#region src/db.ts
9
+ /**
10
+ * SyncedDb - a thin wrapper around the sp00ky core client for React.
11
+ * Delegates all logic to the underlying `Sp00kyClient` instance.
12
+ *
13
+ * NOTE: keep in sync with packages/client-solid/src/index.ts and
14
+ * packages/client-solid2/src/index.ts (SyncedDb). Copied rather than shared so
15
+ * this package's dependency graph never pulls in solid-js. React rows are plain
16
+ * objects (no store proxies), so unlike the Solid 2 copy nothing is unwrapped
17
+ * before a write.
18
+ */
19
+ var SyncedDb = class {
20
+ constructor(config) {
21
+ this.sp00ky = null;
22
+ this._initialized = false;
23
+ this.config = config;
24
+ }
25
+ getSp00ky() {
26
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
27
+ return this.sp00ky;
28
+ }
29
+ /** Initialize the core client. */
30
+ async init() {
31
+ if (this._initialized) return;
32
+ this.sp00ky = new _spooky_sync_core.Sp00kyClient(this.config);
33
+ await this.sp00ky.init();
34
+ this._initialized = true;
35
+ }
36
+ /**
37
+ * Tear down the client: leaves the tabs broker, closes the local store and
38
+ * remote socket, and frees the wasm circuit.
39
+ */
40
+ async close() {
41
+ const instance = this.sp00ky;
42
+ this.sp00ky = null;
43
+ this._initialized = false;
44
+ if (instance) await instance.close();
45
+ }
46
+ /** Create a new record in the database. */
47
+ async create(id, payload) {
48
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
49
+ await this.sp00ky.create(id, payload);
50
+ }
51
+ /** Update an existing record in the database. */
52
+ async update(tableName, recordId, payload, options) {
53
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
54
+ await this.sp00ky.update(tableName, recordId, payload, options);
55
+ }
56
+ /** Delete an existing record in the database. */
57
+ async delete(tableName, selector) {
58
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
59
+ const isRecordId = selector instanceof surrealdb.RecordId || selector?.constructor?.name === "RecordId";
60
+ let id;
61
+ if (typeof selector === "string") id = selector;
62
+ else if (isRecordId) id = `${tableName}:${selector.id}`;
63
+ else throw new Error("Only string ID or RecordId selectors are supported currently with core");
64
+ await this.sp00ky.delete(tableName, id);
65
+ }
66
+ /**
67
+ * Preload/prewarm a built query into the local cache without a component
68
+ * subscribing to it, so a later `useQuery` for the same data paints
69
+ * instantly. Best-effort.
70
+ */
71
+ async preload(finalQuery, options) {
72
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
73
+ await this.sp00ky.preload(finalQuery, options);
74
+ }
75
+ /** Start a query on `table`. Finish it with `.build()` and pass it to `useQuery`. */
76
+ query(table) {
77
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
78
+ return this.sp00ky.query(table, {});
79
+ }
80
+ /**
81
+ * Open a peer to peer channel to `peers` for the rows `query` matches (a
82
+ * query on a `-- @channel` table; only its `where` counts). Prefer the
83
+ * `useChannel` hook, which closes it with the component.
84
+ */
85
+ channel(query, peers) {
86
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
87
+ return this.sp00ky.channel(query, peers);
88
+ }
89
+ /** Run a backend operation (writes an outbox job row). */
90
+ async run(backend, path, payload, options) {
91
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
92
+ await this.sp00ky.run(backend, path, payload, options);
93
+ }
94
+ /** Authenticate the remote connection with a token. */
95
+ async authenticate(token) {
96
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
97
+ await this.sp00ky.authenticate(token);
98
+ }
99
+ /**
100
+ * Tell the client that this app's own impersonation banner is on screen.
101
+ * Only needed with `impersonationBanner: { mode: 'custom' }`; the
102
+ * `useImpersonation({ rendersBanner: true })` hook calls it for you.
103
+ */
104
+ acknowledgeImpersonationBanner() {
105
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
106
+ this.sp00ky.acknowledgeImpersonationBanner();
107
+ }
108
+ /** Sign out, clear session and local storage. */
109
+ async signOut() {
110
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
111
+ await this.sp00ky.auth.signOut();
112
+ }
113
+ /** Execute a function with direct access to the remote database connection. */
114
+ async useRemote(fn) {
115
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
116
+ return await this.sp00ky.useRemote(fn);
117
+ }
118
+ /**
119
+ * Run one SurrealQL statement against the REMOTE database, results shaped
120
+ * like the SDK's own `.query()` (one entry per statement). Nothing is cached
121
+ * locally. Prefer this over `useRemote(s => s.query(...))` for a plain read:
122
+ * the bare SDK client that callback receives skips the connect gate, so a
123
+ * statement issued while the socket is being rebuilt fails with "Specify a
124
+ * namespace to use" instead of waiting for the session.
125
+ */
126
+ async remoteQuery(sql, vars) {
127
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
128
+ return await this.sp00ky.remoteQuery(sql, vars);
129
+ }
130
+ /** Access the remote database service directly. */
131
+ get remote() {
132
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
133
+ return this.sp00ky.remoteClient;
134
+ }
135
+ /** Access the local database service directly. */
136
+ get local() {
137
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
138
+ return this.sp00ky.localClient;
139
+ }
140
+ /** Access the auth service. */
141
+ get auth() {
142
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
143
+ return this.sp00ky.auth;
144
+ }
145
+ get pendingMutationCount() {
146
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
147
+ return this.sp00ky.pendingMutationCount;
148
+ }
149
+ /** Diagnostic, see `Sp00kyClient.liveRetryCount`. */
150
+ get liveRetryCount() {
151
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
152
+ return this.sp00ky.liveRetryCount;
153
+ }
154
+ subscribeToPendingMutations(cb) {
155
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
156
+ return this.sp00ky.subscribeToPendingMutations(cb);
157
+ }
158
+ /** Queries mid-fetch right now. See {@link useSyncActivity}. */
159
+ get fetchingQueryCount() {
160
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
161
+ return this.sp00ky.fetchingQueryCount;
162
+ }
163
+ /**
164
+ * Observe how many queries are fetching from the server. Fires immediately
165
+ * and on every change. Prefer the `useSyncActivity` hook in components.
166
+ */
167
+ subscribeToFetchActivity(cb) {
168
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
169
+ return this.sp00ky.subscribeToFetchActivity(cb);
170
+ }
171
+ /** Current sync-health snapshot. See {@link useSyncStatus}. */
172
+ get syncHealth() {
173
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
174
+ return this.sp00ky.syncHealth;
175
+ }
176
+ /**
177
+ * Observe sync health. Fires immediately with the current status and again
178
+ * on every healthy/degraded transition. Prefer the `useSyncStatus` hook in
179
+ * components; this is the imperative escape hatch.
180
+ */
181
+ subscribeToSyncHealth(cb) {
182
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
183
+ return this.sp00ky.subscribeToSyncHealth(cb);
184
+ }
185
+ /** Current local-store durability snapshot. See {@link useStorageStatus}. */
186
+ get storageHealth() {
187
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
188
+ return this.sp00ky.storageHealth;
189
+ }
190
+ /**
191
+ * Observe local-store durability. Fires immediately with the current
192
+ * snapshot and again on change. Prefer the `useStorageStatus` hook.
193
+ */
194
+ subscribeToStorageHealth(cb) {
195
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
196
+ return this.sp00ky.subscribeToStorageHealth(cb);
197
+ }
198
+ /**
199
+ * Web Push for this browser: `support()`, `subscribe()` (from a click),
200
+ * `devices()`, `notify()` / `test()` (push to yourself), `bridge()` for the
201
+ * service worker. See the push-notifications docs page.
202
+ */
203
+ get webPush() {
204
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
205
+ return this.sp00ky.webPush;
206
+ }
207
+ bucket(name) {
208
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
209
+ return this.sp00ky.bucket(name);
210
+ }
211
+ getBucketConfig(name) {
212
+ return this.config.schema.buckets?.find((b) => b.name === name);
213
+ }
214
+ };
215
+
216
+ //#endregion
217
+ //#region src/provider.tsx
218
+ /** `useLayoutEffect` in the browser, `useEffect` on the server (no warning, same order). */
219
+ const useIsomorphicLayoutEffect = typeof window !== "undefined" ? react.useLayoutEffect : react.useEffect;
220
+ /** Ref that always holds the latest value, for callbacks read from async continuations. */
221
+ function useLatest(value) {
222
+ const ref = (0, react.useRef)(value);
223
+ useIsomorphicLayoutEffect(() => {
224
+ ref.current = value;
225
+ });
226
+ return ref;
227
+ }
228
+ const Sp00kyContext = (0, react.createContext)(null);
229
+ /** The provider's `SyncedDb`, or `null` outside one. */
230
+ function useOptionalDb() {
231
+ return (0, react.useContext)(Sp00kyContext);
232
+ }
233
+ /**
234
+ * The `SyncedDb` the nearest `<Sp00kyProvider>` initialized. Throws outside a
235
+ * provider; every hook in this package goes through it.
236
+ */
237
+ function useDb() {
238
+ const db = (0, react.useContext)(Sp00kyContext);
239
+ if (!db) throw new Error("useDb must be used within a <Sp00kyProvider>. Wrap your app in <Sp00kyProvider config={...}>.");
240
+ return db;
241
+ }
242
+ /**
243
+ * Initializes a sp00ky client and provides it to `useDb()` and every hook
244
+ * below. Renders `fallback` until the client is ready.
245
+ *
246
+ * The client is created in an effect, never during render, so a server render
247
+ * only produces the fallback and StrictMode's double render creates nothing.
248
+ */
249
+ function Sp00kyProvider(props) {
250
+ const [db, setDb] = (0, react.useState)(null);
251
+ const boot = (0, react.useRef)(null);
252
+ const callbacks = useLatest({
253
+ onError: props.onError,
254
+ onReady: props.onReady,
255
+ preload: props.preload
256
+ });
257
+ const config = (0, react.useRef)(props.config).current;
258
+ (0, react.useEffect)(() => {
259
+ let active = true;
260
+ let current = boot.current;
261
+ if (current?.disposeTimer !== void 0) {
262
+ clearTimeout(current.disposeTimer);
263
+ current.disposeTimer = void 0;
264
+ }
265
+ if (!current) {
266
+ const instance = new SyncedDb(config);
267
+ current = boot.current = {
268
+ instance,
269
+ init: instance.init(),
270
+ revealed: false
271
+ };
272
+ }
273
+ const b = current;
274
+ b.init.then(async () => {
275
+ if (!active) return;
276
+ const preload = callbacks.current.preload;
277
+ if (preload && !b.revealed) try {
278
+ await preload(b.instance);
279
+ } catch (e) {
280
+ console.error("Sp00kyProvider: preload failed; revealing UI anyway", e);
281
+ }
282
+ if (!active) return;
283
+ const first = !b.revealed;
284
+ b.revealed = true;
285
+ setDb(b.instance);
286
+ if (first) callbacks.current.onReady?.(b.instance);
287
+ }, (e) => {
288
+ if (!active) return;
289
+ const error = e instanceof Error ? e : new Error(String(e));
290
+ if (callbacks.current.onError) callbacks.current.onError(error);
291
+ else console.error("Sp00kyProvider: Failed to initialize database", error);
292
+ });
293
+ return () => {
294
+ active = false;
295
+ b.disposeTimer = setTimeout(() => {
296
+ b.disposeTimer = void 0;
297
+ if (boot.current !== b) return;
298
+ boot.current = null;
299
+ if (!b.revealed) b.init.then(() => b.instance.close(), () => {});
300
+ }, 0);
301
+ };
302
+ }, []);
303
+ if (!db) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: props.fallback ?? null });
304
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Sp00kyContext.Provider, {
305
+ value: db,
306
+ children: props.children
307
+ });
308
+ }
309
+
310
+ //#endregion
311
+ //#region src/query.ts
312
+ const isPlainObject = (v) => {
313
+ if (v === null || typeof v !== "object") return false;
314
+ const proto = Object.getPrototypeOf(v);
315
+ return proto === Object.prototype || proto === null;
316
+ };
317
+ /**
318
+ * Value equality for the leaves `share` does not descend into. The decoder
319
+ * hands out a fresh RecordId / Date / Uuid / Duration for every record-link
320
+ * and datetime column on every emission, so by identity every such field
321
+ * "changed" every time. Two instances of the same class that print alike are
322
+ * the same value. A class whose `toString` is the default `[object X]`
323
+ * (ArrayBuffer, Map, ...) cannot be compared that way and counts as changed.
324
+ */
325
+ function sameValue(a, b) {
326
+ if (a === b) return true;
327
+ if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;
328
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
329
+ const ctor = a.constructor;
330
+ if (!ctor || ctor !== b.constructor || ctor === Object || ctor === Array) return false;
331
+ const text = String(a);
332
+ return !text.startsWith("[object ") && text === String(b);
333
+ }
334
+ const keyOf = (v) => {
335
+ if (!isPlainObject(v)) return void 0;
336
+ const id = v.id;
337
+ return id === void 0 || id === null ? void 0 : String(id);
338
+ };
339
+ /**
340
+ * Structural sharing between two emissions: returns `prev` itself where
341
+ * `next` is deep-equal to it, and a new value that reuses every unchanged
342
+ * subtree otherwise. Array items with an `id` are matched by id, so a row keeps
343
+ * its object identity across reorders, inserts and deletes; `React.memo` rows
344
+ * and `useMemo` deps keyed on a row only re-run when that row changed.
345
+ *
346
+ * Never mutates either argument: the engine may hand the same row objects to
347
+ * several subscribers.
348
+ */
349
+ function share(prev, next) {
350
+ if (prev === next) return next;
351
+ if (Array.isArray(prev) && Array.isArray(next)) {
352
+ const byKey = /* @__PURE__ */ new Map();
353
+ for (const item of prev) {
354
+ const k = keyOf(item);
355
+ if (k !== void 0) byKey.set(k, item);
356
+ }
357
+ let same = prev.length === next.length;
358
+ const out = next.map((item, i) => {
359
+ const k = keyOf(item);
360
+ const base = k !== void 0 ? byKey.get(k) : prev[i];
361
+ const v = base === void 0 ? item : share(base, item);
362
+ if (v !== prev[i]) same = false;
363
+ return v;
364
+ });
365
+ return same ? prev : out;
366
+ }
367
+ if (isPlainObject(prev) && isPlainObject(next)) {
368
+ const keys = Object.keys(next);
369
+ let same = keys.length === Object.keys(prev).length;
370
+ const out = {};
371
+ for (const k of keys) {
372
+ const v = k in prev ? share(prev[k], next[k]) : next[k];
373
+ if (v !== prev[k] || !(k in prev)) same = false;
374
+ out[k] = v;
375
+ }
376
+ return same ? prev : out;
377
+ }
378
+ return sameValue(prev, next) ? prev : next;
379
+ }
380
+ const initialQueryState = {
381
+ data: null,
382
+ error: void 0,
383
+ isAuthoritative: false,
384
+ hasPainted: false,
385
+ isFetching: false
386
+ };
387
+ /**
388
+ * The query state machine, the same contract as the Solid 2 binding:
389
+ *
390
+ * - `reset` (a new identity) clears authority, the paint latch and the error.
391
+ * The previous `data` stays until the new identity emits, so growing a
392
+ * `.limit()` does not flash an empty list.
393
+ * - `rows` applies every emission as-is (the core only emits what it decided
394
+ * the query holds); one WITH data ends the cold load on its own.
395
+ * - `authority` is the channel that ends a cold load whose honest answer is
396
+ * zero rows. A flip back to false is a bucket switch (another principal):
397
+ * what is painted is the previous one's, so the paint latch goes too.
398
+ *
399
+ * Returns `state` itself when nothing changed, so React skips the render.
400
+ */
401
+ function reduceQuery(state, event) {
402
+ switch (event.type) {
403
+ case "reset":
404
+ if (!state.isAuthoritative && !state.hasPainted && !state.error && !state.isFetching) return state;
405
+ return {
406
+ ...state,
407
+ isAuthoritative: false,
408
+ hasPainted: false,
409
+ error: void 0,
410
+ isFetching: false
411
+ };
412
+ case "rows": {
413
+ const next = event.isOne ? event.rows[0] ?? null : event.rows;
414
+ const hasRows = event.isOne ? next !== null && next !== void 0 : event.rows.length > 0;
415
+ const data = share(state.data, next);
416
+ const hasPainted = state.hasPainted || hasRows;
417
+ if (data === state.data && hasPainted === state.hasPainted) return state;
418
+ return {
419
+ ...state,
420
+ data,
421
+ hasPainted
422
+ };
423
+ }
424
+ case "status": return event.fetching === state.isFetching ? state : {
425
+ ...state,
426
+ isFetching: event.fetching
427
+ };
428
+ case "authority": {
429
+ const hasPainted = event.known ? state.hasPainted : false;
430
+ if (event.known === state.isAuthoritative && hasPainted === state.hasPainted) return state;
431
+ return {
432
+ ...state,
433
+ isAuthoritative: event.known,
434
+ hasPainted
435
+ };
436
+ }
437
+ case "error": return {
438
+ ...state,
439
+ error: event.error
440
+ };
441
+ }
442
+ }
443
+ var QueryStore = class {
444
+ constructor() {
445
+ this.state = initialQueryState;
446
+ this.listeners = /* @__PURE__ */ new Set();
447
+ this.subscribe = (listener) => {
448
+ this.listeners.add(listener);
449
+ return () => {
450
+ this.listeners.delete(listener);
451
+ };
452
+ };
453
+ this.getSnapshot = () => this.state;
454
+ }
455
+ dispatch(event) {
456
+ const next = reduceQuery(this.state, event);
457
+ if (next === this.state) return;
458
+ this.state = next;
459
+ for (const l of this.listeners) l();
460
+ }
461
+ /** Clear the identity flags: the query went away or was disabled. */
462
+ reset() {
463
+ this.dispatch({ type: "reset" });
464
+ }
465
+ /**
466
+ * Register `query` and mirror its rows, fetch status and authority until the
467
+ * returned cleanup runs. Registration can fail (canonically the SSP
468
+ * answering 503 NOT_READY while it bootstraps): that surfaces as `error`, and
469
+ * the sync scheduler retries the registration underneath.
470
+ */
471
+ attach(sp00ky, query) {
472
+ this.dispatch({ type: "reset" });
473
+ let disposed = false;
474
+ const cleanups = [];
475
+ const addCleanup = (c) => {
476
+ if (typeof c === "function") {
477
+ if (disposed) c();
478
+ else cleanups.push(c);
479
+ return;
480
+ }
481
+ c.then((fn) => {
482
+ if (disposed) fn();
483
+ else cleanups.push(fn);
484
+ }, () => {});
485
+ };
486
+ query.run().then(({ hash }) => {
487
+ if (disposed) return;
488
+ this.activeHash = hash;
489
+ addCleanup(sp00ky.subscribeQueryStatus(hash, (status) => {
490
+ if (!disposed) this.dispatch({
491
+ type: "status",
492
+ fetching: status === "fetching"
493
+ });
494
+ }, { immediate: true }));
495
+ addCleanup(sp00ky.subscribe(hash, (rows) => {
496
+ if (disposed) return;
497
+ const t0 = performance.now();
498
+ this.dispatch({
499
+ type: "rows",
500
+ rows,
501
+ isOne: query.isOne
502
+ });
503
+ sp00ky.reportFrontendTiming(hash, performance.now() - t0);
504
+ }, { immediate: true }));
505
+ addCleanup(sp00ky.subscribeQueryAuthority(hash, (known) => {
506
+ if (!disposed) this.dispatch({
507
+ type: "authority",
508
+ known
509
+ });
510
+ }, { immediate: true }));
511
+ }, (err) => {
512
+ if (disposed) return;
513
+ this.dispatch({
514
+ type: "error",
515
+ error: err instanceof Error ? err : new Error(String(err))
516
+ });
517
+ });
518
+ return () => {
519
+ disposed = true;
520
+ for (const c of cleanups) c();
521
+ };
522
+ }
523
+ };
524
+ const EMPTY_LIST = Object.freeze([]);
525
+ function useQuery(dbOrQuery, queryOrOptions, maybeOptions) {
526
+ const explicit = dbOrQuery instanceof SyncedDb ? dbOrQuery : null;
527
+ const contextDb = useOptionalDb();
528
+ const db = explicit ?? contextDb;
529
+ if (!db) throw new Error("useQuery: no db argument and no <Sp00kyProvider> above. Pass a SyncedDb or wrap your app in <Sp00kyProvider>.");
530
+ const query = explicit ? queryOrOptions : dbOrQuery;
531
+ const options = explicit ? maybeOptions : queryOrOptions;
532
+ const [store] = (0, react.useState)(() => new QueryStore());
533
+ const state = (0, react.useSyncExternalStore)(store.subscribe, store.getSnapshot, store.getSnapshot);
534
+ const identity = (options?.enabled ?? true) && query ? query.hash : null;
535
+ (0, react.useEffect)(() => {
536
+ if (identity === null || !query) {
537
+ store.reset();
538
+ return;
539
+ }
540
+ return store.attach(db.getSp00ky(), query);
541
+ }, [
542
+ store,
543
+ db,
544
+ identity
545
+ ]);
546
+ const deregister = options?.deregisterOnCleanup ?? false;
547
+ (0, react.useEffect)(() => {
548
+ if (!deregister) return;
549
+ return () => {
550
+ if (store.activeHash) db.getSp00ky().deregisterQuery(store.activeHash);
551
+ };
552
+ }, [
553
+ store,
554
+ db,
555
+ deregister
556
+ ]);
557
+ const isOne = query?.isOne;
558
+ let data = state.data;
559
+ if (isOne === false && !Array.isArray(data)) data = EMPTY_LIST;
560
+ else if (isOne === true && Array.isArray(data)) data = null;
561
+ const hasData = Array.isArray(data) ? data.length > 0 : data !== null && data !== void 0;
562
+ return {
563
+ data,
564
+ error: state.error,
565
+ isLoading: !state.isAuthoritative && !state.hasPainted && state.error === void 0,
566
+ isFetching: state.isFetching,
567
+ isAuthoritative: state.isAuthoritative,
568
+ hasData,
569
+ isEmpty: state.isAuthoritative && !hasData,
570
+ isSettled: state.isAuthoritative && !state.isFetching
571
+ };
572
+ }
573
+ /**
574
+ * Fire-and-forget prewarm: registers `query` via `db.preload` (a live query
575
+ * nobody subscribes to, evicted a ttl after registration unless a view mounts
576
+ * it first) whenever its identity changes. Nothing to clean up.
577
+ *
578
+ * Typical use: inside a list row, preload the detail query the user is likely
579
+ * to open next, so navigation paints from cache instead of the network.
580
+ */
581
+ function usePreload(query, options) {
582
+ const db = useDb();
583
+ const identity = (options?.enabled ?? true) && query ? query.hash : null;
584
+ const signal = options?.signal;
585
+ (0, react.useEffect)(() => {
586
+ if (identity === null || !query) return;
587
+ db.getSp00ky().preload(query, { signal }).catch(() => {});
588
+ }, [db, identity]);
589
+ }
590
+
591
+ //#endregion
592
+ //#region src/status.ts
593
+ /** Shallow equality for the snapshot objects the engine re-creates on every callback. */
594
+ function shallowEqual(a, b) {
595
+ if (Object.is(a, b)) return true;
596
+ if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
597
+ const ka = Object.keys(a);
598
+ if (ka.length !== Object.keys(b).length) return false;
599
+ return ka.every((k) => Object.is(a[k], b[k]));
600
+ }
601
+ /**
602
+ * React view over an engine subscribe-callback API. The engine's subscribe
603
+ * methods fire immediately with the current value, and `read` seeds the
604
+ * first render so nothing flashes before that lands. `deps` identify the
605
+ * source: a change re-reads and re-subscribes.
606
+ */
607
+ function useEngineValue(subscribe, read, deps) {
608
+ const source = (0, react.useMemo)(() => {
609
+ let value = read();
610
+ return {
611
+ subscribe: (onChange) => subscribe((next) => {
612
+ if (shallowEqual(value, next)) return;
613
+ value = next;
614
+ onChange();
615
+ }),
616
+ getSnapshot: () => value
617
+ };
618
+ }, deps);
619
+ return (0, react.useSyncExternalStore)(source.subscribe, source.getSnapshot, source.getSnapshot);
620
+ }
621
+ /**
622
+ * Count of locally committed mutations the server has not acknowledged yet.
623
+ * Drive an "unsaved changes" indicator off this.
624
+ */
625
+ function usePendingMutations() {
626
+ const db = useDb();
627
+ return useEngineValue((cb) => db.subscribeToPendingMutations(cb), () => db.pendingMutationCount, [db]);
628
+ }
629
+ /**
630
+ * Sync health for a "can't reach the server" banner. Single sync failures are
631
+ * absorbed by the retry; `isDegraded` only turns on once failures persist for
632
+ * `syncHealth.degradeAfterConsecutiveFailures` rounds (default 3).
633
+ */
634
+ function useSyncStatus() {
635
+ const db = useDb();
636
+ const health = useEngineValue((cb) => db.subscribeToSyncHealth(cb), () => db.syncHealth, [db]);
637
+ return {
638
+ health,
639
+ status: health.status,
640
+ isHealthy: health.status === "healthy",
641
+ isDegraded: health.status === "degraded",
642
+ everConnected: health.everConnected,
643
+ isOffline: health.status === "degraded" && health.everConnected,
644
+ connection: health.connection,
645
+ isReconnecting: health.connection === "reconnecting"
646
+ };
647
+ }
648
+ /** `busy` once it has held for `delayMs`; off the same render it clears. */
649
+ function useDelayedOn(busy, delayMs) {
650
+ const [on, setOn] = (0, react.useState)(false);
651
+ (0, react.useEffect)(() => {
652
+ if (!busy) {
653
+ setOn(false);
654
+ return;
655
+ }
656
+ if (delayMs <= 0) {
657
+ setOn(true);
658
+ return;
659
+ }
660
+ const timer = setTimeout(() => setOn(true), delayMs);
661
+ return () => clearTimeout(timer);
662
+ }, [busy, delayMs]);
663
+ return busy && on;
664
+ }
665
+ /**
666
+ * The two directions of sync traffic, for an indicator in the app chrome. Both
667
+ * flags are debounced ON by their delay and drop at once, so a local-first
668
+ * page that answers from cache and confirms within a few ms never flickers.
669
+ */
670
+ function useSyncActivity(dbOrOptions, maybeOptions) {
671
+ const explicitDb = dbOrOptions instanceof SyncedDb ? dbOrOptions : void 0;
672
+ const options = (explicitDb ? maybeOptions : dbOrOptions) ?? {};
673
+ const contextDb = useOptionalDb();
674
+ const db = explicitDb ?? contextDb;
675
+ if (!db) throw new Error("useSyncActivity must be used within a <Sp00kyProvider>, or pass the SyncedDb.");
676
+ const fetchingQueries = useEngineValue((cb) => db.subscribeToFetchActivity(cb), () => db.fetchingQueryCount, [db]);
677
+ const pendingMutations = useEngineValue((cb) => db.subscribeToPendingMutations(cb), () => db.pendingMutationCount, [db]);
678
+ return {
679
+ fetchingQueries,
680
+ pendingMutations,
681
+ isDownloading: useDelayedOn(fetchingQueries > 0, options.downloadDelayMs ?? 200),
682
+ isUploading: useDelayedOn(pendingMutations > (options.uploadThreshold ?? 0), options.uploadDelayMs ?? 150)
683
+ };
684
+ }
685
+ /** How durable the LOCAL cache is, for a "no local storage" warning. */
686
+ function useStorageStatus() {
687
+ const db = useDb();
688
+ const health = useEngineValue((cb) => db.subscribeToStorageHealth(cb), () => db.storageHealth, [db]);
689
+ return {
690
+ health,
691
+ status: health.status,
692
+ isPersistent: health.status === "persistent",
693
+ isMemoryFallback: health.fallback
694
+ };
695
+ }
696
+ /** Observe admin impersonation (started from the DevTools). */
697
+ function useImpersonation(options = {}) {
698
+ const db = useDb();
699
+ const impersonation = useEngineValue((cb) => db.auth.subscribeImpersonation(cb), () => db.auth.impersonation, [db]);
700
+ (0, react.useEffect)(() => {
701
+ if (options.rendersBanner && impersonation) db.acknowledgeImpersonationBanner();
702
+ }, [
703
+ db,
704
+ options.rendersBanner,
705
+ impersonation
706
+ ]);
707
+ const stop = (0, react.useCallback)(() => db.auth.stopImpersonating(), [db]);
708
+ return {
709
+ impersonation,
710
+ isImpersonating: impersonation !== null,
711
+ stop
712
+ };
713
+ }
714
+ /**
715
+ * A feature flag for the signed-in user. Updates live when the assignment in
716
+ * `_00_user_feature` changes (e.g. `spky flag enable <key>`).
717
+ */
718
+ function useFeatureFlag(key, options) {
719
+ const db = useDb();
720
+ const fallback = options?.fallback;
721
+ const ttl = options?.ttl;
722
+ const state = useEngineValue((cb) => {
723
+ const handle = db.getSp00ky().feature(key, {
724
+ fallback,
725
+ ttl
726
+ });
727
+ const off = handle.subscribe((s) => cb({
728
+ variant: s.variant ?? fallback,
729
+ payload: s.payload
730
+ }));
731
+ return () => {
732
+ off();
733
+ handle.close();
734
+ };
735
+ }, () => {
736
+ const peek = db.getSp00ky().feature(key, {
737
+ fallback,
738
+ ttl
739
+ });
740
+ const value = {
741
+ variant: peek.variant(),
742
+ payload: peek.payload()
743
+ };
744
+ peek.close();
745
+ return value;
746
+ }, [
747
+ db,
748
+ key,
749
+ fallback,
750
+ ttl
751
+ ]);
752
+ return {
753
+ variant: state.variant,
754
+ payload: state.payload,
755
+ enabled: state.variant !== void 0 && state.variant !== "off"
756
+ };
757
+ }
758
+ async function reloadForSnapshot(snapshot) {
759
+ if (typeof window === "undefined") return;
760
+ if (snapshot.cacheBust) try {
761
+ if (window.caches) {
762
+ const keys = await window.caches.keys();
763
+ await Promise.all(keys.map((k) => window.caches.delete(k)));
764
+ }
765
+ if (navigator.serviceWorker) {
766
+ const regs = await navigator.serviceWorker.getRegistrations();
767
+ for (const r of regs) r.update().catch(() => {});
768
+ }
769
+ window.location.href = window.location.pathname + "?cb=" + Date.now();
770
+ return;
771
+ } catch {}
772
+ window.location.reload();
773
+ }
774
+ /**
775
+ * The app's announced release (`_00_app_release:<app>`, written by
776
+ * `spky deploy` / `spky release`) compared against the running build.
777
+ */
778
+ function useAppRelease(options) {
779
+ const db = useDb();
780
+ const { app, ttl, currentVersion } = options;
781
+ const snapshot = useEngineValue((cb) => {
782
+ const handle = db.getSp00ky().appRelease(app, { ttl });
783
+ const off = handle.subscribe(cb);
784
+ return () => {
785
+ off();
786
+ handle.close();
787
+ };
788
+ }, () => {
789
+ const peek = db.getSp00ky().appRelease(app, { ttl });
790
+ const value = peek.snapshot();
791
+ peek.close();
792
+ return value;
793
+ }, [
794
+ db,
795
+ app,
796
+ ttl
797
+ ]);
798
+ const updateAvailable = (0, _spooky_sync_core.semverGt)(snapshot.version, currentVersion);
799
+ const latest = useLatest(snapshot);
800
+ const reload = (0, react.useCallback)(() => reloadForSnapshot(latest.current), [latest]);
801
+ return {
802
+ latestVersion: snapshot.version,
803
+ updateAvailable,
804
+ mandatory: updateAvailable && snapshot.mandatory,
805
+ cacheBust: snapshot.cacheBust,
806
+ reload
807
+ };
808
+ }
809
+ /**
810
+ * Pending/error state around a mutation, for a button spinner. The engine is
811
+ * already optimistic local-first (a write commits locally and re-renders
812
+ * through live queries before it syncs), so there is no optimistic layer here.
813
+ * An error means the LOCAL commit failed; sync failures surface through
814
+ * `useSyncStatus` and `usePendingMutations`.
815
+ *
816
+ * `submit` is stable across renders and always calls the latest `fn`.
817
+ */
818
+ function useSubmission(fn) {
819
+ const latest = useLatest(fn);
820
+ const [inFlight, setInFlight] = (0, react.useState)(0);
821
+ const [error, setError] = (0, react.useState)(void 0);
822
+ const [result, setResult] = (0, react.useState)(void 0);
823
+ const submit = (0, react.useCallback)(async (...args) => {
824
+ setError(void 0);
825
+ setInFlight((n) => n + 1);
826
+ try {
827
+ const r = await latest.current(...args);
828
+ setResult(() => r);
829
+ return r;
830
+ } catch (e) {
831
+ setError(e instanceof Error ? e : new Error(String(e)));
832
+ return;
833
+ } finally {
834
+ setInFlight((n) => n - 1);
835
+ }
836
+ }, [latest]);
837
+ const clearError = (0, react.useCallback)(() => setError(void 0), []);
838
+ return {
839
+ submit,
840
+ pending: inFlight > 0,
841
+ error,
842
+ result,
843
+ clearError
844
+ };
845
+ }
846
+
847
+ //#endregion
848
+ //#region src/realtime.ts
849
+ /**
850
+ * Open a `@crdt` field of the record `recordId` names, for an editor to bind
851
+ * to (`field?.getDoc()`). Re-opens when the id changes, closes on unmount.
852
+ *
853
+ * `null` until the field is loaded (`CrdtField.isLoaded`): this device had the
854
+ * document, or the server answered. Until then show the column's text instead
855
+ * of binding an editor to a document still arriving.
856
+ */
857
+ function useCrdtField(table, recordId, field) {
858
+ const db = useDb();
859
+ const key = recordId ? `${table}\u0000${recordId}\u0000${field}` : null;
860
+ const [opened, setOpened] = (0, react.useState)(null);
861
+ (0, react.useEffect)(() => {
862
+ if (!key || !recordId) return;
863
+ const sp00ky = db.getSp00ky();
864
+ let superseded = false;
865
+ let isOpen = false;
866
+ let offLoaded = () => {};
867
+ sp00ky.openCrdtField(table, recordId, field).then((cf) => {
868
+ isOpen = true;
869
+ if (superseded) {
870
+ sp00ky.closeCrdtField(table, recordId, field);
871
+ return;
872
+ }
873
+ offLoaded = cf.onLoaded(() => {
874
+ if (!superseded) setOpened({
875
+ key,
876
+ field: cf
877
+ });
878
+ });
879
+ }).catch((err) => {
880
+ console.error(`[useCrdtField] Failed to open CRDT field ${table}.${field} on ${recordId}:`, err);
881
+ });
882
+ return () => {
883
+ superseded = true;
884
+ offLoaded();
885
+ if (isOpen) sp00ky.closeCrdtField(table, recordId, field);
886
+ setOpened(null);
887
+ };
888
+ }, [db, key]);
889
+ return opened && opened.key === key ? opened.field : null;
890
+ }
891
+ const IDLE = {
892
+ status: "idle",
893
+ peers: []
894
+ };
895
+ /** Identity of a channel's queries: their hashes (a builder is built first). */
896
+ function queriesKey(q) {
897
+ if (!q) return null;
898
+ return (Array.isArray(q) ? q : [q]).map((item) => String("build" in item && typeof item.build === "function" ? item.build().hash : item.hash)).join(",");
899
+ }
900
+ const peersKey = (peers) => [...peers].map((p) => String(p)).join("\0");
901
+ /**
902
+ * Open a peer to peer channel to `peers` for the rows `query` matches, while
903
+ * the component is mounted. The query must be on a `-- @channel` table and
904
+ * only its `where` counts; it is checked against each row, never registered.
905
+ * Writes to matching rows (`db.update` / `db.create` / `db.delete`, or the
906
+ * channel's own) reach the peers over WebRTC in tens of ms; `-- @ephemeral`
907
+ * fields travel only this way. A connection forms when both sides list each
908
+ * other; your own id is skipped.
909
+ *
910
+ * ```tsx
911
+ * const ch = useChannel(db.query('message').where({ conversation: convoId }), [me, other]);
912
+ * ```
913
+ *
914
+ * `query` may be `null` (closes the channel until a query is passed again) or
915
+ * a list of queries. Query and peers are compared by value, so building them
916
+ * inline is fine.
917
+ */
918
+ function useChannel(query, peers) {
919
+ const db = useDb();
920
+ const [state, setState] = (0, react.useState)(IDLE);
921
+ const channel = (0, react.useRef)(null);
922
+ const qKey = queriesKey(query);
923
+ const pKey = peersKey(peers);
924
+ const latest = useLatest({
925
+ query,
926
+ peers
927
+ });
928
+ const isOpen = qKey !== null;
929
+ (0, react.useEffect)(() => {
930
+ if (!isOpen) return;
931
+ const { query: q, peers: p } = latest.current;
932
+ const ch = db.channel(q, p);
933
+ channel.current = ch;
934
+ const stop = ch.subscribe(setState);
935
+ return () => {
936
+ stop();
937
+ ch.close();
938
+ if (channel.current === ch) channel.current = null;
939
+ setState(IDLE);
940
+ };
941
+ }, [db, isOpen]);
942
+ (0, react.useEffect)(() => {
943
+ const q = latest.current.query;
944
+ if (q) channel.current?.setQueries(q);
945
+ }, [qKey]);
946
+ (0, react.useEffect)(() => {
947
+ channel.current?.setPeers(latest.current.peers);
948
+ }, [pKey]);
949
+ const open = (0, react.useCallback)(() => {
950
+ if (!channel.current) throw new Error("This channel is closed (no query was passed).");
951
+ return channel.current;
952
+ }, []);
953
+ const writes = (0, react.useMemo)(() => ({
954
+ update: ((...args) => open().update(...args)),
955
+ create: ((...args) => open().create(...args)),
956
+ delete: ((...args) => open().delete(...args))
957
+ }), [open]);
958
+ return {
959
+ status: state.status,
960
+ peers: state.peers,
961
+ ...writes
962
+ };
963
+ }
964
+
965
+ //#endregion
966
+ //#region src/files.tsx
967
+ const toError = (e) => e instanceof Error ? e : new Error(String(e));
968
+ /** `(bucket, ...rest)` with the provider's db, or `(db, bucket, ...rest)`. */
969
+ function useDbAndArgs(hook, args) {
970
+ const contextDb = useOptionalDb();
971
+ if (args[0] instanceof SyncedDb) return args;
972
+ if (!contextDb) throw new Error(`${hook} must be used within a <Sp00kyProvider>, or pass the SyncedDb.`);
973
+ return [contextDb, ...args];
974
+ }
975
+ function useFileUpload(...args) {
976
+ const [db, bucketName] = useDbAndArgs("useFileUpload", args);
977
+ const [uploads, setUploads] = (0, react.useState)(0);
978
+ const [error, setError] = (0, react.useState)(null);
979
+ const objectUrls = (0, react.useRef)([]);
980
+ (0, react.useEffect)(() => () => {
981
+ for (const url of objectUrls.current) URL.revokeObjectURL(url);
982
+ objectUrls.current = [];
983
+ }, []);
984
+ const clearError = (0, react.useCallback)(() => setError(null), []);
985
+ const upload = (0, react.useCallback)(async (path, file, options) => {
986
+ setError(null);
987
+ const config = db.getBucketConfig(bucketName);
988
+ if (config?.maxSize !== null && config?.maxSize !== void 0 && file.size > config.maxSize) {
989
+ const maxMB = (config.maxSize / (1024 * 1024)).toFixed(1);
990
+ setError(/* @__PURE__ */ new Error(`File exceeds maximum size of ${maxMB} MB.`));
991
+ return;
992
+ }
993
+ const allowed = config?.allowedExtensions;
994
+ const fileName = file.name;
995
+ if (allowed && allowed.length > 0 && fileName) {
996
+ const ext = fileName.split(".").pop()?.toLowerCase();
997
+ if (!ext || !allowed.includes(ext)) {
998
+ setError(/* @__PURE__ */ new Error(`File type not allowed. Accepted: ${allowed.join(", ")}.`));
999
+ return;
1000
+ }
1001
+ }
1002
+ setUploads((n) => n + 1);
1003
+ try {
1004
+ const bytes = await (0, _spooky_sync_core.fileToUint8Array)(file);
1005
+ return await db.bucket(bucketName).put(path, bytes, options);
1006
+ } catch (e) {
1007
+ setError(toError(e));
1008
+ } finally {
1009
+ setUploads((n) => n - 1);
1010
+ }
1011
+ }, [db, bucketName]);
1012
+ const download = (0, react.useCallback)(async (path) => {
1013
+ setError(null);
1014
+ try {
1015
+ const content = await db.bucket(bucketName).get(path);
1016
+ if (!content) return null;
1017
+ const url = URL.createObjectURL(new Blob([content]));
1018
+ objectUrls.current.push(url);
1019
+ return url;
1020
+ } catch (e) {
1021
+ setError(toError(e));
1022
+ return null;
1023
+ }
1024
+ }, [db, bucketName]);
1025
+ const remove = (0, react.useCallback)(async (path) => {
1026
+ setError(null);
1027
+ try {
1028
+ await db.bucket(bucketName).delete(path);
1029
+ } catch (e) {
1030
+ setError(toError(e));
1031
+ }
1032
+ }, [db, bucketName]);
1033
+ const exists = (0, react.useCallback)(async (path) => {
1034
+ setError(null);
1035
+ try {
1036
+ return await db.bucket(bucketName).exists(path);
1037
+ } catch (e) {
1038
+ setError(toError(e));
1039
+ return false;
1040
+ }
1041
+ }, [db, bucketName]);
1042
+ return {
1043
+ isUploading: uploads > 0,
1044
+ error,
1045
+ clearError,
1046
+ upload,
1047
+ download,
1048
+ remove,
1049
+ exists
1050
+ };
1051
+ }
1052
+ function useDownloadFile(...args) {
1053
+ const [db, bucketName, path, options = {}] = useDbAndArgs("useDownloadFile", args);
1054
+ const useCache = options.cache !== false;
1055
+ const persist = options.persist !== false;
1056
+ const { pin, revalidate } = options;
1057
+ const [tick, setTick] = (0, react.useState)(0);
1058
+ const reloadOnce = (0, react.useRef)(false);
1059
+ const request = path ? `${String(bucketName)}\u0000${path}\u0000${tick}` : null;
1060
+ const [state, setState] = (0, react.useState)({
1061
+ request: null,
1062
+ url: null,
1063
+ isLoading: false,
1064
+ error: null
1065
+ });
1066
+ (0, react.useEffect)(() => {
1067
+ if (!path || !request) return;
1068
+ const reload = reloadOnce.current;
1069
+ reloadOnce.current = false;
1070
+ let cancelled = false;
1071
+ let lease = null;
1072
+ let privateUrl = null;
1073
+ setState((s) => ({
1074
+ request,
1075
+ url: s.url,
1076
+ isLoading: true,
1077
+ error: null
1078
+ }));
1079
+ const bucket = db.bucket(bucketName);
1080
+ (useCache ? bucket.url(path, {
1081
+ persist,
1082
+ pin,
1083
+ revalidate,
1084
+ reload
1085
+ }).then((acquired) => {
1086
+ if (!acquired) return null;
1087
+ if (cancelled) {
1088
+ acquired.release();
1089
+ return null;
1090
+ }
1091
+ lease = acquired;
1092
+ return acquired.url;
1093
+ }) : bucket.read(path, {
1094
+ persist: false,
1095
+ reload: true
1096
+ }).then((blob) => {
1097
+ if (!blob || cancelled) return null;
1098
+ privateUrl = URL.createObjectURL(blob);
1099
+ return privateUrl;
1100
+ })).then((url) => {
1101
+ if (!cancelled) setState({
1102
+ request,
1103
+ url,
1104
+ isLoading: false,
1105
+ error: null
1106
+ });
1107
+ }, (err) => {
1108
+ if (!cancelled) setState({
1109
+ request,
1110
+ url: null,
1111
+ isLoading: false,
1112
+ error: toError(err)
1113
+ });
1114
+ });
1115
+ return () => {
1116
+ cancelled = true;
1117
+ lease?.release();
1118
+ if (privateUrl) URL.revokeObjectURL(privateUrl);
1119
+ };
1120
+ }, [
1121
+ db,
1122
+ request,
1123
+ useCache,
1124
+ persist,
1125
+ pin,
1126
+ revalidate
1127
+ ]);
1128
+ const refetch = (0, react.useCallback)(() => {
1129
+ reloadOnce.current = true;
1130
+ setTick((n) => n + 1);
1131
+ }, []);
1132
+ if (!request) return {
1133
+ url: null,
1134
+ isLoading: false,
1135
+ error: null,
1136
+ refetch
1137
+ };
1138
+ if (state.request !== request) return {
1139
+ url: state.url,
1140
+ isLoading: true,
1141
+ error: null,
1142
+ refetch
1143
+ };
1144
+ return {
1145
+ url: state.url,
1146
+ isLoading: state.isLoading,
1147
+ error: state.error,
1148
+ refetch
1149
+ };
1150
+ }
1151
+ function useBlurhash(...args) {
1152
+ const [db, bucketName, path] = useDbAndArgs("useBlurhash", args);
1153
+ const request = path ? `${String(bucketName)}\u0000${path}` : null;
1154
+ const [state, setState] = (0, react.useState)({
1155
+ request: null,
1156
+ hash: null
1157
+ });
1158
+ (0, react.useEffect)(() => {
1159
+ if (!path || !request) return;
1160
+ let cancelled = false;
1161
+ db.bucket(bucketName).blurhash(path).then((hash) => {
1162
+ if (!cancelled) setState({
1163
+ request,
1164
+ hash
1165
+ });
1166
+ }, () => {
1167
+ if (!cancelled) setState({
1168
+ request,
1169
+ hash: null
1170
+ });
1171
+ });
1172
+ return () => {
1173
+ cancelled = true;
1174
+ };
1175
+ }, [db, request]);
1176
+ if (!request) return {
1177
+ hash: null,
1178
+ isLoading: false
1179
+ };
1180
+ if (state.request !== request) return {
1181
+ hash: null,
1182
+ isLoading: true
1183
+ };
1184
+ return {
1185
+ hash: state.hash,
1186
+ isLoading: false
1187
+ };
1188
+ }
1189
+ function useBucketImage(...args) {
1190
+ const [db, bucketName, path, options = {}] = useDbAndArgs("useBucketImage", args);
1191
+ const { hash } = useBlurhash(db, bucketName, options.blurhash !== false ? path : null);
1192
+ const file = useDownloadFile(db, bucketName, path, options);
1193
+ const [decodedUrl, setDecodedUrl] = (0, react.useState)(null);
1194
+ const url = file.url;
1195
+ const gate = (0, react.useCallback)((img) => {
1196
+ if (!img || !url) return;
1197
+ const done = () => setDecodedUrl(url);
1198
+ if (typeof img.decode === "function") img.decode().then(done, done);
1199
+ else if (img.complete) done();
1200
+ else {
1201
+ img.onload = done;
1202
+ img.onerror = done;
1203
+ }
1204
+ }, [url]);
1205
+ return {
1206
+ ...file,
1207
+ blurhash: hash,
1208
+ ready: url !== null && decodedUrl === url,
1209
+ gate
1210
+ };
1211
+ }
1212
+ /** A blurhash painted onto a canvas, once per hash change. */
1213
+ function Blurhash({ hash, width = 32, height = 32, punch = 1, className, style }) {
1214
+ const canvas = (0, react.useRef)(null);
1215
+ (0, react.useEffect)(() => {
1216
+ const el = canvas.current;
1217
+ if (!el) return;
1218
+ el.width = width;
1219
+ el.height = height;
1220
+ if (!hash) return;
1221
+ try {
1222
+ const pixels = (0, _spooky_sync_core.decodeBlurhash)(hash, width, height, punch);
1223
+ const ctx = el.getContext("2d");
1224
+ if (!ctx) return;
1225
+ const imageData = ctx.createImageData(width, height);
1226
+ imageData.data.set(pixels);
1227
+ ctx.putImageData(imageData, 0, 0);
1228
+ } catch {}
1229
+ }, [
1230
+ hash,
1231
+ width,
1232
+ height,
1233
+ punch
1234
+ ]);
1235
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("canvas", {
1236
+ ref: canvas,
1237
+ className,
1238
+ style
1239
+ });
1240
+ }
1241
+ const LAYER = {
1242
+ position: "absolute",
1243
+ inset: 0,
1244
+ width: "100%",
1245
+ height: "100%"
1246
+ };
1247
+ function prefersReducedMotion() {
1248
+ return typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
1249
+ }
1250
+ /**
1251
+ * A bucket image that never pops in. Layers, bottom to top: your `fallback`,
1252
+ * the stored blurhash, and the real image, which stays transparent until its
1253
+ * bitmap is DECODED and then crossfades in. The placeholder layers unmount
1254
+ * once the fade settles. Respects prefers-reduced-motion. The container is
1255
+ * made `position: relative` unless your class positions it already.
1256
+ */
1257
+ function BucketImage(props) {
1258
+ const image = useBucketImage(props.bucket, props.path, {
1259
+ ...props.options,
1260
+ blurhash: props.blurhash !== false
1261
+ });
1262
+ const [reducedMotion] = (0, react.useState)(prefersReducedMotion);
1263
+ const transition = props.transition ?? 300;
1264
+ const root = (0, react.useRef)(null);
1265
+ useIsomorphicLayoutEffect(() => {
1266
+ const el = root.current;
1267
+ if (el && getComputedStyle(el).position === "static") el.style.position = "relative";
1268
+ }, []);
1269
+ const [settledUrl, setSettledUrl] = (0, react.useState)(null);
1270
+ (0, react.useEffect)(() => {
1271
+ if (!image.ready || !image.url) return;
1272
+ const url = image.url;
1273
+ const timer = setTimeout(() => setSettledUrl(url), (reducedMotion ? 0 : transition) + 120);
1274
+ return () => clearTimeout(timer);
1275
+ }, [
1276
+ image.ready,
1277
+ image.url,
1278
+ reducedMotion,
1279
+ transition
1280
+ ]);
1281
+ const settled = image.ready && settledUrl === image.url;
1282
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1283
+ ref: root,
1284
+ className: props.className,
1285
+ style: props.style,
1286
+ children: [!settled && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1287
+ style: LAYER,
1288
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1289
+ style: LAYER,
1290
+ children: props.fallback
1291
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Blurhash, {
1292
+ hash: image.blurhash,
1293
+ style: LAYER
1294
+ })]
1295
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", {
1296
+ ref: image.gate,
1297
+ src: image.url ?? void 0,
1298
+ alt: props.alt ?? "",
1299
+ decoding: "async",
1300
+ className: props.imgClassName,
1301
+ style: {
1302
+ ...LAYER,
1303
+ objectFit: props.fit ?? "cover",
1304
+ opacity: image.ready ? 1 : 0,
1305
+ transition: reducedMotion ? "none" : `opacity ${transition}ms ${props.easing ?? "cubic-bezier(0.16, 1, 0.3, 1)"}`
1306
+ }
1307
+ })]
1308
+ });
1309
+ }
1310
+
1311
+ //#endregion
1312
+ exports.Blurhash = Blurhash;
1313
+ exports.BucketImage = BucketImage;
1314
+ Object.defineProperty(exports, 'RecordId', {
1315
+ enumerable: true,
1316
+ get: function () {
1317
+ return surrealdb.RecordId;
1318
+ }
1319
+ });
1320
+ exports.Sp00kyProvider = Sp00kyProvider;
1321
+ exports.SyncedDb = SyncedDb;
1322
+ Object.defineProperty(exports, 'Uuid', {
1323
+ enumerable: true,
1324
+ get: function () {
1325
+ return surrealdb.Uuid;
1326
+ }
1327
+ });
1328
+ Object.defineProperty(exports, 'WebPushError', {
1329
+ enumerable: true,
1330
+ get: function () {
1331
+ return _spooky_sync_core.WebPushError;
1332
+ }
1333
+ });
1334
+ exports.useAppRelease = useAppRelease;
1335
+ exports.useBlurhash = useBlurhash;
1336
+ exports.useBucketImage = useBucketImage;
1337
+ exports.useChannel = useChannel;
1338
+ exports.useCrdtField = useCrdtField;
1339
+ exports.useDb = useDb;
1340
+ exports.useDownloadFile = useDownloadFile;
1341
+ exports.useFeatureFlag = useFeatureFlag;
1342
+ exports.useFileUpload = useFileUpload;
1343
+ exports.useImpersonation = useImpersonation;
1344
+ exports.usePendingMutations = usePendingMutations;
1345
+ exports.usePreload = usePreload;
1346
+ exports.useQuery = useQuery;
1347
+ exports.useStorageStatus = useStorageStatus;
1348
+ exports.useSubmission = useSubmission;
1349
+ exports.useSyncActivity = useSyncActivity;
1350
+ exports.useSyncStatus = useSyncStatus;
1351
+ //# sourceMappingURL=index.cjs.map