@spooky-sync/client-svelte 0.0.0-stage → 0.0.1-canary.383

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.
@@ -0,0 +1,314 @@
1
+ import { createSubscriber } from 'svelte/reactivity';
2
+ import { semverGt, } from '@spooky-sync/core';
3
+ import { toError, useDb } from './context.js';
4
+ /**
5
+ * Make an engine value reactive without copying it into `$state`: reading the
6
+ * returned function inside an effect, `$derived` or markup subscribes to the
7
+ * engine (once, however many readers), and the subscription ends when the last
8
+ * reader goes away. Outside a reactive scope it costs nothing, and the caller
9
+ * reads the engine's own current value (`db.syncHealth`, ...), so nothing can
10
+ * go stale. This is Svelte's `createSubscriber`, the primitive behind
11
+ * `MediaQuery` and `fromStore`.
12
+ *
13
+ * The engine's subscribe APIs call back immediately with the current value;
14
+ * that first call is dropped, the reader is about to read it anyway.
15
+ */
16
+ function engineSubscriber(subscribe) {
17
+ return createSubscriber((update) => {
18
+ let starting = true;
19
+ const off = subscribe(() => {
20
+ if (!starting)
21
+ update();
22
+ });
23
+ starting = false;
24
+ return off;
25
+ });
26
+ }
27
+ const isDb = (v) => typeof v === 'object' && v !== null && typeof v.getSp00ky === 'function';
28
+ /**
29
+ * Count of locally committed mutations not acknowledged by the server yet.
30
+ * Drive an "unsaved changes" indicator off `.current`.
31
+ */
32
+ export function usePendingMutations(db = useDb()) {
33
+ const subscribe = engineSubscriber((cb) => db.subscribeToPendingMutations(() => cb()));
34
+ return {
35
+ get current() {
36
+ subscribe();
37
+ return db.pendingMutationCount;
38
+ },
39
+ };
40
+ }
41
+ /**
42
+ * Observe sync health for a "can't reach the server" banner / indicator.
43
+ * Individual sync failures are absorbed by the retry; `isDegraded` only turns
44
+ * on once failures persist (core `syncHealth.degradeAfterConsecutiveFailures`,
45
+ * default 3) and turns off on the next successful round.
46
+ *
47
+ * Needs no component: with the client passed explicitly it also works in a
48
+ * shared `.svelte.ts` module.
49
+ */
50
+ export function useSyncStatus(db = useDb()) {
51
+ const subscribe = engineSubscriber((cb) => db.subscribeToSyncHealth(() => cb()));
52
+ const health = () => {
53
+ subscribe();
54
+ return db.syncHealth;
55
+ };
56
+ return {
57
+ get health() {
58
+ return health();
59
+ },
60
+ get status() {
61
+ return health().status;
62
+ },
63
+ get isHealthy() {
64
+ return health().status === 'healthy';
65
+ },
66
+ get isDegraded() {
67
+ return health().status === 'degraded';
68
+ },
69
+ get everConnected() {
70
+ return health().everConnected;
71
+ },
72
+ get isOffline() {
73
+ const h = health();
74
+ return h.status === 'degraded' && h.everConnected;
75
+ },
76
+ get connection() {
77
+ return health().connection;
78
+ },
79
+ get isReconnecting() {
80
+ return health().connection === 'reconnecting';
81
+ },
82
+ };
83
+ }
84
+ /**
85
+ * Observe how durable the LOCAL cache is, for a "no local storage" warning.
86
+ * Under `localEngine: 'sqlite'` + `store: 'indexeddb'` only one client per
87
+ * bucket can hold the OPFS store open; a second tab runs in memory.
88
+ */
89
+ export function useStorageStatus(db = useDb()) {
90
+ const subscribe = engineSubscriber((cb) => db.subscribeToStorageHealth(() => cb()));
91
+ const health = () => {
92
+ subscribe();
93
+ return db.storageHealth;
94
+ };
95
+ return {
96
+ get health() {
97
+ return health();
98
+ },
99
+ get status() {
100
+ return health().status;
101
+ },
102
+ get isPersistent() {
103
+ return health().status === 'persistent';
104
+ },
105
+ get isMemoryFallback() {
106
+ return health().fallback;
107
+ },
108
+ };
109
+ }
110
+ export function useSyncActivity(dbOrOptions, maybeOptions) {
111
+ const db = isDb(dbOrOptions) ? dbOrOptions : useDb();
112
+ const options = (isDb(dbOrOptions) ? maybeOptions : dbOrOptions) ?? {};
113
+ const fetchingSub = engineSubscriber((cb) => db.subscribeToFetchActivity(() => cb()));
114
+ const pendingSub = engineSubscriber((cb) => db.subscribeToPendingMutations(() => cb()));
115
+ const fetchingQueries = () => {
116
+ fetchingSub();
117
+ return db.fetchingQueryCount;
118
+ };
119
+ const pendingMutations = () => {
120
+ pendingSub();
121
+ return db.pendingMutationCount;
122
+ };
123
+ const isDownloading = delayedOn(() => fetchingQueries() > 0, options.downloadDelayMs ?? 200);
124
+ const isUploading = delayedOn(() => pendingMutations() > (options.uploadThreshold ?? 0), options.uploadDelayMs ?? 150);
125
+ return {
126
+ get fetchingQueries() {
127
+ return fetchingQueries();
128
+ },
129
+ get pendingMutations() {
130
+ return pendingMutations();
131
+ },
132
+ get isDownloading() {
133
+ return isDownloading();
134
+ },
135
+ get isUploading() {
136
+ return isUploading();
137
+ },
138
+ };
139
+ }
140
+ /**
141
+ * `busy` held for `delayMs`, dropped the instant it clears. A burst too short
142
+ * to see never flickers, and neither direction can latch on after the work is
143
+ * done.
144
+ */
145
+ function delayedOn(busy, delayMs) {
146
+ let on = $state(false);
147
+ // A boolean, so a count moving 1 -> 2 does not restart the timer.
148
+ const isBusy = $derived(busy());
149
+ $effect(() => {
150
+ if (!isBusy) {
151
+ on = false;
152
+ return;
153
+ }
154
+ if (delayMs <= 0) {
155
+ on = true;
156
+ return;
157
+ }
158
+ const timer = setTimeout(() => {
159
+ on = true;
160
+ }, delayMs);
161
+ return () => clearTimeout(timer);
162
+ });
163
+ return () => on;
164
+ }
165
+ /**
166
+ * Observe admin impersonation (started from the DevTools). The client already
167
+ * shows its own warning bar with a Stop button; use this for anything extra,
168
+ * such as hiding actions an admin should not take on someone's behalf.
169
+ */
170
+ export function useImpersonation(options = {}, db = useDb()) {
171
+ const subscribe = engineSubscriber((cb) => db.auth.subscribeImpersonation(() => cb()));
172
+ const impersonation = () => {
173
+ subscribe();
174
+ return db.auth.impersonation;
175
+ };
176
+ if (options.rendersBanner) {
177
+ // Re-acknowledged per session: a new impersonation restarts the client's
178
+ // fallback timer, and this component is what cancels it.
179
+ $effect(() => {
180
+ if (impersonation())
181
+ db.acknowledgeImpersonationBanner();
182
+ });
183
+ }
184
+ return {
185
+ get impersonation() {
186
+ return impersonation();
187
+ },
188
+ get isImpersonating() {
189
+ return impersonation() !== null;
190
+ },
191
+ stop: () => db.auth.stopImpersonating(),
192
+ };
193
+ }
194
+ /**
195
+ * A feature flag for the signed-in user. Updates whenever the
196
+ * server-materialized assignment in `_00_user_feature` changes, so
197
+ * `spky flag enable <key>` reaches the UI without a refresh. The handle closes
198
+ * with the component.
199
+ */
200
+ export function useFeatureFlag(key, options, db = useDb()) {
201
+ const handle = db.getSp00ky().feature(key, options);
202
+ $effect(() => () => handle.close());
203
+ const subscribe = engineSubscriber((cb) => handle.subscribe(() => cb()));
204
+ return {
205
+ get variant() {
206
+ subscribe();
207
+ return handle.variant();
208
+ },
209
+ get payload() {
210
+ subscribe();
211
+ return handle.payload();
212
+ },
213
+ get enabled() {
214
+ subscribe();
215
+ return handle.enabled();
216
+ },
217
+ };
218
+ }
219
+ async function reloadForSnapshot(snapshot) {
220
+ if (typeof window === 'undefined')
221
+ return;
222
+ if (snapshot.cacheBust) {
223
+ try {
224
+ if (window.caches) {
225
+ const keys = await window.caches.keys();
226
+ await Promise.all(keys.map((k) => window.caches.delete(k)));
227
+ }
228
+ if (navigator.serviceWorker) {
229
+ const regs = await navigator.serviceWorker.getRegistrations();
230
+ for (const r of regs)
231
+ r.update().catch(() => { });
232
+ }
233
+ window.location.href = window.location.pathname + '?cb=' + Date.now();
234
+ return;
235
+ }
236
+ catch {
237
+ /* fall through to a plain reload */
238
+ }
239
+ }
240
+ window.location.reload();
241
+ }
242
+ /**
243
+ * Observe the app's announced release (`_00_app_release:<app>`, written by
244
+ * `spky deploy` / `spky release`) and compare it with the running build, for a
245
+ * "new version available, Reload" notice. Guard an automatic `reload()` on
246
+ * `mandatory` against loops with a per-version marker.
247
+ */
248
+ export function useAppRelease(options, db = useDb()) {
249
+ const handle = db.getSp00ky().appRelease(options.app, { ttl: options.ttl });
250
+ $effect(() => () => handle.close());
251
+ const subscribe = engineSubscriber((cb) => handle.subscribe(() => cb()));
252
+ const snapshot = () => {
253
+ subscribe();
254
+ return handle.snapshot();
255
+ };
256
+ const updateAvailable = () => semverGt(snapshot().version, options.currentVersion);
257
+ return {
258
+ get latestVersion() {
259
+ return snapshot().version;
260
+ },
261
+ get updateAvailable() {
262
+ return updateAvailable();
263
+ },
264
+ get mandatory() {
265
+ return updateAvailable() && snapshot().mandatory;
266
+ },
267
+ get cacheBust() {
268
+ return snapshot().cacheBust;
269
+ },
270
+ reload: () => reloadForSnapshot(handle.snapshot()),
271
+ };
272
+ }
273
+ /**
274
+ * Button pending / error state around a mutation. Deliberately no optimistic
275
+ * layer: the engine already commits writes locally and re-renders through live
276
+ * queries before it syncs. An `error` here means the LOCAL commit failed; sync
277
+ * failures surface through `useSyncStatus` and `usePendingMutations`. Needs no
278
+ * component and no provider.
279
+ */
280
+ export function useSubmission(fn) {
281
+ let inFlight = $state(0);
282
+ let error = $state.raw(undefined);
283
+ let result = $state.raw(undefined);
284
+ return {
285
+ submit: async (...args) => {
286
+ error = undefined;
287
+ inFlight += 1;
288
+ try {
289
+ const r = await fn(...args);
290
+ result = r;
291
+ return r;
292
+ }
293
+ catch (e) {
294
+ error = toError(e);
295
+ return undefined;
296
+ }
297
+ finally {
298
+ inFlight -= 1;
299
+ }
300
+ },
301
+ get pending() {
302
+ return inFlight > 0;
303
+ },
304
+ get error() {
305
+ return error;
306
+ },
307
+ get result() {
308
+ return result;
309
+ },
310
+ clearError: () => {
311
+ error = undefined;
312
+ },
313
+ };
314
+ }
@@ -0,0 +1,62 @@
1
+ import type { Snippet } from 'svelte';
2
+ import type { RecordId } from 'surrealdb';
3
+ import type { Sp00kyConfig } from '@spooky-sync/core';
4
+ import type { GenericSchema, GetTable, SchemaStructure, TableModel, TableNames } from '@spooky-sync/query-builder';
5
+ import type { SyncedDb } from './db.js';
6
+ export type { GenericModel, GenericSchema } from '@spooky-sync/query-builder';
7
+ export type Model<T> = T;
8
+ export type ModelPayload<T> = T & {
9
+ id: RecordId;
10
+ };
11
+ /**
12
+ * A value, or a getter that returns it. Svelte only tracks state that is read
13
+ * inside a reactive scope, so an input that should follow `$state` / `$props`
14
+ * is passed as a getter (`() => id`); a plain value is read once.
15
+ */
16
+ export type MaybeGetter<T> = T | (() => T);
17
+ /** Options for database provisioning. */
18
+ export interface ProvisionOptions {
19
+ /** Force re-provision even if schema already exists */
20
+ force?: boolean;
21
+ }
22
+ export type CacheStrategy = 'memory' | 'indexeddb';
23
+ /** Infer Schema type (Record<TableName, Model>) from the schema const. */
24
+ export type InferSchemaFromConst<S extends SchemaStructure> = {
25
+ [K in TableNames<S>]: TableModel<GetTable<S, K>>;
26
+ };
27
+ /**
28
+ * Infer Relationships type from the schema const's relationships array,
29
+ * converted from array format to nested object format.
30
+ */
31
+ export type InferRelationshipsFromConst<S extends SchemaStructure, Schema extends GenericSchema> = {
32
+ [TableName in TableNames<S>]: {
33
+ [Rel in Extract<S['relationships'][number], {
34
+ from: TableName;
35
+ }> as Rel['field']]: {
36
+ model: Rel['to'] extends keyof Schema ? Schema[Rel['to']] : any;
37
+ table: Rel['to'];
38
+ cardinality: Rel['cardinality'];
39
+ };
40
+ };
41
+ };
42
+ type Prettify<T> = {
43
+ [K in keyof T]: T[K];
44
+ } & {};
45
+ export type SyncedDbConfig<S extends SchemaStructure> = Prettify<Sp00kyConfig<S>>;
46
+ export interface Sp00kyProviderProps<S extends SchemaStructure> {
47
+ /** Client config. Read once when the provider mounts; wrap it in `{#key}` to switch databases. */
48
+ config: SyncedDbConfig<S>;
49
+ /** Rendered until the client is ready (and on the server). */
50
+ fallback?: Snippet;
51
+ /** Init failed. Without it the error is logged. */
52
+ onError?: (error: Error) => void;
53
+ /** The client is ready, right before the children render. */
54
+ onReady?: (db: SyncedDb<S>) => void;
55
+ /**
56
+ * Prewarm data into the local cache before revealing the UI. Runs after
57
+ * `init()`; the `fallback` stays up until it resolves. Best-effort: a
58
+ * rejection is logged and the UI is revealed anyway.
59
+ */
60
+ preload?: (db: SyncedDb<S>) => Promise<void>;
61
+ children: Snippet;
62
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "@spooky-sync/client-svelte",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1-canary.383",
4
+ "type": "module",
5
+ "sideEffects": false,
6
+ "description": "Svelte 5 (runes) bindings for the sp00ky local-first sync client",
7
+ "svelte": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "svelte": "./dist/index.js",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "skills",
19
+ "AGENTS.md",
20
+ "QUICK_START.md",
21
+ "README.md"
22
+ ],
23
+ "scripts": {
24
+ "build": "svelte-package -i src -o dist",
25
+ "build:watch": "svelte-package -i src -o dist --watch",
26
+ "dev": "svelte-package -i src -o dist --watch",
27
+ "test": "vitest run",
28
+ "type-check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings"
29
+ },
30
+ "keywords": [
31
+ "surrealdb",
32
+ "database",
33
+ "browser",
34
+ "offline",
35
+ "sync",
36
+ "svelte",
37
+ "svelte-5",
38
+ "runes",
39
+ "local-first",
40
+ "tanstack-intent"
41
+ ],
42
+ "author": "",
43
+ "license": "MIT",
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "https://github.com/mono424/sp00ky.git",
47
+ "directory": "packages/client-svelte"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "packageManager": "pnpm@9.0.0",
53
+ "dependencies": {
54
+ "@spooky-sync/core": "0.0.1-canary.383",
55
+ "@spooky-sync/query-builder": "0.0.1-canary.383",
56
+ "@surrealdb/wasm": "^3.1.0",
57
+ "surrealdb": "2.1.0"
58
+ },
59
+ "peerDependencies": {
60
+ "svelte": "^5.29.0"
61
+ },
62
+ "devDependencies": {
63
+ "@sveltejs/package": "^2.5.0",
64
+ "@sveltejs/vite-plugin-svelte": "^4.0.4",
65
+ "@types/node": "^22.5.2",
66
+ "happy-dom": "^21.0.4",
67
+ "svelte": "^5.43.0",
68
+ "svelte-check": "^4.3.0",
69
+ "typescript": "^5.6.2",
70
+ "vitest": "^3.2.0"
71
+ }
72
+ }
@@ -0,0 +1,84 @@
1
+ ---
2
+ name: sp00ky-svelte
3
+ description: >-
4
+ Svelte 5 (runes) integration for the Sp00ky reactive local-first SurrealDB
5
+ framework. Use when a Svelte 5 or SvelteKit app uses sp00ky: setting up
6
+ Sp00kyProvider, useQuery with getter inputs for live data, mutations via
7
+ plain db calls or useSubmission, status hooks (sync, storage, feature flags,
8
+ app release), CRDT fields, peer to peer channels, file upload/download and
9
+ BucketImage. Not for Svelte 4; for React apps use the sp00ky-react skill, for
10
+ Solid apps sp00ky-solid or sp00ky-solid2.
11
+ metadata:
12
+ author: sp00ky-sync
13
+ version: '0.0.1'
14
+ ---
15
+
16
+ # Sp00ky Svelte Client
17
+
18
+ `@spooky-sync/client-svelte` targets Svelte 5.29+ in the browser. Hooks return objects whose fields are reactive getters; inputs that follow state are getters. `useQuery` rows are structurally shared between live emissions: rows matched by `id` keep their object identity, a deep-equal emission changes nothing.
19
+
20
+ ## Setup
21
+
22
+ ```svelte
23
+ <!-- src/routes/+layout.svelte -->
24
+ <script lang="ts">
25
+ import { Sp00kyProvider } from '@spooky-sync/client-svelte';
26
+ let { children } = $props();
27
+ </script>
28
+
29
+ <Sp00kyProvider config={{ database: {...}, schema, schemaSurql }}>
30
+ {#snippet fallback()}<Splash />{/snippet}
31
+ {@render children()}
32
+ </Sp00kyProvider>
33
+ ```
34
+
35
+ `config` is read once at mount. SvelteKit: `export const ssr = false` in the root `+layout.ts` (the core is browser-only). Vite needs `vite-plugin-wasm`, `vite-plugin-top-level-await`, `build.target: 'esnext'` and `optimizeDeps.exclude: ['@surrealdb/wasm', '@surrealdb/wasm-native', '@sqlite.org/sqlite-wasm']`.
36
+
37
+ ## Queries
38
+
39
+ ```svelte
40
+ <script lang="ts">
41
+ const db = useDb<typeof schema>();
42
+ const posts = useQuery(() => db.query('post').orderBy('created_at', 'desc').limit(20).build());
43
+ </script>
44
+
45
+ {#if posts.isLoading}<Spinner />
46
+ {:else if posts.isEmpty}<Empty />
47
+ {:else}
48
+ {#each posts.data as p (String(p.id))}<PostRow post={p} />{/each}
49
+ {/if}
50
+ ```
51
+
52
+ - Pass a getter; it is re-read when the state it reads changes, and the query re-registers only when its identity (surql + vars) changes.
53
+ - Return `null` to skip: `useQuery(() => (id ? db.query('post').where({ id }).one().build() : null))`.
54
+ - Result getters: `data`, `error`, `isLoading` (cold first load only), `isFetching`, `isAuthoritative`, `hasData`, `isEmpty` (server said "no rows"), `isSettled` (authoritative and idle).
55
+ - Never destructure a result; read `posts.data` where it is used.
56
+ - Options: `{ enabled?: boolean | (() => boolean), deregisterOnCleanup?: boolean }`.
57
+ - `usePreload(() => query)` warms the cache for a likely-next screen.
58
+
59
+ ## Mutations
60
+
61
+ Plain awaited calls; the engine is optimistic local-first. `$state` payloads are fine (copied before the workers):
62
+
63
+ ```ts
64
+ await db.create('post:' + crypto.randomUUID(), { title });
65
+ await db.update('post', id, { title });
66
+ await db.delete('post', row.id);
67
+ await db.run('backend', 'route', payload);
68
+ ```
69
+
70
+ Button state: `const save = useSubmission(fn)` gives `submit`, `pending`, `error`, `result`, `clearError`.
71
+
72
+ ## Hooks
73
+
74
+ `useDb`, `usePendingMutations().current`, `useSyncStatus`, `useSyncActivity`, `useStorageStatus`, `useImpersonation`, `useFeatureFlag`, `useAppRelease`, `useCrdtField(table, () => id, field).current`, `useChannel(() => query, () => peers)`, `useFileUpload(bucket)`, `useDownloadFile(bucket, () => path)`, `useBlurhash`, `useBucketImage` (with the `{@attach image.gate}` attachment), plus `<BucketImage>` (`class`, `imgClass`, `fallback` snippet) and `<Blurhash>`. `setDbContext(db)` provides a self-created client instead of the provider.
75
+
76
+ ## Gotchas
77
+
78
+ - Hooks run during component init (top of `<script>`), not in handlers or after `await`.
79
+ - No suspense mode; branch on `isLoading`.
80
+ - Svelte 4 is not supported.
81
+ - Row ids are `RecordId`; key with `String(row.id)`.
82
+ - Every hook needs `<Sp00kyProvider>` (or `setDbContext`) above it, except the `(db, ...)` forms.
83
+
84
+ Full API: `node_modules/@spooky-sync/client-svelte/AGENTS.md`.