@spooky-sync/client-solid 0.0.1-canary.98 → 1.0.0-beta.2

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