@spooky-sync/core 0.0.1-canary.381 → 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.
- package/AGENTS.md +2 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +10 -10
- package/dist/otel/index.d.ts +1 -1
- package/dist/types.d.ts +31 -1
- package/package.json +10 -4
- package/src/services/database/local.ts +10 -5
- package/src/services/database/sqlite-cache-engine.ts +1 -1
- package/src/services/database/sqlite-transport.ts +7 -2
- package/src/types.ts +31 -0
package/AGENTS.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## What this package is
|
|
4
4
|
|
|
5
|
-
The sync engine. A `Sp00kyClient<S>` owns a local database (memory or IndexedDB), a remote SurrealDB connection, a mutation queue, and a CRDT manager. It's framework-agnostic — UI bindings live in `@spooky-sync/client-solid`
|
|
5
|
+
The sync engine. A `Sp00kyClient<S>` owns a local database (memory or IndexedDB), a remote SurrealDB connection, a mutation queue, and a CRDT manager. It's framework-agnostic — UI bindings live in `@spooky-sync/client-solid`, `client-solid2`, `client-react`, `client-svelte` and `client-angular`. Most app code touches this package indirectly through a UI binding's `useDb()` hook.
|
|
6
6
|
|
|
7
7
|
## Mental model
|
|
8
8
|
|
|
@@ -65,6 +65,7 @@ re-materialized from state, never patched in place.
|
|
|
65
65
|
- **`db.preload` is a registered query.** Resolved before on this device (a `_00_view` row exists) it returns at once; never resolved it waits until the server's membership and every body are local. A signed-out session without `enableAnonymousLiveQueries` is never sent membership, so its preload returns at once instead of blocking. It holds no subscriber, so it is evicted a ttl after registration unless a view mounts the same query. `refresh`/`staleTime` are ignored; pass `signal` to abort a cold wait.
|
|
66
66
|
- **A never-resolved query paints only vouched rows.** Before the server answers (`cold`), the local predicate scan shows a cached body only if some `_00_view` row names it (as a member or subquery child) or a write for it is in flight. A body no view names is an orphan (deleted upstream while nothing watched it): it stays hidden, and the GC deletes it 30 s after boot and then hourly. A `_00_view` row no query has resolved for 14 days is retired by the same sweep, so that query paints cold again.
|
|
67
67
|
- **`database.store` defaults to `'memory'`.** `'indexeddb'` keeps one IndexedDB database per user bucket (`sp00ky-<bucket>`) and needs `@surrealdb/wasm` >= 3.1.0: the 3.0.x engine opened the store but failed every write (`An IndexedDB error occured: idb error`), so each session fell back to memory. 3.1.0 ships the engine as `@surrealdb/wasm-native`; a Vite app lists it in `optimizeDeps.exclude` next to `@surrealdb/wasm`. A store that still cannot open after a drop runs the session in memory (error log `falling back to in-memory`). Under `localEngine: 'sqlite'`, `'indexeddb'` means OPFS.
|
|
68
|
+
- **`database.workers` lets the app start the local store's worker.** Only for a bundler that does not bundle a `new Worker(new URL(...))` inside a dependency, i.e. the Angular CLI: `workers.surreal` returns a module worker whose entry is `import '@surrealdb/wasm/worker'`, `workers.sqlite` (with `localEngine: 'sqlite'`) one whose entry is `import '@spooky-sync/core/sqlite-worker'` (an export kept in `sideEffects` so the bare import survives tree shaking). Unset, the built-in worker expressions run as before; Vite / Rollup / webpack apps leave it unset.
|
|
68
69
|
- **Boot owns the first identity.** The facade subscribes to auth with `immediate: false`: boot opens the bucket the hint names and `auth.restoreSession` announces the user. `LocalDatabaseService.switchStore` also waits for an in-flight `connect`, and lets statements already past the gate finish before it closes a client: the 3.1 engine streams results from its worker, and a statement whose client closed under it stayed pending until its 30 s deadline with every later local statement queued behind it.
|
|
69
70
|
- **A rejected write is not lost.** Application errors roll the local row back (create/update/delete) and move the mutation to `_00_failed_mutations`; the tray API above lists, retries (as a fresh write) or discards it. Network errors keep the row queued, and so does a write SurrealDB refused only because sp00ky's own `_00_` ingest event could not post to the scheduler/SSP (refused, past its TIMEOUT, DNS, 5xx/408/429; `SP00KY_EVENT_POST_FAILED` in `utils/error-classification.ts`).
|
|
70
71
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as
|
|
1
|
+
import { $ as WebPushInfo, $t as ChannelScope, A as RecordVersionArray, At as AuthEventTypeMap, B as StorageHealthStatus, Bt as ImpersonationTimerHost, C as QueryState, Ct as AuthService, D as QueryTimings, Dt as SignOutContext, E as QueryTimeToLive, Et as SIGN_OUT_HOOK_TIMEOUT_MS, F as Sp00kyChannel, Ft as SealedQuery, G as TimingPhase, Gt as decodeTokenClaims, H as SyncHealth, Ht as ORIGIN_TOKEN_KEY, I as Sp00kyConfig, It as EventDefinition, J as PushDeviceKind, Jt as sameImpersonation, K as UpdateOptions, Kt as impersonationFromToken, L as Sp00kyQueryResult, Lt as EventSystem, M as RegistrationTimings, Mt as createAuthEventSystem, N as RunOptions, Nt as RemoteDatabaseService, O as QueryUpdateCallback, Ot as SignOutHook, P as ServerViewMeta, Pt as LocalStore, Q as WebPushErrorCode, Qt as ChannelOp, R as Sp00kyQueryResultPromise, Rt as IMPERSONATION_ACCESS, S as QueryHash, St as ActiveImpersonation, T as QueryStatusCallback, Tt as REFUSAL_RECHECK_MIN_MS, U as SyncHealthConfig, Ut as SESSION_POLL_MS, V as StoreType, Vt as ImpersonationTimers, W as SyncHealthStatus, Wt as TokenClaims, X as WebPushDevice, Xt as ChannelHandle, Y as WebPushConfig, Yt as ChannelAcceptRule, Z as WebPushError, Zt as ChannelMessage, _ as PreloadOptions, _t as PushPayload, a as EventSubscriptionOptions, an as PeerRef, at as WebPushSyncOptions, b as QueryConfig, bt as WebPushClientMessage, c as LocalWorkers, cn as unusedArgs, ct as WebPushUnsupportedReason, d as MutationCallback, dt as BridgeSignOutMessage, en as ChannelState, et as WebPushMessage, f as MutationEvent, ft as BridgeTokenMessage, g as PinoTransmit, gt as PushOp, h as PhaseStat, ht as PushNotificationAction, i as EdgeDelta, in as ChannelsConfig, it as WebPushSupport, j as RecordVersionDiff, jt as AuthEventTypes, k as ReconnectConfig, kt as AuthEventSystem, l as MATERIALIZATION_SAMPLE_WINDOW, ln as LogTap, lt as WebPushUpdateOptions, m as PersistenceClient, mt as PushNotification, n as ConnectionState, nn as ChannelTransport, nt as WebPushModule, o as InlineRow, on as TransportHooks, ot as WebPushSyncStatus, p as MutationEventType, pt as PUSH_PAYLOAD_VERSION, q as PUSH_ENDPOINT_KEY, qt as renewDelayMs, r as DebounceOptions, rn as ChannelTransportFactory, rt as WebPushSubscribeOptions, s as Level, sn as matchesWhere, st as WebPushUnsubscribeOptions, t as ChannelQuery, tn as ChannelStatus, tt as WebPushMessageInput, u as MembershipOutcome, un as Logger$1, ut as detectWebPushSupport, v as PreloadRefresh, vt as PushPayloadKind, w as QueryStatus, wt as ImpersonationCandidate, x as QueryConfigRecord, xt as isPushPayload, y as QueryAuthorityCallback, yt as PushUrgency, z as StorageHealth, zt as ImpersonationInfo } from "./types.js";
|
|
2
2
|
import { BackendNames, BackendRoutes, BucketNames, ChannelPeer, ChannelTableNames, FinalQuery, GetTable, QueryBuilder, QueryOptions, QueryPlan, RecordId, RoutePayload, SchemaStructure, TableModel, TableNames } from "@spooky-sync/query-builder";
|
|
3
3
|
import * as surrealdb0 from "surrealdb";
|
|
4
4
|
import { Duration, RecordId as RecordId$1, Surreal } from "surrealdb";
|
|
@@ -2353,4 +2353,4 @@ declare class LocalOpTimeoutError extends Error {
|
|
|
2353
2353
|
* select on a throttled tab is seconds, not tens of seconds. */
|
|
2354
2354
|
declare const DEFAULT_LOCAL_OP_TIMEOUT_MS = 30000;
|
|
2355
2355
|
//#endregion
|
|
2356
|
-
export { ActiveImpersonation, AppReleaseHandle, AppReleaseModule, type AppReleaseOptions, type AppReleaseSnapshot, AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BLURHASH_IMAGE_EXTENSIONS, type BlobCacheStats, type BlobEntry, type BlobKey, type BlobReadOptions, type BlobUrlLease, type BlurhashEncodeOptions, type BlurhashSetting, type BridgeSignOutMessage, type BridgeTokenMessage, BucketHandle, BucketPutOptions, BucketPutResult, CURSOR_COLORS, type ChannelAcceptRule, type ChannelHandle, type ChannelMessage, type ChannelOp, ChannelQuery, type ChannelScope, type ChannelState, type ChannelStatus, type ChannelTransport, type ChannelTransportFactory, type ChannelsConfig, ConnectionState, CrdtField, CrdtManager, DEFAULT_LOCAL_OP_TIMEOUT_MS, DebounceOptions, EdgeDelta, EventSubscriptionOptions, type FailedMutationRow as FailedMutation, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagOverride, type FeatureFlagSnapshot, IMPERSONATION_ACCESS, ImpersonationCandidate, ImpersonationInfo, ImpersonationTimerHost, ImpersonationTimers, InlineRow, Level, LocalOpTimeoutError, MATERIALIZATION_SAMPLE_WINDOW, MembershipOutcome, MutationCallback, MutationEvent, MutationEventType, ORIGIN_TOKEN_KEY, type OutgoingSignal, PUSH_ENDPOINT_KEY, PUSH_PAYLOAD_VERSION, type PeerRef, PersistenceClient, PhaseStat, PinoTransmit, PreloadOptions, PreloadRefresh, type PushDeviceKind, type PushNotification, type PushNotificationAction, type PushOp, type PushPayload, type PushPayloadKind, type PushUrgency, QueryAuthorityCallback, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryStatus, QueryStatusCallback, QueryTimeToLive, QueryTimings, QueryUpdateCallback, REFUSAL_RECHECK_MIN_MS, ReconnectConfig, RecordVersionArray, RecordVersionDiff, RegistrationTimings, RunOptions, SESSION_POLL_MS, SIGN_OUT_HOOK_TIMEOUT_MS, ServerViewMeta, SignOutContext, SignOutHook, type Signal, type SignalPort, Sp00kyChannel, Sp00kyClient, Sp00kyClientDeps, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StorageHealth, StorageHealthStatus, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, TokenClaims, type TransportHooks, UpdateOptions, type WebPushClientMessage, type WebPushConfig, type WebPushDevice, WebPushError, type WebPushErrorCode, type WebPushInfo, type WebPushMessage, type WebPushMessageInput, WebPushModule, type WebPushSubscribeOptions, type WebPushSupport, type WebPushSyncOptions, type WebPushSyncStatus, type WebPushUnsubscribeOptions, type WebPushUnsupportedReason, type WebPushUpdateOptions, blurhashSidecarPath, bucketContentToBlob, createAuthEventSystem, cursorColorFromName, decode as decodeBlurhash, decodeTokenClaims, detectWebPushSupport, encode as encodeBlurhash, encodeImageToBlurhash, fileToUint8Array, impersonationFromToken, isBlurhashValid, isImagePath, isPushPayload, matchesWhere, renewDelayMs, sameImpersonation, semverGt, surrealSignal, textToHtml, unusedArgs, webrtcTransport };
|
|
2356
|
+
export { ActiveImpersonation, AppReleaseHandle, AppReleaseModule, type AppReleaseOptions, type AppReleaseSnapshot, AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BLURHASH_IMAGE_EXTENSIONS, type BlobCacheStats, type BlobEntry, type BlobKey, type BlobReadOptions, type BlobUrlLease, type BlurhashEncodeOptions, type BlurhashSetting, type BridgeSignOutMessage, type BridgeTokenMessage, BucketHandle, BucketPutOptions, BucketPutResult, CURSOR_COLORS, type ChannelAcceptRule, type ChannelHandle, type ChannelMessage, type ChannelOp, ChannelQuery, type ChannelScope, type ChannelState, type ChannelStatus, type ChannelTransport, type ChannelTransportFactory, type ChannelsConfig, ConnectionState, CrdtField, CrdtManager, DEFAULT_LOCAL_OP_TIMEOUT_MS, DebounceOptions, EdgeDelta, EventSubscriptionOptions, type FailedMutationRow as FailedMutation, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagOverride, type FeatureFlagSnapshot, IMPERSONATION_ACCESS, ImpersonationCandidate, ImpersonationInfo, ImpersonationTimerHost, ImpersonationTimers, InlineRow, Level, LocalOpTimeoutError, LocalWorkers, MATERIALIZATION_SAMPLE_WINDOW, MembershipOutcome, MutationCallback, MutationEvent, MutationEventType, ORIGIN_TOKEN_KEY, type OutgoingSignal, PUSH_ENDPOINT_KEY, PUSH_PAYLOAD_VERSION, type PeerRef, PersistenceClient, PhaseStat, PinoTransmit, PreloadOptions, PreloadRefresh, type PushDeviceKind, type PushNotification, type PushNotificationAction, type PushOp, type PushPayload, type PushPayloadKind, type PushUrgency, QueryAuthorityCallback, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryStatus, QueryStatusCallback, QueryTimeToLive, QueryTimings, QueryUpdateCallback, REFUSAL_RECHECK_MIN_MS, ReconnectConfig, RecordVersionArray, RecordVersionDiff, RegistrationTimings, RunOptions, SESSION_POLL_MS, SIGN_OUT_HOOK_TIMEOUT_MS, ServerViewMeta, SignOutContext, SignOutHook, type Signal, type SignalPort, Sp00kyChannel, Sp00kyClient, Sp00kyClientDeps, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StorageHealth, StorageHealthStatus, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, TokenClaims, type TransportHooks, UpdateOptions, type WebPushClientMessage, type WebPushConfig, type WebPushDevice, WebPushError, type WebPushErrorCode, type WebPushInfo, type WebPushMessage, type WebPushMessageInput, WebPushModule, type WebPushSubscribeOptions, type WebPushSupport, type WebPushSyncOptions, type WebPushSyncStatus, type WebPushUnsubscribeOptions, type WebPushUnsupportedReason, type WebPushUpdateOptions, blurhashSidecarPath, bucketContentToBlob, createAuthEventSystem, cursorColorFromName, decode as decodeBlurhash, decodeTokenClaims, detectWebPushSupport, encode as encodeBlurhash, encodeImageToBlurhash, fileToUint8Array, impersonationFromToken, isBlurhashValid, isImagePath, isPushPayload, matchesWhere, renewDelayMs, sameImpersonation, semverGt, surrealSignal, textToHtml, unusedArgs, webrtcTransport };
|
package/dist/index.js
CHANGED
|
@@ -3659,8 +3659,8 @@ function trimHistory(history, cap) {
|
|
|
3659
3659
|
|
|
3660
3660
|
//#endregion
|
|
3661
3661
|
//#region src/modules/devtools/index.ts
|
|
3662
|
-
const CORE_VERSION = "0.0.1-canary.
|
|
3663
|
-
const WASM_VERSION = "0.0.1-canary.
|
|
3662
|
+
const CORE_VERSION = "0.0.1-canary.383";
|
|
3663
|
+
const WASM_VERSION = "0.0.1-canary.383";
|
|
3664
3664
|
const SURREAL_VERSION = "3.1.0";
|
|
3665
3665
|
var DevToolsService = class DevToolsService {
|
|
3666
3666
|
version = CORE_VERSION;
|
|
@@ -9965,11 +9965,11 @@ function createBareSurrealClient() {
|
|
|
9965
9965
|
* only enters the graph as a separate chunk fetched on first connect (module-
|
|
9966
9966
|
* cached thereafter — `switchStore`'s await is instant).
|
|
9967
9967
|
*/
|
|
9968
|
-
async function createLocalSurrealClient(logger) {
|
|
9968
|
+
async function createLocalSurrealClient(logger, createWorker) {
|
|
9969
9969
|
const { createWasmWorkerEngines } = await import("@surrealdb/wasm");
|
|
9970
9970
|
return new Surreal({
|
|
9971
9971
|
codecOptions: localCodecOptions,
|
|
9972
|
-
engines: applyDiagnostics(createWasmWorkerEngines(), ({ key, type, phase, ...other }) => {
|
|
9972
|
+
engines: applyDiagnostics(createWasmWorkerEngines(createWorker ? { createWorker } : void 0), ({ key, type, phase, ...other }) => {
|
|
9973
9973
|
if (phase === "progress" || phase === "after") logger.trace({
|
|
9974
9974
|
...other,
|
|
9975
9975
|
key,
|
|
@@ -10067,7 +10067,7 @@ var LocalDatabaseService = class extends AbstractDatabaseService {
|
|
|
10067
10067
|
Category: "sp00ky-client::LocalDatabaseService::connect"
|
|
10068
10068
|
}, "Connecting to local database");
|
|
10069
10069
|
this.registerUnloadClose();
|
|
10070
|
-
this.client = await createLocalSurrealClient(this.logger);
|
|
10070
|
+
this.client = await createLocalSurrealClient(this.logger, this.config.workers?.surreal);
|
|
10071
10071
|
await this.openWithRecovery(this.client, storeUrl, namespace, database, bucketId, store);
|
|
10072
10072
|
}
|
|
10073
10073
|
/**
|
|
@@ -10103,7 +10103,7 @@ var LocalDatabaseService = class extends AbstractDatabaseService {
|
|
|
10103
10103
|
}, "Reset in-memory local store for bucket switch");
|
|
10104
10104
|
return;
|
|
10105
10105
|
}
|
|
10106
|
-
const next = await createLocalSurrealClient(this.logger);
|
|
10106
|
+
const next = await createLocalSurrealClient(this.logger, this.config.workers?.surreal);
|
|
10107
10107
|
this.pendingSwitchClient = next;
|
|
10108
10108
|
try {
|
|
10109
10109
|
await this.openWithRecovery(next, bucketStoreUrl(bucketId), namespace, database, bucketId, store);
|
|
@@ -11604,9 +11604,9 @@ var WorkerSqliteTransport = class extends BaseTransport {
|
|
|
11604
11604
|
/** Fired when the worker reports it fenced itself after a leadership steal
|
|
11605
11605
|
* (see sqlite-worker.js). The engine must treat the store as gone. */
|
|
11606
11606
|
onLockLost = null;
|
|
11607
|
-
constructor(logger) {
|
|
11607
|
+
constructor(logger, createWorker) {
|
|
11608
11608
|
super(logger);
|
|
11609
|
-
this.worker = new Worker(new URL("./sqlite-worker.js", import.meta.url), { type: "module" });
|
|
11609
|
+
this.worker = createWorker?.() ?? new Worker(new URL("./sqlite-worker.js", import.meta.url), { type: "module" });
|
|
11610
11610
|
this.worker.onmessage = (ev) => {
|
|
11611
11611
|
if (ev.data?.type === "lock-lost") {
|
|
11612
11612
|
this.logger.error({
|
|
@@ -12069,7 +12069,7 @@ var SqliteCacheEngine = class {
|
|
|
12069
12069
|
*/
|
|
12070
12070
|
/** Seam for tests: swap in a fake transport instead of a real Worker. */
|
|
12071
12071
|
createTransport() {
|
|
12072
|
-
return new WorkerSqliteTransport(this.logger);
|
|
12072
|
+
return new WorkerSqliteTransport(this.logger, this.config.workers?.sqlite);
|
|
12073
12073
|
}
|
|
12074
12074
|
async openInternal(bucketId, extras) {
|
|
12075
12075
|
if (!this.transport || this.transport.kind !== "worker" || !this.transport.connected) {
|
|
@@ -17618,7 +17618,7 @@ function createTabsCoordinator(config, s, host) {
|
|
|
17618
17618
|
return new TabsCoordinator({
|
|
17619
17619
|
tabId: s.tabId,
|
|
17620
17620
|
fingerprint: computeTabsFingerprint({
|
|
17621
|
-
coreVersion: "0.0.1-canary.
|
|
17621
|
+
coreVersion: "0.0.1-canary.383",
|
|
17622
17622
|
schemaHash: hash53(config.schemaSurql),
|
|
17623
17623
|
endpoint: config.database.endpoint ?? "",
|
|
17624
17624
|
namespace: config.database.namespace,
|
package/dist/otel/index.d.ts
CHANGED
package/dist/types.d.ts
CHANGED
|
@@ -1613,6 +1613,29 @@ type Sp00kyQueryResultPromise = Promise<Sp00kyQueryResult>;
|
|
|
1613
1613
|
interface EventSubscriptionOptions {
|
|
1614
1614
|
priority?: number;
|
|
1615
1615
|
}
|
|
1616
|
+
/**
|
|
1617
|
+
* Factories for the local store's web workers (`database.workers`). Each one
|
|
1618
|
+
* must start a MODULE worker (`{ type: 'module' }`) whose entry imports the
|
|
1619
|
+
* module named below, bundled by the app's own build:
|
|
1620
|
+
*
|
|
1621
|
+
* ```ts
|
|
1622
|
+
* // sp00ky-surreal.worker.ts
|
|
1623
|
+
* import '@surrealdb/wasm/worker';
|
|
1624
|
+
*
|
|
1625
|
+
* // config
|
|
1626
|
+
* workers: {
|
|
1627
|
+
* surreal: () => new Worker(new URL('./sp00ky-surreal.worker', import.meta.url), { type: 'module' }),
|
|
1628
|
+
* }
|
|
1629
|
+
* ```
|
|
1630
|
+
*
|
|
1631
|
+
* A factory left out falls back to the built-in worker.
|
|
1632
|
+
*/
|
|
1633
|
+
interface LocalWorkers {
|
|
1634
|
+
/** The default engine's worker (`localEngine: 'surrealdb'`): runs `@surrealdb/wasm/worker`. */
|
|
1635
|
+
surreal?: () => Worker;
|
|
1636
|
+
/** The SQLite engine's worker (`localEngine: 'sqlite'`): runs `@spooky-sync/core/sqlite-worker`. */
|
|
1637
|
+
sqlite?: () => Worker;
|
|
1638
|
+
}
|
|
1616
1639
|
/**
|
|
1617
1640
|
* Configuration options for the Sp00ky client.
|
|
1618
1641
|
* @template S The schema structure type.
|
|
@@ -1663,6 +1686,13 @@ interface Sp00kyConfig<S extends SchemaStructure> {
|
|
|
1663
1686
|
* not retried). `0` disables. Defaults to `30_000`.
|
|
1664
1687
|
*/
|
|
1665
1688
|
localOpTimeoutMs?: number;
|
|
1689
|
+
/**
|
|
1690
|
+
* Start the local store's web worker yourself. Only needed under a bundler
|
|
1691
|
+
* that does not bundle a worker started inside a dependency, which is the
|
|
1692
|
+
* Angular CLI; Vite, Rollup and webpack bundle the built-in workers on
|
|
1693
|
+
* their own, so leave it unset there. See {@link LocalWorkers}.
|
|
1694
|
+
*/
|
|
1695
|
+
workers?: LocalWorkers;
|
|
1666
1696
|
};
|
|
1667
1697
|
/** The schema definition. */
|
|
1668
1698
|
schema: S;
|
|
@@ -2401,4 +2431,4 @@ interface Sp00kyChannel<S extends SchemaStructure, T extends string> extends Omi
|
|
|
2401
2431
|
delete<N extends T>(table: N, id: string): Promise<void>;
|
|
2402
2432
|
}
|
|
2403
2433
|
//#endregion
|
|
2404
|
-
export {
|
|
2434
|
+
export { WebPushInfo as $, ChannelScope 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, PeerRef as an, WebPushSyncOptions as at, QueryConfig as b, WebPushClientMessage as bt, LocalWorkers as c, unusedArgs as cn, WebPushUnsupportedReason as ct, MutationCallback as d, BridgeSignOutMessage as dt, ChannelState as en, WebPushMessage as et, MutationEvent as f, BridgeTokenMessage as ft, PinoTransmit as g, PushOp as gt, PhaseStat as h, PushNotificationAction as ht, EdgeDelta as i, ChannelsConfig as in, WebPushSupport as it, RecordVersionDiff as j, AuthEventTypes as jt, ReconnectConfig as k, AuthEventSystem as kt, MATERIALIZATION_SAMPLE_WINDOW as l, LogTap as ln, WebPushUpdateOptions as lt, PersistenceClient as m, PushNotification as mt, ConnectionState as n, ChannelTransport as nn, WebPushModule as nt, InlineRow as o, TransportHooks as on, WebPushSyncStatus as ot, MutationEventType as p, PUSH_PAYLOAD_VERSION as pt, PUSH_ENDPOINT_KEY as q, renewDelayMs as qt, DebounceOptions as r, ChannelTransportFactory as rn, WebPushSubscribeOptions as rt, Level$1 as s, matchesWhere as sn, WebPushUnsubscribeOptions as st, ChannelQuery as t, ChannelStatus as tn, WebPushMessageInput as tt, MembershipOutcome as u, Logger$1 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,8 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spooky-sync/core",
|
|
3
|
-
"version": "0.0.1-canary.
|
|
3
|
+
"version": "0.0.1-canary.383",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"sideEffects":
|
|
5
|
+
"sideEffects": [
|
|
6
|
+
"./dist/sqlite-worker.js"
|
|
7
|
+
],
|
|
6
8
|
"main": "./dist/index.js",
|
|
7
9
|
"types": "./dist/index.d.ts",
|
|
8
10
|
"exports": {
|
|
@@ -25,6 +27,10 @@
|
|
|
25
27
|
"./sw": {
|
|
26
28
|
"types": "./dist/sw.d.ts",
|
|
27
29
|
"import": "./dist/sw.js"
|
|
30
|
+
},
|
|
31
|
+
"./sqlite-worker": {
|
|
32
|
+
"types": "./dist/sqlite-worker.d.ts",
|
|
33
|
+
"import": "./dist/sqlite-worker.js"
|
|
28
34
|
}
|
|
29
35
|
},
|
|
30
36
|
"scripts": {
|
|
@@ -75,8 +81,8 @@
|
|
|
75
81
|
}
|
|
76
82
|
},
|
|
77
83
|
"dependencies": {
|
|
78
|
-
"@spooky-sync/query-builder": "0.0.1-canary.
|
|
79
|
-
"@spooky-sync/ssp-wasm": "0.0.1-canary.
|
|
84
|
+
"@spooky-sync/query-builder": "0.0.1-canary.383",
|
|
85
|
+
"@spooky-sync/ssp-wasm": "0.0.1-canary.383",
|
|
80
86
|
"@sqlite.org/sqlite-wasm": "3.53.0-build1",
|
|
81
87
|
"@surrealdb/wasm": "^3.1.0",
|
|
82
88
|
"@surrealdb/wasm-native": "^3.3.4",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Diagnostic} from 'surrealdb';
|
|
2
2
|
import { DEFAULT_LOCAL_OP_TIMEOUT_MS, LocalOpTimeoutError } from './errors';
|
|
3
3
|
import { applyDiagnostics, DateTime, RecordId, Surreal } from 'surrealdb';
|
|
4
|
-
import type { Sp00kyConfig } from '../../types';
|
|
4
|
+
import type { LocalWorkers, Sp00kyConfig } from '../../types';
|
|
5
5
|
import type { Logger } from '../logger/index';
|
|
6
6
|
import { AbstractDatabaseService } from './database';
|
|
7
7
|
import { createDatabaseEventSystem, DatabaseEventTypes } from './events/index';
|
|
@@ -61,12 +61,17 @@ function createBareSurrealClient(): Surreal {
|
|
|
61
61
|
* only enters the graph as a separate chunk fetched on first connect (module-
|
|
62
62
|
* cached thereafter — `switchStore`'s await is instant).
|
|
63
63
|
*/
|
|
64
|
-
async function createLocalSurrealClient(
|
|
64
|
+
async function createLocalSurrealClient(
|
|
65
|
+
logger: Logger,
|
|
66
|
+
createWorker: LocalWorkers['surreal']
|
|
67
|
+
): Promise<Surreal> {
|
|
65
68
|
const { createWasmWorkerEngines } = await import('@surrealdb/wasm');
|
|
66
69
|
return new Surreal({
|
|
67
70
|
codecOptions: localCodecOptions,
|
|
68
71
|
engines: applyDiagnostics(
|
|
69
|
-
|
|
72
|
+
// An app-supplied worker (`database.workers.surreal`) for bundlers that
|
|
73
|
+
// do not bundle the engine's own `new Worker(new URL(...))`.
|
|
74
|
+
createWasmWorkerEngines(createWorker ? { createWorker } : undefined),
|
|
70
75
|
({ key, type, phase, ...other }: Diagnostic) => {
|
|
71
76
|
if (phase === 'progress' || phase === 'after') {
|
|
72
77
|
logger.trace(
|
|
@@ -201,7 +206,7 @@ export class LocalDatabaseService extends AbstractDatabaseService {
|
|
|
201
206
|
// Build the real engine-backed client lazily here (first `@surrealdb/wasm`
|
|
202
207
|
// load), replacing the constructor's engine-less placeholder before any
|
|
203
208
|
// query runs.
|
|
204
|
-
this.client = await createLocalSurrealClient(this.logger);
|
|
209
|
+
this.client = await createLocalSurrealClient(this.logger, this.config.workers?.surreal);
|
|
205
210
|
await this.openWithRecovery(this.client, storeUrl, namespace, database, bucketId, store);
|
|
206
211
|
}
|
|
207
212
|
|
|
@@ -246,7 +251,7 @@ export class LocalDatabaseService extends AbstractDatabaseService {
|
|
|
246
251
|
return;
|
|
247
252
|
}
|
|
248
253
|
|
|
249
|
-
const next = await createLocalSurrealClient(this.logger);
|
|
254
|
+
const next = await createLocalSurrealClient(this.logger, this.config.workers?.surreal);
|
|
250
255
|
this.pendingSwitchClient = next;
|
|
251
256
|
try {
|
|
252
257
|
await this.openWithRecovery(
|
|
@@ -399,7 +399,7 @@ export class SqliteCacheEngine implements LocalStore {
|
|
|
399
399
|
*/
|
|
400
400
|
/** Seam for tests: swap in a fake transport instead of a real Worker. */
|
|
401
401
|
protected createTransport(): SqliteTransport {
|
|
402
|
-
return new WorkerSqliteTransport(this.logger);
|
|
402
|
+
return new WorkerSqliteTransport(this.logger, this.config.workers?.sqlite);
|
|
403
403
|
}
|
|
404
404
|
|
|
405
405
|
private async openInternal(
|
|
@@ -104,7 +104,7 @@ export class WorkerSqliteTransport extends BaseTransport {
|
|
|
104
104
|
* (see sqlite-worker.ts). The engine must treat the store as gone. */
|
|
105
105
|
onLockLost: ((reason: string) => void) | null = null;
|
|
106
106
|
|
|
107
|
-
constructor(logger: Logger) {
|
|
107
|
+
constructor(logger: Logger, createWorker?: () => Worker) {
|
|
108
108
|
super(logger);
|
|
109
109
|
// Source references the `.ts` so the monorepo's src-bundling consumers
|
|
110
110
|
// (e.g. the example app, which aliases `@spooky-sync/core` to `src`)
|
|
@@ -113,7 +113,12 @@ export class WorkerSqliteTransport extends BaseTransport {
|
|
|
113
113
|
// emitted entry; see tsdown.config.ts), which the flat `dist/index.js`
|
|
114
114
|
// resolves. The worker (+ `@sqlite.org/sqlite-wasm`) still loads lazily —
|
|
115
115
|
// only when `localEngine: 'sqlite'` is used.
|
|
116
|
-
|
|
116
|
+
// `createWorker` (`database.workers.sqlite`) is for bundlers that do not
|
|
117
|
+
// bundle this expression from a dependency (the Angular CLI); it starts
|
|
118
|
+
// the same entry, `@spooky-sync/core/sqlite-worker`, bundled by the app.
|
|
119
|
+
this.worker =
|
|
120
|
+
createWorker?.() ??
|
|
121
|
+
new Worker(new URL('./sqlite-worker.ts', import.meta.url), { type: 'module' });
|
|
117
122
|
this.worker.onmessage = (ev: MessageEvent) => {
|
|
118
123
|
// Unsolicited worker-initiated notification, not a reply.
|
|
119
124
|
if (ev.data?.type === 'lock-lost') {
|
package/src/types.ts
CHANGED
|
@@ -104,6 +104,30 @@ export interface EventSubscriptionOptions {
|
|
|
104
104
|
priority?: number;
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
+
/**
|
|
108
|
+
* Factories for the local store's web workers (`database.workers`). Each one
|
|
109
|
+
* must start a MODULE worker (`{ type: 'module' }`) whose entry imports the
|
|
110
|
+
* module named below, bundled by the app's own build:
|
|
111
|
+
*
|
|
112
|
+
* ```ts
|
|
113
|
+
* // sp00ky-surreal.worker.ts
|
|
114
|
+
* import '@surrealdb/wasm/worker';
|
|
115
|
+
*
|
|
116
|
+
* // config
|
|
117
|
+
* workers: {
|
|
118
|
+
* surreal: () => new Worker(new URL('./sp00ky-surreal.worker', import.meta.url), { type: 'module' }),
|
|
119
|
+
* }
|
|
120
|
+
* ```
|
|
121
|
+
*
|
|
122
|
+
* A factory left out falls back to the built-in worker.
|
|
123
|
+
*/
|
|
124
|
+
export interface LocalWorkers {
|
|
125
|
+
/** The default engine's worker (`localEngine: 'surrealdb'`): runs `@surrealdb/wasm/worker`. */
|
|
126
|
+
surreal?: () => Worker;
|
|
127
|
+
/** The SQLite engine's worker (`localEngine: 'sqlite'`): runs `@spooky-sync/core/sqlite-worker`. */
|
|
128
|
+
sqlite?: () => Worker;
|
|
129
|
+
}
|
|
130
|
+
|
|
107
131
|
/**
|
|
108
132
|
* Configuration options for the Sp00ky client.
|
|
109
133
|
* @template S The schema structure type.
|
|
@@ -154,6 +178,13 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
|
|
|
154
178
|
* not retried). `0` disables. Defaults to `30_000`.
|
|
155
179
|
*/
|
|
156
180
|
localOpTimeoutMs?: number;
|
|
181
|
+
/**
|
|
182
|
+
* Start the local store's web worker yourself. Only needed under a bundler
|
|
183
|
+
* that does not bundle a worker started inside a dependency, which is the
|
|
184
|
+
* Angular CLI; Vite, Rollup and webpack bundle the built-in workers on
|
|
185
|
+
* their own, so leave it unset there. See {@link LocalWorkers}.
|
|
186
|
+
*/
|
|
187
|
+
workers?: LocalWorkers;
|
|
157
188
|
};
|
|
158
189
|
/** The schema definition. */
|
|
159
190
|
schema: S;
|