@spooky-sync/client-solid2 0.0.1-canary.200

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,903 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let _spooky_sync_core = require("@spooky-sync/core");
3
+ let surrealdb = require("surrealdb");
4
+ let solid_js = require("solid-js");
5
+
6
+ //#region src/lib/conflate.ts
7
+ /**
8
+ * Latest-wins async iterable over a subscribe-callback source.
9
+ *
10
+ * Bridges spooky's push-callback subscriptions into the AsyncIterable shape
11
+ * Solid 2 computations consume natively. Each spooky emission is a full result
12
+ * set, so intermediate values are droppable: only the newest unconsumed value
13
+ * is buffered, and a pending pull resolves with it immediately.
14
+ *
15
+ * Teardown contract (probed in rc-semantics.test.ts): Solid 2 does NOT
16
+ * terminate a superseded/disposed computation's async generator — no
17
+ * `return()`, no `finally`. Consumers MUST call `it.return()` themselves from
18
+ * an `onCleanup` registered synchronously in the compute scope. `return()`
19
+ * unsubscribes (awaiting the unsubscribe if the subscribe returned a promise,
20
+ * as `sp00ky.subscribe` does) and resolves any parked pull as done.
21
+ */
22
+ function conflate(subscribe) {
23
+ return { [Symbol.asyncIterator]() {
24
+ let buffered;
25
+ let resolveNext;
26
+ let done = false;
27
+ const unsubMaybe = subscribe((v) => {
28
+ if (done) return;
29
+ if (resolveNext) {
30
+ const r = resolveNext;
31
+ resolveNext = void 0;
32
+ r({
33
+ value: v,
34
+ done: false
35
+ });
36
+ } else buffered = { v };
37
+ });
38
+ const finish = () => {
39
+ if (done) return;
40
+ done = true;
41
+ buffered = void 0;
42
+ Promise.resolve(unsubMaybe).then((unsub) => unsub()).catch(() => {});
43
+ if (resolveNext) {
44
+ const r = resolveNext;
45
+ resolveNext = void 0;
46
+ r({
47
+ value: void 0,
48
+ done: true
49
+ });
50
+ }
51
+ };
52
+ return {
53
+ next() {
54
+ if (done) return Promise.resolve({
55
+ value: void 0,
56
+ done: true
57
+ });
58
+ if (buffered) {
59
+ const v = buffered.v;
60
+ buffered = void 0;
61
+ return Promise.resolve({
62
+ value: v,
63
+ done: false
64
+ });
65
+ }
66
+ return new Promise((r) => resolveNext = r);
67
+ },
68
+ return() {
69
+ finish();
70
+ return Promise.resolve({
71
+ value: void 0,
72
+ done: true
73
+ });
74
+ },
75
+ throw(e) {
76
+ finish();
77
+ return Promise.reject(e);
78
+ }
79
+ };
80
+ } };
81
+ }
82
+
83
+ //#endregion
84
+ //#region src/lib/from-subscription.ts
85
+ /**
86
+ * Reactive view over a spooky subscribe-callback API.
87
+ *
88
+ * The memo's async generator pulls from a conflated (latest-wins) iterator;
89
+ * `initial` is committed as the memo's `loadingValue`, so the accessor is
90
+ * readable synchronously from birth and never suspends. Spooky's subscribe
91
+ * APIs fire immediately with the current value, so the real value lands within
92
+ * a tick of the first read.
93
+ *
94
+ * Teardown is manual by contract (see conflate.ts): onCleanup terminates the
95
+ * iterator, which unsubscribes.
96
+ */
97
+ function fromSubscription(subscribe, initial) {
98
+ return (0, solid_js.createMemo)(async function* () {
99
+ const it = conflate(subscribe)[Symbol.asyncIterator]();
100
+ (0, solid_js.onCleanup)(() => void it.return?.());
101
+ while (true) {
102
+ const r = await it.next();
103
+ if (r.done) break;
104
+ yield r.value;
105
+ }
106
+ }, { loadingValue: initial });
107
+ }
108
+
109
+ //#endregion
110
+ //#region src/lib/context.ts
111
+ const Sp00kyContext = (0, solid_js.createContext)();
112
+ function useDb() {
113
+ try {
114
+ return (0, solid_js.useContext)(Sp00kyContext);
115
+ } catch {
116
+ throw new Error("useDb must be used within a <Sp00kyProvider>. Wrap your app in <Sp00kyProvider config={...}>.");
117
+ }
118
+ }
119
+ /**
120
+ * Count of locally-committed mutations not yet acknowledged by the server.
121
+ * Drive an "unsaved changes" indicator off this.
122
+ */
123
+ function usePendingMutations() {
124
+ const db = useDb();
125
+ return fromSubscription((cb) => db.subscribeToPendingMutations(cb), db.pendingMutationCount);
126
+ }
127
+
128
+ //#endregion
129
+ //#region src/lib/create-query.ts
130
+ function createQuery(dbOrQuery, queryOrOptions, maybeOptions) {
131
+ let db;
132
+ let finalQuery;
133
+ let options;
134
+ if (dbOrQuery instanceof SyncedDb) {
135
+ db = dbOrQuery;
136
+ finalQuery = queryOrOptions;
137
+ options = maybeOptions;
138
+ } else {
139
+ db = useDb();
140
+ finalQuery = dbOrQuery;
141
+ options = queryOrOptions;
142
+ }
143
+ const sp00ky = db.getSp00ky();
144
+ const [error, setError] = (0, solid_js.createSignal)(void 0, { ownedWrite: true });
145
+ const [isFetched, setIsFetched] = (0, solid_js.createSignal)(false, { ownedWrite: true });
146
+ const [isFetching, setIsFetching] = (0, solid_js.createSignal)(false, { ownedWrite: true });
147
+ let activeHash;
148
+ const store = (0, solid_js.createProjection)(async function* () {
149
+ const enabled = options?.enabled?.() ?? true;
150
+ const query = typeof finalQuery === "function" ? finalQuery() : finalQuery;
151
+ if (!enabled || !query) {
152
+ setIsFetched(false);
153
+ setError(void 0);
154
+ return;
155
+ }
156
+ setIsFetched(false);
157
+ setError(void 0);
158
+ const iterators = [];
159
+ const cleanups = [];
160
+ (0, solid_js.onCleanup)(() => {
161
+ for (const it of iterators) it.return?.();
162
+ for (const c of cleanups) c();
163
+ });
164
+ try {
165
+ /**
166
+ * Registration can fail — the canonical case is the SSP answering 503
167
+ * NOT_READY while it bootstraps. Surface it as `error()` instead of
168
+ * throwing into the graph: the sync scheduler retries the
169
+ * registration underneath, so a transient failure still recovers, and
170
+ * a spinner driven by `isLoading()` resolves via `error()`.
171
+ */
172
+ const { hash } = await query.run();
173
+ activeHash = hash;
174
+ cleanups.push(sp00ky.subscribeQueryStatus(hash, (status) => setIsFetching(status === "fetching"), { immediate: true }));
175
+ const it = conflate((cb) => sp00ky.subscribe(hash, cb, { immediate: true }))[Symbol.asyncIterator]();
176
+ iterators.push(it);
177
+ let isFirstCall = true;
178
+ while (true) {
179
+ const r = await it.next();
180
+ if (r.done) break;
181
+ const e = r.value;
182
+ const queryData = query.isOne ? e[0] ?? null : e;
183
+ const hasData = query.isOne ? queryData !== null && queryData !== void 0 : e.length > 0;
184
+ if (!isFirstCall || hasData) setIsFetched(true);
185
+ isFirstCall = false;
186
+ const t0 = performance.now();
187
+ yield { value: queryData };
188
+ sp00ky.reportFrontendTiming(hash, performance.now() - t0);
189
+ }
190
+ } catch (err) {
191
+ setError(err instanceof Error ? err : new Error(String(err)));
192
+ }
193
+ }, { value: null }, {
194
+ key: "id",
195
+ seedLoadingValue: true
196
+ });
197
+ const emptyList = [];
198
+ const data = () => {
199
+ const v = store.value;
200
+ if (v === null || v === void 0) {
201
+ const query = typeof finalQuery === "function" ? finalQuery() : finalQuery;
202
+ if (query && !query.isOne) return emptyList;
203
+ }
204
+ return v;
205
+ };
206
+ const readyGate = (0, solid_js.createMemo)(async () => {
207
+ if (isFetched() || error()) return true;
208
+ await new Promise(() => {});
209
+ return true;
210
+ });
211
+ const ready = () => {
212
+ readyGate();
213
+ return data();
214
+ };
215
+ (0, solid_js.onCleanup)(() => {
216
+ if (options?.deregisterOnCleanup && activeHash) sp00ky.deregisterQuery(activeHash);
217
+ });
218
+ const isLoading = () => !isFetched() && error() === void 0;
219
+ const isSettled = () => isFetched() && !isFetching();
220
+ return {
221
+ data,
222
+ ready,
223
+ error,
224
+ isLoading,
225
+ isFetching,
226
+ isSettled
227
+ };
228
+ }
229
+ /** @deprecated Renamed `createQuery` in the Solid 2 binding. */
230
+ const useQuery = createQuery;
231
+
232
+ //#endregion
233
+ //#region src/lib/create-preload.ts
234
+ /**
235
+ * Reactive, fire-and-forget prewarm. Resolves the query (calling it if it's a
236
+ * function so it tracks reactive deps), dedupes on the query's stable identity
237
+ * hash, and warms it into the local cache via `db.preload`. No subscription and
238
+ * no cleanup: preload registers nothing that needs tearing down.
239
+ *
240
+ * Typical use: inside a list row, preload the detail query the user is likely
241
+ * to open next, so navigation paints from cache instead of the network.
242
+ */
243
+ function createPreload(dbOrQuery, queryOrOptions, maybeOptions) {
244
+ let db;
245
+ let finalQuery;
246
+ let options;
247
+ if (dbOrQuery instanceof SyncedDb) {
248
+ db = dbOrQuery;
249
+ finalQuery = queryOrOptions;
250
+ options = maybeOptions;
251
+ } else {
252
+ db = useDb();
253
+ finalQuery = dbOrQuery;
254
+ options = queryOrOptions;
255
+ }
256
+ let prevHash;
257
+ (0, solid_js.createEffect)(() => {
258
+ if (!(options?.enabled?.() ?? true)) return void 0;
259
+ const query = typeof finalQuery === "function" ? finalQuery() : finalQuery;
260
+ if (!query) return void 0;
261
+ if (query.hash === prevHash) return void 0;
262
+ prevHash = query.hash;
263
+ return query;
264
+ }, (query) => {
265
+ if (!query) return;
266
+ db.getSp00ky().preload(query, {
267
+ refresh: options?.refresh,
268
+ staleTime: options?.staleTime
269
+ });
270
+ });
271
+ }
272
+
273
+ //#endregion
274
+ //#region src/lib/use-sync-status.ts
275
+ /**
276
+ * Observe sync health for a "can't reach the server" banner / indicator.
277
+ *
278
+ * Backed by `db.subscribeToSyncHealth`. Individual sync failures (a transient
279
+ * remote 500 on query registration, a dropped socket) are absorbed by the
280
+ * retry and never flip this; `isDegraded()` only goes true once failures
281
+ * persist for the configured number of consecutive rounds (sp00ky core config
282
+ * `syncHealth.degradeAfterConsecutiveFailures`, default 3), and flips back on
283
+ * the next successful round. Must be used within a `<Sp00kyProvider>`.
284
+ */
285
+ function useSyncStatus() {
286
+ const db = useDb();
287
+ const health = fromSubscription((cb) => db.subscribeToSyncHealth(cb), db.syncHealth);
288
+ return {
289
+ health,
290
+ status: () => health().status,
291
+ isHealthy: () => health().status === "healthy",
292
+ isDegraded: () => health().status === "degraded",
293
+ everConnected: () => health().everConnected,
294
+ isOffline: () => health().status === "degraded" && health().everConnected,
295
+ connection: () => health().connection,
296
+ isReconnecting: () => health().connection === "reconnecting"
297
+ };
298
+ }
299
+
300
+ //#endregion
301
+ //#region src/lib/use-storage-status.ts
302
+ /**
303
+ * Observe how durable the LOCAL cache is, for a "no local storage" warning.
304
+ *
305
+ * Under `localEngine: 'sqlite'` with `store: 'indexeddb'` the durable store is
306
+ * the OPFS SAHPool VFS, and only ONE client per bucket can hold it open: a
307
+ * second tab of the same app cannot get it and runs in memory instead (the
308
+ * engine retries first, so a closing tab's lock is usually waited out). Must be
309
+ * used within a `<Sp00kyProvider>`.
310
+ */
311
+ function useStorageStatus() {
312
+ const db = useDb();
313
+ const health = fromSubscription((cb) => db.subscribeToStorageHealth(cb), db.storageHealth);
314
+ return {
315
+ health,
316
+ status: () => health().status,
317
+ isPersistent: () => health().status === "persistent",
318
+ isMemoryFallback: () => health().fallback
319
+ };
320
+ }
321
+
322
+ //#endregion
323
+ //#region src/lib/use-crdt-field.ts
324
+ function useCrdtField(table, recordId, field, fallbackText) {
325
+ const db = useDb();
326
+ const [crdtField, setCrdtField] = (0, solid_js.createSignal)(null, { ownedWrite: true });
327
+ (0, solid_js.createEffect)(() => recordId(), (id) => {
328
+ if (!id) {
329
+ setCrdtField(null);
330
+ return;
331
+ }
332
+ const sp00ky = db.getSp00ky();
333
+ let superseded = false;
334
+ const text = fallbackText?.();
335
+ sp00ky.openCrdtField(table, id, field, text).then((cf) => {
336
+ if (!superseded) setCrdtField(cf);
337
+ else sp00ky.closeCrdtField(table, id, field);
338
+ }).catch((err) => {
339
+ console.error(`[useCrdtField] Failed to open CRDT field ${table}.${field} on ${id}:`, err);
340
+ });
341
+ return () => {
342
+ superseded = true;
343
+ if (crdtField()) {
344
+ sp00ky.closeCrdtField(table, id, field);
345
+ setCrdtField(null);
346
+ }
347
+ };
348
+ });
349
+ return crdtField;
350
+ }
351
+
352
+ //#endregion
353
+ //#region src/lib/use-feature-flag.ts
354
+ /**
355
+ * Subscribe to a feature flag for the currently authenticated user.
356
+ *
357
+ * Returns three Solid accessors that update reactively whenever the
358
+ * server-materialized assignment in `_00_user_feature` changes. Backed by
359
+ * the same SSP + sync pipeline that powers `createQuery`, so toggling a flag
360
+ * via `spky flag enable <key>` propagates to the UI without a refresh.
361
+ *
362
+ * `enabled()` is `true` when the resolved variant exists and is not 'off'.
363
+ * For multi-variant flags, prefer `variant()` directly.
364
+ */
365
+ function useFeatureFlag(key, options) {
366
+ const handle = useDb().getSp00ky().feature(key, options);
367
+ (0, solid_js.onCleanup)(() => handle.close());
368
+ const state = fromSubscription((cb) => handle.subscribe((s) => cb({
369
+ variant: s.variant ?? options?.fallback,
370
+ payload: s.payload
371
+ })), {
372
+ variant: handle.variant(),
373
+ payload: handle.payload()
374
+ });
375
+ return {
376
+ variant: () => state().variant,
377
+ payload: () => state().payload,
378
+ enabled: () => {
379
+ const v = state().variant;
380
+ return v !== void 0 && v !== "off";
381
+ }
382
+ };
383
+ }
384
+
385
+ //#endregion
386
+ //#region src/lib/use-app-release.ts
387
+ async function reloadForSnapshot(snapshot) {
388
+ if (typeof window === "undefined") return;
389
+ if (snapshot.cacheBust) try {
390
+ if (window.caches) {
391
+ const keys = await window.caches.keys();
392
+ await Promise.all(keys.map((k) => window.caches.delete(k)));
393
+ }
394
+ if (navigator.serviceWorker) {
395
+ const regs = await navigator.serviceWorker.getRegistrations();
396
+ for (const r of regs) r.update().catch(() => {});
397
+ }
398
+ window.location.href = window.location.pathname + "?cb=" + Date.now();
399
+ return;
400
+ } catch {}
401
+ window.location.reload();
402
+ }
403
+ /**
404
+ * Observe the app's announced release (`_00_app_release:<app>`, written by
405
+ * `spky deploy` / `spky release`) and compare it against the running build.
406
+ *
407
+ * Typical use: mount a small "new version available — Reload" notification
408
+ * gated on `updateAvailable()`, auto-invoking `reload()` when `mandatory()`
409
+ * (guard the auto path against reload loops with a per-version marker, since
410
+ * a client can reload while the deploy is still rolling out and land on the
411
+ * old bundle again).
412
+ */
413
+ function useAppRelease(options) {
414
+ const handle = useDb().getSp00ky().appRelease(options.app, { ttl: options.ttl });
415
+ (0, solid_js.onCleanup)(() => handle.close());
416
+ const snapshot = fromSubscription((cb) => handle.subscribe(cb), handle.snapshot());
417
+ const updateAvailable = () => (0, _spooky_sync_core.semverGt)(snapshot().version, options.currentVersion);
418
+ return {
419
+ latestVersion: () => snapshot().version,
420
+ updateAvailable,
421
+ mandatory: () => updateAvailable() && snapshot().mandatory,
422
+ cacheBust: () => snapshot().cacheBust,
423
+ reload: () => reloadForSnapshot(snapshot())
424
+ };
425
+ }
426
+
427
+ //#endregion
428
+ //#region src/lib/use-file-upload.ts
429
+ function useFileUpload(dbOrBucketName, maybeBucketName) {
430
+ let db;
431
+ let bucketName;
432
+ if (typeof dbOrBucketName === "string") {
433
+ db = useDb();
434
+ bucketName = dbOrBucketName;
435
+ } else {
436
+ db = dbOrBucketName;
437
+ bucketName = maybeBucketName;
438
+ }
439
+ const [isUploading, setIsUploading] = (0, solid_js.createSignal)(false, { ownedWrite: true });
440
+ const [error, setError] = (0, solid_js.createSignal)(null, { ownedWrite: true });
441
+ const objectUrls = [];
442
+ (0, solid_js.onCleanup)(() => {
443
+ for (const url of objectUrls) URL.revokeObjectURL(url);
444
+ });
445
+ const clearError = () => setError(null);
446
+ const validate = (file) => {
447
+ const config = db.getBucketConfig(bucketName);
448
+ if (!config) return;
449
+ if (config.maxSize !== null && config.maxSize !== void 0 && file.size > config.maxSize) {
450
+ const maxMB = (config.maxSize / (1024 * 1024)).toFixed(1);
451
+ throw new Error(`File exceeds maximum size of ${maxMB} MB.`);
452
+ }
453
+ if (config.allowedExtensions && config.allowedExtensions.length > 0) {
454
+ const fileName = file.name;
455
+ if (fileName) {
456
+ const ext = fileName.split(".").pop()?.toLowerCase();
457
+ if (!ext || !config.allowedExtensions.includes(ext)) throw new Error(`File type not allowed. Accepted: ${config.allowedExtensions.join(", ")}.`);
458
+ }
459
+ }
460
+ };
461
+ const upload = async (path, file, options) => {
462
+ setError(null);
463
+ try {
464
+ validate(file);
465
+ } catch (e) {
466
+ setError(e instanceof Error ? e : new Error(String(e)));
467
+ return;
468
+ }
469
+ setIsUploading(true);
470
+ try {
471
+ const bytes = await (0, _spooky_sync_core.fileToUint8Array)(file);
472
+ return await db.bucket(bucketName).put(path, bytes, options);
473
+ } catch (e) {
474
+ setError(e instanceof Error ? e : new Error(String(e)));
475
+ } finally {
476
+ setIsUploading(false);
477
+ }
478
+ };
479
+ const download = async (path) => {
480
+ setError(null);
481
+ try {
482
+ const content = await db.bucket(bucketName).get(path);
483
+ if (!content) return null;
484
+ const objectUrl = URL.createObjectURL(new Blob([content]));
485
+ objectUrls.push(objectUrl);
486
+ return objectUrl;
487
+ } catch (e) {
488
+ setError(e instanceof Error ? e : new Error(String(e)));
489
+ return null;
490
+ }
491
+ };
492
+ const remove = async (path) => {
493
+ setError(null);
494
+ try {
495
+ await db.bucket(bucketName).delete(path);
496
+ } catch (e) {
497
+ setError(e instanceof Error ? e : new Error(String(e)));
498
+ }
499
+ };
500
+ const exists = async (path) => {
501
+ setError(null);
502
+ try {
503
+ return await db.bucket(bucketName).exists(path);
504
+ } catch (e) {
505
+ setError(e instanceof Error ? e : new Error(String(e)));
506
+ return false;
507
+ }
508
+ };
509
+ return {
510
+ isUploading,
511
+ error,
512
+ clearError,
513
+ upload,
514
+ download,
515
+ remove,
516
+ exists
517
+ };
518
+ }
519
+
520
+ //#endregion
521
+ //#region src/lib/use-download-file.ts
522
+ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeOptions) {
523
+ let db;
524
+ let bucketName;
525
+ let path;
526
+ let options;
527
+ if (typeof dbOrBucketName === "string") {
528
+ db = useDb();
529
+ bucketName = dbOrBucketName;
530
+ path = bucketNameOrPath;
531
+ options = pathOrOptions ?? {};
532
+ } else {
533
+ db = dbOrBucketName;
534
+ bucketName = bucketNameOrPath;
535
+ path = pathOrOptions;
536
+ options = maybeOptions ?? {};
537
+ }
538
+ const useCache = options.cache !== false;
539
+ const [url, setUrl] = (0, solid_js.createSignal)(null, { ownedWrite: true });
540
+ const [isLoading, setIsLoading] = (0, solid_js.createSignal)(false, { ownedWrite: true });
541
+ const [error, setError] = (0, solid_js.createSignal)(null, { ownedWrite: true });
542
+ let lease = null;
543
+ let privateUrl = null;
544
+ const [refetchSignal, setRefetchSignal] = (0, solid_js.createSignal)(0);
545
+ /** Consumed by the next effect run, so `refetch()` bypasses every layer once. */
546
+ let reloadOnce = false;
547
+ function releaseCurrent() {
548
+ lease?.release();
549
+ lease = null;
550
+ if (privateUrl) {
551
+ URL.revokeObjectURL(privateUrl);
552
+ privateUrl = null;
553
+ }
554
+ }
555
+ (0, solid_js.createEffect)(() => {
556
+ refetchSignal();
557
+ return path();
558
+ }, (filePath) => {
559
+ releaseCurrent();
560
+ if (!filePath) {
561
+ setUrl(null);
562
+ setIsLoading(false);
563
+ setError(null);
564
+ return;
565
+ }
566
+ const reload = reloadOnce;
567
+ reloadOnce = false;
568
+ let cancelled = false;
569
+ setIsLoading(true);
570
+ setError(null);
571
+ const bucket = db.bucket(bucketName);
572
+ (useCache ? bucket.url(filePath, {
573
+ persist: options.persist !== false,
574
+ pin: options.pin,
575
+ revalidate: options.revalidate,
576
+ reload
577
+ }).then((acquired) => {
578
+ if (!acquired) return null;
579
+ if (cancelled) {
580
+ acquired.release();
581
+ return null;
582
+ }
583
+ lease = acquired;
584
+ return acquired.url;
585
+ }) : bucket.read(filePath, {
586
+ persist: false,
587
+ reload: true
588
+ }).then((blob) => {
589
+ if (!blob || cancelled) return null;
590
+ privateUrl = URL.createObjectURL(blob);
591
+ return privateUrl;
592
+ })).then((result) => {
593
+ if (!cancelled) {
594
+ setUrl(result);
595
+ setIsLoading(false);
596
+ }
597
+ }, (err) => {
598
+ if (!cancelled) {
599
+ setError(err instanceof Error ? err : new Error(String(err)));
600
+ setIsLoading(false);
601
+ }
602
+ });
603
+ return () => {
604
+ cancelled = true;
605
+ };
606
+ });
607
+ (0, solid_js.onCleanup)(() => {
608
+ releaseCurrent();
609
+ });
610
+ const refetch = () => {
611
+ reloadOnce = true;
612
+ setRefetchSignal((n) => n + 1);
613
+ };
614
+ return {
615
+ url,
616
+ isLoading,
617
+ error,
618
+ refetch
619
+ };
620
+ }
621
+
622
+ //#endregion
623
+ //#region src/lib/Sp00kyProvider.ts
624
+ function Sp00kyProvider(props) {
625
+ const merged = (0, solid_js.merge)({ fallback: void 0 }, props);
626
+ const [db, setDb] = (0, solid_js.createSignal)(void 0, { ownedWrite: true });
627
+ let disposed = false;
628
+ (0, solid_js.onCleanup)(() => {
629
+ disposed = true;
630
+ });
631
+ (0, solid_js.onSettled)(() => {
632
+ (async () => {
633
+ try {
634
+ const instance = new SyncedDb(merged.config);
635
+ await instance.init();
636
+ if (disposed) {
637
+ await instance.close();
638
+ return;
639
+ }
640
+ if (merged.preload) try {
641
+ await merged.preload(instance);
642
+ } catch (e) {
643
+ console.error("Sp00kyProvider: preload failed; revealing UI anyway", e);
644
+ }
645
+ setDb(() => instance);
646
+ merged.onReady?.(instance);
647
+ } catch (e) {
648
+ const error = e instanceof Error ? e : new Error(String(e));
649
+ if (merged.onError) merged.onError(error);
650
+ else console.error("Sp00kyProvider: Failed to initialize database", error);
651
+ }
652
+ })();
653
+ });
654
+ return (0, solid_js.createMemo)(() => {
655
+ const instance = db();
656
+ if (!instance) return merged.fallback;
657
+ return (0, solid_js.createComponent)(Sp00kyContext, {
658
+ value: instance,
659
+ get children() {
660
+ return merged.children;
661
+ }
662
+ });
663
+ });
664
+ }
665
+
666
+ //#endregion
667
+ //#region src/lib/create-submission.ts
668
+ /**
669
+ * Thin submission-state wrapper for mutations — button spinner/disable state
670
+ * around `db.create/update/delete/run` calls.
671
+ *
672
+ * Deliberately NOT built on Solid 2's `action()`/`createOptimisticStore`: the
673
+ * spooky engine is already optimistic local-first (writes commit to the local
674
+ * DB and re-render through live queries before sync; `run()` is an outbox
675
+ * CREATE), so a transaction/revert layer on top buys nothing and `action()`'s
676
+ * await-vs-yield transaction escape is a real footgun. Errors here mean the
677
+ * LOCAL commit failed — sync/push failures surface through `useSyncStatus`
678
+ * and `usePendingMutations` instead.
679
+ */
680
+ function createSubmission(fn) {
681
+ const [inFlight, setInFlight] = (0, solid_js.createSignal)(0, { ownedWrite: true });
682
+ const [error, setError] = (0, solid_js.createSignal)(void 0, { ownedWrite: true });
683
+ const [result, setResult] = (0, solid_js.createSignal)(void 0, { ownedWrite: true });
684
+ const submit = async (...args) => {
685
+ setError(void 0);
686
+ setInFlight((n) => n + 1);
687
+ try {
688
+ const r = await fn(...args);
689
+ setResult(() => r);
690
+ return r;
691
+ } catch (e) {
692
+ setError(e instanceof Error ? e : new Error(String(e)));
693
+ return;
694
+ } finally {
695
+ setInFlight((n) => n - 1);
696
+ }
697
+ };
698
+ return {
699
+ submit,
700
+ pending: () => inFlight() > 0,
701
+ error,
702
+ result,
703
+ clearError: () => setError(void 0)
704
+ };
705
+ }
706
+
707
+ //#endregion
708
+ //#region src/index.ts
709
+ /**
710
+ * SyncedDb - A thin wrapper around sp00ky-ts for Solid.js integration.
711
+ * Delegates all logic to the underlying sp00ky-ts instance.
712
+ *
713
+ * NOTE: keep in sync with packages/client-solid/src/index.ts (SyncedDb).
714
+ * Copied rather than shared so this package's dependency graph never pulls
715
+ * in solid-js 1.x; fold the two together once client-solid moves to Solid 2.
716
+ */
717
+ var SyncedDb = class {
718
+ constructor(config) {
719
+ this.sp00ky = null;
720
+ this._initialized = false;
721
+ this.config = config;
722
+ }
723
+ getSp00ky() {
724
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
725
+ return this.sp00ky;
726
+ }
727
+ /**
728
+ * Initialize the sp00ky-ts instance
729
+ */
730
+ async init() {
731
+ if (this._initialized) return;
732
+ this.sp00ky = new _spooky_sync_core.Sp00kyClient(this.config);
733
+ await this.sp00ky.init();
734
+ this._initialized = true;
735
+ }
736
+ /**
737
+ * Tear down the client: leaves the tabs broker, closes the local store and
738
+ * remote socket, and frees the wasm circuit. Without this a remounted provider
739
+ * (or an HMR reload) strands a whole client, and the abandoned wasm heaps stay
740
+ * resident because V8 cannot see how much wasm memory a dropped wrapper holds.
741
+ */
742
+ async close() {
743
+ const instance = this.sp00ky;
744
+ this.sp00ky = null;
745
+ this._initialized = false;
746
+ if (instance) await instance.close();
747
+ }
748
+ /**
749
+ * Create a new record in the database
750
+ */
751
+ async create(id, payload) {
752
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
753
+ await this.sp00ky.create(id, payload);
754
+ }
755
+ /**
756
+ * Update an existing record in the database
757
+ */
758
+ async update(tableName, recordId, payload, options) {
759
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
760
+ await this.sp00ky.update(tableName, recordId, payload, options);
761
+ }
762
+ /**
763
+ * Delete an existing record in the database
764
+ */
765
+ async delete(tableName, selector) {
766
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
767
+ const ctorName = selector?.constructor?.name;
768
+ const isRecordId = selector instanceof surrealdb.RecordId || ctorName === "RecordId" || ctorName === "bound RecordId";
769
+ let id;
770
+ if (typeof selector === "string") id = selector;
771
+ else if (isRecordId) id = `${tableName}:${selector.id}`;
772
+ else throw new Error("Only string ID or RecordId selectors are supported currently with core");
773
+ await this.sp00ky.delete(tableName, id);
774
+ }
775
+ /**
776
+ * Preload/prewarm a built query into the local cache without registering a
777
+ * live view. Fetches once and stores the rows (+ embedded related children)
778
+ * locally so a later `createQuery` for the same data paints instantly. Best-effort.
779
+ */
780
+ async preload(finalQuery, options) {
781
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
782
+ await this.sp00ky.preload(finalQuery, options);
783
+ }
784
+ /**
785
+ * Query data from the database
786
+ */
787
+ query(table) {
788
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
789
+ return this.sp00ky.query(table, {});
790
+ }
791
+ /**
792
+ * Run a backend operation
793
+ */
794
+ async run(backend, path, payload, options) {
795
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
796
+ await this.sp00ky.run(backend, path, payload, options);
797
+ }
798
+ /**
799
+ * Sign out, clear session and local storage
800
+ */
801
+ async signOut() {
802
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
803
+ await this.sp00ky.auth.signOut();
804
+ }
805
+ /**
806
+ * Execute a function with direct access to the remote database connection
807
+ */
808
+ async useRemote(fn) {
809
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
810
+ return await this.sp00ky.useRemote(fn);
811
+ }
812
+ /**
813
+ * Access the remote database service directly
814
+ */
815
+ get remote() {
816
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
817
+ return this.sp00ky.remoteClient;
818
+ }
819
+ /**
820
+ * Access the local database service directly
821
+ */
822
+ get local() {
823
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
824
+ return this.sp00ky.localClient;
825
+ }
826
+ /**
827
+ * Access the auth service
828
+ */
829
+ get auth() {
830
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
831
+ return this.sp00ky.auth;
832
+ }
833
+ get pendingMutationCount() {
834
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
835
+ return this.sp00ky.pendingMutationCount;
836
+ }
837
+ /** Diagnostic — see `Sp00kyClient.liveRetryCount`. */
838
+ get liveRetryCount() {
839
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
840
+ return this.sp00ky.liveRetryCount;
841
+ }
842
+ subscribeToPendingMutations(cb) {
843
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
844
+ return this.sp00ky.subscribeToPendingMutations(cb);
845
+ }
846
+ /** Current sync-health snapshot. See {@link useSyncStatus}. */
847
+ get syncHealth() {
848
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
849
+ return this.sp00ky.syncHealth;
850
+ }
851
+ /**
852
+ * Observe sync health. Fires immediately with the current status and again
853
+ * on every healthy↔degraded transition. Prefer the `useSyncStatus` hook in
854
+ * components; this is the imperative escape hatch.
855
+ */
856
+ subscribeToSyncHealth(cb) {
857
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
858
+ return this.sp00ky.subscribeToSyncHealth(cb);
859
+ }
860
+ /** Current local-store durability snapshot. See {@link useStorageStatus}. */
861
+ get storageHealth() {
862
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
863
+ return this.sp00ky.storageHealth;
864
+ }
865
+ /**
866
+ * Observe local-store durability. Fires immediately with the current snapshot
867
+ * and again on change. Prefer the `useStorageStatus` hook in components; this
868
+ * is the imperative escape hatch.
869
+ */
870
+ subscribeToStorageHealth(cb) {
871
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
872
+ return this.sp00ky.subscribeToStorageHealth(cb);
873
+ }
874
+ bucket(name) {
875
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
876
+ return this.sp00ky.bucket(name);
877
+ }
878
+ getBucketConfig(name) {
879
+ return this.config.schema.buckets?.find((b) => b.name === name);
880
+ }
881
+ };
882
+
883
+ //#endregion
884
+ exports.RecordId = surrealdb.RecordId;
885
+ exports.Sp00kyProvider = Sp00kyProvider;
886
+ exports.SyncedDb = SyncedDb;
887
+ exports.Uuid = surrealdb.Uuid;
888
+ exports.conflate = conflate;
889
+ exports.createPreload = createPreload;
890
+ exports.createQuery = createQuery;
891
+ exports.createSubmission = createSubmission;
892
+ exports.fromSubscription = fromSubscription;
893
+ exports.useAppRelease = useAppRelease;
894
+ exports.useCrdtField = useCrdtField;
895
+ exports.useDb = useDb;
896
+ exports.useDownloadFile = useDownloadFile;
897
+ exports.useFeatureFlag = useFeatureFlag;
898
+ exports.useFileUpload = useFileUpload;
899
+ exports.usePendingMutations = usePendingMutations;
900
+ exports.useQuery = useQuery;
901
+ exports.useStorageStatus = useStorageStatus;
902
+ exports.useSyncStatus = useSyncStatus;
903
+ //# sourceMappingURL=index.cjs.map