@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.cjs CHANGED
@@ -2,6 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  let _spooky_sync_core = require("@spooky-sync/core");
3
3
  let surrealdb = require("surrealdb");
4
4
  let solid_js = require("solid-js");
5
+ let solid_js_store = require("solid-js/store");
5
6
 
6
7
  //#region src/lib/context.ts
7
8
  const Sp00kyContext = (0, solid_js.createContext)();
@@ -28,24 +29,81 @@ function useQuery(dbOrQuery, queryOrOptions, maybeOptions) {
28
29
  finalQuery = dbOrQuery;
29
30
  options = queryOrOptions;
30
31
  }
31
- const [data, setData] = (0, solid_js.createSignal)(void 0);
32
32
  const [error, setError] = (0, solid_js.createSignal)(void 0);
33
33
  const [isFetched, setIsFetched] = (0, solid_js.createSignal)(false);
34
- const [unsubscribe, setUnsubscribe] = (0, solid_js.createSignal)(void 0);
34
+ const [isFetching, setIsFetching] = (0, solid_js.createSignal)(false);
35
+ const [state, setState] = (0, solid_js_store.createStore)({ value: void 0 });
36
+ const [version, setVersion] = (0, solid_js.createSignal)(0);
37
+ const data = () => {
38
+ version();
39
+ return state.value;
40
+ };
35
41
  let prevQueryString;
42
+ let runId = 0;
43
+ let activeUnsub;
44
+ let activeHash;
45
+ const teardownActive = () => {
46
+ activeUnsub?.();
47
+ activeUnsub = void 0;
48
+ };
36
49
  const sp00ky = db.getSp00ky();
37
- const initQuery = async (query) => {
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
+ */
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) => {
38
68
  const { hash } = await query.run();
69
+ if (myRun !== runId) return;
70
+ activeHash = hash;
39
71
  setError(void 0);
40
72
  let isFirstCall = true;
41
73
  const unsub = await sp00ky.subscribe(hash, (e) => {
42
74
  const queryData = query.isOne ? e[0] : e;
43
- setData(() => queryData);
75
+ const reconcileStart = performance.now();
76
+ setState("value", (0, solid_js_store.reconcile)(queryData, { key: "id" }));
77
+ setVersion((v) => v + 1);
78
+ sp00ky.reportFrontendTiming(hash, performance.now() - reconcileStart);
44
79
  const hasData = query.isOne ? queryData !== null && queryData !== void 0 : e.length > 0;
45
80
  if (!isFirstCall || hasData) setIsFetched(true);
46
81
  isFirstCall = false;
47
82
  }, { immediate: true });
48
- setUnsubscribe(() => unsub);
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 });
97
+ const teardown = () => {
98
+ unsub();
99
+ unsubStatus();
100
+ unsubAuthority();
101
+ };
102
+ if (myRun !== runId) {
103
+ teardown();
104
+ return;
105
+ }
106
+ activeUnsub = teardown;
49
107
  };
50
108
  (0, solid_js.createEffect)(() => {
51
109
  if (!(options?.enabled?.() ?? true)) {
@@ -54,22 +112,342 @@ function useQuery(dbOrQuery, queryOrOptions, maybeOptions) {
54
112
  }
55
113
  const query = typeof finalQuery === "function" ? finalQuery() : finalQuery;
56
114
  if (!query) return;
57
- const queryString = JSON.stringify(query);
115
+ const queryString = String(query.hash);
58
116
  if (queryString === prevQueryString) return;
59
117
  prevQueryString = queryString;
118
+ const myRun = ++runId;
119
+ teardownActive();
60
120
  setIsFetched(false);
61
- initQuery(query);
62
- (0, solid_js.onCleanup)(() => {
63
- unsubscribe()?.();
64
- });
121
+ setError(void 0);
122
+ initQuery(query, myRun);
123
+ });
124
+ (0, solid_js.onCleanup)(() => {
125
+ runId++;
126
+ teardownActive();
127
+ if (options?.deregisterOnCleanup && activeHash) sp00ky.deregisterQuery(activeHash);
65
128
  });
66
129
  const isLoading = () => {
67
130
  return !isFetched() && error() === void 0;
68
131
  };
132
+ const isSettled = () => isFetched() && !isFetching();
69
133
  return {
70
134
  data,
71
135
  error,
72
- isLoading
136
+ isLoading,
137
+ isFetching,
138
+ isSettled
139
+ };
140
+ }
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
+
180
+ //#endregion
181
+ //#region src/lib/use-sync-status.ts
182
+ /**
183
+ * Observe sync health for a "can't reach the server" banner / indicator.
184
+ *
185
+ * Backed by `db.subscribeToSyncHealth`. Individual sync failures (a transient
186
+ * remote 500 on query registration, a dropped socket) are absorbed by the
187
+ * retry and never flip this; `isDegraded()` only goes true once failures
188
+ * persist for the configured number of consecutive rounds (sp00ky core config
189
+ * `syncHealth.degradeAfterConsecutiveFailures`, default 3), and flips back on
190
+ * the next successful round. Must be used within a `<Sp00kyProvider>`.
191
+ */
192
+ function useSyncStatus() {
193
+ const db = useDb();
194
+ const [health, setHealth] = (0, solid_js.createSignal)(db.syncHealth);
195
+ (0, solid_js.onCleanup)(db.subscribeToSyncHealth(setHealth));
196
+ return {
197
+ health,
198
+ status: () => health().status,
199
+ isHealthy: () => health().status === "healthy",
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
250
+ };
251
+ }
252
+
253
+ //#endregion
254
+ //#region src/lib/use-crdt-field.ts
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) {
265
+ const db = (0, solid_js.useContext)(Sp00kyContext);
266
+ if (!db) throw new Error("useCrdtField must be used within a <Sp00kyProvider>");
267
+ const [crdtField, setCrdtField] = (0, solid_js.createSignal)(null);
268
+ (0, solid_js.createEffect)((0, solid_js.on)((0, solid_js.createMemo)(recordId), (current) => {
269
+ if (!current) return;
270
+ const sp00ky = db.getSp00ky();
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
+ });
283
+ }).catch((err) => {
284
+ console.error(`[useCrdtField] Failed to open CRDT field ${table}.${field} on ${current}:`, err);
285
+ });
286
+ (0, solid_js.onCleanup)(() => {
287
+ active = false;
288
+ offLoaded();
289
+ setCrdtField(null);
290
+ if (opened) sp00ky.closeCrdtField(table, current, field);
291
+ });
292
+ }));
293
+ return crdtField;
294
+ }
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
+
373
+ //#endregion
374
+ //#region src/lib/use-feature-flag.ts
375
+ /**
376
+ * Subscribe to a feature flag for the currently authenticated user.
377
+ *
378
+ * Returns three Solid accessors that update reactively whenever the
379
+ * server-materialized assignment in `_00_user_feature` changes. Backed by
380
+ * the same SSP + sync pipeline that powers `useQuery`, so toggling a flag
381
+ * via `spky flag enable <key>` propagates to the UI without a refresh.
382
+ *
383
+ * `enabled()` is `true` when the resolved variant exists and is not 'off'.
384
+ * For multi-variant flags, prefer `variant()` directly.
385
+ */
386
+ function useFeatureFlag(key, options) {
387
+ const handle = useDb().getSp00ky().feature(key, options);
388
+ const [variant, setVariant] = (0, solid_js.createSignal)(handle.variant());
389
+ const [payload, setPayload] = (0, solid_js.createSignal)(handle.payload());
390
+ const unsub = handle.subscribe((s) => {
391
+ setVariant(s.variant ?? options?.fallback);
392
+ setPayload(s.payload);
393
+ });
394
+ (0, solid_js.onCleanup)(() => {
395
+ unsub();
396
+ handle.close();
397
+ });
398
+ return {
399
+ variant,
400
+ payload,
401
+ enabled: () => {
402
+ const v = variant();
403
+ return v !== void 0 && v !== "off";
404
+ }
405
+ };
406
+ }
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())
73
451
  };
74
452
  }
75
453
 
@@ -107,7 +485,7 @@ function useFileUpload(dbOrBucketName, maybeBucketName) {
107
485
  }
108
486
  }
109
487
  };
110
- const upload = async (path, file) => {
488
+ const upload = async (path, file, options) => {
111
489
  setError(null);
112
490
  try {
113
491
  validate(file);
@@ -118,7 +496,7 @@ function useFileUpload(dbOrBucketName, maybeBucketName) {
118
496
  setIsUploading(true);
119
497
  try {
120
498
  const bytes = await (0, _spooky_sync_core.fileToUint8Array)(file);
121
- await db.bucket(bucketName).put(path, bytes);
499
+ return await db.bucket(bucketName).put(path, bytes, options);
122
500
  } catch (e) {
123
501
  setError(e instanceof Error ? e : new Error(String(e)));
124
502
  } finally {
@@ -168,20 +546,6 @@ function useFileUpload(dbOrBucketName, maybeBucketName) {
168
546
 
169
547
  //#endregion
170
548
  //#region src/lib/use-download-file.ts
171
- const downloadCache = /* @__PURE__ */ new Map();
172
- const inflightRequests = /* @__PURE__ */ new Map();
173
- function cacheKey(bucket, path) {
174
- return `${bucket}:${path}`;
175
- }
176
- function releaseEntry(key) {
177
- const entry = downloadCache.get(key);
178
- if (!entry) return;
179
- entry.refCount--;
180
- if (entry.refCount <= 0) {
181
- URL.revokeObjectURL(entry.url);
182
- downloadCache.delete(key);
183
- }
184
- }
185
549
  function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeOptions) {
186
550
  let db;
187
551
  let bucketName;
@@ -202,62 +566,15 @@ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeO
202
566
  const [url, setUrl] = (0, solid_js.createSignal)(null);
203
567
  const [isLoading, setIsLoading] = (0, solid_js.createSignal)(false);
204
568
  const [error, setError] = (0, solid_js.createSignal)(null);
205
- let currentKey = null;
569
+ let lease = null;
206
570
  let privateUrl = null;
207
571
  const [refetchSignal, setRefetchSignal] = (0, solid_js.createSignal)(0);
208
- const refetchTrigger = () => setRefetchSignal((n) => n + 1);
209
- async function doDownload(key, filePath) {
210
- if (useCache) {
211
- const cached = downloadCache.get(key);
212
- if (cached) {
213
- cached.refCount++;
214
- currentKey = key;
215
- return cached.url;
216
- }
217
- const inflight = inflightRequests.get(key);
218
- if (inflight) {
219
- const result = await inflight;
220
- if (result) {
221
- const entry = downloadCache.get(key);
222
- if (entry) {
223
- entry.refCount++;
224
- currentKey = key;
225
- }
226
- }
227
- return result;
228
- }
229
- const promise = (async () => {
230
- const content = await db.bucket(bucketName).get(filePath);
231
- if (!content) return null;
232
- const objectUrl = URL.createObjectURL(new Blob([content]));
233
- downloadCache.set(key, {
234
- url: objectUrl,
235
- refCount: 1
236
- });
237
- return objectUrl;
238
- })();
239
- inflightRequests.set(key, promise);
240
- try {
241
- const result = await promise;
242
- currentKey = key;
243
- return result;
244
- } finally {
245
- inflightRequests.delete(key);
246
- }
247
- } else {
248
- const content = await db.bucket(bucketName).get(filePath);
249
- if (!content) return null;
250
- const objectUrl = URL.createObjectURL(new Blob([content]));
251
- privateUrl = objectUrl;
252
- return objectUrl;
253
- }
254
- }
255
- function releaseCurrentEntry() {
256
- if (useCache && currentKey) {
257
- releaseEntry(currentKey);
258
- currentKey = null;
259
- }
260
- 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) {
261
578
  URL.revokeObjectURL(privateUrl);
262
579
  privateUrl = null;
263
580
  }
@@ -265,29 +582,40 @@ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeO
265
582
  (0, solid_js.createEffect)(() => {
266
583
  const filePath = path();
267
584
  refetchSignal();
268
- releaseCurrentEntry();
585
+ releaseCurrent();
269
586
  if (!filePath) {
270
587
  setUrl(null);
271
588
  setIsLoading(false);
272
589
  setError(null);
273
590
  return;
274
591
  }
275
- const key = cacheKey(bucketName, filePath);
276
- if (useCache) {
277
- const cached = downloadCache.get(key);
278
- if (cached) {
279
- cached.refCount++;
280
- currentKey = key;
281
- setUrl(cached.url);
282
- setIsLoading(false);
283
- setError(null);
284
- return;
285
- }
286
- }
592
+ const reload = reloadOnce;
593
+ reloadOnce = false;
287
594
  let cancelled = false;
288
595
  setIsLoading(true);
289
596
  setError(null);
290
- 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) => {
291
619
  if (!cancelled) {
292
620
  setUrl(result);
293
621
  setIsLoading(false);
@@ -303,18 +631,11 @@ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeO
303
631
  });
304
632
  });
305
633
  (0, solid_js.onCleanup)(() => {
306
- releaseCurrentEntry();
634
+ releaseCurrent();
307
635
  });
308
636
  const refetch = () => {
309
- if (useCache && currentKey) {
310
- const entry = downloadCache.get(currentKey);
311
- if (entry) {
312
- URL.revokeObjectURL(entry.url);
313
- downloadCache.delete(currentKey);
314
- }
315
- currentKey = null;
316
- }
317
- refetchTrigger();
637
+ reloadOnce = true;
638
+ setRefetchSignal((n) => n + 1);
318
639
  };
319
640
  return {
320
641
  url,
@@ -324,15 +645,240 @@ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeO
324
645
  };
325
646
  }
326
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
+
327
860
  //#endregion
328
861
  //#region src/lib/Sp00kyProvider.ts
329
862
  function Sp00kyProvider(props) {
330
863
  const merged = (0, solid_js.mergeProps)({ fallback: void 0 }, props);
331
864
  const [db, setDb] = (0, solid_js.createSignal)(void 0);
865
+ let disposed = false;
866
+ (0, solid_js.onCleanup)(() => {
867
+ disposed = true;
868
+ });
332
869
  (0, solid_js.onMount)(async () => {
333
870
  try {
334
871
  const instance = new SyncedDb(merged.config);
335
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
+ }
336
882
  setDb(() => instance);
337
883
  merged.onReady?.(instance);
338
884
  } catch (e) {
@@ -379,6 +925,18 @@ var SyncedDb = class {
379
925
  this._initialized = true;
380
926
  }
381
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
+ /**
382
940
  * Create a new record in the database
383
941
  */
384
942
  async create(id, payload) {
@@ -397,8 +955,21 @@ var SyncedDb = class {
397
955
  */
398
956
  async delete(tableName, selector) {
399
957
  if (!this.sp00ky) throw new Error("SyncedDb not initialized");
400
- if (typeof selector !== "string") throw new Error("Only string ID selectors are supported currently with core");
401
- await this.sp00ky.delete(tableName, selector);
958
+ const isRecordId = selector instanceof surrealdb.RecordId || selector?.constructor?.name === "RecordId";
959
+ let id;
960
+ if (typeof selector === "string") id = selector;
961
+ else if (isRecordId) id = `${tableName}:${selector.id}`;
962
+ else throw new Error("Only string ID or RecordId selectors are supported currently with core");
963
+ await this.sp00ky.delete(tableName, id);
964
+ }
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);
402
973
  }
403
974
  /**
404
975
  * Query data from the database
@@ -408,6 +979,15 @@ var SyncedDb = class {
408
979
  return this.sp00ky.query(table, {});
409
980
  }
410
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
+ /**
411
991
  * Run a backend operation
412
992
  */
413
993
  async run(backend, path, payload, options) {
@@ -429,6 +1009,15 @@ var SyncedDb = class {
429
1009
  await this.signOut();
430
1010
  }
431
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
+ /**
432
1021
  * Sign out, clear session and local storage
433
1022
  */
434
1023
  async signOut() {
@@ -443,6 +1032,19 @@ var SyncedDb = class {
443
1032
  return await this.sp00ky.useRemote(fn);
444
1033
  }
445
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
+ /**
446
1048
  * Access the remote database service directly
447
1049
  */
448
1050
  get remote() {
@@ -467,10 +1069,52 @@ var SyncedDb = class {
467
1069
  if (!this.sp00ky) throw new Error("SyncedDb not initialized");
468
1070
  return this.sp00ky.pendingMutationCount;
469
1071
  }
1072
+ /** Diagnostic — see `Sp00kyClient.liveRetryCount`. */
1073
+ get liveRetryCount() {
1074
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1075
+ return this.sp00ky.liveRetryCount;
1076
+ }
470
1077
  subscribeToPendingMutations(cb) {
471
1078
  if (!this.sp00ky) throw new Error("SyncedDb not initialized");
472
1079
  return this.sp00ky.subscribeToPendingMutations(cb);
473
1080
  }
1081
+ /** Current sync-health snapshot. See {@link useSyncStatus}. */
1082
+ get syncHealth() {
1083
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1084
+ return this.sp00ky.syncHealth;
1085
+ }
1086
+ /**
1087
+ * Observe sync health. Fires immediately with the current status and again
1088
+ * on every healthy↔degraded transition. Prefer the `useSyncStatus` hook in
1089
+ * components; this is the imperative escape hatch.
1090
+ */
1091
+ subscribeToSyncHealth(cb) {
1092
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1093
+ return this.sp00ky.subscribeToSyncHealth(cb);
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
+ }
474
1118
  bucket(name) {
475
1119
  if (!this.sp00ky) throw new Error("SyncedDb not initialized");
476
1120
  return this.sp00ky.bucket(name);
@@ -481,12 +1125,30 @@ var SyncedDb = class {
481
1125
  };
482
1126
 
483
1127
  //#endregion
1128
+ exports.Blurhash = Blurhash;
1129
+ exports.BucketImage = BucketImage;
484
1130
  exports.RecordId = surrealdb.RecordId;
485
1131
  exports.Sp00kyProvider = Sp00kyProvider;
486
1132
  exports.SyncedDb = SyncedDb;
487
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;
1145
+ exports.useCrdtField = useCrdtField;
488
1146
  exports.useDb = useDb;
489
1147
  exports.useDownloadFile = useDownloadFile;
1148
+ exports.useFeatureFlag = useFeatureFlag;
490
1149
  exports.useFileUpload = useFileUpload;
1150
+ exports.useImpersonation = useImpersonation;
491
1151
  exports.useQuery = useQuery;
1152
+ exports.useStorageStatus = useStorageStatus;
1153
+ exports.useSyncStatus = useSyncStatus;
492
1154
  //# sourceMappingURL=index.cjs.map