@syncular/client 0.1.2 → 0.2.0
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/README.md +227 -709
- package/dist/apply.d.ts +80 -0
- package/dist/apply.js +301 -0
- package/dist/blob.d.ts +127 -0
- package/dist/blob.js +201 -0
- package/dist/bun-database.d.ts +22 -0
- package/dist/bun-database.js +61 -0
- package/dist/client.d.ts +320 -69
- package/dist/client.js +1627 -163
- package/dist/content-type.d.ts +2 -0
- package/dist/content-type.js +2 -0
- package/dist/database.d.ts +35 -80
- package/dist/database.js +32 -947
- package/dist/encryption.d.ts +47 -0
- package/dist/encryption.js +75 -0
- package/dist/errors.d.ts +8 -22
- package/dist/errors.js +10 -207
- package/dist/http.d.ts +32 -0
- package/dist/http.js +196 -0
- package/dist/index.d.ts +28 -16
- package/dist/index.js +25 -12
- package/dist/invalidation.d.ts +69 -0
- package/dist/invalidation.js +84 -0
- package/dist/leader-lock.d.ts +28 -0
- package/dist/leader-lock.js +38 -0
- package/dist/multi-tab.d.ts +134 -0
- package/dist/multi-tab.js +399 -0
- package/dist/node-database.d.ts +41 -0
- package/dist/node-database.js +133 -0
- package/dist/outbox.d.ts +56 -0
- package/dist/outbox.js +140 -0
- package/dist/schema.d.ts +107 -0
- package/dist/schema.js +267 -0
- package/dist/state.d.ts +40 -0
- package/dist/state.js +77 -0
- package/dist/transport.d.ts +44 -0
- package/dist/transport.js +7 -0
- package/dist/wasm-database.d.ts +30 -0
- package/dist/wasm-database.js +170 -0
- package/dist/window.d.ts +64 -0
- package/dist/window.js +0 -0
- package/dist/worker-entry.d.ts +16 -2
- package/dist/worker-entry.js +300 -456
- package/dist/worker-host.d.ts +174 -0
- package/dist/worker-host.js +536 -0
- package/dist/worker-protocol.d.ts +173 -61
- package/dist/worker-protocol.js +7 -16
- package/package.json +45 -112
- package/src/apply.ts +435 -0
- package/src/blob.ts +333 -0
- package/src/bun-database.ts +75 -0
- package/src/client.ts +2247 -277
- package/src/content-type.ts +2 -0
- package/src/database.ts +63 -1389
- package/src/encryption.ts +123 -0
- package/src/errors.ts +11 -265
- package/src/http.ts +254 -0
- package/src/index.ts +25 -20
- package/src/invalidation.ts +128 -0
- package/src/leader-lock.ts +68 -0
- package/src/multi-tab.ts +550 -0
- package/src/node-database.ts +180 -0
- package/src/outbox.ts +206 -0
- package/src/schema.ts +397 -0
- package/src/state.ts +126 -0
- package/src/transport.ts +52 -0
- package/src/wasm-database.ts +279 -0
- package/src/window.ts +0 -0
- package/src/worker-entry.ts +391 -545
- package/src/worker-host.ts +800 -0
- package/src/worker-protocol.ts +204 -99
- package/dist/auth-leases.d.ts +0 -11
- package/dist/auth-leases.d.ts.map +0 -1
- package/dist/auth-leases.js +0 -140
- package/dist/auth-leases.js.map +0 -1
- package/dist/blob-limits.d.ts +0 -15
- package/dist/blob-limits.d.ts.map +0 -1
- package/dist/blob-limits.js +0 -66
- package/dist/blob-limits.js.map +0 -1
- package/dist/bridge-client.d.ts +0 -69
- package/dist/bridge-client.d.ts.map +0 -1
- package/dist/bridge-client.js +0 -282
- package/dist/bridge-client.js.map +0 -1
- package/dist/client-config.d.ts +0 -6
- package/dist/client-config.d.ts.map +0 -1
- package/dist/client-config.js +0 -18
- package/dist/client-config.js.map +0 -1
- package/dist/client.d.ts.map +0 -1
- package/dist/client.js.map +0 -1
- package/dist/command-history.d.ts +0 -35
- package/dist/command-history.d.ts.map +0 -1
- package/dist/command-history.js +0 -378
- package/dist/command-history.js.map +0 -1
- package/dist/console-diagnostics.d.ts +0 -33
- package/dist/console-diagnostics.d.ts.map +0 -1
- package/dist/console-diagnostics.js +0 -496
- package/dist/console-diagnostics.js.map +0 -1
- package/dist/crdt-yjs/index.d.ts +0 -4
- package/dist/crdt-yjs/index.d.ts.map +0 -1
- package/dist/crdt-yjs/index.js +0 -4
- package/dist/crdt-yjs/index.js.map +0 -1
- package/dist/crdt-yjs/webview-host-facade.d.ts +0 -126
- package/dist/crdt-yjs/webview-host-facade.d.ts.map +0 -1
- package/dist/crdt-yjs/webview-host-facade.js +0 -284
- package/dist/crdt-yjs/webview-host-facade.js.map +0 -1
- package/dist/crdt-yjs/yjs-document-field-adapter.d.ts +0 -153
- package/dist/crdt-yjs/yjs-document-field-adapter.d.ts.map +0 -1
- package/dist/crdt-yjs/yjs-document-field-adapter.js +0 -406
- package/dist/crdt-yjs/yjs-document-field-adapter.js.map +0 -1
- package/dist/crdt-yjs/yjs-prosemirror-bridge.d.ts +0 -73
- package/dist/crdt-yjs/yjs-prosemirror-bridge.d.ts.map +0 -1
- package/dist/crdt-yjs/yjs-prosemirror-bridge.js +0 -169
- package/dist/crdt-yjs/yjs-prosemirror-bridge.js.map +0 -1
- package/dist/database.d.ts.map +0 -1
- package/dist/database.js.map +0 -1
- package/dist/diagnostics.d.ts +0 -10
- package/dist/diagnostics.d.ts.map +0 -1
- package/dist/diagnostics.js +0 -83
- package/dist/diagnostics.js.map +0 -1
- package/dist/errors.d.ts.map +0 -1
- package/dist/errors.js.map +0 -1
- package/dist/generated-bridge.d.ts +0 -365
- package/dist/generated-bridge.d.ts.map +0 -1
- package/dist/generated-bridge.js +0 -250
- package/dist/generated-bridge.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/mutations.d.ts +0 -72
- package/dist/mutations.d.ts.map +0 -1
- package/dist/mutations.js +0 -63
- package/dist/mutations.js.map +0 -1
- package/dist/network.d.ts +0 -3
- package/dist/network.d.ts.map +0 -1
- package/dist/network.js +0 -17
- package/dist/network.js.map +0 -1
- package/dist/react/index.d.ts +0 -169
- package/dist/react/index.d.ts.map +0 -1
- package/dist/react/index.js +0 -628
- package/dist/react/index.js.map +0 -1
- package/dist/react-native/index.d.ts +0 -35
- package/dist/react-native/index.d.ts.map +0 -1
- package/dist/react-native/index.js +0 -49
- package/dist/react-native/index.js.map +0 -1
- package/dist/runtime-contract.d.ts +0 -13
- package/dist/runtime-contract.d.ts.map +0 -1
- package/dist/runtime-contract.js +0 -24
- package/dist/runtime-contract.js.map +0 -1
- package/dist/rust-client.d.ts +0 -106
- package/dist/rust-client.d.ts.map +0 -1
- package/dist/rust-client.js +0 -938
- package/dist/rust-client.js.map +0 -1
- package/dist/sentry.d.ts +0 -35
- package/dist/sentry.d.ts.map +0 -1
- package/dist/sentry.js +0 -155
- package/dist/sentry.js.map +0 -1
- package/dist/sql-safety.d.ts +0 -3
- package/dist/sql-safety.d.ts.map +0 -1
- package/dist/sql-safety.js +0 -62
- package/dist/sql-safety.js.map +0 -1
- package/dist/syncular-runtime-artifacts.json +0 -61
- package/dist/tauri/index.d.ts +0 -35
- package/dist/tauri/index.d.ts.map +0 -1
- package/dist/tauri/index.js +0 -114
- package/dist/tauri/index.js.map +0 -1
- package/dist/types.d.ts +0 -1096
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js +0 -2
- package/dist/types.js.map +0 -1
- package/dist/wasm/.syncular-wasm-profile +0 -1
- package/dist/wasm/syncular-runtime-artifact.json +0 -21
- package/dist/wasm/syncular.d.ts +0 -207
- package/dist/wasm/syncular.js +0 -2341
- package/dist/wasm/syncular_bg.wasm +0 -0
- package/dist/wasm/syncular_bg.wasm.d.ts +0 -97
- package/dist/wasm-bindings/runtime-contract.d.ts +0 -22
- package/dist/wasm-bindings/runtime-contract.d.ts.map +0 -1
- package/dist/wasm-bindings/runtime-contract.js +0 -112
- package/dist/wasm-bindings/runtime-contract.js.map +0 -1
- package/dist/wasm-core/.syncular-wasm-profile +0 -1
- package/dist/wasm-core/syncular-runtime-artifact.json +0 -17
- package/dist/wasm-core/syncular.d.ts +0 -162
- package/dist/wasm-core/syncular.js +0 -1847
- package/dist/wasm-core/syncular_bg.wasm +0 -0
- package/dist/wasm-core/syncular_bg.wasm.d.ts +0 -77
- package/dist/wasm-perf/.syncular-wasm-profile +0 -1
- package/dist/wasm-perf/syncular-runtime-artifact.json +0 -21
- package/dist/wasm-perf/syncular.d.ts +0 -207
- package/dist/wasm-perf/syncular.js +0 -2341
- package/dist/wasm-perf/syncular_bg.wasm +0 -0
- package/dist/wasm-perf/syncular_bg.wasm.d.ts +0 -97
- package/dist/wasm-runtime.d.ts +0 -23
- package/dist/wasm-runtime.d.ts.map +0 -1
- package/dist/wasm-runtime.js +0 -69
- package/dist/wasm-runtime.js.map +0 -1
- package/dist/worker-client.d.ts +0 -123
- package/dist/worker-client.d.ts.map +0 -1
- package/dist/worker-client.js +0 -1735
- package/dist/worker-client.js.map +0 -1
- package/dist/worker-entry.d.ts.map +0 -1
- package/dist/worker-entry.js.map +0 -1
- package/dist/worker-protocol.d.ts.map +0 -1
- package/dist/worker-protocol.js.map +0 -1
- package/dist/worker-realtime.d.ts +0 -39
- package/dist/worker-realtime.d.ts.map +0 -1
- package/dist/worker-realtime.js +0 -677
- package/dist/worker-realtime.js.map +0 -1
- package/src/auth-leases.ts +0 -251
- package/src/blob-limits.ts +0 -98
- package/src/bridge-client.ts +0 -512
- package/src/client-config.ts +0 -29
- package/src/command-history.ts +0 -623
- package/src/console-diagnostics.ts +0 -617
- package/src/crdt-yjs/index.ts +0 -3
- package/src/crdt-yjs/webview-host-facade.ts +0 -477
- package/src/crdt-yjs/yjs-document-field-adapter.ts +0 -733
- package/src/crdt-yjs/yjs-prosemirror-bridge.ts +0 -272
- package/src/diagnostics.ts +0 -116
- package/src/generated-bridge.ts +0 -741
- package/src/mutations.ts +0 -168
- package/src/network.ts +0 -32
- package/src/react/index.ts +0 -1036
- package/src/react-native/index.ts +0 -152
- package/src/runtime-contract.ts +0 -48
- package/src/rust-client.ts +0 -1491
- package/src/sentry.ts +0 -215
- package/src/sql-safety.ts +0 -61
- package/src/tauri/index.ts +0 -211
- package/src/types.ts +0 -1397
- package/src/wasm-bindings/generated-wasm-bindings.d.ts +0 -70
- package/src/wasm-bindings/runtime-contract.ts +0 -158
- package/src/wasm-runtime.ts +0 -145
- package/src/worker-client.ts +0 -2289
- package/src/worker-realtime.ts +0 -843
package/src/database.ts
CHANGED
|
@@ -1,1396 +1,70 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
CompiledQuery as KyselyCompiledQuery,
|
|
18
|
-
type QueryResult,
|
|
19
|
-
} from 'kysely';
|
|
20
|
-
import { BaseSqliteDialect, BaseSqliteDriver } from 'kysely-generic-sqlite';
|
|
21
|
-
import {
|
|
22
|
-
assertSyncularBlobPayloadLimit,
|
|
23
|
-
type SyncularBlobLimitInput,
|
|
24
|
-
syncularBlobInputSize,
|
|
25
|
-
} from './blob-limits';
|
|
26
|
-
import {
|
|
27
|
-
getSyncularClientStatus,
|
|
28
|
-
SyncularClientLifecycle,
|
|
29
|
-
type SyncularClientStatus,
|
|
30
|
-
type SyncularConflictsClientLike,
|
|
31
|
-
type SyncularPresenceClientLike,
|
|
32
|
-
} from './client';
|
|
33
|
-
import { createSyncularConsoleDiagnosticsPublisher } from './console-diagnostics';
|
|
34
|
-
import { isSyncularOfflineError } from './errors';
|
|
35
|
-
import {
|
|
36
|
-
createMutationsApi,
|
|
37
|
-
type MutationsApi,
|
|
38
|
-
type MutationsCommitFn,
|
|
39
|
-
type MutationsTx,
|
|
40
|
-
} from './mutations';
|
|
41
|
-
import { browserSyncularNetworkStatusSource } from './network';
|
|
42
|
-
import { assertSyncularReadonlySql } from './sql-safety';
|
|
43
|
-
import type {
|
|
44
|
-
CreateSyncularDatabaseOptions,
|
|
45
|
-
SyncularAuthLeaseRecord,
|
|
46
|
-
SyncularBlobStoreOptions,
|
|
47
|
-
SyncularBlobs,
|
|
48
|
-
SyncularClientEventSink,
|
|
49
|
-
SyncularClientEventType,
|
|
50
|
-
SyncularCrdtYjsFieldConfig,
|
|
51
|
-
SyncularDiagnosticSnapshot,
|
|
52
|
-
SyncularLiveQueries,
|
|
53
|
-
SyncularLiveQueryDependencyHint,
|
|
54
|
-
SyncularLiveQueryEvent,
|
|
55
|
-
SyncularLiveQueryOptions,
|
|
56
|
-
SyncularLiveQuerySubscription,
|
|
57
|
-
SyncularNetworkStatusSource,
|
|
58
|
-
SyncularRuntimeClient,
|
|
59
|
-
SyncularSqlClient,
|
|
60
|
-
SyncularSubscriptionSpec,
|
|
61
|
-
SyncularSyncRequestOptions,
|
|
62
|
-
SyncularSyncResult,
|
|
63
|
-
SyncularTableConfigMap,
|
|
64
|
-
SyncularUnsafeSqlClient,
|
|
65
|
-
} from './types';
|
|
66
|
-
import { createSyncularWorkerClient } from './worker-client';
|
|
67
|
-
|
|
68
|
-
type SyncularDriverClient = SyncularRuntimeClient &
|
|
69
|
-
Partial<SyncularUnsafeSqlClient>;
|
|
70
|
-
type SyncularConnectionClient = SyncularSqlClient &
|
|
71
|
-
Partial<SyncularUnsafeSqlClient>;
|
|
72
|
-
|
|
73
|
-
export interface SyncularDialect extends Dialect, SyncularLiveQueries {
|
|
74
|
-
destroyLiveQueries(): Promise<void>;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export interface SyncularDialectOptions {
|
|
78
|
-
appTables?: readonly string[];
|
|
79
|
-
tableConfig?: SyncularTableConfigMap;
|
|
80
|
-
unsafeWrites?: boolean;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export interface SyncularDatabase<DB> extends SyncularLiveQueries {
|
|
84
|
-
db: Kysely<DB>;
|
|
85
|
-
client: SyncularRuntimeClient;
|
|
86
|
-
dialect: SyncularDialect;
|
|
87
|
-
mutations: MutationsApi<DB, undefined>;
|
|
88
|
-
leasedMutations: MutationsApi<DB, undefined>;
|
|
89
|
-
blobs: SyncularBlobs;
|
|
1
|
+
/**
|
|
2
|
+
* Storage abstraction (REVISE B3): the client core runs on any SQLite that
|
|
3
|
+
* implements this minimal synchronous surface. Tests use bun:sqlite
|
|
4
|
+
* (`./bun-database`); browsers use sqlite-wasm + OPFS (`./wasm-database`).
|
|
5
|
+
* Methods are synchronous because both backends execute synchronously once
|
|
6
|
+
* open — only opening a database is async, which lives in the factories.
|
|
7
|
+
*/
|
|
8
|
+
export type SqlValue = string | number | bigint | boolean | Uint8Array | null;
|
|
9
|
+
|
|
10
|
+
export type SqlRow = Record<string, SqlValue>;
|
|
11
|
+
|
|
12
|
+
export interface ClientDatabase {
|
|
13
|
+
/** Execute a single statement (no result rows). */
|
|
14
|
+
exec(sql: string, params?: readonly SqlValue[]): void;
|
|
15
|
+
/** Execute a single statement and return its rows as objects. */
|
|
16
|
+
query(sql: string, params?: readonly SqlValue[]): SqlRow[];
|
|
90
17
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
* and stops on `close()`. Reach for it directly only for advanced control;
|
|
94
|
-
* `start`/`stop`/`sync` proxy to it.
|
|
18
|
+
* Run `fn` atomically. Nested calls are savepoints: an inner failure
|
|
19
|
+
* rolls back only the inner scope.
|
|
95
20
|
*/
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
)
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
): Promise<Result> {
|
|
130
|
-
const client = assertUnsafeSqlClient(database.client);
|
|
131
|
-
const dialect = createSyncularDialect(client, { unsafeWrites: true });
|
|
132
|
-
const db = new Kysely<any>({ dialect });
|
|
133
|
-
try {
|
|
134
|
-
return await callback(db);
|
|
135
|
-
} finally {
|
|
136
|
-
await dialect.destroyLiveQueries();
|
|
137
|
-
await db.destroy();
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
export interface SyncularMutationsMeta {
|
|
142
|
-
operations: SyncOperation[];
|
|
143
|
-
localMutations: Array<{
|
|
144
|
-
table: string;
|
|
145
|
-
rowId: string;
|
|
146
|
-
op: 'upsert' | 'delete';
|
|
147
|
-
}>;
|
|
148
|
-
clientCommitIds: string[];
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
export interface SyncularMutationsOptions {
|
|
152
|
-
client: Pick<
|
|
153
|
-
SyncularRuntimeClient,
|
|
154
|
-
| 'applyMutation'
|
|
155
|
-
| 'applyMutationsBatch'
|
|
156
|
-
| 'applyMutationsCommit'
|
|
157
|
-
| 'applyYjsEnvelopeToPayload'
|
|
158
|
-
| 'executeSql'
|
|
159
|
-
> &
|
|
160
|
-
Partial<
|
|
161
|
-
Pick<
|
|
162
|
-
SyncularRuntimeClient,
|
|
163
|
-
'applyLeasedMutation' | 'applyLeasedMutationsCommit'
|
|
164
|
-
>
|
|
165
|
-
>;
|
|
166
|
-
requireAuthLease?: boolean;
|
|
167
|
-
codecs?: ColumnCodecSource;
|
|
168
|
-
codecDialect?: ColumnCodecDialect;
|
|
169
|
-
idColumn?: string;
|
|
170
|
-
versionColumn?: string | null;
|
|
171
|
-
omitColumns?: string[];
|
|
172
|
-
tableConfig?: SyncularTableConfigMap;
|
|
173
|
-
readBaseVersion?: (args: {
|
|
174
|
-
table: string;
|
|
175
|
-
rowId: string;
|
|
176
|
-
idColumn: string;
|
|
177
|
-
versionColumn: string;
|
|
178
|
-
}) => Promise<number | null>;
|
|
179
|
-
afterCommit?: (meta: SyncularMutationsMeta) => void | Promise<void>;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
export async function createSyncularDatabase<DB>(
|
|
183
|
-
options: CreateSyncularDatabaseOptions
|
|
184
|
-
): Promise<SyncularDatabase<DB>> {
|
|
185
|
-
const client = await createSyncularWorkerClient(options);
|
|
186
|
-
const dialect = createSyncularDialect(client, {
|
|
187
|
-
appTables: options.appTables,
|
|
188
|
-
tableConfig: options.tableConfig,
|
|
189
|
-
});
|
|
190
|
-
const db = new Kysely<DB>({
|
|
191
|
-
dialect,
|
|
192
|
-
plugins: options.codecs
|
|
193
|
-
? [
|
|
194
|
-
createColumnCodecsPlugin({
|
|
195
|
-
codecs: options.codecs,
|
|
196
|
-
dialect: 'sqlite',
|
|
197
|
-
}),
|
|
198
|
-
]
|
|
199
|
-
: undefined,
|
|
200
|
-
});
|
|
201
|
-
let closed = false;
|
|
202
|
-
const localClientMode = (options.config.mode ?? 'remote') !== 'remote';
|
|
203
|
-
const mutationSyncScheduler = createMutationSyncScheduler(client, {
|
|
204
|
-
enabled: options.sync?.autoSyncAfterMutation ?? !localClientMode,
|
|
205
|
-
debounceMs: options.sync?.mutationSyncDebounceMs ?? 10,
|
|
206
|
-
network:
|
|
207
|
-
options.sync?.network === false
|
|
208
|
-
? undefined
|
|
209
|
-
: (options.sync?.network ?? browserSyncularNetworkStatusSource()),
|
|
210
|
-
isClosed: () => closed,
|
|
211
|
-
});
|
|
212
|
-
const blobUploadScheduler = createBlobUploadScheduler(client, {
|
|
213
|
-
enabled: options.sync?.autoProcessBlobUploadsAfterStore ?? false,
|
|
214
|
-
debounceMs: options.sync?.blobUploadDebounceMs ?? 10,
|
|
215
|
-
isClosed: () => closed,
|
|
216
|
-
});
|
|
217
|
-
const consoleDiagnostics =
|
|
218
|
-
options.consoleDiagnostics === undefined ||
|
|
219
|
-
options.consoleDiagnostics === false
|
|
220
|
-
? undefined
|
|
221
|
-
: createSyncularConsoleDiagnosticsPublisher(client, {
|
|
222
|
-
...(options.consoleDiagnostics === true
|
|
223
|
-
? {}
|
|
224
|
-
: options.consoleDiagnostics),
|
|
225
|
-
config: options.config,
|
|
226
|
-
isClosed: () => closed,
|
|
227
|
-
});
|
|
228
|
-
const mutations = createSyncularMutations<DB>({
|
|
229
|
-
client,
|
|
230
|
-
codecs: options.codecs,
|
|
231
|
-
codecDialect: 'sqlite',
|
|
232
|
-
tableConfig: options.tableConfig,
|
|
233
|
-
readBaseVersion: (args) => readCurrentBaseVersion(client, args),
|
|
234
|
-
afterCommit: () => mutationSyncScheduler.schedule(),
|
|
235
|
-
});
|
|
236
|
-
const leasedMutations = createSyncularMutations<DB>({
|
|
237
|
-
client,
|
|
238
|
-
requireAuthLease: true,
|
|
239
|
-
codecs: options.codecs,
|
|
240
|
-
codecDialect: 'sqlite',
|
|
241
|
-
tableConfig: options.tableConfig,
|
|
242
|
-
readBaseVersion: (args) => readCurrentBaseVersion(client, args),
|
|
243
|
-
afterCommit: () => mutationSyncScheduler.schedule(),
|
|
244
|
-
});
|
|
245
|
-
const blobs = createSyncularBlobClient(client, {
|
|
246
|
-
diagnostics: options.diagnostics,
|
|
247
|
-
limits: options.blobLimits,
|
|
248
|
-
afterStore: ({ options }) => {
|
|
249
|
-
if (options?.immediate) return;
|
|
250
|
-
blobUploadScheduler.schedule();
|
|
251
|
-
},
|
|
252
|
-
});
|
|
253
|
-
const lifecycle = new SyncularClientLifecycle(client, {
|
|
254
|
-
realtime: options.realtime ?? true,
|
|
255
|
-
initialSync: options.lifecycle?.initialSync,
|
|
256
|
-
syncOnRealtimeConnect: options.lifecycle?.syncOnRealtimeConnect,
|
|
257
|
-
pollIntervalMs: options.pollIntervalMs,
|
|
258
|
-
network: options.sync?.network,
|
|
259
|
-
});
|
|
260
|
-
|
|
261
|
-
const database: SyncularDatabase<DB> = {
|
|
262
|
-
db,
|
|
263
|
-
client,
|
|
264
|
-
dialect,
|
|
265
|
-
mutations,
|
|
266
|
-
leasedMutations,
|
|
267
|
-
blobs,
|
|
268
|
-
lifecycle,
|
|
269
|
-
live: (query, liveOptions) => dialect.live(query, liveOptions),
|
|
270
|
-
start: () => lifecycle.start(),
|
|
271
|
-
stop: () => lifecycle.stop(),
|
|
272
|
-
sync: () => lifecycle.sync(),
|
|
273
|
-
on: (event, listener) => client.addEventListener(event, listener),
|
|
274
|
-
getStatus: () => getSyncularClientStatus(client),
|
|
275
|
-
setSubscriptions: (subscriptions) => client.setSubscriptions(subscriptions),
|
|
276
|
-
resumeFromBackground: (syncOptions) =>
|
|
277
|
-
client.resumeFromBackground(syncOptions),
|
|
278
|
-
issueAuthLease: (request) => client.issueAuthLease(request),
|
|
279
|
-
upsertAuthLease: (lease) => client.upsertAuthLease(lease),
|
|
280
|
-
authLease: (leaseId) => client.authLease(leaseId),
|
|
281
|
-
activeAuthLeases: (actorId, nowMs) =>
|
|
282
|
-
client.activeAuthLeases(actorId, nowMs),
|
|
283
|
-
diagnosticSnapshot: () => client.diagnosticSnapshot(),
|
|
284
|
-
presence: {
|
|
285
|
-
get: (scopeKey) => client.getPresence(scopeKey),
|
|
286
|
-
join: (scopeKey, metadata) => client.joinPresence(scopeKey, metadata),
|
|
287
|
-
leave: (scopeKey) => client.leavePresence(scopeKey),
|
|
288
|
-
updateMetadata: (scopeKey, metadata) =>
|
|
289
|
-
client.updatePresenceMetadata(scopeKey, metadata),
|
|
290
|
-
onChange: (listener) => client.addPresenceListener(listener),
|
|
291
|
-
},
|
|
292
|
-
conflicts: {
|
|
293
|
-
list: () => client.conflictSummaries(),
|
|
294
|
-
retryKeepLocal: (id) => client.retryConflictKeepLocal(id),
|
|
295
|
-
resolve: (id, resolution) => client.resolveConflict(id, resolution),
|
|
296
|
-
},
|
|
297
|
-
async close() {
|
|
298
|
-
if (closed) return;
|
|
299
|
-
closed = true;
|
|
300
|
-
mutationSyncScheduler.destroy();
|
|
301
|
-
blobUploadScheduler.destroy();
|
|
302
|
-
consoleDiagnostics?.destroy();
|
|
303
|
-
try {
|
|
304
|
-
await lifecycle.stop().catch(() => undefined);
|
|
305
|
-
await dialect.destroyLiveQueries();
|
|
306
|
-
await db.destroy();
|
|
307
|
-
} finally {
|
|
308
|
-
await client.close();
|
|
309
|
-
}
|
|
310
|
-
},
|
|
311
|
-
};
|
|
312
|
-
|
|
21
|
+
transaction<T>(fn: () => T): T;
|
|
22
|
+
/**
|
|
23
|
+
* Optional sqlite-image capability (SPEC §5.3): expose `bytes` as an
|
|
24
|
+
* attached read-only database schema named `alias` for the duration of
|
|
25
|
+
* `fn`, then detach. Presence of this method is what makes the client
|
|
26
|
+
* advertise `accept` bit 2 (§4.2). MUST be called outside any open
|
|
27
|
+
* transaction (SQLite cannot ATTACH inside one); `fn` may open its own.
|
|
28
|
+
*/
|
|
29
|
+
withSqliteImage?<T>(bytes: Uint8Array, alias: string, fn: () => T): T;
|
|
30
|
+
close(): void;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Attach-schema aliases are code-chosen, never user input — enforce it. */
|
|
34
|
+
export function assertImageAlias(alias: string): void {
|
|
35
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(alias)) {
|
|
36
|
+
throw new Error(`invalid sqlite-image alias ${JSON.stringify(alias)}`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Savepoint-based transaction helper shared by database implementations.
|
|
42
|
+
* `run` executes a parameterless statement.
|
|
43
|
+
*/
|
|
44
|
+
export function runTransaction<T>(
|
|
45
|
+
depthHolder: { depth: number },
|
|
46
|
+
run: (sql: string) => void,
|
|
47
|
+
fn: () => T,
|
|
48
|
+
): T {
|
|
49
|
+
const depth = depthHolder.depth;
|
|
50
|
+
const savepoint = `syncular_sp_${depth}`;
|
|
51
|
+
if (depth === 0) run('BEGIN');
|
|
52
|
+
else run(`SAVEPOINT ${savepoint}`);
|
|
53
|
+
depthHolder.depth = depth + 1;
|
|
313
54
|
try {
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
}
|
|
55
|
+
const result = fn();
|
|
56
|
+
depthHolder.depth = depth;
|
|
57
|
+
if (depth === 0) run('COMMIT');
|
|
58
|
+
else run(`RELEASE ${savepoint}`);
|
|
59
|
+
return result;
|
|
320
60
|
} catch (error) {
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
function createMutationSyncScheduler(
|
|
329
|
-
client: Pick<SyncularRuntimeClient, 'syncOnce'>,
|
|
330
|
-
options: {
|
|
331
|
-
enabled: boolean;
|
|
332
|
-
debounceMs: number | false;
|
|
333
|
-
network: SyncularNetworkStatusSource | undefined;
|
|
334
|
-
isClosed: () => boolean;
|
|
335
|
-
}
|
|
336
|
-
): { schedule(): void; destroy(): void } {
|
|
337
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
338
|
-
let inFlight: Promise<void> | undefined;
|
|
339
|
-
let queued = false;
|
|
340
|
-
const isOnline = () => options.network?.isOnline() !== false;
|
|
341
|
-
const clear = () => {
|
|
342
|
-
if (timer) clearTimeout(timer);
|
|
343
|
-
timer = undefined;
|
|
344
|
-
};
|
|
345
|
-
const run = async () => {
|
|
346
|
-
if (options.isClosed()) return;
|
|
347
|
-
if (!isOnline()) {
|
|
348
|
-
queued = true;
|
|
349
|
-
return;
|
|
350
|
-
}
|
|
351
|
-
if (inFlight) {
|
|
352
|
-
queued = true;
|
|
353
|
-
return;
|
|
354
|
-
}
|
|
355
|
-
inFlight = client
|
|
356
|
-
.syncOnce()
|
|
357
|
-
.then(() => undefined)
|
|
358
|
-
.catch((error) => {
|
|
359
|
-
if (!isOnline() || isSyncularOfflineError(error)) queued = true;
|
|
360
|
-
})
|
|
361
|
-
.finally(() => {
|
|
362
|
-
inFlight = undefined;
|
|
363
|
-
if (queued && !options.isClosed() && isOnline()) {
|
|
364
|
-
queued = false;
|
|
365
|
-
schedule();
|
|
366
|
-
}
|
|
367
|
-
});
|
|
368
|
-
await inFlight;
|
|
369
|
-
};
|
|
370
|
-
const schedule = () => {
|
|
371
|
-
if (!options.enabled || options.isClosed()) return;
|
|
372
|
-
if (!isOnline()) {
|
|
373
|
-
queued = true;
|
|
374
|
-
clear();
|
|
375
|
-
return;
|
|
376
|
-
}
|
|
377
|
-
if (inFlight) {
|
|
378
|
-
queued = true;
|
|
379
|
-
return;
|
|
380
|
-
}
|
|
381
|
-
clear();
|
|
382
|
-
if (options.debounceMs === false || options.debounceMs <= 0) {
|
|
383
|
-
queueMicrotask(() => void run());
|
|
384
|
-
return;
|
|
385
|
-
}
|
|
386
|
-
timer = setTimeout(() => void run(), options.debounceMs);
|
|
387
|
-
};
|
|
388
|
-
const handleOnline = () => {
|
|
389
|
-
if (!queued || options.isClosed()) return;
|
|
390
|
-
queued = false;
|
|
391
|
-
schedule();
|
|
392
|
-
};
|
|
393
|
-
options.network?.addEventListener?.('online', handleOnline);
|
|
394
|
-
return {
|
|
395
|
-
schedule,
|
|
396
|
-
destroy() {
|
|
397
|
-
clear();
|
|
398
|
-
queued = false;
|
|
399
|
-
options.network?.removeEventListener?.('online', handleOnline);
|
|
400
|
-
},
|
|
401
|
-
};
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
function createBlobUploadScheduler(
|
|
405
|
-
client: Pick<SyncularRuntimeClient, 'processBlobUploadQueue'>,
|
|
406
|
-
options: {
|
|
407
|
-
enabled: boolean;
|
|
408
|
-
debounceMs: number | false;
|
|
409
|
-
isClosed: () => boolean;
|
|
410
|
-
}
|
|
411
|
-
): { schedule(): void; destroy(): void } {
|
|
412
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
413
|
-
let inFlight: Promise<void> | undefined;
|
|
414
|
-
let queued = false;
|
|
415
|
-
const clear = () => {
|
|
416
|
-
if (timer) clearTimeout(timer);
|
|
417
|
-
timer = undefined;
|
|
418
|
-
};
|
|
419
|
-
const run = async () => {
|
|
420
|
-
if (options.isClosed()) return;
|
|
421
|
-
if (inFlight) {
|
|
422
|
-
queued = true;
|
|
423
|
-
return;
|
|
424
|
-
}
|
|
425
|
-
inFlight = client
|
|
426
|
-
.processBlobUploadQueue()
|
|
427
|
-
.then(() => undefined)
|
|
428
|
-
.catch(() => undefined)
|
|
429
|
-
.finally(() => {
|
|
430
|
-
inFlight = undefined;
|
|
431
|
-
if (queued && !options.isClosed()) {
|
|
432
|
-
queued = false;
|
|
433
|
-
schedule();
|
|
434
|
-
}
|
|
435
|
-
});
|
|
436
|
-
await inFlight;
|
|
437
|
-
};
|
|
438
|
-
const schedule = () => {
|
|
439
|
-
if (!options.enabled || options.isClosed()) return;
|
|
440
|
-
if (inFlight) {
|
|
441
|
-
queued = true;
|
|
442
|
-
return;
|
|
443
|
-
}
|
|
444
|
-
clear();
|
|
445
|
-
if (options.debounceMs === false || options.debounceMs <= 0) {
|
|
446
|
-
queueMicrotask(() => void run());
|
|
447
|
-
return;
|
|
448
|
-
}
|
|
449
|
-
timer = setTimeout(() => void run(), options.debounceMs);
|
|
450
|
-
};
|
|
451
|
-
return {
|
|
452
|
-
schedule,
|
|
453
|
-
destroy() {
|
|
454
|
-
clear();
|
|
455
|
-
queued = false;
|
|
456
|
-
},
|
|
457
|
-
};
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
export function createSyncularBlobClient(
|
|
461
|
-
client: Pick<
|
|
462
|
-
SyncularRuntimeClient,
|
|
463
|
-
| 'storeBlob'
|
|
464
|
-
| 'retrieveBlob'
|
|
465
|
-
| 'isBlobLocal'
|
|
466
|
-
| 'processBlobUploadQueue'
|
|
467
|
-
| 'blobUploadQueueStats'
|
|
468
|
-
| 'blobCacheStats'
|
|
469
|
-
| 'pruneBlobCache'
|
|
470
|
-
| 'clearBlobCache'
|
|
471
|
-
>,
|
|
472
|
-
hooks: {
|
|
473
|
-
limits?: CreateSyncularDatabaseOptions['blobLimits'];
|
|
474
|
-
diagnostics?: CreateSyncularDatabaseOptions['diagnostics'];
|
|
475
|
-
afterStore?: (args: {
|
|
476
|
-
ref: BlobRef;
|
|
477
|
-
options?: SyncularBlobStoreOptions;
|
|
478
|
-
}) => void | Promise<void>;
|
|
479
|
-
} = {}
|
|
480
|
-
): SyncularBlobs {
|
|
481
|
-
const assertRetrieveWithinLimit = (ref: BlobRef) =>
|
|
482
|
-
assertSyncularBlobPayloadLimit({
|
|
483
|
-
operation: 'retrieve',
|
|
484
|
-
size: ref.size,
|
|
485
|
-
limits: hooks.limits,
|
|
486
|
-
refHash: ref.hash,
|
|
487
|
-
diagnostics: hooks.diagnostics,
|
|
488
|
-
});
|
|
489
|
-
return {
|
|
490
|
-
async store(data, storeOptions) {
|
|
491
|
-
assertSyncularBlobPayloadLimit({
|
|
492
|
-
operation: 'store',
|
|
493
|
-
size: syncularBlobInputSize(data as SyncularBlobLimitInput),
|
|
494
|
-
limits: hooks.limits,
|
|
495
|
-
options: storeOptions,
|
|
496
|
-
diagnostics: hooks.diagnostics,
|
|
497
|
-
});
|
|
498
|
-
const ref = await client.storeBlob(
|
|
499
|
-
await toUint8Array(data),
|
|
500
|
-
storeOptions
|
|
501
|
-
);
|
|
502
|
-
await hooks.afterStore?.({
|
|
503
|
-
ref,
|
|
504
|
-
...(storeOptions === undefined ? {} : { options: storeOptions }),
|
|
505
|
-
});
|
|
506
|
-
return ref;
|
|
507
|
-
},
|
|
508
|
-
async retrieve(ref) {
|
|
509
|
-
assertRetrieveWithinLimit(ref);
|
|
510
|
-
return client.retrieveBlob(ref);
|
|
511
|
-
},
|
|
512
|
-
isLocal(hash) {
|
|
513
|
-
return client.isBlobLocal(hash);
|
|
514
|
-
},
|
|
515
|
-
async preload(refs) {
|
|
516
|
-
for (const ref of refs) assertRetrieveWithinLimit(ref);
|
|
517
|
-
await Promise.all(refs.map((ref) => client.retrieveBlob(ref)));
|
|
518
|
-
},
|
|
519
|
-
processUploadQueue(options) {
|
|
520
|
-
return client.processBlobUploadQueue(options);
|
|
521
|
-
},
|
|
522
|
-
getUploadQueueStats() {
|
|
523
|
-
return client.blobUploadQueueStats();
|
|
524
|
-
},
|
|
525
|
-
getCacheStats() {
|
|
526
|
-
return client.blobCacheStats();
|
|
527
|
-
},
|
|
528
|
-
pruneCache(maxBytes) {
|
|
529
|
-
return client.pruneBlobCache(maxBytes);
|
|
530
|
-
},
|
|
531
|
-
clearCache() {
|
|
532
|
-
return client.clearBlobCache();
|
|
533
|
-
},
|
|
534
|
-
};
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
export function createSyncularDialect(
|
|
538
|
-
client: SyncularRuntimeClient,
|
|
539
|
-
options: SyncularDialectOptions = {}
|
|
540
|
-
): SyncularDialect {
|
|
541
|
-
const driver = new SyncularDriver(client, options);
|
|
542
|
-
const dialect = new BaseSqliteDialect(() => driver) as SyncularDialect;
|
|
543
|
-
dialect.live = (query, liveOptions) => driver.live(query, liveOptions);
|
|
544
|
-
dialect.destroyLiveQueries = () => driver.destroy();
|
|
545
|
-
return dialect;
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
export function createSyncularMutations<DB>(
|
|
549
|
-
options: SyncularMutationsOptions
|
|
550
|
-
): MutationsApi<DB, undefined> {
|
|
551
|
-
return createMutationsApi(createSyncularCommit<DB>(options));
|
|
552
|
-
}
|
|
553
|
-
|
|
554
|
-
export function createSyncularCommit<DB>(
|
|
555
|
-
options: SyncularMutationsOptions
|
|
556
|
-
): MutationsCommitFn<DB, SyncularMutationsMeta, undefined> {
|
|
557
|
-
const idColumn = options.idColumn ?? 'id';
|
|
558
|
-
const versionColumn = options.versionColumn ?? 'server_version';
|
|
559
|
-
const omitColumns = options.omitColumns ?? [];
|
|
560
|
-
const codecDialect = options.codecDialect ?? 'sqlite';
|
|
561
|
-
const resolveTableCodecs = createTableColumnCodecsResolver(options.codecs, {
|
|
562
|
-
dialect: codecDialect,
|
|
563
|
-
});
|
|
564
|
-
|
|
565
|
-
return async (fn) => {
|
|
566
|
-
const operations: SyncOperation[] = [];
|
|
567
|
-
const batch: Array<{
|
|
568
|
-
operation: SyncOperation;
|
|
569
|
-
localRow?: unknown | null;
|
|
570
|
-
}> = [];
|
|
571
|
-
const localMutations: SyncularMutationsMeta['localMutations'] = [];
|
|
572
|
-
const txTableCache = new Map<string, unknown>();
|
|
573
|
-
|
|
574
|
-
const makeTxTable = (table: string) => {
|
|
575
|
-
const cached = txTableCache.get(table);
|
|
576
|
-
if (cached) return cached;
|
|
577
|
-
const tableConfig = options.tableConfig?.[table];
|
|
578
|
-
const tableIdColumn = tableConfig?.primaryKeyColumn ?? idColumn;
|
|
579
|
-
const tableVersionColumn =
|
|
580
|
-
tableConfig?.serverVersionColumn === undefined
|
|
581
|
-
? versionColumn
|
|
582
|
-
: tableConfig.serverVersionColumn;
|
|
583
|
-
const softDeleteColumn = tableConfig?.softDeleteColumn ?? null;
|
|
584
|
-
const crdtYjsFields = serverMergeCrdtYjsFields(
|
|
585
|
-
tableConfig?.crdtYjsFields ?? []
|
|
586
|
-
);
|
|
587
|
-
|
|
588
|
-
const prepareInsert = async (values: unknown) => {
|
|
589
|
-
const raw = objectRecord(values);
|
|
590
|
-
const rawId = raw[tableIdColumn];
|
|
591
|
-
const id = typeof rawId === 'string' && rawId ? rawId : randomId();
|
|
592
|
-
const row = { ...raw, [tableIdColumn]: id };
|
|
593
|
-
const payload = sanitizeOperationPayload(row, {
|
|
594
|
-
omit: [
|
|
595
|
-
tableIdColumn,
|
|
596
|
-
...(tableVersionColumn ? [tableVersionColumn] : []),
|
|
597
|
-
...omitColumns,
|
|
598
|
-
],
|
|
599
|
-
});
|
|
600
|
-
const syncPayload = stripCrdtYjsMaterializedPayloadFields(
|
|
601
|
-
payload,
|
|
602
|
-
crdtYjsFields
|
|
603
|
-
);
|
|
604
|
-
const localPayload = sanitizeOperationPayload(row, {
|
|
605
|
-
omit: [
|
|
606
|
-
tableIdColumn,
|
|
607
|
-
...(tableVersionColumn ? [tableVersionColumn] : []),
|
|
608
|
-
],
|
|
609
|
-
});
|
|
610
|
-
const transformedLocalPayload = await transformCrdtYjsMutationPayload({
|
|
611
|
-
client: options.client,
|
|
612
|
-
table,
|
|
613
|
-
rowId: id,
|
|
614
|
-
payload: localPayload,
|
|
615
|
-
crdtYjsFields,
|
|
616
|
-
});
|
|
617
|
-
const localDbPayload = applyCodecsToDbRow(
|
|
618
|
-
transformedLocalPayload,
|
|
619
|
-
resolveTableCodecs(table, transformedLocalPayload),
|
|
620
|
-
codecDialect
|
|
621
|
-
);
|
|
622
|
-
const operation: SyncOperation = {
|
|
623
|
-
table,
|
|
624
|
-
row_id: id,
|
|
625
|
-
op: 'upsert',
|
|
626
|
-
payload: syncPayload,
|
|
627
|
-
base_version: null,
|
|
628
|
-
};
|
|
629
|
-
return {
|
|
630
|
-
id,
|
|
631
|
-
operation,
|
|
632
|
-
localRow: { ...localDbPayload, [tableIdColumn]: id },
|
|
633
|
-
};
|
|
634
|
-
};
|
|
635
|
-
|
|
636
|
-
const tableApi = {
|
|
637
|
-
async insert(values: unknown) {
|
|
638
|
-
const prepared = await prepareInsert(values);
|
|
639
|
-
const { id, operation, localRow } = prepared;
|
|
640
|
-
operations.push(operation);
|
|
641
|
-
batch.push({ operation, localRow });
|
|
642
|
-
localMutations.push({ table, rowId: id, op: 'upsert' });
|
|
643
|
-
return id;
|
|
644
|
-
},
|
|
645
|
-
async insertMany(rows: unknown[]) {
|
|
646
|
-
if (rows.length === 0) {
|
|
647
|
-
throw new Error('insertMany requires at least one row');
|
|
648
|
-
}
|
|
649
|
-
const ids: string[] = [];
|
|
650
|
-
for (const row of rows) {
|
|
651
|
-
const { id, operation, localRow } = await prepareInsert(row);
|
|
652
|
-
ids.push(id);
|
|
653
|
-
operations.push(operation);
|
|
654
|
-
batch.push({ operation, localRow });
|
|
655
|
-
localMutations.push({ table, rowId: id, op: 'upsert' });
|
|
656
|
-
}
|
|
657
|
-
return ids;
|
|
658
|
-
},
|
|
659
|
-
async update(
|
|
660
|
-
id: string,
|
|
661
|
-
patch: unknown,
|
|
662
|
-
opts?: { baseVersion?: number | null }
|
|
663
|
-
) {
|
|
664
|
-
await applyUpsert(id, patch, opts, { mergeExistingLocalRow: true });
|
|
665
|
-
},
|
|
666
|
-
async delete(id: string, opts?: { baseVersion?: number | null }) {
|
|
667
|
-
const baseVersion = await resolveBaseVersion({
|
|
668
|
-
options,
|
|
669
|
-
table,
|
|
670
|
-
rowId: id,
|
|
671
|
-
idColumn: tableIdColumn,
|
|
672
|
-
versionColumn: tableVersionColumn,
|
|
673
|
-
explicit: opts?.baseVersion,
|
|
674
|
-
});
|
|
675
|
-
if (softDeleteColumn) {
|
|
676
|
-
const payload = { [softDeleteColumn]: 1 };
|
|
677
|
-
const localDbPayload = applyCodecsToDbRow(
|
|
678
|
-
payload,
|
|
679
|
-
resolveTableCodecs(table, payload),
|
|
680
|
-
codecDialect
|
|
681
|
-
);
|
|
682
|
-
const operation: SyncOperation = {
|
|
683
|
-
table,
|
|
684
|
-
row_id: id,
|
|
685
|
-
op: 'upsert',
|
|
686
|
-
payload,
|
|
687
|
-
base_version: baseVersion,
|
|
688
|
-
};
|
|
689
|
-
operations.push(operation);
|
|
690
|
-
batch.push({
|
|
691
|
-
operation,
|
|
692
|
-
localRow: { ...localDbPayload, [tableIdColumn]: id },
|
|
693
|
-
});
|
|
694
|
-
localMutations.push({ table, rowId: id, op: 'upsert' });
|
|
695
|
-
return;
|
|
696
|
-
}
|
|
697
|
-
const operation: SyncOperation = {
|
|
698
|
-
table,
|
|
699
|
-
row_id: id,
|
|
700
|
-
op: 'delete',
|
|
701
|
-
payload: null,
|
|
702
|
-
base_version: baseVersion,
|
|
703
|
-
};
|
|
704
|
-
operations.push(operation);
|
|
705
|
-
batch.push({ operation, localRow: null });
|
|
706
|
-
localMutations.push({ table, rowId: id, op: 'delete' });
|
|
707
|
-
},
|
|
708
|
-
async upsert(
|
|
709
|
-
id: string,
|
|
710
|
-
patch: unknown,
|
|
711
|
-
opts?: { baseVersion?: number | null }
|
|
712
|
-
) {
|
|
713
|
-
await applyUpsert(id, patch, opts, { mergeExistingLocalRow: false });
|
|
714
|
-
},
|
|
715
|
-
};
|
|
716
|
-
|
|
717
|
-
const applyUpsert = async (
|
|
718
|
-
id: string,
|
|
719
|
-
patch: unknown,
|
|
720
|
-
opts: { baseVersion?: number | null } | undefined,
|
|
721
|
-
behavior: { mergeExistingLocalRow: boolean }
|
|
722
|
-
) => {
|
|
723
|
-
const rawPatch = objectRecord(patch);
|
|
724
|
-
const payload = sanitizeOperationPayload(rawPatch, {
|
|
725
|
-
omit: [
|
|
726
|
-
tableIdColumn,
|
|
727
|
-
...(tableVersionColumn ? [tableVersionColumn] : []),
|
|
728
|
-
...omitColumns,
|
|
729
|
-
],
|
|
730
|
-
});
|
|
731
|
-
const syncPayload = stripCrdtYjsMaterializedPayloadFields(
|
|
732
|
-
payload,
|
|
733
|
-
crdtYjsFields
|
|
734
|
-
);
|
|
735
|
-
const existingLocalRow = behavior.mergeExistingLocalRow
|
|
736
|
-
? await readExistingLocalRow({
|
|
737
|
-
client: options.client,
|
|
738
|
-
table,
|
|
739
|
-
rowId: id,
|
|
740
|
-
idColumn: tableIdColumn,
|
|
741
|
-
})
|
|
742
|
-
: null;
|
|
743
|
-
const rawLocalPayload = existingLocalRow
|
|
744
|
-
? { ...existingLocalRow, ...rawPatch }
|
|
745
|
-
: rawPatch;
|
|
746
|
-
const localPayload = sanitizeOperationPayload(rawLocalPayload, {
|
|
747
|
-
omit: [
|
|
748
|
-
tableIdColumn,
|
|
749
|
-
...(tableVersionColumn ? [tableVersionColumn] : []),
|
|
750
|
-
],
|
|
751
|
-
});
|
|
752
|
-
const existingRow = await readCrdtYjsExistingRow({
|
|
753
|
-
client: options.client,
|
|
754
|
-
table,
|
|
755
|
-
rowId: id,
|
|
756
|
-
idColumn: tableIdColumn,
|
|
757
|
-
crdtYjsFields,
|
|
758
|
-
});
|
|
759
|
-
const transformedLocalPayload = await transformCrdtYjsMutationPayload({
|
|
760
|
-
client: options.client,
|
|
761
|
-
table,
|
|
762
|
-
rowId: id,
|
|
763
|
-
payload: localPayload,
|
|
764
|
-
existingRow,
|
|
765
|
-
crdtYjsFields,
|
|
766
|
-
});
|
|
767
|
-
const localDbPayload = applyCodecsToDbRow(
|
|
768
|
-
transformedLocalPayload,
|
|
769
|
-
resolveTableCodecs(table, transformedLocalPayload),
|
|
770
|
-
codecDialect
|
|
771
|
-
);
|
|
772
|
-
const operation: SyncOperation = {
|
|
773
|
-
table,
|
|
774
|
-
row_id: id,
|
|
775
|
-
op: 'upsert',
|
|
776
|
-
payload: syncPayload,
|
|
777
|
-
base_version: await resolveBaseVersion({
|
|
778
|
-
options,
|
|
779
|
-
table,
|
|
780
|
-
rowId: id,
|
|
781
|
-
idColumn: tableIdColumn,
|
|
782
|
-
versionColumn: tableVersionColumn,
|
|
783
|
-
explicit: opts?.baseVersion,
|
|
784
|
-
}),
|
|
785
|
-
};
|
|
786
|
-
operations.push(operation);
|
|
787
|
-
batch.push({
|
|
788
|
-
operation,
|
|
789
|
-
localRow: { ...localDbPayload, [tableIdColumn]: id },
|
|
790
|
-
});
|
|
791
|
-
localMutations.push({ table, rowId: id, op: 'upsert' });
|
|
792
|
-
};
|
|
793
|
-
|
|
794
|
-
txTableCache.set(table, tableApi);
|
|
795
|
-
return tableApi;
|
|
796
|
-
};
|
|
797
|
-
|
|
798
|
-
const tx = new Proxy(
|
|
799
|
-
{},
|
|
800
|
-
{
|
|
801
|
-
get(_target, prop) {
|
|
802
|
-
if (prop === 'then') return undefined;
|
|
803
|
-
if (typeof prop !== 'string') return undefined;
|
|
804
|
-
return makeTxTable(prop);
|
|
805
|
-
},
|
|
806
|
-
}
|
|
807
|
-
);
|
|
808
|
-
|
|
809
|
-
const result = await fn(tx as MutationsTx<DB>);
|
|
810
|
-
if (operations.length === 0) throw new Error('No mutations were enqueued');
|
|
811
|
-
const clientCommitId = options.requireAuthLease
|
|
812
|
-
? await requireLeasedMutationClient(
|
|
813
|
-
options.client
|
|
814
|
-
).applyLeasedMutationsCommit(batch)
|
|
815
|
-
: await options.client.applyMutationsCommit(batch);
|
|
816
|
-
const meta = {
|
|
817
|
-
operations,
|
|
818
|
-
localMutations,
|
|
819
|
-
clientCommitIds: [clientCommitId],
|
|
820
|
-
};
|
|
821
|
-
await options.afterCommit?.(meta);
|
|
822
|
-
return {
|
|
823
|
-
result,
|
|
824
|
-
receipt: { commitId: clientCommitId, clientCommitId },
|
|
825
|
-
meta,
|
|
826
|
-
};
|
|
827
|
-
};
|
|
828
|
-
}
|
|
829
|
-
|
|
830
|
-
function requireLeasedMutationClient(
|
|
831
|
-
client: SyncularMutationsOptions['client']
|
|
832
|
-
): Required<
|
|
833
|
-
Pick<
|
|
834
|
-
SyncularRuntimeClient,
|
|
835
|
-
'applyLeasedMutation' | 'applyLeasedMutationsCommit'
|
|
836
|
-
>
|
|
837
|
-
> {
|
|
838
|
-
if (typeof client.applyLeasedMutationsCommit !== 'function') {
|
|
839
|
-
throw new Error(
|
|
840
|
-
'Syncular leased mutations require applyLeasedMutationsCommit support'
|
|
841
|
-
);
|
|
842
|
-
}
|
|
843
|
-
if (typeof client.applyLeasedMutation !== 'function') {
|
|
844
|
-
throw new Error(
|
|
845
|
-
'Syncular leased mutations require applyLeasedMutation support'
|
|
846
|
-
);
|
|
847
|
-
}
|
|
848
|
-
return client as Required<
|
|
849
|
-
Pick<
|
|
850
|
-
SyncularRuntimeClient,
|
|
851
|
-
'applyLeasedMutation' | 'applyLeasedMutationsCommit'
|
|
852
|
-
>
|
|
853
|
-
>;
|
|
854
|
-
}
|
|
855
|
-
|
|
856
|
-
class SyncularDriver extends BaseSqliteDriver {
|
|
857
|
-
#listeners = new Map<
|
|
858
|
-
string,
|
|
859
|
-
(event: SyncularLiveQueryEvent<Record<string, unknown>>) => void
|
|
860
|
-
>();
|
|
861
|
-
readonly #appTables: Set<string> | undefined;
|
|
862
|
-
readonly #tableConfig: SyncularTableConfigMap | undefined;
|
|
863
|
-
|
|
864
|
-
constructor(
|
|
865
|
-
private readonly client: SyncularDriverClient,
|
|
866
|
-
options: SyncularDialectOptions = {}
|
|
867
|
-
) {
|
|
868
|
-
super(async () => {
|
|
869
|
-
this.conn = new SyncularConnection(client, options.unsafeWrites ?? false);
|
|
870
|
-
});
|
|
871
|
-
this.#appTables =
|
|
872
|
-
options.appTables == null
|
|
873
|
-
? undefined
|
|
874
|
-
: new Set(normalizeLiveQueryTables(options.appTables));
|
|
875
|
-
this.#tableConfig = options.tableConfig;
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
async live<Row extends Record<string, unknown>>(
|
|
879
|
-
query: { compile(): CompiledQuery },
|
|
880
|
-
options: SyncularLiveQueryOptions<Row>
|
|
881
|
-
): Promise<SyncularLiveQuerySubscription> {
|
|
882
|
-
const compiled = query.compile();
|
|
883
|
-
const tables = normalizeLiveQueryTables(
|
|
884
|
-
options.tables ?? inferTablesFromCompiledQuery(compiled, this.#appTables),
|
|
885
|
-
this.#appTables
|
|
886
|
-
);
|
|
887
|
-
if (tables.length === 0) {
|
|
888
|
-
throw new Error(
|
|
889
|
-
'Could not infer live query table dependencies. Pass { tables: [...] } explicitly.'
|
|
890
|
-
);
|
|
61
|
+
depthHolder.depth = depth;
|
|
62
|
+
if (depth === 0) {
|
|
63
|
+
run('ROLLBACK');
|
|
64
|
+
} else {
|
|
65
|
+
run(`ROLLBACK TO ${savepoint}`);
|
|
66
|
+
run(`RELEASE ${savepoint}`);
|
|
891
67
|
}
|
|
892
|
-
|
|
893
|
-
options.dependencyHints ??
|
|
894
|
-
inferDependencyHintsFromCompiledQuery(
|
|
895
|
-
compiled,
|
|
896
|
-
tables,
|
|
897
|
-
this.#tableConfig
|
|
898
|
-
),
|
|
899
|
-
tables,
|
|
900
|
-
this.#appTables
|
|
901
|
-
);
|
|
902
|
-
const snapshot = await this.client.subscribeQuery<Row>(
|
|
903
|
-
compiled.sql,
|
|
904
|
-
compiled.parameters,
|
|
905
|
-
tables,
|
|
906
|
-
dependencyHints
|
|
907
|
-
);
|
|
908
|
-
const listener = (
|
|
909
|
-
event: SyncularLiveQueryEvent<Record<string, unknown>>
|
|
910
|
-
) => {
|
|
911
|
-
const typed = event as SyncularLiveQueryEvent<Row>;
|
|
912
|
-
options.onChange(typed.rows, { ...typed, initial: false });
|
|
913
|
-
};
|
|
914
|
-
this.#listeners.set(snapshot.id, listener);
|
|
915
|
-
this.client.addLiveQueryListener(snapshot.id, listener);
|
|
916
|
-
options.onChange(snapshot.rows, {
|
|
917
|
-
queryId: snapshot.id,
|
|
918
|
-
version: Date.now(),
|
|
919
|
-
changedRows: [],
|
|
920
|
-
rows: snapshot.rows,
|
|
921
|
-
initial: true,
|
|
922
|
-
});
|
|
923
|
-
|
|
924
|
-
return {
|
|
925
|
-
id: snapshot.id,
|
|
926
|
-
unsubscribe: () => {
|
|
927
|
-
void this.#unsubscribeQuery(snapshot.id).catch(() => undefined);
|
|
928
|
-
},
|
|
929
|
-
};
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
async beginTransaction(connection: DatabaseConnection): Promise<void> {
|
|
933
|
-
await connection.executeQuery(KyselyCompiledQuery.raw('begin'));
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
override async destroy(): Promise<void> {
|
|
937
|
-
const ids = [...this.#listeners.keys()];
|
|
938
|
-
for (const id of ids) this.client.removeLiveQueryListener(id);
|
|
939
|
-
this.#listeners.clear();
|
|
940
|
-
await Promise.allSettled(ids.map((id) => this.client.unsubscribeQuery(id)));
|
|
941
|
-
}
|
|
942
|
-
|
|
943
|
-
async #unsubscribeQuery(id: string): Promise<void> {
|
|
944
|
-
if (!this.#listeners.has(id)) return;
|
|
945
|
-
this.#listeners.delete(id);
|
|
946
|
-
this.client.removeLiveQueryListener(id);
|
|
947
|
-
await this.client.unsubscribeQuery(id);
|
|
948
|
-
}
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
class SyncularConnection implements DatabaseConnection {
|
|
952
|
-
constructor(
|
|
953
|
-
private readonly client: SyncularConnectionClient,
|
|
954
|
-
private readonly unsafeWrites: boolean
|
|
955
|
-
) {}
|
|
956
|
-
|
|
957
|
-
async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {
|
|
958
|
-
if (!this.unsafeWrites) assertSyncularReadonlySql(compiledQuery.sql);
|
|
959
|
-
const result = this.unsafeWrites
|
|
960
|
-
? await assertUnsafeSqlClient(this.client).executeUnsafeSql<
|
|
961
|
-
R & Record<string, unknown>
|
|
962
|
-
>(compiledQuery.sql, compiledQuery.parameters)
|
|
963
|
-
: await this.client.executeSql<R & Record<string, unknown>>(
|
|
964
|
-
compiledQuery.sql,
|
|
965
|
-
compiledQuery.parameters
|
|
966
|
-
);
|
|
967
|
-
return {
|
|
968
|
-
rows: result.rows as R[],
|
|
969
|
-
numAffectedRows:
|
|
970
|
-
result.numAffectedRows == null
|
|
971
|
-
? undefined
|
|
972
|
-
: BigInt(result.numAffectedRows),
|
|
973
|
-
insertId: result.insertId == null ? undefined : BigInt(result.insertId),
|
|
974
|
-
};
|
|
975
|
-
}
|
|
976
|
-
|
|
977
|
-
streamQuery<R>(
|
|
978
|
-
_compiledQuery: CompiledQuery,
|
|
979
|
-
_chunkSize?: number
|
|
980
|
-
): AsyncIterableIterator<QueryResult<R>> {
|
|
981
|
-
throw new Error('syncular sqlite dialect does not support streaming');
|
|
982
|
-
}
|
|
983
|
-
}
|
|
984
|
-
|
|
985
|
-
function assertUnsafeSqlClient<Client extends SyncularSqlClient>(
|
|
986
|
-
client: Client
|
|
987
|
-
): Client & SyncularUnsafeSqlClient {
|
|
988
|
-
const maybe = client as Partial<SyncularUnsafeSqlClient>;
|
|
989
|
-
if (typeof maybe.executeUnsafeSql === 'function') {
|
|
990
|
-
return client as Client & SyncularUnsafeSqlClient;
|
|
991
|
-
}
|
|
992
|
-
throw new Error(
|
|
993
|
-
'Syncular schema installation requires an internal unsafe SQL client.'
|
|
994
|
-
);
|
|
995
|
-
}
|
|
996
|
-
|
|
997
|
-
function objectRecord(value: unknown): Record<string, unknown> {
|
|
998
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
|
|
999
|
-
return { ...(value as Record<string, unknown>) };
|
|
1000
|
-
}
|
|
1001
|
-
|
|
1002
|
-
async function toUint8Array(
|
|
1003
|
-
data: Blob | File | Uint8Array
|
|
1004
|
-
): Promise<Uint8Array> {
|
|
1005
|
-
if (data instanceof Uint8Array) return data;
|
|
1006
|
-
return new Uint8Array(await data.arrayBuffer());
|
|
1007
|
-
}
|
|
1008
|
-
|
|
1009
|
-
function sanitizeOperationPayload(
|
|
1010
|
-
payload: Record<string, unknown>,
|
|
1011
|
-
args: { omit: readonly string[] }
|
|
1012
|
-
): Record<string, unknown> {
|
|
1013
|
-
if (args.omit.length === 0) return payload;
|
|
1014
|
-
const omit = new Set(args.omit);
|
|
1015
|
-
const out: Record<string, unknown> = {};
|
|
1016
|
-
for (const [key, value] of Object.entries(payload)) {
|
|
1017
|
-
if (!omit.has(key)) out[key] = value;
|
|
1018
|
-
}
|
|
1019
|
-
return out;
|
|
1020
|
-
}
|
|
1021
|
-
|
|
1022
|
-
function serverMergeCrdtYjsFields(
|
|
1023
|
-
fields: readonly SyncularCrdtYjsFieldConfig[]
|
|
1024
|
-
): readonly SyncularCrdtYjsFieldConfig[] {
|
|
1025
|
-
return fields.filter(
|
|
1026
|
-
(field) => field.syncMode === undefined || field.syncMode === 'server-merge'
|
|
1027
|
-
);
|
|
1028
|
-
}
|
|
1029
|
-
|
|
1030
|
-
async function transformCrdtYjsMutationPayload(args: {
|
|
1031
|
-
client: Pick<SyncularRuntimeClient, 'applyYjsEnvelopeToPayload'>;
|
|
1032
|
-
table: string;
|
|
1033
|
-
rowId: string;
|
|
1034
|
-
payload: Record<string, unknown>;
|
|
1035
|
-
existingRow?: Record<string, unknown> | null;
|
|
1036
|
-
crdtYjsFields: readonly SyncularCrdtYjsFieldConfig[];
|
|
1037
|
-
}): Promise<Record<string, unknown>> {
|
|
1038
|
-
if (args.crdtYjsFields.length === 0 || !('__yjs' in args.payload)) {
|
|
1039
|
-
return args.payload;
|
|
1040
|
-
}
|
|
1041
|
-
return args.client.applyYjsEnvelopeToPayload({
|
|
1042
|
-
table: args.table,
|
|
1043
|
-
rowId: args.rowId,
|
|
1044
|
-
payload: args.payload,
|
|
1045
|
-
existingRow: args.existingRow ?? null,
|
|
1046
|
-
rules: args.crdtYjsFields.map((field) => ({
|
|
1047
|
-
table: args.table,
|
|
1048
|
-
field: field.field,
|
|
1049
|
-
stateColumn: field.stateColumn,
|
|
1050
|
-
containerKey: field.containerKey ?? field.field,
|
|
1051
|
-
rowIdField: field.rowIdField ?? 'id',
|
|
1052
|
-
kind: field.kind ?? 'text',
|
|
1053
|
-
})),
|
|
1054
|
-
stripEnvelope: true,
|
|
1055
|
-
});
|
|
1056
|
-
}
|
|
1057
|
-
|
|
1058
|
-
function stripCrdtYjsMaterializedPayloadFields(
|
|
1059
|
-
payload: Record<string, unknown>,
|
|
1060
|
-
crdtYjsFields: readonly SyncularCrdtYjsFieldConfig[]
|
|
1061
|
-
): Record<string, unknown> {
|
|
1062
|
-
const envelope = objectRecord(payload.__yjs);
|
|
1063
|
-
if (crdtYjsFields.length === 0 || Object.keys(envelope).length === 0) {
|
|
1064
|
-
return payload;
|
|
1065
|
-
}
|
|
1066
|
-
let next: Record<string, unknown> | null = null;
|
|
1067
|
-
const ensureNext = () => {
|
|
1068
|
-
next ??= { ...payload };
|
|
1069
|
-
return next;
|
|
1070
|
-
};
|
|
1071
|
-
for (const field of crdtYjsFields) {
|
|
1072
|
-
if (!(field.field in envelope)) continue;
|
|
1073
|
-
delete ensureNext()[field.field];
|
|
1074
|
-
delete ensureNext()[field.stateColumn];
|
|
1075
|
-
}
|
|
1076
|
-
return next ?? payload;
|
|
1077
|
-
}
|
|
1078
|
-
|
|
1079
|
-
async function readCrdtYjsExistingRow(args: {
|
|
1080
|
-
client: Pick<SyncularRuntimeClient, 'executeSql'>;
|
|
1081
|
-
table: string;
|
|
1082
|
-
rowId: string;
|
|
1083
|
-
idColumn: string;
|
|
1084
|
-
crdtYjsFields: readonly SyncularCrdtYjsFieldConfig[];
|
|
1085
|
-
}): Promise<Record<string, unknown> | null> {
|
|
1086
|
-
if (args.crdtYjsFields.length === 0) return null;
|
|
1087
|
-
const columns = new Set<string>([args.idColumn]);
|
|
1088
|
-
for (const field of args.crdtYjsFields) {
|
|
1089
|
-
columns.add(field.field);
|
|
1090
|
-
columns.add(field.stateColumn);
|
|
1091
|
-
}
|
|
1092
|
-
const result = await args.client.executeSql(
|
|
1093
|
-
`select ${[...columns].map(quoteSqlIdentifier).join(', ')} from ${quoteSqlIdentifier(args.table)} where ${quoteSqlIdentifier(args.idColumn)} = ? limit 1`,
|
|
1094
|
-
[args.rowId]
|
|
1095
|
-
);
|
|
1096
|
-
return result.rows[0] ?? null;
|
|
1097
|
-
}
|
|
1098
|
-
|
|
1099
|
-
async function readExistingLocalRow(args: {
|
|
1100
|
-
client: Pick<SyncularRuntimeClient, 'executeSql'>;
|
|
1101
|
-
table: string;
|
|
1102
|
-
rowId: string;
|
|
1103
|
-
idColumn: string;
|
|
1104
|
-
}): Promise<Record<string, unknown> | null> {
|
|
1105
|
-
const result = await args.client.executeSql(
|
|
1106
|
-
`select * from ${quoteSqlIdentifier(args.table)} where ${quoteSqlIdentifier(args.idColumn)} = ? limit 1`,
|
|
1107
|
-
[args.rowId]
|
|
1108
|
-
);
|
|
1109
|
-
return result.rows[0] ?? null;
|
|
1110
|
-
}
|
|
1111
|
-
|
|
1112
|
-
function quoteSqlIdentifier(identifier: string): string {
|
|
1113
|
-
if (!identifier) throw new Error('SQLite identifier cannot be empty');
|
|
1114
|
-
return `"${identifier.replace(/"/g, '""')}"`;
|
|
1115
|
-
}
|
|
1116
|
-
|
|
1117
|
-
async function readCurrentBaseVersion(
|
|
1118
|
-
client: Pick<SyncularRuntimeClient, 'executeSql'>,
|
|
1119
|
-
args: {
|
|
1120
|
-
table: string;
|
|
1121
|
-
rowId: string;
|
|
1122
|
-
idColumn: string;
|
|
1123
|
-
versionColumn: string;
|
|
1124
|
-
}
|
|
1125
|
-
): Promise<number | null> {
|
|
1126
|
-
const result = await client.executeSql(
|
|
1127
|
-
`select ${quoteSqlIdentifier(args.versionColumn)} as version from ${quoteSqlIdentifier(args.table)} where ${quoteSqlIdentifier(args.idColumn)} = ? limit 1`,
|
|
1128
|
-
[args.rowId]
|
|
1129
|
-
);
|
|
1130
|
-
return coerceBaseVersion(result.rows[0]?.version);
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
|
-
function coerceBaseVersion(value: unknown): number | null {
|
|
1134
|
-
if (value == null) return null;
|
|
1135
|
-
const numeric = typeof value === 'number' ? value : Number(value);
|
|
1136
|
-
if (!Number.isFinite(numeric) || numeric < 0) return null;
|
|
1137
|
-
return numeric;
|
|
1138
|
-
}
|
|
1139
|
-
|
|
1140
|
-
async function resolveBaseVersion(args: {
|
|
1141
|
-
options: SyncularMutationsOptions;
|
|
1142
|
-
table: string;
|
|
1143
|
-
rowId: string;
|
|
1144
|
-
idColumn: string;
|
|
1145
|
-
versionColumn: string | null;
|
|
1146
|
-
explicit?: number | null;
|
|
1147
|
-
}): Promise<number | null> {
|
|
1148
|
-
if (args.explicit !== undefined) return coerceBaseVersion(args.explicit);
|
|
1149
|
-
if (!args.versionColumn) return null;
|
|
1150
|
-
const readBaseVersion =
|
|
1151
|
-
args.options.readBaseVersion ??
|
|
1152
|
-
((readArgs: {
|
|
1153
|
-
table: string;
|
|
1154
|
-
rowId: string;
|
|
1155
|
-
idColumn: string;
|
|
1156
|
-
versionColumn: string;
|
|
1157
|
-
}) => readCurrentBaseVersion(args.options.client, readArgs));
|
|
1158
|
-
return readBaseVersion({
|
|
1159
|
-
table: args.table,
|
|
1160
|
-
rowId: args.rowId,
|
|
1161
|
-
idColumn: args.idColumn,
|
|
1162
|
-
versionColumn: args.versionColumn,
|
|
1163
|
-
});
|
|
1164
|
-
}
|
|
1165
|
-
|
|
1166
|
-
function inferTablesFromCompiledQuery(
|
|
1167
|
-
query: CompiledQuery,
|
|
1168
|
-
appTables?: ReadonlySet<string>
|
|
1169
|
-
): string[] {
|
|
1170
|
-
const tables = new Set<string>();
|
|
1171
|
-
collectTables(query.query as OperationNodeLike, tables);
|
|
1172
|
-
return [...tables].filter(
|
|
1173
|
-
(table) => appTables == null || appTables.has(table)
|
|
1174
|
-
);
|
|
1175
|
-
}
|
|
1176
|
-
|
|
1177
|
-
function inferDependencyHintsFromCompiledQuery(
|
|
1178
|
-
query: CompiledQuery,
|
|
1179
|
-
tables: readonly string[],
|
|
1180
|
-
tableConfig?: SyncularTableConfigMap
|
|
1181
|
-
): SyncularLiveQueryDependencyHint[] {
|
|
1182
|
-
if (tables.length !== 1) return [];
|
|
1183
|
-
const table = tables[0]!;
|
|
1184
|
-
const primaryKey = tableConfig?.[table]?.primaryKeyColumn ?? 'id';
|
|
1185
|
-
const rowIds = primaryKeyEqualityValues(query.query, table, primaryKey);
|
|
1186
|
-
return rowIds.length > 0 ? [{ table, rowIds }] : [];
|
|
1187
|
-
}
|
|
1188
|
-
|
|
1189
|
-
function normalizeLiveQueryDependencyHints(
|
|
1190
|
-
hints: readonly SyncularLiveQueryDependencyHint[],
|
|
1191
|
-
tables: readonly string[],
|
|
1192
|
-
appTables?: ReadonlySet<string>
|
|
1193
|
-
): SyncularLiveQueryDependencyHint[] {
|
|
1194
|
-
const observedTables = new Set(tables);
|
|
1195
|
-
const normalized: SyncularLiveQueryDependencyHint[] = [];
|
|
1196
|
-
for (const hint of hints) {
|
|
1197
|
-
if (hint.table.length === 0) {
|
|
1198
|
-
throw new Error('Live query dependency hint tables must not be empty.');
|
|
1199
|
-
}
|
|
1200
|
-
if (!observedTables.has(hint.table)) {
|
|
1201
|
-
throw new Error(
|
|
1202
|
-
`Live query dependency hint table ${hint.table} is not one of the observed tables.`
|
|
1203
|
-
);
|
|
1204
|
-
}
|
|
1205
|
-
if (appTables != null && !appTables.has(hint.table)) {
|
|
1206
|
-
throw new Error(
|
|
1207
|
-
`Live query dependency hint table ${hint.table} is not part of the generated app schema.`
|
|
1208
|
-
);
|
|
1209
|
-
}
|
|
1210
|
-
const rowIds = uniqueDefinedStrings(hint.rowIds);
|
|
1211
|
-
const fields = uniqueDefinedStrings(hint.fields);
|
|
1212
|
-
normalized.push({
|
|
1213
|
-
table: hint.table,
|
|
1214
|
-
...(rowIds.length > 0 ? { rowIds } : {}),
|
|
1215
|
-
...(fields.length > 0 ? { fields } : {}),
|
|
1216
|
-
});
|
|
1217
|
-
}
|
|
1218
|
-
return normalized;
|
|
1219
|
-
}
|
|
1220
|
-
|
|
1221
|
-
function primaryKeyEqualityValues(
|
|
1222
|
-
query: unknown,
|
|
1223
|
-
table: string,
|
|
1224
|
-
primaryKey: string
|
|
1225
|
-
): string[] {
|
|
1226
|
-
if (!isOperationNode(query) || query.kind !== 'SelectQueryNode') return [];
|
|
1227
|
-
const where = query.where;
|
|
1228
|
-
if (!isOperationNode(where) || where.kind !== 'WhereNode') return [];
|
|
1229
|
-
return collectConjunctivePrimaryKeyValues(where.where, table, primaryKey);
|
|
1230
|
-
}
|
|
1231
|
-
|
|
1232
|
-
function collectConjunctivePrimaryKeyValues(
|
|
1233
|
-
node: unknown,
|
|
1234
|
-
table: string,
|
|
1235
|
-
primaryKey: string
|
|
1236
|
-
): string[] {
|
|
1237
|
-
if (!isOperationNode(node)) return [];
|
|
1238
|
-
if (node.kind === 'AndNode') {
|
|
1239
|
-
return uniqueStrings([
|
|
1240
|
-
...collectConjunctivePrimaryKeyValues(node.left, table, primaryKey),
|
|
1241
|
-
...collectConjunctivePrimaryKeyValues(node.right, table, primaryKey),
|
|
1242
|
-
]);
|
|
1243
|
-
}
|
|
1244
|
-
const equality = primaryKeyEqualityValue(node, table, primaryKey);
|
|
1245
|
-
return equality == null ? [] : [equality];
|
|
1246
|
-
}
|
|
1247
|
-
|
|
1248
|
-
function primaryKeyEqualityValue(
|
|
1249
|
-
node: unknown,
|
|
1250
|
-
table: string,
|
|
1251
|
-
primaryKey: string
|
|
1252
|
-
): string | undefined {
|
|
1253
|
-
if (!isOperationNode(node) || node.kind !== 'BinaryOperationNode') {
|
|
1254
|
-
return undefined;
|
|
1255
|
-
}
|
|
1256
|
-
const operator = node.operator;
|
|
1257
|
-
if (
|
|
1258
|
-
!isOperationNode(operator) ||
|
|
1259
|
-
operator.kind !== 'OperatorNode' ||
|
|
1260
|
-
operator.operator !== '='
|
|
1261
|
-
) {
|
|
1262
|
-
return undefined;
|
|
1263
|
-
}
|
|
1264
|
-
return (
|
|
1265
|
-
equalityValueForReference(
|
|
1266
|
-
node.leftOperand,
|
|
1267
|
-
node.rightOperand,
|
|
1268
|
-
table,
|
|
1269
|
-
primaryKey
|
|
1270
|
-
) ??
|
|
1271
|
-
equalityValueForReference(
|
|
1272
|
-
node.rightOperand,
|
|
1273
|
-
node.leftOperand,
|
|
1274
|
-
table,
|
|
1275
|
-
primaryKey
|
|
1276
|
-
)
|
|
1277
|
-
);
|
|
1278
|
-
}
|
|
1279
|
-
|
|
1280
|
-
function equalityValueForReference(
|
|
1281
|
-
reference: unknown,
|
|
1282
|
-
value: unknown,
|
|
1283
|
-
table: string,
|
|
1284
|
-
primaryKey: string
|
|
1285
|
-
): string | undefined {
|
|
1286
|
-
if (!referenceMatchesColumn(reference, table, primaryKey)) return undefined;
|
|
1287
|
-
if (!isOperationNode(value) || value.kind !== 'ValueNode') return undefined;
|
|
1288
|
-
if (typeof value.value === 'string') return value.value;
|
|
1289
|
-
if (typeof value.value === 'number' && Number.isFinite(value.value)) {
|
|
1290
|
-
return String(value.value);
|
|
1291
|
-
}
|
|
1292
|
-
return undefined;
|
|
1293
|
-
}
|
|
1294
|
-
|
|
1295
|
-
function referenceMatchesColumn(
|
|
1296
|
-
reference: unknown,
|
|
1297
|
-
table: string,
|
|
1298
|
-
column: string
|
|
1299
|
-
): boolean {
|
|
1300
|
-
if (!isOperationNode(reference) || reference.kind !== 'ReferenceNode') {
|
|
1301
|
-
return false;
|
|
1302
|
-
}
|
|
1303
|
-
if (
|
|
1304
|
-
reference.table != null &&
|
|
1305
|
-
tableNameFromTableNode(reference.table) !== table
|
|
1306
|
-
) {
|
|
1307
|
-
return false;
|
|
1308
|
-
}
|
|
1309
|
-
const columnNode = reference.column;
|
|
1310
|
-
if (!isOperationNode(columnNode) || columnNode.kind !== 'ColumnNode') {
|
|
1311
|
-
return false;
|
|
1312
|
-
}
|
|
1313
|
-
const identifier = columnNode.column;
|
|
1314
|
-
return (
|
|
1315
|
-
isOperationNode(identifier) &&
|
|
1316
|
-
identifier.kind === 'IdentifierNode' &&
|
|
1317
|
-
identifier.name === column
|
|
1318
|
-
);
|
|
1319
|
-
}
|
|
1320
|
-
|
|
1321
|
-
function uniqueStrings(values: readonly string[]): string[] {
|
|
1322
|
-
return [...new Set(values)];
|
|
1323
|
-
}
|
|
1324
|
-
|
|
1325
|
-
function uniqueDefinedStrings(values: readonly string[] | undefined): string[] {
|
|
1326
|
-
if (values == null) return [];
|
|
1327
|
-
const unique: string[] = [];
|
|
1328
|
-
for (const value of values) {
|
|
1329
|
-
if (value.length === 0) {
|
|
1330
|
-
throw new Error('Live query dependency hint values must not be empty.');
|
|
1331
|
-
}
|
|
1332
|
-
if (!unique.includes(value)) unique.push(value);
|
|
1333
|
-
}
|
|
1334
|
-
return unique;
|
|
1335
|
-
}
|
|
1336
|
-
|
|
1337
|
-
interface OperationNodeLike {
|
|
1338
|
-
kind?: string;
|
|
1339
|
-
[key: string]: unknown;
|
|
1340
|
-
}
|
|
1341
|
-
|
|
1342
|
-
function collectTables(node: unknown, tables: Set<string>): void {
|
|
1343
|
-
if (Array.isArray(node)) {
|
|
1344
|
-
for (const item of node) collectTables(item, tables);
|
|
1345
|
-
return;
|
|
1346
|
-
}
|
|
1347
|
-
if (!isOperationNode(node)) return;
|
|
1348
|
-
|
|
1349
|
-
if (node.kind === 'TableNode') collectTableNode(node, tables);
|
|
1350
|
-
for (const value of Object.values(node)) collectTables(value, tables);
|
|
1351
|
-
}
|
|
1352
|
-
|
|
1353
|
-
function collectTableNode(node: unknown, tables: Set<string>): void {
|
|
1354
|
-
const table = tableNameFromTableNode(node);
|
|
1355
|
-
if (table != null) tables.add(table);
|
|
1356
|
-
}
|
|
1357
|
-
|
|
1358
|
-
function tableNameFromTableNode(node: unknown): string | undefined {
|
|
1359
|
-
if (!isOperationNode(node)) return undefined;
|
|
1360
|
-
if (node.kind === 'AliasNode') return tableNameFromTableNode(node.node);
|
|
1361
|
-
if (node.kind !== 'TableNode') return undefined;
|
|
1362
|
-
const table = node.table;
|
|
1363
|
-
if (!isOperationNode(table) || table.kind !== 'SchemableIdentifierNode') {
|
|
1364
|
-
return undefined;
|
|
1365
|
-
}
|
|
1366
|
-
const identifier = table.identifier;
|
|
1367
|
-
if (!isOperationNode(identifier) || identifier.kind !== 'IdentifierNode') {
|
|
1368
|
-
return undefined;
|
|
1369
|
-
}
|
|
1370
|
-
return typeof identifier.name === 'string' ? identifier.name : undefined;
|
|
1371
|
-
}
|
|
1372
|
-
|
|
1373
|
-
function isOperationNode(value: unknown): value is OperationNodeLike {
|
|
1374
|
-
return Boolean(value && typeof value === 'object' && 'kind' in value);
|
|
1375
|
-
}
|
|
1376
|
-
|
|
1377
|
-
function normalizeLiveQueryTables(
|
|
1378
|
-
tables: readonly string[],
|
|
1379
|
-
appTables?: ReadonlySet<string>
|
|
1380
|
-
): string[] {
|
|
1381
|
-
const normalized: string[] = [];
|
|
1382
|
-
for (const table of tables) {
|
|
1383
|
-
if (table.length === 0) {
|
|
1384
|
-
throw new Error(
|
|
1385
|
-
'Live query table dependencies must not contain empty names.'
|
|
1386
|
-
);
|
|
1387
|
-
}
|
|
1388
|
-
if (appTables != null && !appTables.has(table)) {
|
|
1389
|
-
throw new Error(
|
|
1390
|
-
`Live query table ${table} is not part of the generated app schema.`
|
|
1391
|
-
);
|
|
1392
|
-
}
|
|
1393
|
-
if (!normalized.includes(table)) normalized.push(table);
|
|
68
|
+
throw error;
|
|
1394
69
|
}
|
|
1395
|
-
return normalized;
|
|
1396
70
|
}
|