@spooky-sync/client-solid 0.0.1-canary.37 → 0.0.1-canary.370

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.js CHANGED
@@ -1,6 +1,7 @@
1
- import { Sp00kyClient, fileToUint8Array } from "@spooky-sync/core";
1
+ import { Sp00kyClient, WebPushError, decodeBlurhash, fileToUint8Array, semverGt } from "@spooky-sync/core";
2
2
  import { RecordId, Uuid } from "surrealdb";
3
- import { createComponent, createContext, createEffect, createMemo, createSignal, mergeProps, onCleanup, onMount, useContext } from "solid-js";
3
+ import { children, createComponent, createContext, createEffect, createMemo, createSignal, mergeProps, on, onCleanup, onMount, untrack, useContext } from "solid-js";
4
+ import { createStore, reconcile } from "solid-js/store";
4
5
 
5
6
  //#region src/lib/context.ts
6
7
  const Sp00kyContext = createContext();
@@ -27,24 +28,81 @@ function useQuery(dbOrQuery, queryOrOptions, maybeOptions) {
27
28
  finalQuery = dbOrQuery;
28
29
  options = queryOrOptions;
29
30
  }
30
- const [data, setData] = createSignal(void 0);
31
31
  const [error, setError] = createSignal(void 0);
32
32
  const [isFetched, setIsFetched] = createSignal(false);
33
- const [unsubscribe, setUnsubscribe] = createSignal(void 0);
33
+ const [isFetching, setIsFetching] = createSignal(false);
34
+ const [state, setState] = createStore({ value: void 0 });
35
+ const [version, setVersion] = createSignal(0);
36
+ const data = () => {
37
+ version();
38
+ return state.value;
39
+ };
34
40
  let prevQueryString;
41
+ let runId = 0;
42
+ let activeUnsub;
43
+ let activeHash;
44
+ const teardownActive = () => {
45
+ activeUnsub?.();
46
+ activeUnsub = void 0;
47
+ };
35
48
  const sp00ky = db.getSp00ky();
36
- const initQuery = async (query) => {
49
+ /**
50
+ * Registration can fail — the canonical case is the SSP answering 503
51
+ * NOT_READY while it bootstraps. Nothing here used to catch that: the
52
+ * rejection escaped as an unhandled promise, `isFetched` stayed false, and
53
+ * `isLoading()` therefore stayed true FOREVER, which is what a spinner that
54
+ * never resolves actually was. Surface it as `error()` instead; the sync
55
+ * scheduler retries the registration underneath, so a transient failure
56
+ * still recovers on its own.
57
+ */
58
+ const initQuery = async (query, myRun) => {
59
+ try {
60
+ await subscribeQuery(query, myRun);
61
+ } catch (err) {
62
+ if (myRun !== runId) return;
63
+ setError(err instanceof Error ? err : new Error(String(err)));
64
+ }
65
+ };
66
+ const subscribeQuery = async (query, myRun) => {
37
67
  const { hash } = await query.run();
68
+ if (myRun !== runId) return;
69
+ activeHash = hash;
38
70
  setError(void 0);
39
71
  let isFirstCall = true;
40
72
  const unsub = await sp00ky.subscribe(hash, (e) => {
41
73
  const queryData = query.isOne ? e[0] : e;
42
- setData(() => queryData);
74
+ const reconcileStart = performance.now();
75
+ setState("value", reconcile(queryData, { key: "id" }));
76
+ setVersion((v) => v + 1);
77
+ sp00ky.reportFrontendTiming(hash, performance.now() - reconcileStart);
43
78
  const hasData = query.isOne ? queryData !== null && queryData !== void 0 : e.length > 0;
44
79
  if (!isFirstCall || hasData) setIsFetched(true);
45
80
  isFirstCall = false;
46
81
  }, { immediate: true });
47
- setUnsubscribe(() => unsub);
82
+ let known = false;
83
+ let idle = false;
84
+ const settleFromServer = () => {
85
+ if (known && idle && myRun === runId) setIsFetched(true);
86
+ };
87
+ const unsubStatus = sp00ky.subscribeQueryStatus(hash, (status) => {
88
+ setIsFetching(status === "fetching");
89
+ idle = status === "idle";
90
+ settleFromServer();
91
+ }, { immediate: true });
92
+ const unsubAuthority = sp00ky.subscribeQueryAuthority(hash, (k) => {
93
+ known = k;
94
+ settleFromServer();
95
+ }, { immediate: true });
96
+ const teardown = () => {
97
+ unsub();
98
+ unsubStatus();
99
+ unsubAuthority();
100
+ };
101
+ if (myRun !== runId) {
102
+ teardown();
103
+ return;
104
+ }
105
+ activeUnsub = teardown;
48
106
  };
49
107
  createEffect(() => {
50
108
  if (!(options?.enabled?.() ?? true)) {
@@ -53,22 +111,342 @@ function useQuery(dbOrQuery, queryOrOptions, maybeOptions) {
53
111
  }
54
112
  const query = typeof finalQuery === "function" ? finalQuery() : finalQuery;
55
113
  if (!query) return;
56
- const queryString = JSON.stringify(query);
114
+ const queryString = String(query.hash);
57
115
  if (queryString === prevQueryString) return;
58
116
  prevQueryString = queryString;
117
+ const myRun = ++runId;
118
+ teardownActive();
59
119
  setIsFetched(false);
60
- initQuery(query);
61
- onCleanup(() => {
62
- unsubscribe()?.();
63
- });
120
+ setError(void 0);
121
+ initQuery(query, myRun);
122
+ });
123
+ onCleanup(() => {
124
+ runId++;
125
+ teardownActive();
126
+ if (options?.deregisterOnCleanup && activeHash) sp00ky.deregisterQuery(activeHash);
64
127
  });
65
128
  const isLoading = () => {
66
129
  return !isFetched() && error() === void 0;
67
130
  };
131
+ const isSettled = () => isFetched() && !isFetching();
68
132
  return {
69
133
  data,
70
134
  error,
71
- isLoading
135
+ isLoading,
136
+ isFetching,
137
+ isSettled
138
+ };
139
+ }
140
+
141
+ //#endregion
142
+ //#region src/lib/create-preload.ts
143
+ /**
144
+ * Reactive, fire-and-forget prewarm. Resolves the query (calling it if it's a
145
+ * function so it tracks reactive deps), dedupes on the query's stable identity
146
+ * hash, and registers it via `db.preload`: a live query nobody subscribes to,
147
+ * evicted a ttl after it was registered unless a view mounts it first. Nothing
148
+ * to clean up here.
149
+ *
150
+ * Typical use: inside a list row, preload the detail query the user is likely
151
+ * to open next, so navigation paints from cache instead of the network.
152
+ */
153
+ function createPreload(dbOrQuery, queryOrOptions, maybeOptions) {
154
+ let db;
155
+ let finalQuery;
156
+ let options;
157
+ if (dbOrQuery instanceof SyncedDb) {
158
+ db = dbOrQuery;
159
+ finalQuery = queryOrOptions;
160
+ options = maybeOptions;
161
+ } else {
162
+ const contextDb = useContext(Sp00kyContext);
163
+ if (!contextDb) throw new Error("createPreload: No db argument provided and no Sp00kyContext found. Either pass a SyncedDb instance or wrap your app in <Sp00kyProvider>.");
164
+ db = contextDb;
165
+ finalQuery = dbOrQuery;
166
+ options = queryOrOptions;
167
+ }
168
+ let prevHash;
169
+ createEffect(() => {
170
+ if (!(options?.enabled?.() ?? true)) return;
171
+ const query = typeof finalQuery === "function" ? finalQuery() : finalQuery;
172
+ if (!query) return;
173
+ if (query.hash === prevHash) return;
174
+ prevHash = query.hash;
175
+ db.getSp00ky().preload(query, { signal: options?.signal });
176
+ });
177
+ }
178
+
179
+ //#endregion
180
+ //#region src/lib/use-sync-status.ts
181
+ /**
182
+ * Observe sync health for a "can't reach the server" banner / indicator.
183
+ *
184
+ * Backed by `db.subscribeToSyncHealth`. Individual sync failures (a transient
185
+ * remote 500 on query registration, a dropped socket) are absorbed by the
186
+ * retry and never flip this; `isDegraded()` only goes true once failures
187
+ * persist for the configured number of consecutive rounds (sp00ky core config
188
+ * `syncHealth.degradeAfterConsecutiveFailures`, default 3), and flips back on
189
+ * the next successful round. Must be used within a `<Sp00kyProvider>`.
190
+ */
191
+ function useSyncStatus() {
192
+ const db = useDb();
193
+ const [health, setHealth] = createSignal(db.syncHealth);
194
+ onCleanup(db.subscribeToSyncHealth(setHealth));
195
+ return {
196
+ health,
197
+ status: () => health().status,
198
+ isHealthy: () => health().status === "healthy",
199
+ isDegraded: () => health().status === "degraded",
200
+ everConnected: () => health().everConnected,
201
+ isOffline: () => health().status === "degraded" && health().everConnected,
202
+ connection: () => health().connection,
203
+ isReconnecting: () => health().connection === "reconnecting"
204
+ };
205
+ }
206
+
207
+ //#endregion
208
+ //#region src/lib/use-impersonation.ts
209
+ /**
210
+ * Observe admin impersonation (started from the DevTools). The client already
211
+ * shows its own warning bar with a Stop button; use this for anything extra,
212
+ * such as hiding actions an admin should not take on someone's behalf.
213
+ * Must be used within a `<Sp00kyProvider>`.
214
+ */
215
+ function useImpersonation(options = {}) {
216
+ const db = useDb();
217
+ const [impersonation, setImpersonation] = createSignal(db.auth.impersonation);
218
+ onCleanup(db.auth.subscribeImpersonation(setImpersonation));
219
+ createEffect(() => {
220
+ if (options.rendersBanner && impersonation()) db.acknowledgeImpersonationBanner();
221
+ });
222
+ return {
223
+ impersonation,
224
+ isImpersonating: () => impersonation() !== null,
225
+ stop: () => db.auth.stopImpersonating()
226
+ };
227
+ }
228
+
229
+ //#endregion
230
+ //#region src/lib/use-storage-status.ts
231
+ /**
232
+ * Observe how durable the LOCAL cache is, for a "no local storage" warning.
233
+ *
234
+ * Under `localEngine: 'sqlite'` with `store: 'indexeddb'` the durable store is
235
+ * the OPFS SAHPool VFS, and only ONE client per bucket can hold it open: a
236
+ * second tab of the same app cannot get it and runs in memory instead (the
237
+ * engine retries first, so a closing tab's lock is usually waited out). Must be
238
+ * used within a `<Sp00kyProvider>`.
239
+ */
240
+ function useStorageStatus() {
241
+ const db = useDb();
242
+ const [health, setHealth] = createSignal(db.storageHealth);
243
+ onCleanup(db.subscribeToStorageHealth(setHealth));
244
+ return {
245
+ health,
246
+ status: () => health().status,
247
+ isPersistent: () => health().status === "persistent",
248
+ isMemoryFallback: () => health().fallback
249
+ };
250
+ }
251
+
252
+ //#endregion
253
+ //#region src/lib/use-crdt-field.ts
254
+ /**
255
+ * Open a `@crdt` field of the record `recordId()` names, for an editor to bind
256
+ * to (`field()?.getDoc()`). Re-opens when the id changes; closes on cleanup.
257
+ *
258
+ * The accessor stays `null` until the field is loaded (`CrdtField.isLoaded`):
259
+ * this device had the document, or the server answered. Until then the
260
+ * document may be empty only because nothing has arrived yet, so show the
261
+ * column's text instead of binding an editor to it.
262
+ */
263
+ function useCrdtField(table, recordId, field) {
264
+ const db = useContext(Sp00kyContext);
265
+ if (!db) throw new Error("useCrdtField must be used within a <Sp00kyProvider>");
266
+ const [crdtField, setCrdtField] = createSignal(null);
267
+ createEffect(on(createMemo(recordId), (current) => {
268
+ if (!current) return;
269
+ const sp00ky = db.getSp00ky();
270
+ let active = true;
271
+ let opened = false;
272
+ let offLoaded = () => {};
273
+ sp00ky.openCrdtField(table, current, field).then((cf) => {
274
+ opened = true;
275
+ if (!active) {
276
+ sp00ky.closeCrdtField(table, current, field);
277
+ return;
278
+ }
279
+ offLoaded = cf.onLoaded(() => {
280
+ if (active) setCrdtField(cf);
281
+ });
282
+ }).catch((err) => {
283
+ console.error(`[useCrdtField] Failed to open CRDT field ${table}.${field} on ${current}:`, err);
284
+ });
285
+ onCleanup(() => {
286
+ active = false;
287
+ offLoaded();
288
+ setCrdtField(null);
289
+ if (opened) sp00ky.closeCrdtField(table, current, field);
290
+ });
291
+ }));
292
+ return crdtField;
293
+ }
294
+
295
+ //#endregion
296
+ //#region src/lib/use-channel.ts
297
+ const IDLE = {
298
+ status: "idle",
299
+ peers: []
300
+ };
301
+ /**
302
+ * Open a peer to peer channel to `peers` for the rows `query` matches, for
303
+ * the lifetime of the component. The query must be on a `-- @channel` table
304
+ * and only its `where` counts; it is checked against each row, never
305
+ * registered. Writes to matching rows (`db.update` / `db.create` /
306
+ * `db.delete`, or the channel's own) reach the peers over WebRTC in tens of
307
+ * ms; `-- @ephemeral` fields travel only this way. A connection forms when
308
+ * both sides list each other; your own id is skipped.
309
+ *
310
+ * ```ts
311
+ * const ch = useChannel(
312
+ * () => db.query('message').where({ conversation: convoId() }),
313
+ * () => [me(), other()]
314
+ * );
315
+ * ```
316
+ *
317
+ * `query` may be an accessor (re-read when it changes; `null` closes the
318
+ * channel until it returns a query again) or a list of queries.
319
+ */
320
+ function useChannel(query, peers) {
321
+ const db = useContext(Sp00kyContext);
322
+ if (!db) throw new Error("useChannel must be used within a <Sp00kyProvider>.");
323
+ const queries = query;
324
+ const readQueries = () => typeof queries === "function" ? queries() : queries;
325
+ const readPeers = () => typeof peers === "function" ? peers() ?? [] : peers;
326
+ const [state, setState] = createSignal(IDLE);
327
+ let channel = null;
328
+ let stop = () => {};
329
+ const close = () => {
330
+ stop();
331
+ channel?.close();
332
+ channel = null;
333
+ setState(IDLE);
334
+ };
335
+ const sync = (q) => {
336
+ if (!q) return close();
337
+ if (channel) return channel.setQueries(q);
338
+ channel = db.channel(q, untrack(readPeers));
339
+ stop = channel.subscribe(setState);
340
+ };
341
+ sync(untrack(readQueries));
342
+ if (typeof queries === "function") {
343
+ let first = true;
344
+ createEffect(() => {
345
+ const q = queries();
346
+ if (first) return void (first = false);
347
+ sync(q);
348
+ });
349
+ }
350
+ if (typeof peers === "function") {
351
+ let first = true;
352
+ createEffect(() => {
353
+ const next = [...readPeers()];
354
+ if (first) return void (first = false);
355
+ channel?.setPeers(next);
356
+ });
357
+ }
358
+ onCleanup(close);
359
+ const open = () => {
360
+ if (!channel) throw new Error("This channel is closed (its query accessor returned nothing).");
361
+ return channel;
362
+ };
363
+ return {
364
+ status: () => state().status,
365
+ peers: () => state().peers,
366
+ update: ((...args) => open().update(...args)),
367
+ create: ((...args) => open().create(...args)),
368
+ delete: ((...args) => open().delete(...args))
369
+ };
370
+ }
371
+
372
+ //#endregion
373
+ //#region src/lib/use-feature-flag.ts
374
+ /**
375
+ * Subscribe to a feature flag for the currently authenticated user.
376
+ *
377
+ * Returns three Solid accessors that update reactively whenever the
378
+ * server-materialized assignment in `_00_user_feature` changes. Backed by
379
+ * the same SSP + sync pipeline that powers `useQuery`, so toggling a flag
380
+ * via `spky flag enable <key>` propagates to the UI without a refresh.
381
+ *
382
+ * `enabled()` is `true` when the resolved variant exists and is not 'off'.
383
+ * For multi-variant flags, prefer `variant()` directly.
384
+ */
385
+ function useFeatureFlag(key, options) {
386
+ const handle = useDb().getSp00ky().feature(key, options);
387
+ const [variant, setVariant] = createSignal(handle.variant());
388
+ const [payload, setPayload] = createSignal(handle.payload());
389
+ const unsub = handle.subscribe((s) => {
390
+ setVariant(s.variant ?? options?.fallback);
391
+ setPayload(s.payload);
392
+ });
393
+ onCleanup(() => {
394
+ unsub();
395
+ handle.close();
396
+ });
397
+ return {
398
+ variant,
399
+ payload,
400
+ enabled: () => {
401
+ const v = variant();
402
+ return v !== void 0 && v !== "off";
403
+ }
404
+ };
405
+ }
406
+
407
+ //#endregion
408
+ //#region src/lib/use-app-release.ts
409
+ async function reloadForSnapshot(snapshot) {
410
+ if (typeof window === "undefined") return;
411
+ if (snapshot.cacheBust) try {
412
+ if (window.caches) {
413
+ const keys = await window.caches.keys();
414
+ await Promise.all(keys.map((k) => window.caches.delete(k)));
415
+ }
416
+ if (navigator.serviceWorker) {
417
+ const regs = await navigator.serviceWorker.getRegistrations();
418
+ for (const r of regs) r.update().catch(() => {});
419
+ }
420
+ window.location.href = window.location.pathname + "?cb=" + Date.now();
421
+ return;
422
+ } catch {}
423
+ window.location.reload();
424
+ }
425
+ /**
426
+ * Observe the app's announced release (`_00_app_release:<app>`, written by
427
+ * `spky deploy` / `spky release`) and compare it against the running build.
428
+ *
429
+ * Typical use: mount a small "new version available — Reload" notification
430
+ * gated on `updateAvailable()`, auto-invoking `reload()` when `mandatory()`
431
+ * (guard the auto path against reload loops with a per-version marker, since
432
+ * a client can reload while the deploy is still rolling out and land on the
433
+ * old bundle again).
434
+ */
435
+ function useAppRelease(options) {
436
+ const handle = useDb().getSp00ky().appRelease(options.app, { ttl: options.ttl });
437
+ const [snapshot, setSnapshot] = createSignal(handle.snapshot());
438
+ const unsub = handle.subscribe(setSnapshot);
439
+ onCleanup(() => {
440
+ unsub();
441
+ handle.close();
442
+ });
443
+ const updateAvailable = () => semverGt(snapshot().version, options.currentVersion);
444
+ return {
445
+ latestVersion: () => snapshot().version,
446
+ updateAvailable,
447
+ mandatory: () => updateAvailable() && snapshot().mandatory,
448
+ cacheBust: () => snapshot().cacheBust,
449
+ reload: () => reloadForSnapshot(snapshot())
72
450
  };
73
451
  }
74
452
 
@@ -106,7 +484,7 @@ function useFileUpload(dbOrBucketName, maybeBucketName) {
106
484
  }
107
485
  }
108
486
  };
109
- const upload = async (path, file) => {
487
+ const upload = async (path, file, options) => {
110
488
  setError(null);
111
489
  try {
112
490
  validate(file);
@@ -117,7 +495,7 @@ function useFileUpload(dbOrBucketName, maybeBucketName) {
117
495
  setIsUploading(true);
118
496
  try {
119
497
  const bytes = await fileToUint8Array(file);
120
- await db.bucket(bucketName).put(path, bytes);
498
+ return await db.bucket(bucketName).put(path, bytes, options);
121
499
  } catch (e) {
122
500
  setError(e instanceof Error ? e : new Error(String(e)));
123
501
  } finally {
@@ -167,20 +545,6 @@ function useFileUpload(dbOrBucketName, maybeBucketName) {
167
545
 
168
546
  //#endregion
169
547
  //#region src/lib/use-download-file.ts
170
- const downloadCache = /* @__PURE__ */ new Map();
171
- const inflightRequests = /* @__PURE__ */ new Map();
172
- function cacheKey(bucket, path) {
173
- return `${bucket}:${path}`;
174
- }
175
- function releaseEntry(key) {
176
- const entry = downloadCache.get(key);
177
- if (!entry) return;
178
- entry.refCount--;
179
- if (entry.refCount <= 0) {
180
- URL.revokeObjectURL(entry.url);
181
- downloadCache.delete(key);
182
- }
183
- }
184
548
  function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeOptions) {
185
549
  let db;
186
550
  let bucketName;
@@ -201,62 +565,15 @@ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeO
201
565
  const [url, setUrl] = createSignal(null);
202
566
  const [isLoading, setIsLoading] = createSignal(false);
203
567
  const [error, setError] = createSignal(null);
204
- let currentKey = null;
568
+ let lease = null;
205
569
  let privateUrl = null;
206
570
  const [refetchSignal, setRefetchSignal] = createSignal(0);
207
- const refetchTrigger = () => setRefetchSignal((n) => n + 1);
208
- async function doDownload(key, filePath) {
209
- if (useCache) {
210
- const cached = downloadCache.get(key);
211
- if (cached) {
212
- cached.refCount++;
213
- currentKey = key;
214
- return cached.url;
215
- }
216
- const inflight = inflightRequests.get(key);
217
- if (inflight) {
218
- const result = await inflight;
219
- if (result) {
220
- const entry = downloadCache.get(key);
221
- if (entry) {
222
- entry.refCount++;
223
- currentKey = key;
224
- }
225
- }
226
- return result;
227
- }
228
- const promise = (async () => {
229
- const content = await db.bucket(bucketName).get(filePath);
230
- if (!content) return null;
231
- const objectUrl = URL.createObjectURL(new Blob([content]));
232
- downloadCache.set(key, {
233
- url: objectUrl,
234
- refCount: 1
235
- });
236
- return objectUrl;
237
- })();
238
- inflightRequests.set(key, promise);
239
- try {
240
- const result = await promise;
241
- currentKey = key;
242
- return result;
243
- } finally {
244
- inflightRequests.delete(key);
245
- }
246
- } else {
247
- const content = await db.bucket(bucketName).get(filePath);
248
- if (!content) return null;
249
- const objectUrl = URL.createObjectURL(new Blob([content]));
250
- privateUrl = objectUrl;
251
- return objectUrl;
252
- }
253
- }
254
- function releaseCurrentEntry() {
255
- if (useCache && currentKey) {
256
- releaseEntry(currentKey);
257
- currentKey = null;
258
- }
259
- if (!useCache && privateUrl) {
571
+ /** Consumed by the next effect run, so `refetch()` bypasses every layer once. */
572
+ let reloadOnce = false;
573
+ function releaseCurrent() {
574
+ lease?.release();
575
+ lease = null;
576
+ if (privateUrl) {
260
577
  URL.revokeObjectURL(privateUrl);
261
578
  privateUrl = null;
262
579
  }
@@ -264,29 +581,40 @@ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeO
264
581
  createEffect(() => {
265
582
  const filePath = path();
266
583
  refetchSignal();
267
- releaseCurrentEntry();
584
+ releaseCurrent();
268
585
  if (!filePath) {
269
586
  setUrl(null);
270
587
  setIsLoading(false);
271
588
  setError(null);
272
589
  return;
273
590
  }
274
- const key = cacheKey(bucketName, filePath);
275
- if (useCache) {
276
- const cached = downloadCache.get(key);
277
- if (cached) {
278
- cached.refCount++;
279
- currentKey = key;
280
- setUrl(cached.url);
281
- setIsLoading(false);
282
- setError(null);
283
- return;
284
- }
285
- }
591
+ const reload = reloadOnce;
592
+ reloadOnce = false;
286
593
  let cancelled = false;
287
594
  setIsLoading(true);
288
595
  setError(null);
289
- doDownload(key, filePath).then((result) => {
596
+ const bucket = db.bucket(bucketName);
597
+ (useCache ? bucket.url(filePath, {
598
+ persist: options.persist !== false,
599
+ pin: options.pin,
600
+ revalidate: options.revalidate,
601
+ reload
602
+ }).then((acquired) => {
603
+ if (!acquired) return null;
604
+ if (cancelled) {
605
+ acquired.release();
606
+ return null;
607
+ }
608
+ lease = acquired;
609
+ return acquired.url;
610
+ }) : bucket.read(filePath, {
611
+ persist: false,
612
+ reload: true
613
+ }).then((blob) => {
614
+ if (!blob || cancelled) return null;
615
+ privateUrl = URL.createObjectURL(blob);
616
+ return privateUrl;
617
+ })).then((result) => {
290
618
  if (!cancelled) {
291
619
  setUrl(result);
292
620
  setIsLoading(false);
@@ -302,18 +630,11 @@ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeO
302
630
  });
303
631
  });
304
632
  onCleanup(() => {
305
- releaseCurrentEntry();
633
+ releaseCurrent();
306
634
  });
307
635
  const refetch = () => {
308
- if (useCache && currentKey) {
309
- const entry = downloadCache.get(currentKey);
310
- if (entry) {
311
- URL.revokeObjectURL(entry.url);
312
- downloadCache.delete(currentKey);
313
- }
314
- currentKey = null;
315
- }
316
- refetchTrigger();
636
+ reloadOnce = true;
637
+ setRefetchSignal((n) => n + 1);
317
638
  };
318
639
  return {
319
640
  url,
@@ -323,15 +644,240 @@ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeO
323
644
  };
324
645
  }
325
646
 
647
+ //#endregion
648
+ //#region src/lib/use-blurhash.ts
649
+ function useBlurhash(dbOrBucketName, bucketNameOrPath, maybePath) {
650
+ let db;
651
+ let bucketName;
652
+ let path;
653
+ if (typeof dbOrBucketName === "string") {
654
+ db = useDb();
655
+ bucketName = dbOrBucketName;
656
+ path = bucketNameOrPath;
657
+ } else {
658
+ db = dbOrBucketName;
659
+ bucketName = bucketNameOrPath;
660
+ path = maybePath;
661
+ }
662
+ const [hash, setHash] = createSignal(null);
663
+ const [isLoading, setIsLoading] = createSignal(false);
664
+ createEffect(() => {
665
+ const filePath = path();
666
+ if (!filePath) {
667
+ setHash(null);
668
+ setIsLoading(false);
669
+ return;
670
+ }
671
+ let cancelled = false;
672
+ setIsLoading(true);
673
+ db.bucket(bucketName).blurhash(filePath).then((result) => {
674
+ if (cancelled) return;
675
+ setHash(result);
676
+ setIsLoading(false);
677
+ }).catch(() => {
678
+ if (cancelled) return;
679
+ setHash(null);
680
+ setIsLoading(false);
681
+ });
682
+ onCleanup(() => {
683
+ cancelled = true;
684
+ });
685
+ });
686
+ return {
687
+ hash,
688
+ isLoading
689
+ };
690
+ }
691
+
692
+ //#endregion
693
+ //#region src/lib/use-bucket-image.ts
694
+ function useBucketImage(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeOptions) {
695
+ let db;
696
+ let bucketName;
697
+ let path;
698
+ let options;
699
+ if (typeof dbOrBucketName === "string") {
700
+ db = useDb();
701
+ bucketName = dbOrBucketName;
702
+ path = bucketNameOrPath;
703
+ options = pathOrOptions ?? {};
704
+ } else {
705
+ db = dbOrBucketName;
706
+ bucketName = bucketNameOrPath;
707
+ path = pathOrOptions;
708
+ options = maybeOptions ?? {};
709
+ }
710
+ const wantHash = options.blurhash !== false;
711
+ const { hash } = useBlurhash(db, bucketName, () => wantHash ? path() : null);
712
+ const file = useDownloadFile(db, bucketName, path, options);
713
+ const [ready, setReady] = createSignal(false);
714
+ createEffect(on(file.url, () => setReady(false), { defer: true }));
715
+ const gate = (img) => {
716
+ const done = () => setReady(true);
717
+ if (typeof img.decode === "function") img.decode().then(done, done);
718
+ else if (img.complete) done();
719
+ else {
720
+ img.onload = done;
721
+ img.onerror = done;
722
+ }
723
+ };
724
+ return {
725
+ ...file,
726
+ blurhash: hash,
727
+ ready,
728
+ gate
729
+ };
730
+ }
731
+
732
+ //#endregion
733
+ //#region src/lib/Blurhash.ts
734
+ /**
735
+ * A blurhash painted onto a canvas, once per hash change. Size the canvas via
736
+ * `class`/`style` (e.g. `absolute inset-0 w-full h-full`); the internal decode
737
+ * resolution stays tiny regardless of the displayed size.
738
+ */
739
+ function Blurhash(props) {
740
+ if (typeof document === "undefined") return null;
741
+ const canvas = document.createElement("canvas");
742
+ createEffect(() => {
743
+ canvas.className = props.class ?? "";
744
+ });
745
+ createEffect(() => {
746
+ canvas.style.cssText = props.style ?? "";
747
+ });
748
+ createEffect(() => {
749
+ const width = props.width ?? 32;
750
+ const height = props.height ?? 32;
751
+ canvas.width = width;
752
+ canvas.height = height;
753
+ const hash = props.hash;
754
+ if (!hash) return;
755
+ try {
756
+ const pixels = decodeBlurhash(hash, width, height, props.punch ?? 1);
757
+ const ctx = canvas.getContext("2d");
758
+ if (!ctx) return;
759
+ const imageData = ctx.createImageData(width, height);
760
+ imageData.data.set(pixels);
761
+ ctx.putImageData(imageData, 0, 0);
762
+ } catch {}
763
+ });
764
+ return canvas;
765
+ }
766
+
767
+ //#endregion
768
+ //#region src/lib/BucketImage.ts
769
+ const LAYER_STYLE = "position:absolute;inset:0;width:100%;height:100%;";
770
+ /**
771
+ * A bucket image that never pops in: it layers (bottom to top) your `fallback`
772
+ * plate, the automatically stored blurhash, and the real image, which stays
773
+ * transparent until the bitmap is DECODED and then crossfades over the
774
+ * placeholders. Placeholder layers unmount once the fade settles. Respects
775
+ * prefers-reduced-motion (instant swap). The container is made
776
+ * `position: relative` unless your `class` positions it already.
777
+ *
778
+ * ```tsx
779
+ * <BucketImage bucket="covers" path={row.cover_key} class="absolute inset-0"
780
+ * fallback={<MyPlate />} alt="" />
781
+ * ```
782
+ */
783
+ function BucketImage(props) {
784
+ if (typeof document === "undefined") return null;
785
+ const image = useBucketImage(props.bucket, () => props.path, {
786
+ ...props.options,
787
+ blurhash: props.blurhash !== false
788
+ });
789
+ const reducedMotion = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
790
+ const root = document.createElement("div");
791
+ createEffect(() => {
792
+ root.className = props.class ?? "";
793
+ });
794
+ onMount(() => {
795
+ if (getComputedStyle(root).position === "static") root.style.position = "relative";
796
+ });
797
+ const placeholder = document.createElement("div");
798
+ placeholder.style.cssText = LAYER_STYLE;
799
+ const fallbackHolder = document.createElement("div");
800
+ fallbackHolder.style.cssText = LAYER_STYLE;
801
+ placeholder.append(fallbackHolder);
802
+ const resolvedFallback = children(() => props.fallback);
803
+ createEffect(() => {
804
+ const nodes = resolvedFallback.toArray().filter((node) => node instanceof Node);
805
+ fallbackHolder.replaceChildren(...nodes);
806
+ });
807
+ const hashCanvas = Blurhash({
808
+ get hash() {
809
+ return image.blurhash();
810
+ },
811
+ style: LAYER_STYLE
812
+ });
813
+ if (hashCanvas instanceof Node) placeholder.append(hashCanvas);
814
+ const img = document.createElement("img");
815
+ img.decoding = "async";
816
+ img.style.cssText = `${LAYER_STYLE}opacity:0;`;
817
+ createEffect(() => {
818
+ img.className = props.imgClass ?? "";
819
+ });
820
+ createEffect(() => {
821
+ img.style.objectFit = props.fit ?? "cover";
822
+ });
823
+ createEffect(() => {
824
+ img.alt = props.alt ?? "";
825
+ });
826
+ createEffect(() => {
827
+ img.style.transition = reducedMotion ? "none" : `opacity ${props.transition ?? 300}ms ${props.easing ?? "cubic-bezier(0.16, 1, 0.3, 1)"}`;
828
+ });
829
+ createEffect(() => {
830
+ const url = image.url();
831
+ if (!url) {
832
+ img.removeAttribute("src");
833
+ return;
834
+ }
835
+ img.src = url;
836
+ image.gate(img);
837
+ });
838
+ createEffect(() => {
839
+ img.style.opacity = image.ready() ? "1" : "0";
840
+ });
841
+ const [settled, setSettled] = createSignal(false);
842
+ createEffect(() => {
843
+ if (!image.ready()) {
844
+ setSettled(false);
845
+ return;
846
+ }
847
+ const wait = (reducedMotion ? 0 : props.transition ?? 300) + 120;
848
+ const timer = setTimeout(() => setSettled(true), wait);
849
+ onCleanup(() => clearTimeout(timer));
850
+ });
851
+ createEffect(() => {
852
+ if (settled()) placeholder.remove();
853
+ else if (!placeholder.isConnected) root.insertBefore(placeholder, img);
854
+ });
855
+ root.append(placeholder, img);
856
+ return root;
857
+ }
858
+
326
859
  //#endregion
327
860
  //#region src/lib/Sp00kyProvider.ts
328
861
  function Sp00kyProvider(props) {
329
862
  const merged = mergeProps({ fallback: void 0 }, props);
330
863
  const [db, setDb] = createSignal(void 0);
864
+ let disposed = false;
865
+ onCleanup(() => {
866
+ disposed = true;
867
+ });
331
868
  onMount(async () => {
332
869
  try {
333
870
  const instance = new SyncedDb(merged.config);
334
871
  await instance.init();
872
+ if (disposed) {
873
+ await instance.close();
874
+ return;
875
+ }
876
+ if (merged.preload) try {
877
+ await merged.preload(instance);
878
+ } catch (e) {
879
+ console.error("Sp00kyProvider: preload failed; revealing UI anyway", e);
880
+ }
335
881
  setDb(() => instance);
336
882
  merged.onReady?.(instance);
337
883
  } catch (e) {
@@ -378,6 +924,18 @@ var SyncedDb = class {
378
924
  this._initialized = true;
379
925
  }
380
926
  /**
927
+ * Tear down the client: leaves the tabs broker, closes the local store and
928
+ * remote socket, and frees the wasm circuit. Without this a remounted provider
929
+ * (or an HMR reload) strands a whole client, and the abandoned wasm heaps stay
930
+ * resident because V8 cannot see how much wasm memory a dropped wrapper holds.
931
+ */
932
+ async close() {
933
+ const instance = this.sp00ky;
934
+ this.sp00ky = null;
935
+ this._initialized = false;
936
+ if (instance) await instance.close();
937
+ }
938
+ /**
381
939
  * Create a new record in the database
382
940
  */
383
941
  async create(id, payload) {
@@ -396,8 +954,21 @@ var SyncedDb = class {
396
954
  */
397
955
  async delete(tableName, selector) {
398
956
  if (!this.sp00ky) throw new Error("SyncedDb not initialized");
399
- if (typeof selector !== "string") throw new Error("Only string ID selectors are supported currently with core");
400
- await this.sp00ky.delete(tableName, selector);
957
+ const isRecordId = selector instanceof RecordId || selector?.constructor?.name === "RecordId";
958
+ let id;
959
+ if (typeof selector === "string") id = selector;
960
+ else if (isRecordId) id = `${tableName}:${selector.id}`;
961
+ else throw new Error("Only string ID or RecordId selectors are supported currently with core");
962
+ await this.sp00ky.delete(tableName, id);
963
+ }
964
+ /**
965
+ * Preload/prewarm a built query into the local cache without registering a
966
+ * live view. Fetches once and stores the rows (+ embedded related children)
967
+ * locally so a later `useQuery` for the same data paints instantly. Best-effort.
968
+ */
969
+ async preload(finalQuery, options) {
970
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
971
+ await this.sp00ky.preload(finalQuery, options);
401
972
  }
402
973
  /**
403
974
  * Query data from the database
@@ -407,6 +978,15 @@ var SyncedDb = class {
407
978
  return this.sp00ky.query(table, {});
408
979
  }
409
980
  /**
981
+ * Open a peer to peer channel to `peers` for the rows `query` matches (a
982
+ * query on a `-- @channel` table; only its `where` counts). Prefer the
983
+ * `useChannel` hook, which closes it with the component.
984
+ */
985
+ channel(query, peers) {
986
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
987
+ return this.sp00ky.channel(query, peers);
988
+ }
989
+ /**
410
990
  * Run a backend operation
411
991
  */
412
992
  async run(backend, path, payload, options) {
@@ -428,6 +1008,15 @@ var SyncedDb = class {
428
1008
  await this.signOut();
429
1009
  }
430
1010
  /**
1011
+ * Tell the client that this app's own impersonation banner is on screen.
1012
+ * Only needed with `impersonationBanner: { mode: 'custom' }`; the
1013
+ * `useImpersonation({ rendersBanner: true })` hook calls it for you.
1014
+ */
1015
+ acknowledgeImpersonationBanner() {
1016
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1017
+ this.sp00ky.acknowledgeImpersonationBanner();
1018
+ }
1019
+ /**
431
1020
  * Sign out, clear session and local storage
432
1021
  */
433
1022
  async signOut() {
@@ -442,6 +1031,19 @@ var SyncedDb = class {
442
1031
  return await this.sp00ky.useRemote(fn);
443
1032
  }
444
1033
  /**
1034
+ * Run one SurrealQL statement on the server and return its result array.
1035
+ * Nothing is cached locally. Prefer this over `useRemote(s => s.query(...))`
1036
+ * for a plain read or write: the bare SDK client that callback receives
1037
+ * skips the connect gate, so a statement issued while the socket is being
1038
+ * rebuilt fails with "Specify a namespace to use" instead of waiting for
1039
+ * the session. This one is also bounded by the remote service's
1040
+ * concurrency limit and query timeout.
1041
+ */
1042
+ async remoteQuery(sql, vars) {
1043
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1044
+ return await this.sp00ky.remoteQuery(sql, vars);
1045
+ }
1046
+ /**
445
1047
  * Access the remote database service directly
446
1048
  */
447
1049
  get remote() {
@@ -466,10 +1068,52 @@ var SyncedDb = class {
466
1068
  if (!this.sp00ky) throw new Error("SyncedDb not initialized");
467
1069
  return this.sp00ky.pendingMutationCount;
468
1070
  }
1071
+ /** Diagnostic — see `Sp00kyClient.liveRetryCount`. */
1072
+ get liveRetryCount() {
1073
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1074
+ return this.sp00ky.liveRetryCount;
1075
+ }
469
1076
  subscribeToPendingMutations(cb) {
470
1077
  if (!this.sp00ky) throw new Error("SyncedDb not initialized");
471
1078
  return this.sp00ky.subscribeToPendingMutations(cb);
472
1079
  }
1080
+ /** Current sync-health snapshot. See {@link useSyncStatus}. */
1081
+ get syncHealth() {
1082
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1083
+ return this.sp00ky.syncHealth;
1084
+ }
1085
+ /**
1086
+ * Observe sync health. Fires immediately with the current status and again
1087
+ * on every healthy↔degraded transition. Prefer the `useSyncStatus` hook in
1088
+ * components; this is the imperative escape hatch.
1089
+ */
1090
+ subscribeToSyncHealth(cb) {
1091
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1092
+ return this.sp00ky.subscribeToSyncHealth(cb);
1093
+ }
1094
+ /** Current local-store durability snapshot. See {@link useStorageStatus}. */
1095
+ get storageHealth() {
1096
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1097
+ return this.sp00ky.storageHealth;
1098
+ }
1099
+ /**
1100
+ * Observe local-store durability. Fires immediately with the current snapshot
1101
+ * and again on change. Prefer the `useStorageStatus` hook in components; this
1102
+ * is the imperative escape hatch.
1103
+ */
1104
+ subscribeToStorageHealth(cb) {
1105
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1106
+ return this.sp00ky.subscribeToStorageHealth(cb);
1107
+ }
1108
+ /**
1109
+ * Web Push for this browser: `support()`, `subscribe()` (from a click),
1110
+ * `devices()`, `notify()` / `test()` (push to yourself), `bridge()` for the
1111
+ * service worker. See the push-notifications docs page.
1112
+ */
1113
+ get webPush() {
1114
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1115
+ return this.sp00ky.webPush;
1116
+ }
473
1117
  bucket(name) {
474
1118
  if (!this.sp00ky) throw new Error("SyncedDb not initialized");
475
1119
  return this.sp00ky.bucket(name);
@@ -480,5 +1124,5 @@ var SyncedDb = class {
480
1124
  };
481
1125
 
482
1126
  //#endregion
483
- export { RecordId, Sp00kyProvider, SyncedDb, Uuid, useDb, useDownloadFile, useFileUpload, useQuery };
1127
+ export { Blurhash, BucketImage, RecordId, Sp00kyProvider, SyncedDb, Uuid, WebPushError, createPreload, useAppRelease, useBlurhash, useBucketImage, useChannel, useCrdtField, useDb, useDownloadFile, useFeatureFlag, useFileUpload, useImpersonation, useQuery, useStorageStatus, useSyncStatus };
484
1128
  //# sourceMappingURL=index.js.map