@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,292 @@
1
+ import { fileToUint8Array, } from '@spooky-sync/core';
2
+ import { SyncedDb } from './db.js';
3
+ import { read, toError, useDb } from './context.js';
4
+ export function useFileUpload(dbOrBucketName, maybeBucketName) {
5
+ const db = dbOrBucketName instanceof SyncedDb ? dbOrBucketName : useDb();
6
+ const bucketName = (dbOrBucketName instanceof SyncedDb ? maybeBucketName : dbOrBucketName);
7
+ let isUploading = $state(false);
8
+ let error = $state.raw(null);
9
+ const objectUrls = [];
10
+ $effect(() => () => {
11
+ for (const url of objectUrls)
12
+ URL.revokeObjectURL(url);
13
+ });
14
+ const validate = (file) => {
15
+ const config = db.getBucketConfig(bucketName);
16
+ if (!config)
17
+ return;
18
+ if (config.maxSize !== null && config.maxSize !== undefined && file.size > config.maxSize) {
19
+ const maxMB = (config.maxSize / (1024 * 1024)).toFixed(1);
20
+ throw new Error(`File exceeds maximum size of ${maxMB} MB.`);
21
+ }
22
+ if (config.allowedExtensions && config.allowedExtensions.length > 0) {
23
+ const fileName = file.name;
24
+ if (fileName) {
25
+ const ext = fileName.split('.').pop()?.toLowerCase();
26
+ if (!ext || !config.allowedExtensions.includes(ext)) {
27
+ throw new Error(`File type not allowed. Accepted: ${config.allowedExtensions.join(', ')}.`);
28
+ }
29
+ }
30
+ }
31
+ };
32
+ return {
33
+ get isUploading() {
34
+ return isUploading;
35
+ },
36
+ get error() {
37
+ return error;
38
+ },
39
+ clearError: () => {
40
+ error = null;
41
+ },
42
+ upload: async (path, file, options) => {
43
+ error = null;
44
+ try {
45
+ validate(file);
46
+ }
47
+ catch (e) {
48
+ error = toError(e);
49
+ return;
50
+ }
51
+ isUploading = true;
52
+ try {
53
+ const bytes = await fileToUint8Array(file);
54
+ return await db.bucket(bucketName).put(path, bytes, options);
55
+ }
56
+ catch (e) {
57
+ error = toError(e);
58
+ }
59
+ finally {
60
+ isUploading = false;
61
+ }
62
+ },
63
+ download: async (path) => {
64
+ error = null;
65
+ try {
66
+ const content = await db.bucket(bucketName).get(path);
67
+ if (!content)
68
+ return null;
69
+ const objectUrl = URL.createObjectURL(new Blob([content]));
70
+ objectUrls.push(objectUrl);
71
+ return objectUrl;
72
+ }
73
+ catch (e) {
74
+ error = toError(e);
75
+ return null;
76
+ }
77
+ },
78
+ remove: async (path) => {
79
+ error = null;
80
+ try {
81
+ await db.bucket(bucketName).delete(path);
82
+ }
83
+ catch (e) {
84
+ error = toError(e);
85
+ }
86
+ },
87
+ exists: async (path) => {
88
+ error = null;
89
+ try {
90
+ return await db.bucket(bucketName).exists(path);
91
+ }
92
+ catch (e) {
93
+ error = toError(e);
94
+ return false;
95
+ }
96
+ },
97
+ };
98
+ }
99
+ export function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeOptions) {
100
+ const explicit = dbOrBucketName instanceof SyncedDb;
101
+ const db = explicit ? dbOrBucketName : useDb();
102
+ const bucketName = (explicit ? bucketNameOrPath : dbOrBucketName);
103
+ const path = (explicit ? pathOrOptions : bucketNameOrPath);
104
+ const options = ((explicit ? maybeOptions : pathOrOptions) ?? {});
105
+ const useCache = options.cache !== false;
106
+ let url = $state(null);
107
+ let isLoading = $state(false);
108
+ let error = $state.raw(null);
109
+ let refetchTick = $state(0);
110
+ /** Consumed by the next fetch, so `refetch()` bypasses every layer once. */
111
+ let reloadOnce = false;
112
+ // What backs the current `url`: a refcounted lease on the shared cache entry,
113
+ // or a private URL this instance minted and must revoke itself.
114
+ let held = null;
115
+ const release = () => {
116
+ held?.lease?.release();
117
+ if (held?.privateUrl)
118
+ URL.revokeObjectURL(held.privateUrl);
119
+ held = null;
120
+ };
121
+ $effect(() => release);
122
+ $effect(() => {
123
+ void refetchTick;
124
+ const filePath = read(path);
125
+ if (!filePath) {
126
+ release();
127
+ url = null;
128
+ isLoading = false;
129
+ error = null;
130
+ return;
131
+ }
132
+ const reload = reloadOnce;
133
+ reloadOnce = false;
134
+ let cancelled = false;
135
+ isLoading = true;
136
+ error = null;
137
+ const bucket = db.bucket(bucketName);
138
+ const next = useCache
139
+ ? bucket
140
+ .url(filePath, {
141
+ persist: options.persist !== false,
142
+ pin: options.pin,
143
+ revalidate: options.revalidate,
144
+ reload,
145
+ })
146
+ .then((lease) => (lease ? { lease, url: lease.url } : null))
147
+ : bucket.read(filePath, { persist: false, reload: true }).then((blob) => {
148
+ if (!blob)
149
+ return null;
150
+ const privateUrl = URL.createObjectURL(blob);
151
+ return { privateUrl, url: privateUrl };
152
+ });
153
+ next.then((result) => {
154
+ if (cancelled) {
155
+ // Destroyed, or the path changed mid-flight: hand the reference
156
+ // straight back, or the entry never drops to zero and its object URL
157
+ // leaks for the life of the tab.
158
+ result?.lease?.release();
159
+ if (result?.privateUrl)
160
+ URL.revokeObjectURL(result.privateUrl);
161
+ return;
162
+ }
163
+ release();
164
+ held = result;
165
+ url = result?.url ?? null;
166
+ isLoading = false;
167
+ }, (err) => {
168
+ if (cancelled)
169
+ return;
170
+ error = toError(err);
171
+ isLoading = false;
172
+ });
173
+ return () => {
174
+ cancelled = true;
175
+ };
176
+ });
177
+ return {
178
+ get url() {
179
+ return url;
180
+ },
181
+ get isLoading() {
182
+ return isLoading;
183
+ },
184
+ get error() {
185
+ return error;
186
+ },
187
+ refetch: () => {
188
+ reloadOnce = true;
189
+ refetchTick += 1;
190
+ },
191
+ };
192
+ }
193
+ export function useBlurhash(dbOrBucketName, bucketNameOrPath, maybePath) {
194
+ const explicit = dbOrBucketName instanceof SyncedDb;
195
+ const db = explicit ? dbOrBucketName : useDb();
196
+ const bucketName = (explicit ? bucketNameOrPath : dbOrBucketName);
197
+ const path = (explicit ? maybePath : bucketNameOrPath);
198
+ let hash = $state(null);
199
+ let isLoading = $state(false);
200
+ $effect(() => {
201
+ const filePath = read(path);
202
+ if (!filePath) {
203
+ hash = null;
204
+ isLoading = false;
205
+ return;
206
+ }
207
+ let cancelled = false;
208
+ isLoading = true;
209
+ db.bucket(bucketName)
210
+ .blurhash(filePath)
211
+ .then((result) => {
212
+ if (cancelled)
213
+ return;
214
+ hash = result;
215
+ isLoading = false;
216
+ }, () => {
217
+ if (cancelled)
218
+ return;
219
+ hash = null;
220
+ isLoading = false;
221
+ });
222
+ return () => {
223
+ cancelled = true;
224
+ };
225
+ });
226
+ return {
227
+ get hash() {
228
+ return hash;
229
+ },
230
+ get isLoading() {
231
+ return isLoading;
232
+ },
233
+ };
234
+ }
235
+ export function useBucketImage(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeOptions) {
236
+ const explicit = dbOrBucketName instanceof SyncedDb;
237
+ const db = explicit ? dbOrBucketName : useDb();
238
+ const bucketName = (explicit ? bucketNameOrPath : dbOrBucketName);
239
+ const path = (explicit ? pathOrOptions : bucketNameOrPath);
240
+ const options = ((explicit ? maybeOptions : pathOrOptions) ?? {});
241
+ // Declared BEFORE the download so the sidecar read enters the serialized
242
+ // remote queue first: the placeholder should never wait behind the bytes it
243
+ // stands in for.
244
+ const wantHash = options.blurhash !== false;
245
+ const sidecar = useBlurhash(db, bucketName, () => (wantHash ? read(path) : null));
246
+ const file = useDownloadFile(db, bucketName, path, options);
247
+ let ready = $state(false);
248
+ const gate = (img) => {
249
+ const src = file.url;
250
+ ready = false;
251
+ if (!src) {
252
+ img.removeAttribute('src');
253
+ return;
254
+ }
255
+ img.src = src;
256
+ let cancelled = false;
257
+ const reveal = () => {
258
+ if (!cancelled)
259
+ ready = true;
260
+ };
261
+ if (typeof img.decode === 'function')
262
+ img.decode().then(reveal, reveal);
263
+ else if (img.complete)
264
+ reveal();
265
+ else {
266
+ img.onload = reveal;
267
+ img.onerror = reveal;
268
+ }
269
+ return () => {
270
+ cancelled = true;
271
+ };
272
+ };
273
+ return {
274
+ get url() {
275
+ return file.url;
276
+ },
277
+ get isLoading() {
278
+ return file.isLoading;
279
+ },
280
+ get error() {
281
+ return file.error;
282
+ },
283
+ refetch: file.refetch,
284
+ get blurhash() {
285
+ return sidecar.hash;
286
+ },
287
+ get ready() {
288
+ return ready;
289
+ },
290
+ gate,
291
+ };
292
+ }
@@ -0,0 +1,37 @@
1
+ import type { GetTable, SchemaStructure, TableModel, TableNames, QueryResult, RelatedFieldsMap, RelationshipFieldsFromSchema, GetRelationship, RelatedFieldMapEntry, QueryModifier, QueryModifierBuilder, QueryInfo, RelationshipsMetadata, RelationshipDefinition, InferRelatedModelFromMetadata, GetCardinality } from '@spooky-sync/query-builder';
2
+ export { RecordId, Uuid } from 'surrealdb';
3
+ export { SyncedDb, plain } from './db.js';
4
+ export { default as Sp00kyProvider } from './Sp00kyProvider.svelte';
5
+ export { useDb, setDbContext } from './context.js';
6
+ export { useQuery, usePreload, share, sameValue, type QueryState, type QueryData, type QueryOptions, type PreloadOptions, } from './query.svelte.js';
7
+ export { usePendingMutations, useSyncStatus, useSyncActivity, useStorageStatus, useImpersonation, useFeatureFlag, useAppRelease, useSubmission, type ReactiveValue, type UseSyncStatus, type UseSyncActivity, type UseSyncActivityOptions, type UseStorageStatus, type UseImpersonation, type UseImpersonationOptions, type UseFeatureFlag, type UseAppRelease, type UseAppReleaseOptions, type Submission, } from './status.svelte.js';
8
+ export { useCrdtField, useChannel, type UseChannel, type ChannelPeers, type ChannelQueries, } from './realtime.svelte.js';
9
+ export { useFileUpload, useDownloadFile, useBlurhash, useBucketImage, type FileUploadResult, type UseDownloadFileOptions, type UseDownloadFileResult, type UseBlurhashResult, type UseBucketImageOptions, type UseBucketImageResult, } from './files.svelte.js';
10
+ export { default as Blurhash, type BlurhashProps } from './Blurhash.svelte';
11
+ export { default as BucketImage, type BucketImageProps } from './BucketImage.svelte';
12
+ export type { PreloadRefresh } from '@spooky-sync/core';
13
+ export type { SyncHealth, SyncHealthStatus, SyncHealthConfig, ConnectionState, ReconnectConfig, StorageHealth, StorageHealthStatus, ChannelState, ChannelStatus, ChannelOp, ChannelsConfig, Sp00kyChannel, } from '@spooky-sync/core';
14
+ export { WebPushError, type WebPushModule, type WebPushConfig, type WebPushSupport, type WebPushUnsupportedReason, type WebPushInfo, type WebPushDevice, type PushDeviceKind, type WebPushSubscribeOptions, type WebPushUnsubscribeOptions, type WebPushSyncOptions, type WebPushSyncStatus, type WebPushUpdateOptions, type WebPushMessageInput, type WebPushMessage, type WebPushErrorCode, type WebPushClientMessage, type PushPayload, type PushNotification, } from '@spooky-sync/core';
15
+ export type { QueryModifier, QueryModifierBuilder, QueryInfo, RelationshipsMetadata, RelationshipDefinition, InferRelatedModelFromMetadata, GetCardinality, GetTable, TableModel, TableNames, QueryResult, };
16
+ export type RelationshipField<Schema extends SchemaStructure, TableName extends TableNames<Schema>, Field extends RelationshipFieldsFromSchema<Schema, TableName>> = GetRelationship<Schema, TableName, Field>;
17
+ export type RelatedFieldsTableScoped<Schema extends SchemaStructure, TableName extends TableNames<Schema>, RelatedFields extends RelationshipFieldsFromSchema<Schema, TableName> = RelationshipFieldsFromSchema<Schema, TableName>> = {
18
+ [K in RelatedFields]: {
19
+ to: RelationshipField<Schema, TableName, K>['to'];
20
+ relatedFields: RelatedFieldsMap;
21
+ cardinality: RelationshipField<Schema, TableName, K>['cardinality'];
22
+ };
23
+ };
24
+ export type InferModel<Schema extends SchemaStructure, TableName extends TableNames<Schema>, RelatedFields extends RelatedFieldsTableScoped<Schema, TableName>> = QueryResult<Schema, TableName, RelatedFields, true>;
25
+ export type WithRelated<Field extends string, RelatedFields extends RelatedFieldsMap = {}> = {
26
+ [K in Field]: Omit<RelatedFieldMapEntry, 'relatedFields'> & {
27
+ relatedFields: RelatedFields;
28
+ };
29
+ };
30
+ export type WithRelatedMany<Field extends string, RelatedFields extends RelatedFieldsMap = {}> = {
31
+ [K in Field]: {
32
+ to: Field;
33
+ relatedFields: RelatedFields;
34
+ cardinality: 'many';
35
+ };
36
+ };
37
+ export * from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ export { RecordId, Uuid } from 'surrealdb';
2
+ export { SyncedDb, plain } from './db.js';
3
+ export { default as Sp00kyProvider } from './Sp00kyProvider.svelte';
4
+ export { useDb, setDbContext } from './context.js';
5
+ export { useQuery, usePreload, share, sameValue, } from './query.svelte.js';
6
+ export { usePendingMutations, useSyncStatus, useSyncActivity, useStorageStatus, useImpersonation, useFeatureFlag, useAppRelease, useSubmission, } from './status.svelte.js';
7
+ export { useCrdtField, useChannel, } from './realtime.svelte.js';
8
+ export { useFileUpload, useDownloadFile, useBlurhash, useBucketImage, } from './files.svelte.js';
9
+ export { default as Blurhash } from './Blurhash.svelte';
10
+ export { default as BucketImage } from './BucketImage.svelte';
11
+ export { WebPushError, } from '@spooky-sync/core';
12
+ export * from './types.js';
@@ -0,0 +1,130 @@
1
+ import type { ColumnSchema, FinalQuery, QueryResult, SchemaStructure, TableNames } from '@spooky-sync/query-builder';
2
+ import type { PreloadOptions as CorePreloadOptions, Sp00kyQueryResultPromise } from '@spooky-sync/core';
3
+ import { SyncedDb } from './db.js';
4
+ import type { MaybeGetter } from './types.js';
5
+ /**
6
+ * Value equality for the leaves `share` does not descend into. The decoder
7
+ * hands out a fresh RecordId / Date / Uuid / Duration for every record-link
8
+ * and datetime column on every emission, so by identity every such field
9
+ * "changed" every time. Two instances of the same class that print alike are
10
+ * the same value. A class whose `toString` is the default `[object X]`
11
+ * (ArrayBuffer, Map, ...) cannot be compared that way and counts as changed.
12
+ */
13
+ export declare function sameValue(a: unknown, b: unknown): boolean;
14
+ /**
15
+ * Structural sharing between two emissions: returns `prev` itself where
16
+ * `next` is deep-equal to it, and a new value that reuses every unchanged
17
+ * subtree otherwise. Array items with an `id` are matched by id, so a row keeps
18
+ * its object identity across reorders, inserts and deletes.
19
+ *
20
+ * That is what makes `$state.raw` fine-grained enough here: a keyed `{#each}`
21
+ * hands an unchanged row the same object, so its block does not update, and a
22
+ * deep-equal emission is the same value, so nothing reading `data` re-runs.
23
+ *
24
+ * Never mutates either argument: the engine may hand the same row objects to
25
+ * several subscribers.
26
+ */
27
+ export declare function share<T>(prev: unknown, next: T): T;
28
+ type AnyFinalQuery = FinalQuery<any, any, any, any, any, Sp00kyQueryResultPromise>;
29
+ type BuiltQuery<S extends SchemaStructure, TableName extends TableNames<S>, T extends {
30
+ columns: Record<string, ColumnSchema>;
31
+ }, RelatedFields extends Record<string, any>, IsOne extends boolean> = FinalQuery<S, TableName, T, RelatedFields, IsOne, Sp00kyQueryResultPromise>;
32
+ type QueryArg<S extends SchemaStructure, TableName extends TableNames<S>, T extends {
33
+ columns: Record<string, ColumnSchema>;
34
+ }, RelatedFields extends Record<string, any>, IsOne extends boolean> = MaybeGetter<BuiltQuery<S, TableName, T, RelatedFields, IsOne> | null | undefined>;
35
+ export interface QueryOptions {
36
+ /** Only register while true (default `true`). `false` keeps the last data. */
37
+ enabled?: MaybeGetter<boolean>;
38
+ /**
39
+ * Tear down the query (remote `_00_query` view + local WASM view) when this
40
+ * component is destroyed and no other subscriber remains, instead of keeping
41
+ * it resident for cheap re-subscription. Use for viewport-windowed lists that
42
+ * mount and unmount a query per scroll window. Trade-off: scrolling back to
43
+ * a torn-down window re-registers it.
44
+ */
45
+ deregisterOnCleanup?: boolean;
46
+ }
47
+ /**
48
+ * A live query. Every field is a reactive getter: read it as `posts.data`,
49
+ * `posts.isLoading` in markup, `$derived` or `$effect`. Do not destructure it,
50
+ * a destructured field is a one-time copy.
51
+ */
52
+ export interface QueryState<TData> {
53
+ /**
54
+ * The result. `[]` / `null` before the first emission, then each live
55
+ * emission with structural sharing: unchanged rows keep their object
56
+ * identity, so a keyed `{#each}` only updates the rows that changed.
57
+ */
58
+ readonly data: TData;
59
+ /** Registration or sync error (e.g. SSP 503 during bootstrap). Never thrown. */
60
+ readonly error: Error | undefined;
61
+ /**
62
+ * True only on a COLD first load: nothing painted for this identity, the
63
+ * server has not answered, and registration has not failed. A paint from the
64
+ * local cache ends it, and so does the server answering with zero rows.
65
+ */
66
+ readonly isLoading: boolean;
67
+ /** A fetch cycle is in flight (registration, a sync round). */
68
+ readonly isFetching: boolean;
69
+ /**
70
+ * `data` holds the rendered rows of a known membership for this identity:
71
+ * the server's answer, or the membership an earlier session left on this
72
+ * device. From here `data` is an answer, not a cache guess.
73
+ */
74
+ readonly isAuthoritative: boolean;
75
+ /** `data` holds something: rows for a list, a row for `.one()`. */
76
+ readonly hasData: boolean;
77
+ /** Authoritative AND no data: the server said "no rows". Render empty states on this. */
78
+ readonly isEmpty: boolean;
79
+ /**
80
+ * Authoritative AND idle. The gate for trusting a short window as the end of
81
+ * a list, and for "create it if it is missing". Not monotonic: a later sync
82
+ * round re-enters `isFetching`.
83
+ */
84
+ readonly isSettled: boolean;
85
+ }
86
+ /**
87
+ * What `data` holds: a list is never null (`[]` until the first emission), a
88
+ * `.one()` row is `null` until it exists.
89
+ */
90
+ export type QueryData<S extends SchemaStructure, TableName extends TableNames<S>, RelatedFields extends Record<string, any>, IsOne extends boolean> = IsOne extends true ? QueryResult<S, TableName, RelatedFields, true> | null : QueryResult<S, TableName, RelatedFields, false>;
91
+ /**
92
+ * Live query. Pass a getter that builds the query, so it follows the state it
93
+ * reads (`() => db.query('post').where({ author: userId }).build()`); return
94
+ * `null` / `undefined` to skip. The query is re-registered only when its
95
+ * identity hash (surql + vars) changes, not on every rebuild.
96
+ *
97
+ * Call it while a component initialises (it reads context and owns effects
98
+ * that end with the component), or pass the client first:
99
+ * `useQuery(db, () => ..., options)`.
100
+ *
101
+ * ```svelte
102
+ * <script lang="ts">
103
+ * const db = useDb<typeof schema>();
104
+ * const posts = useQuery(() => db.query('post').orderBy('created_at', 'desc').limit(20).build());
105
+ * </script>
106
+ *
107
+ * {#each posts.data as post (String(post.id))}<p>{post.title}</p>{/each}
108
+ * ```
109
+ */
110
+ export declare function useQuery<S extends SchemaStructure, TableName extends TableNames<S>, T extends {
111
+ columns: Record<string, ColumnSchema>;
112
+ }, RelatedFields extends Record<string, any>, IsOne extends boolean, TData = QueryData<S, TableName, RelatedFields, IsOne>>(query: QueryArg<S, TableName, T, RelatedFields, IsOne>, options?: QueryOptions): QueryState<TData>;
113
+ export declare function useQuery<S extends SchemaStructure, TableName extends TableNames<S>, T extends {
114
+ columns: Record<string, ColumnSchema>;
115
+ }, RelatedFields extends Record<string, any>, IsOne extends boolean, TData = QueryData<S, TableName, RelatedFields, IsOne>>(db: SyncedDb<S>, query: QueryArg<S, TableName, T, RelatedFields, IsOne>, options?: QueryOptions): QueryState<TData>;
116
+ export interface PreloadOptions extends CorePreloadOptions {
117
+ /** Only preload while true (default `true`). */
118
+ enabled?: MaybeGetter<boolean>;
119
+ }
120
+ /**
121
+ * Fire-and-forget prewarm: registers the query via `db.preload` (a live query
122
+ * nobody subscribes to, evicted a ttl after registration unless a view mounts
123
+ * it first) whenever its identity changes. Nothing to clean up.
124
+ *
125
+ * Typical use: inside a list row, preload the detail query the user is likely
126
+ * to open next, so navigation paints from cache instead of the network.
127
+ */
128
+ export declare function usePreload(query: MaybeGetter<AnyFinalQuery | null | undefined>, options?: PreloadOptions): void;
129
+ export declare function usePreload(db: SyncedDb<any>, query: MaybeGetter<AnyFinalQuery | null | undefined>, options?: PreloadOptions): void;
130
+ export {};