@spooky-sync/core 1.0.0-beta.1 → 1.0.0-beta.11
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/AGENTS.md +4 -3
- package/dist/index.d.ts +170 -9
- package/dist/index.js +5398 -2968
- package/dist/rows-worker.d.ts +1 -0
- package/dist/rows-worker.js +2731 -0
- package/dist/sqlite-open.js +1 -1
- package/dist/sqlite-worker.js +1 -1
- package/dist/types.d.ts +131 -13
- package/package.json +9 -4
- package/scripts/check-worker-entries.mjs +15 -2
- package/skills/sp00ky-core/SKILL.md +2 -0
- package/src/client/bucket-handle.ts +21 -1
- package/src/client/eager-paint.test.ts +82 -0
- package/src/client/services.ts +4 -1
- package/src/client/sp00ky-client.test.ts +143 -1
- package/src/client/sp00ky-client.ts +158 -19
- package/src/index.ts +9 -0
- package/src/kernel/effects.ts +12 -2
- package/src/kernel/interpreter.test.ts +17 -0
- package/src/kernel/interpreter.ts +5 -2
- package/src/modules/channel/hub.test.ts +223 -0
- package/src/modules/channel/hub.ts +355 -0
- package/src/modules/channel/index.ts +358 -14
- package/src/modules/channel/room.test.ts +340 -0
- package/src/modules/channel/room.ts +367 -0
- package/src/modules/channel/rooms.fixture.ts +383 -0
- package/src/modules/channel/share.test.ts +535 -0
- package/src/modules/channel/webrtc.ts +2 -2
- package/src/modules/devtools/storage-info.ts +4 -3
- package/src/query/materialize.saga.test.ts +16 -0
- package/src/query/materialize.saga.ts +7 -26
- package/src/query/materialize.ts +79 -3
- package/src/query/register.saga.test.ts +61 -0
- package/src/query/register.saga.ts +39 -2
- package/src/services/database/cache-engine.ts +17 -3
- package/src/services/database/engine-factory.ts +7 -0
- package/src/services/database/index.ts +1 -0
- package/src/services/database/rows-cache-engine.test.ts +1584 -0
- package/src/services/database/rows-cache-engine.ts +1203 -0
- package/src/services/database/rows-exec.integration.test.ts +589 -0
- package/src/services/database/rows-exec.ts +1027 -0
- package/src/services/database/rows-prewarm.ts +251 -0
- package/src/services/database/rows-store.test.ts +635 -0
- package/src/services/database/rows-store.ts +1208 -0
- package/src/services/database/rows-transport.fixture.ts +151 -0
- package/src/services/database/rows-worker.ts +607 -0
- package/src/services/database/rows-yield.test.ts +141 -0
- package/src/services/database/rows-yield.ts +92 -0
- package/src/services/database/sqlite-cache-engine.test.ts +22 -1
- package/src/services/database/sqlite-cache-engine.ts +55 -34
- package/src/services/database/sqlite-transport.ts +7 -5
- package/src/services/tabs/support.ts +6 -4
- package/src/types.ts +41 -6
- package/tsdown.config.ts +42 -1
- package/vitest.config.ts +4 -0
package/dist/sqlite-open.js
CHANGED
|
@@ -389,4 +389,4 @@ async function openDb(sqlite3, dbName, useOpfs, opts = {}) {
|
|
|
389
389
|
}
|
|
390
390
|
|
|
391
391
|
//#endregion
|
|
392
|
-
export {
|
|
392
|
+
export { projectedDataSql as a, reviveRow as c, recordIdKey as d, resolveRelations as f, project as i, serializeMergeRow as l, openDb as n, renderOrderSql as o, stableKey as p, fromBase64 as r, renderWhereSql as s, PROMOTION_OPEN_OPTIONS as t, serializeRow as u };
|
package/dist/sqlite-worker.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { a as projectedDataSql, c as reviveRow, f as resolveRelations, i as project, n as openDb, o as renderOrderSql, p as stableKey, s as renderWhereSql } from "./sqlite-open.js";
|
|
2
2
|
import sqlite3InitModule from "@sqlite.org/sqlite-wasm";
|
|
3
3
|
|
|
4
4
|
//#region src/services/database/sqlite-lock-verify.ts
|
package/dist/types.d.ts
CHANGED
|
@@ -157,10 +157,36 @@ interface ChannelTransport {
|
|
|
157
157
|
readonly supported: boolean;
|
|
158
158
|
/** Users this tab wants connections to: the union over open channels. */
|
|
159
159
|
want(users: ReadonlySet<string>): void;
|
|
160
|
-
send(to: PeerRef, message:
|
|
160
|
+
send(to: PeerRef, message: ChannelWire): void;
|
|
161
161
|
close(): void;
|
|
162
162
|
}
|
|
163
163
|
type ChannelTransportFactory = (hooks: TransportHooks) => ChannelTransport;
|
|
164
|
+
/** Which rows of a table are shared: all of them, or the ones a test passes. */
|
|
165
|
+
type ChannelShareRule = boolean | ((row: Row$1) => boolean);
|
|
166
|
+
/**
|
|
167
|
+
* Sharing optimistic writes with the user's own other devices (see
|
|
168
|
+
* `ChannelsConfig.share`). Needs `ChannelsConfig.relay`.
|
|
169
|
+
*/
|
|
170
|
+
interface ChannelShareConfig {
|
|
171
|
+
/**
|
|
172
|
+
* Per table: `true` shares every row, a function only the rows it returns
|
|
173
|
+
* true for (asked on the device that writes, and again on the one that
|
|
174
|
+
* receives). A table left out, or set to `false`, is never shared. The
|
|
175
|
+
* table needs no `-- @channel` mark: these writes only ever reach devices
|
|
176
|
+
* signed in as the same user.
|
|
177
|
+
*/
|
|
178
|
+
tables: Record<string, ChannelShareRule>;
|
|
179
|
+
}
|
|
180
|
+
/** Where the room relay (`sp00ky-relay`) is, and how to use it. */
|
|
181
|
+
interface ChannelRelayConfig {
|
|
182
|
+
/** Its WebSocket address, e.g. `wss://relay.example.com/room`. */
|
|
183
|
+
url: string;
|
|
184
|
+
/**
|
|
185
|
+
* Two browsers alone in a room also open a direct WebRTC link and talk over
|
|
186
|
+
* that while it is up. `false` keeps everything on the relay. Default true.
|
|
187
|
+
*/
|
|
188
|
+
direct?: boolean;
|
|
189
|
+
}
|
|
164
190
|
interface ChannelsConfig {
|
|
165
191
|
/**
|
|
166
192
|
* Per table: decide whether to apply a peer's update. Runs after the
|
|
@@ -175,6 +201,18 @@ interface ChannelsConfig {
|
|
|
175
201
|
transport?: ChannelTransportFactory;
|
|
176
202
|
/** How long a peer's persistent value shows without the server confirming it. Default 5000. */
|
|
177
203
|
confirmTimeoutMs?: number;
|
|
204
|
+
/**
|
|
205
|
+
* The room relay this user's devices meet on: its address, or an object
|
|
206
|
+
* with more. One socket per browser, whatever the number of tabs.
|
|
207
|
+
*/
|
|
208
|
+
relay?: string | ChannelRelayConfig;
|
|
209
|
+
/**
|
|
210
|
+
* Send this user's optimistic writes straight to their other devices, so a
|
|
211
|
+
* change made on the phone shows on the laptop before the server has seen
|
|
212
|
+
* it. Off unless set, and per table. The devices tell each other which
|
|
213
|
+
* rows their open queries can show, and a write nobody shows is not sent.
|
|
214
|
+
*/
|
|
215
|
+
share?: ChannelShareConfig;
|
|
178
216
|
}
|
|
179
217
|
/** `table:id` for a record id in any spelling, or null. */
|
|
180
218
|
|
|
@@ -182,6 +220,8 @@ interface ChannelsConfig {
|
|
|
182
220
|
interface ChannelScope {
|
|
183
221
|
readonly table: string;
|
|
184
222
|
readonly where: ReadonlyArray<WhereNode>;
|
|
223
|
+
/** A further test on the row (a share rule given as a function). */
|
|
224
|
+
readonly test?: (row: Row$1) => boolean;
|
|
185
225
|
}
|
|
186
226
|
/** Whether `row` passes a query's `where` (a conjunction of comparisons and `_or` groups). */
|
|
187
227
|
declare function matchesWhere(where: ReadonlyArray<WhereNode>, row: Row$1): boolean;
|
|
@@ -197,6 +237,27 @@ declare function unusedArgs(plan: QueryPlan, isOne?: boolean): string[];
|
|
|
197
237
|
* limit and projection do not matter to a channel and are ignored.
|
|
198
238
|
*/
|
|
199
239
|
|
|
240
|
+
/**
|
|
241
|
+
* A device telling its user's other devices what it shows, so they do not
|
|
242
|
+
* send it writes it has no use for. `all`: everything (it could not say more).
|
|
243
|
+
* Only ever exchanged between devices of one user.
|
|
244
|
+
*/
|
|
245
|
+
interface InterestMessage {
|
|
246
|
+
readonly t: 'interest';
|
|
247
|
+
readonly all?: true;
|
|
248
|
+
/** Per table `true` or a list of filters, their values wire-encoded (see `encodeValue`). */
|
|
249
|
+
readonly v?: Record<string, unknown>;
|
|
250
|
+
}
|
|
251
|
+
/** Everything a transport carries. */
|
|
252
|
+
type ChannelWire = ChannelMessage | InterestMessage;
|
|
253
|
+
/**
|
|
254
|
+
* What a registered query can show: the rows of its own table that pass its
|
|
255
|
+
* filter, and every row of the tables it reads through `.related()` (which
|
|
256
|
+
* children it shows depends on the parents, not on the child row alone).
|
|
257
|
+
* Order, limit and offset are ignored: a row inside the filter and outside
|
|
258
|
+
* the window is sent and then not shown.
|
|
259
|
+
*/
|
|
260
|
+
|
|
200
261
|
/** An open channel. `client.channel(...)` wraps it with scoped writes. */
|
|
201
262
|
interface ChannelHandle {
|
|
202
263
|
/** The tables its queries read. */
|
|
@@ -495,7 +556,7 @@ type DatabaseEventSystem = EventSystem<DatabaseEventTypeMap>;
|
|
|
495
556
|
//#region src/modules/devtools/storage-info.d.ts
|
|
496
557
|
/** Engine-side numbers only the engine can produce (worker round-trips). */
|
|
497
558
|
interface EngineStorageDiagnostics {
|
|
498
|
-
engine: 'sqlite';
|
|
559
|
+
engine: 'sqlite' | 'rows';
|
|
499
560
|
bucketId: string;
|
|
500
561
|
useOpfs: boolean;
|
|
501
562
|
workerSelectConfigured: boolean;
|
|
@@ -504,7 +565,8 @@ interface EngineStorageDiagnostics {
|
|
|
504
565
|
workerSelectEffective: boolean;
|
|
505
566
|
/** page_count * page_size. */
|
|
506
567
|
dbSizeBytes?: number;
|
|
507
|
-
/** freelist_count * page_size — reclaimable via VACUUM.
|
|
568
|
+
/** freelist_count * page_size — reclaimable via VACUUM. On the row store:
|
|
569
|
+
* dead bytes in the log, reclaimed by its next compaction. */
|
|
508
570
|
freelistBytes?: number;
|
|
509
571
|
tableCounts?: {
|
|
510
572
|
table: string;
|
|
@@ -584,7 +646,9 @@ interface LocalCacheEngine extends RowFetcher {
|
|
|
584
646
|
* Materialize a query, including its `.related()` tree (via §3
|
|
585
647
|
* decomposition). Params bind `where` `paramRef`s and any windowing id-set.
|
|
586
648
|
*/
|
|
587
|
-
select(plan: QueryPlan$1, params?: Record<string, unknown
|
|
649
|
+
select(plan: QueryPlan$1, params?: Record<string, unknown>, opts?: {
|
|
650
|
+
paintKey?: string;
|
|
651
|
+
}): Promise<Row[]>;
|
|
588
652
|
/** Fetch rows by primary id, preserving `ids` order; missing ids are skipped. */
|
|
589
653
|
selectByIds(table: string, ids: Id[], opts?: {
|
|
590
654
|
select?: string[];
|
|
@@ -632,7 +696,7 @@ interface LocalStore extends LocalCacheEngine {
|
|
|
632
696
|
/** Which built-in backend this is. OPTIONAL: absent (custom engines) is
|
|
633
697
|
* reported as `'custom'` by DevTools. More robust than `instanceof` for
|
|
634
698
|
* engines constructed outside this package. */
|
|
635
|
-
readonly engineKind?: 'surrealdb' | 'sqlite';
|
|
699
|
+
readonly engineKind?: 'surrealdb' | 'sqlite' | 'rows';
|
|
636
700
|
/** Engine-specific storage numbers for DevTools (DB file size, per-table
|
|
637
701
|
* row counts). OPTIONAL: only engines with something to report implement it. */
|
|
638
702
|
getStorageDiagnostics?(opts?: {
|
|
@@ -676,6 +740,25 @@ interface LocalStore extends LocalCacheEngine {
|
|
|
676
740
|
* readable by follower tabs over the port transport. OPTIONAL: an engine
|
|
677
741
|
* without it primes from `scanVersions` alone.
|
|
678
742
|
*/
|
|
743
|
+
/**
|
|
744
|
+
* What `select(plan, params)` / `selectByIds` answered the last time the app
|
|
745
|
+
* asked at startup, SYNCHRONOUSLY and before the store is open, or `null`.
|
|
746
|
+
* Something to paint from; the read itself stays the answer and must follow.
|
|
747
|
+
* OPTIONAL: only an engine that keeps such a copy (`'rows'`) has them.
|
|
748
|
+
*/
|
|
749
|
+
peekSelect?(plan: QueryPlan$1, params?: Record<string, unknown>, opts?: {
|
|
750
|
+
paintKey?: string;
|
|
751
|
+
}): Row[] | null;
|
|
752
|
+
/**
|
|
753
|
+
* The bucket `connect` is about to be called with, told ahead: a store that
|
|
754
|
+
* keeps rows to paint from can then answer {@link peekSelect} before it is
|
|
755
|
+
* open. Ignored by a store that keeps none.
|
|
756
|
+
*/
|
|
757
|
+
expectBucket?(bucketId: string): void;
|
|
758
|
+
peekByIds?(table: string, ids: Id[], opts?: {
|
|
759
|
+
select?: string[];
|
|
760
|
+
orderBy?: OrderBy;
|
|
761
|
+
}): Row[] | null;
|
|
679
762
|
getSnapshot?(key: string): Promise<StoredSnapshot | null>;
|
|
680
763
|
putSnapshot?(key: string, bytes: Uint8Array, meta: SnapshotMeta): Promise<void>;
|
|
681
764
|
deleteSnapshot?(key: string): Promise<void>;
|
|
@@ -696,7 +779,7 @@ interface StoredSnapshot {
|
|
|
696
779
|
meta: SnapshotMeta;
|
|
697
780
|
}
|
|
698
781
|
/** Selected local cache backend. Mirrors the `persistenceClient` config pattern. */
|
|
699
|
-
type LocalEngineChoice = 'surrealdb' | 'sqlite' | LocalStore;
|
|
782
|
+
type LocalEngineChoice = 'surrealdb' | 'sqlite' | 'rows' | LocalStore;
|
|
700
783
|
/** Thrown when relation decomposition nests past {@link MAX_RELATION_DEPTH} —
|
|
701
784
|
* a guard against a cyclic schema producing unbounded fan-out. */
|
|
702
785
|
//#endregion
|
|
@@ -1635,6 +1718,8 @@ interface LocalWorkers {
|
|
|
1635
1718
|
surreal?: () => Worker;
|
|
1636
1719
|
/** The SQLite engine's worker (`localEngine: 'sqlite'`): runs `@spooky-sync/core/sqlite-worker`. */
|
|
1637
1720
|
sqlite?: () => Worker;
|
|
1721
|
+
/** The row store's worker (`localEngine: 'rows'`): runs `@spooky-sync/core/rows-worker`. */
|
|
1722
|
+
rows?: () => Worker;
|
|
1638
1723
|
}
|
|
1639
1724
|
/**
|
|
1640
1725
|
* Configuration options for the Sp00ky client.
|
|
@@ -1676,6 +1761,30 @@ interface Sp00kyConfig<S extends SchemaStructure> {
|
|
|
1676
1761
|
* failure the queue retries. `0` disables. Defaults to `60_000`.
|
|
1677
1762
|
*/
|
|
1678
1763
|
queryTimeoutMs?: number;
|
|
1764
|
+
/**
|
|
1765
|
+
* `localEngine: 'rows'` only. Keep a copy of the rows the app reads at
|
|
1766
|
+
* startup in localStorage (up to about 1 MB), so `peekSelect` / `peekByIds`
|
|
1767
|
+
* can hand a screen what it showed last time before the store is open.
|
|
1768
|
+
* Works with `sharedTabs`: a copy is dropped for every tab as soon as any
|
|
1769
|
+
* tab writes to a table it was read from.
|
|
1770
|
+
* Default `true` for a durable store; `false` turns it off.
|
|
1771
|
+
*/
|
|
1772
|
+
paintCache?: boolean;
|
|
1773
|
+
/**
|
|
1774
|
+
* `localEngine: 'rows'` with `sharedTabs` only. Where a follower tab's
|
|
1775
|
+
* reads are answered.
|
|
1776
|
+
* - `'leader'` (default): by the leader tab's worker, over a port.
|
|
1777
|
+
* - `'direct'`: by a worker of the follower's own that reads the store's
|
|
1778
|
+
* file beside the leader. A read then never waits for the leader's
|
|
1779
|
+
* work (a sync-down in another tab), and crosses no tab boundary.
|
|
1780
|
+
* Writes still go to the leader. Needs shared OPFS access handles
|
|
1781
|
+
* (Chrome 121+); elsewhere, and whenever its worker fails, a follower
|
|
1782
|
+
* reads through the leader as before. The price: nothing but the
|
|
1783
|
+
* leader's lock stands between two writers of the file, where the
|
|
1784
|
+
* default has the browser refuse a second one, and each follower
|
|
1785
|
+
* holds the store's index in memory.
|
|
1786
|
+
*/
|
|
1787
|
+
followerReads?: 'leader' | 'direct';
|
|
1679
1788
|
/**
|
|
1680
1789
|
* Deadline (ms) for every LOCAL store operation (a SQLite worker round trip,
|
|
1681
1790
|
* or a query on the in-process surrealdb engine). Local ops are serialized
|
|
@@ -1708,9 +1817,13 @@ interface Sp00kyConfig<S extends SchemaStructure> {
|
|
|
1708
1817
|
/**
|
|
1709
1818
|
* Local cache engine backend. `'surrealdb'` (default) uses the in-browser
|
|
1710
1819
|
* SurrealDB-WASM store; `'sqlite'` uses official SQLite-WASM in a Worker with
|
|
1711
|
-
* OPFS persistence;
|
|
1712
|
-
*
|
|
1713
|
-
* this
|
|
1820
|
+
* OPFS persistence; `'rows'` (experimental) uses sp00ky's own row store in a
|
|
1821
|
+
* Worker, also on OPFS: an append-only file per bucket with a flat index,
|
|
1822
|
+
* built for this client's reads and writes and nothing else, and answering
|
|
1823
|
+
* every query the way `'sqlite'` does; or pass a custom
|
|
1824
|
+
* {@link LocalCacheEngine}. The local cache is a passive queryable store —
|
|
1825
|
+
* reactivity is driven by the remote SSP, not this engine. See
|
|
1826
|
+
* `services/database/cache-engine.ts` and `services/database/rows-store.ts`.
|
|
1714
1827
|
*/
|
|
1715
1828
|
localEngine?: LocalEngineChoice;
|
|
1716
1829
|
/**
|
|
@@ -1741,7 +1854,7 @@ interface Sp00kyConfig<S extends SchemaStructure> {
|
|
|
1741
1854
|
};
|
|
1742
1855
|
/**
|
|
1743
1856
|
* Share ONE durable local store across all tabs of this origin (default
|
|
1744
|
-
* `false`). Requires `localEngine: 'sqlite'`. A SharedWorker broker elects a
|
|
1857
|
+
* `false`). Requires `localEngine: 'sqlite'` or `'rows'`. A SharedWorker broker elects a
|
|
1745
1858
|
* leader tab per bucket via Web Locks; the leader owns the OPFS SQLite
|
|
1746
1859
|
* worker and the sync loop, and follower tabs read/write the same store over
|
|
1747
1860
|
* MessagePorts, so every tab is durable instead of only the first one.
|
|
@@ -1760,8 +1873,8 @@ interface Sp00kyConfig<S extends SchemaStructure> {
|
|
|
1760
1873
|
/**
|
|
1761
1874
|
* Persist the in-browser SSP circuit's store as a snapshot in the local
|
|
1762
1875
|
* store, so a reload restores it and only steps in what changed since.
|
|
1763
|
-
* Defaults to `true` under `localEngine: 'sqlite'` (the
|
|
1764
|
-
* can hold the bytes) and `false` otherwise.
|
|
1876
|
+
* Defaults to `true` under `localEngine: 'sqlite'` and `'rows'` (the
|
|
1877
|
+
* OPFS-backed stores can hold the bytes) and `false` otherwise.
|
|
1765
1878
|
*
|
|
1766
1879
|
* Without a snapshot the circuit is primed by reading every cached row back
|
|
1767
1880
|
* out of the local store; either way a reload never re-downloads the working
|
|
@@ -1826,6 +1939,11 @@ interface Sp00kyConfig<S extends SchemaStructure> {
|
|
|
1826
1939
|
* apply. `iceServers` configures the default WebRTC transport (a public
|
|
1827
1940
|
* STUN server when omitted; add TURN for networks that block direct
|
|
1828
1941
|
* connections), `transport` replaces it.
|
|
1942
|
+
*
|
|
1943
|
+
* `share` sends this user's optimistic writes straight to their other
|
|
1944
|
+
* devices, per table (`share: { tables: { game: true, note: (row) =>
|
|
1945
|
+
* !row.draft } }`), through the room relay named by `relay` (the
|
|
1946
|
+
* `sp00ky-relay` server, one socket per browser). Off unless set.
|
|
1829
1947
|
*/
|
|
1830
1948
|
channels?: ChannelsConfig;
|
|
1831
1949
|
/**
|
|
@@ -2431,4 +2549,4 @@ interface Sp00kyChannel<S extends SchemaStructure, T extends string> extends Omi
|
|
|
2431
2549
|
delete<N extends T>(table: N, id: string): Promise<void>;
|
|
2432
2550
|
}
|
|
2433
2551
|
//#endregion
|
|
2434
|
-
export { WebPushInfo as $,
|
|
2552
|
+
export { WebPushInfo as $, ChannelRelayConfig as $t, RecordVersionArray as A, AuthEventTypeMap as At, StorageHealthStatus as B, ImpersonationTimerHost as Bt, QueryState as C, AuthService as Ct, QueryTimings as D, SignOutContext as Dt, QueryTimeToLive as E, SIGN_OUT_HOOK_TIMEOUT_MS as Et, Sp00kyChannel as F, SealedQuery as Ft, TimingPhase as G, decodeTokenClaims as Gt, SyncHealth as H, ORIGIN_TOKEN_KEY as Ht, Sp00kyConfig as I, EventDefinition as It, PushDeviceKind as J, sameImpersonation as Jt, UpdateOptions as K, impersonationFromToken as Kt, Sp00kyQueryResult as L, EventSystem as Lt, RegistrationTimings as M, createAuthEventSystem as Mt, RunOptions as N, RemoteDatabaseService as Nt, QueryUpdateCallback as O, SignOutHook as Ot, ServerViewMeta as P, LocalStore as Pt, WebPushErrorCode as Q, ChannelOp as Qt, Sp00kyQueryResultPromise as R, IMPERSONATION_ACCESS as Rt, QueryHash as S, ActiveImpersonation as St, QueryStatusCallback as T, REFUSAL_RECHECK_MIN_MS as Tt, SyncHealthConfig as U, SESSION_POLL_MS as Ut, StoreType as V, ImpersonationTimers as Vt, SyncHealthStatus as W, TokenClaims as Wt, WebPushDevice as X, ChannelHandle as Xt, WebPushConfig as Y, ChannelAcceptRule as Yt, WebPushError as Z, ChannelMessage as Zt, PreloadOptions as _, PushPayload as _t, EventSubscriptionOptions as a, ChannelTransport as an, WebPushSyncOptions as at, QueryConfig as b, WebPushClientMessage as bt, LocalWorkers as c, ChannelsConfig as cn, WebPushUnsupportedReason as ct, MutationCallback as d, TransportHooks as dn, BridgeSignOutMessage as dt, ChannelScope as en, WebPushMessage as et, MutationEvent as f, matchesWhere as fn, BridgeTokenMessage as ft, PinoTransmit as g, PushOp as gt, PhaseStat as h, Logger$1 as hn, PushNotificationAction as ht, EdgeDelta as i, ChannelStatus as in, WebPushSupport as it, RecordVersionDiff as j, AuthEventTypes as jt, ReconnectConfig as k, AuthEventSystem as kt, MATERIALIZATION_SAMPLE_WINDOW as l, InterestMessage as ln, WebPushUpdateOptions as lt, PersistenceClient as m, LogTap as mn, PushNotification as mt, ConnectionState as n, ChannelShareRule as nn, WebPushModule as nt, InlineRow as o, ChannelTransportFactory as on, WebPushSyncStatus as ot, MutationEventType as p, unusedArgs as pn, PUSH_PAYLOAD_VERSION as pt, PUSH_ENDPOINT_KEY as q, renewDelayMs as qt, DebounceOptions as r, ChannelState as rn, WebPushSubscribeOptions as rt, Level$1 as s, ChannelWire as sn, WebPushUnsubscribeOptions as st, ChannelQuery as t, ChannelShareConfig as tn, WebPushMessageInput as tt, MembershipOutcome as u, PeerRef as un, detectWebPushSupport as ut, PreloadRefresh as v, PushPayloadKind as vt, QueryStatus as w, ImpersonationCandidate as wt, QueryConfigRecord as x, isPushPayload as xt, QueryAuthorityCallback as y, PushUrgency as yt, StorageHealth as z, ImpersonationInfo as zt };
|
package/package.json
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spooky-sync/core",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.11",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": [
|
|
6
|
-
"./dist/sqlite-worker.js"
|
|
6
|
+
"./dist/sqlite-worker.js",
|
|
7
|
+
"./dist/rows-worker.js"
|
|
7
8
|
],
|
|
8
9
|
"main": "./dist/index.js",
|
|
9
10
|
"types": "./dist/index.d.ts",
|
|
@@ -31,6 +32,10 @@
|
|
|
31
32
|
"./sqlite-worker": {
|
|
32
33
|
"types": "./dist/sqlite-worker.d.ts",
|
|
33
34
|
"import": "./dist/sqlite-worker.js"
|
|
35
|
+
},
|
|
36
|
+
"./rows-worker": {
|
|
37
|
+
"types": "./dist/rows-worker.d.ts",
|
|
38
|
+
"import": "./dist/rows-worker.js"
|
|
34
39
|
}
|
|
35
40
|
},
|
|
36
41
|
"scripts": {
|
|
@@ -81,8 +86,8 @@
|
|
|
81
86
|
}
|
|
82
87
|
},
|
|
83
88
|
"dependencies": {
|
|
84
|
-
"@spooky-sync/query-builder": "1.0.0-beta.
|
|
85
|
-
"@spooky-sync/ssp-wasm": "1.0.0-beta.
|
|
89
|
+
"@spooky-sync/query-builder": "1.0.0-beta.11",
|
|
90
|
+
"@spooky-sync/ssp-wasm": "1.0.0-beta.11",
|
|
86
91
|
"@sqlite.org/sqlite-wasm": "3.53.0-build1",
|
|
87
92
|
"@surrealdb/wasm": "^3.1.0",
|
|
88
93
|
"@surrealdb/wasm-native": "^3.3.4",
|
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
// has none of them; an access at module top level would throw on import);
|
|
8
8
|
// - `/sw` does not even pull in the `surrealdb` SDK.
|
|
9
9
|
// Each entry is then really imported in this Node process (no DOM globals)
|
|
10
|
-
// to catch top-level side effects the static scan cannot see
|
|
10
|
+
// to catch top-level side effects the static scan cannot see, and so is
|
|
11
|
+
// dist/index.js, which must load in Node ESM too. Prints the
|
|
11
12
|
// gzipped size of each entry (own code, and fully bundled with its npm
|
|
12
13
|
// dependencies when rolldown is reachable). Run after `tsdown` in the build.
|
|
13
14
|
import { readFileSync, existsSync } from 'node:fs';
|
|
@@ -133,6 +134,18 @@ for (const entry of ENTRIES) {
|
|
|
133
134
|
}
|
|
134
135
|
}
|
|
135
136
|
|
|
137
|
+
// The main entry carries the wasm engines, so none of the scans above apply,
|
|
138
|
+
// but it must still load in Node ESM: the client bindings import it during
|
|
139
|
+
// SSR and consumers import it from Vitest. Node resolves a CommonJS
|
|
140
|
+
// dependency through its `main`, where a named import the CJS export lexer
|
|
141
|
+
// cannot see fails at link time (`import { applyPatch } from 'fast-json-patch'`
|
|
142
|
+
// did, with "does not provide an export named 'applyPatch'").
|
|
143
|
+
try {
|
|
144
|
+
await import(pathToFileURL(join(dist, 'index.js')).href);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
problems.push(`index.js fails to import in Node: ${error?.message ?? error}`);
|
|
147
|
+
}
|
|
148
|
+
|
|
136
149
|
// Fully bundled size (entry + npm deps, minified), when rolldown is reachable
|
|
137
150
|
// through tsdown. Informational only.
|
|
138
151
|
async function bundledGzip(entry) {
|
|
@@ -166,7 +179,7 @@ for (const s of sizes) {
|
|
|
166
179
|
if (problems.length > 0) {
|
|
167
180
|
for (const p of problems) console.error(`check-worker-entries: ${p}`);
|
|
168
181
|
console.error(
|
|
169
|
-
'The /pure, /live and /sw entries must stay free of wasm, the logger and DOM globals.'
|
|
182
|
+
'The /pure, /live and /sw entries must stay free of wasm, the logger and DOM globals, and every entry must import in Node.'
|
|
170
183
|
);
|
|
171
184
|
process.exit(1);
|
|
172
185
|
}
|
|
@@ -143,6 +143,8 @@ write) and `db.discardFailedMutation(id)`.
|
|
|
143
143
|
|
|
144
144
|
On `-- @channel` tables, `client.channel(query, peers)` opens WebRTC channels to the users listed (both sides must list each other) for the rows the query's `where` matches (checked per row, never registered). Plain `client.update` / `create` / `delete` reach the peers of every open channel whose filter the row matches; the handle's own writes limit that to its peers. `-- @ephemeral` fields go only to peers. Order/limit/select/`.one()` warn unless `.ignoreUnusedArgs()`. Follow status with `ch.subscribe(cb)`, close with `ch.close()`. Config: `channels: { accept, iceServers, transport, confirmTimeoutMs }`. Docs: `/docs/client/channels`.
|
|
145
145
|
|
|
146
|
+
**Your own devices.** `channels: { relay: 'wss://relay.example.com/room', share: { tables: { game: true, note: (row) => !row.draft } } }` sends the signed-in user's optimistic writes on those tables straight to their other devices, whatever those run: the Flutter and Rust clients join the same rooms (the tables need no `-- @channel`). `relay` is the address of the `sp00ky-relay` server (`apps/relay`), which puts each socket into the room of the user its session token belongs to. One socket per browser is shared by its tabs; two browsers alone also talk over a direct WebRTC link (`relay: { url, direct: false }` turns that off). A device is only sent writes its open queries can show. `client.shareState()` / `client.subscribeShareState(cb)` report `{ status, peers }`. Off unless `share` is set.
|
|
147
|
+
|
|
146
148
|
## Authentication
|
|
147
149
|
|
|
148
150
|
See [references/auth.md](references/auth.md) for the full auth API.
|
|
@@ -189,7 +189,14 @@ export class BucketHandle {
|
|
|
189
189
|
remote: RemoteDatabaseService,
|
|
190
190
|
/** Absent on the raw handle the cache itself reads through. */
|
|
191
191
|
private blobs?: BlobCache | null,
|
|
192
|
-
private settings?: BucketHandleSettings
|
|
192
|
+
private settings?: BucketHandleSettings,
|
|
193
|
+
/**
|
|
194
|
+
* Resolves once the client is open; nothing to wait for when it already
|
|
195
|
+
* is. Every call below awaits it, so a file asked for by a component that
|
|
196
|
+
* rendered before the client was ready (a provider's `eager` mode) is
|
|
197
|
+
* fetched then, where it used to fail for want of a connection.
|
|
198
|
+
*/
|
|
199
|
+
private opened?: () => Promise<void> | undefined
|
|
193
200
|
) {
|
|
194
201
|
this.io =
|
|
195
202
|
settings?.backend === 'r2'
|
|
@@ -209,6 +216,7 @@ export class BucketHandle {
|
|
|
209
216
|
content: string | Uint8Array | Blob,
|
|
210
217
|
options?: BucketPutOptions
|
|
211
218
|
): Promise<BucketPutResult> {
|
|
219
|
+
await this.opened?.();
|
|
212
220
|
// Start hashing while the upload is in flight; both browser-side costs
|
|
213
221
|
// overlap and the sidecar put only queues once the main put resolved.
|
|
214
222
|
const encodeOptions = this.resolveBlurhash(options?.blurhash);
|
|
@@ -247,6 +255,7 @@ export class BucketHandle {
|
|
|
247
255
|
* serialized remote read per session.
|
|
248
256
|
*/
|
|
249
257
|
async blurhash(path: string): Promise<string | null> {
|
|
258
|
+
await this.opened?.();
|
|
250
259
|
const cacheKey = `${this.bucketName}:${path}`;
|
|
251
260
|
if (missingBlurhash.has(cacheKey)) return null;
|
|
252
261
|
try {
|
|
@@ -270,6 +279,7 @@ export class BucketHandle {
|
|
|
270
279
|
}
|
|
271
280
|
|
|
272
281
|
async get(path: string): Promise<unknown> {
|
|
282
|
+
await this.opened?.();
|
|
273
283
|
return this.io.get(path);
|
|
274
284
|
}
|
|
275
285
|
|
|
@@ -279,6 +289,7 @@ export class BucketHandle {
|
|
|
279
289
|
* file exists in neither place.
|
|
280
290
|
*/
|
|
281
291
|
async read(path: string, options?: BlobReadOptions): Promise<Blob | null> {
|
|
292
|
+
await this.opened?.();
|
|
282
293
|
if (!this.blobs) return bucketContentToBlob(await this.get(path));
|
|
283
294
|
return this.blobs.read({ bucket: this.bucketName, path }, options);
|
|
284
295
|
}
|
|
@@ -289,6 +300,7 @@ export class BucketHandle {
|
|
|
289
300
|
* file does not exist, or when object URLs are unavailable (non-browser).
|
|
290
301
|
*/
|
|
291
302
|
async url(path: string, options?: BlobReadOptions): Promise<BlobUrlLease | null> {
|
|
303
|
+
await this.opened?.();
|
|
292
304
|
if (!this.blobs) return null;
|
|
293
305
|
return this.blobs.acquireUrl({ bucket: this.bucketName, path }, options);
|
|
294
306
|
}
|
|
@@ -304,15 +316,18 @@ export class BucketHandle {
|
|
|
304
316
|
|
|
305
317
|
/** Drop `path` from the local cache without touching the remote file. */
|
|
306
318
|
async evict(path: string): Promise<void> {
|
|
319
|
+
await this.opened?.();
|
|
307
320
|
await this.blobs?.invalidate({ bucket: this.bucketName, path });
|
|
308
321
|
}
|
|
309
322
|
|
|
310
323
|
/** Warm the cache for offline use. Already-cached paths are skipped. */
|
|
311
324
|
async prefetch(paths: string[]): Promise<void> {
|
|
325
|
+
await this.opened?.();
|
|
312
326
|
await this.blobs?.prefetch(paths.map((path) => ({ bucket: this.bucketName, path })));
|
|
313
327
|
}
|
|
314
328
|
|
|
315
329
|
async delete(path: string): Promise<void> {
|
|
330
|
+
await this.opened?.();
|
|
316
331
|
await this.io.delete(path);
|
|
317
332
|
await this.blobs?.invalidate({ bucket: this.bucketName, path });
|
|
318
333
|
// Symmetry with put: an image's blurhash sidecar dies with it. Best-effort,
|
|
@@ -330,22 +345,27 @@ export class BucketHandle {
|
|
|
330
345
|
}
|
|
331
346
|
|
|
332
347
|
async exists(path: string): Promise<boolean> {
|
|
348
|
+
await this.opened?.();
|
|
333
349
|
return this.io.exists(path);
|
|
334
350
|
}
|
|
335
351
|
|
|
336
352
|
async head(path: string): Promise<Record<string, unknown>> {
|
|
353
|
+
await this.opened?.();
|
|
337
354
|
return this.io.head(path);
|
|
338
355
|
}
|
|
339
356
|
|
|
340
357
|
async copy(sourcePath: string, targetPath: string): Promise<void> {
|
|
358
|
+
await this.opened?.();
|
|
341
359
|
await this.io.copy(sourcePath, targetPath);
|
|
342
360
|
}
|
|
343
361
|
|
|
344
362
|
async rename(sourcePath: string, targetPath: string): Promise<void> {
|
|
363
|
+
await this.opened?.();
|
|
345
364
|
await this.io.rename(sourcePath, targetPath);
|
|
346
365
|
}
|
|
347
366
|
|
|
348
367
|
async list(prefix?: string): Promise<string[]> {
|
|
368
|
+
await this.opened?.();
|
|
349
369
|
return this.io.list(prefix ?? '');
|
|
350
370
|
}
|
|
351
371
|
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
|
2
|
+
import { Sp00kyClient } from './sp00ky-client';
|
|
3
|
+
import { RowsCacheEngine } from '../services/database/rows-cache-engine';
|
|
4
|
+
import { inProcessRows, type RowsDisks } from '../services/database/rows-transport.fixture';
|
|
5
|
+
import { paintKeyOf } from '../query/materialize';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The whole way from one page load to the next, with the real client and the
|
|
9
|
+
* real row store engine: a query renders, the engine keeps what it read, and
|
|
10
|
+
* the next page's client, built and not yet initialized, hands those rows to
|
|
11
|
+
* a component synchronously.
|
|
12
|
+
*/
|
|
13
|
+
describe('painting a query before init (row store)', () => {
|
|
14
|
+
const g = globalThis as Record<string, unknown>;
|
|
15
|
+
let stored: Map<string, string>;
|
|
16
|
+
const schema = { tables: [{ name: 'thing', columns: { n: {} } }] } as any;
|
|
17
|
+
const config = {
|
|
18
|
+
database: { namespace: 'n', database: 'd', store: 'indexeddb' },
|
|
19
|
+
localEngine: 'rows',
|
|
20
|
+
schema,
|
|
21
|
+
schemaSurql: '',
|
|
22
|
+
logLevel: 'silent',
|
|
23
|
+
} as any;
|
|
24
|
+
const logger = { info() {}, warn() {}, error() {}, debug() {}, trace() {}, child: () => logger } as any;
|
|
25
|
+
|
|
26
|
+
beforeEach(() => {
|
|
27
|
+
stored = new Map();
|
|
28
|
+
g.localStorage = {
|
|
29
|
+
getItem: (k: string) => stored.get(k) ?? null,
|
|
30
|
+
setItem: (k: string, v: string) => void stored.set(k, v),
|
|
31
|
+
removeItem: (k: string) => void stored.delete(k),
|
|
32
|
+
key: (i: number) => [...stored.keys()][i] ?? null,
|
|
33
|
+
get length() {
|
|
34
|
+
return stored.size;
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
afterEach(() => {
|
|
40
|
+
delete g.localStorage;
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
/** The first page load: the engine as the client drives it for one query's membership render. */
|
|
44
|
+
async function lastSession(bucket: string, surql: string): Promise<Record<string, unknown>[]> {
|
|
45
|
+
const disks: RowsDisks = new Map();
|
|
46
|
+
const engine = new RowsCacheEngine(config.database, logger, { useOpfs: true });
|
|
47
|
+
inProcessRows(engine, disks);
|
|
48
|
+
await engine.connect(bucket);
|
|
49
|
+
await engine.upsert('thing', 'thing:a', { n: 1 }, 'replace');
|
|
50
|
+
await engine.upsert('thing', 'thing:b', { n: 2 }, 'replace');
|
|
51
|
+
// What `materialize` does: the render set by id, named after the query.
|
|
52
|
+
const rows = await engine.select({ table: 'thing' }, {}, { paintKey: paintKeyOf({ surql, params: {} }, []) });
|
|
53
|
+
(engine as unknown as { paint: { flush(): void } }).paint.flush();
|
|
54
|
+
await engine.close();
|
|
55
|
+
return rows;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
it('hands a component the rows the query showed last time, with the client not opened', async () => {
|
|
59
|
+
stored.set('sp00ky:last_bucket', 'user_a');
|
|
60
|
+
const probe = new Sp00kyClient<any>(config);
|
|
61
|
+
const surql = probe.query('thing', {}).build().innerQuery.selectQuery.query;
|
|
62
|
+
const rows = await lastSession('user_a', surql);
|
|
63
|
+
expect(rows.map((r) => r.id)).toEqual(['thing:a', 'thing:b']);
|
|
64
|
+
|
|
65
|
+
// The next page load: a client that has been built and nothing more.
|
|
66
|
+
const client = new Sp00kyClient<any>(config);
|
|
67
|
+
expect(client.isLocalReady()).toBe(false);
|
|
68
|
+
expect(client.peekQuery(client.query('thing', {}).build())).toEqual(rows);
|
|
69
|
+
// Another query has no copy.
|
|
70
|
+
expect(client.peekQuery(client.query('thing', {}).where({ n: 1 }).build())).toBeNull();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('paints nothing from another user\'s bucket', async () => {
|
|
74
|
+
stored.set('sp00ky:last_bucket', 'user_a');
|
|
75
|
+
const surql = new Sp00kyClient<any>(config).query('thing', {}).build().innerQuery.selectQuery.query;
|
|
76
|
+
await lastSession('user_a', surql);
|
|
77
|
+
// The browser was last used by someone else: boot will open their bucket.
|
|
78
|
+
stored.set('sp00ky:last_bucket', 'user_b');
|
|
79
|
+
const client = new Sp00kyClient<any>(config);
|
|
80
|
+
expect(client.peekQuery(client.query('thing', {}).build())).toBeNull();
|
|
81
|
+
});
|
|
82
|
+
});
|
package/src/client/services.ts
CHANGED
|
@@ -173,7 +173,10 @@ export function createServices<S extends SchemaStructure>(config: Sp00kyConfig<S
|
|
|
173
173
|
else persistence = config.persistenceClient;
|
|
174
174
|
persistence = new ResilientPersistenceClient(persistence, logger);
|
|
175
175
|
const streamProcessor = new StreamProcessorService(new EventSystem(['stream_update']), local, logger);
|
|
176
|
-
streamProcessor.configureCircuitPersistence(
|
|
176
|
+
streamProcessor.configureCircuitPersistence(
|
|
177
|
+
config.persistCircuit ?? (config.localEngine === 'sqlite' || config.localEngine === 'rows'),
|
|
178
|
+
config.circuitCheckpointMs
|
|
179
|
+
);
|
|
177
180
|
streamProcessor.configureProjection(config.circuitProjection ?? true);
|
|
178
181
|
const migrator = new LocalMigrator(local, logger);
|
|
179
182
|
const crdt = new CrdtManager(config.schema, local, remote, logger, config.crdtDebounceMs ?? 50, config.crdtSendIntervalMs ?? 200);
|