@syncular/client 0.1.3 → 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.
Files changed (233) hide show
  1. package/README.md +227 -709
  2. package/dist/apply.d.ts +80 -0
  3. package/dist/apply.js +301 -0
  4. package/dist/blob.d.ts +127 -0
  5. package/dist/blob.js +201 -0
  6. package/dist/bun-database.d.ts +22 -0
  7. package/dist/bun-database.js +61 -0
  8. package/dist/client.d.ts +320 -69
  9. package/dist/client.js +1627 -163
  10. package/dist/content-type.d.ts +2 -0
  11. package/dist/content-type.js +2 -0
  12. package/dist/database.d.ts +35 -80
  13. package/dist/database.js +32 -947
  14. package/dist/encryption.d.ts +47 -0
  15. package/dist/encryption.js +75 -0
  16. package/dist/errors.d.ts +8 -22
  17. package/dist/errors.js +10 -207
  18. package/dist/http.d.ts +32 -0
  19. package/dist/http.js +196 -0
  20. package/dist/index.d.ts +28 -16
  21. package/dist/index.js +25 -12
  22. package/dist/invalidation.d.ts +69 -0
  23. package/dist/invalidation.js +84 -0
  24. package/dist/leader-lock.d.ts +28 -0
  25. package/dist/leader-lock.js +38 -0
  26. package/dist/multi-tab.d.ts +134 -0
  27. package/dist/multi-tab.js +399 -0
  28. package/dist/node-database.d.ts +41 -0
  29. package/dist/node-database.js +133 -0
  30. package/dist/outbox.d.ts +56 -0
  31. package/dist/outbox.js +140 -0
  32. package/dist/schema.d.ts +107 -0
  33. package/dist/schema.js +267 -0
  34. package/dist/state.d.ts +40 -0
  35. package/dist/state.js +77 -0
  36. package/dist/transport.d.ts +44 -0
  37. package/dist/transport.js +7 -0
  38. package/dist/wasm-database.d.ts +30 -0
  39. package/dist/wasm-database.js +170 -0
  40. package/dist/window.d.ts +64 -0
  41. package/dist/window.js +0 -0
  42. package/dist/worker-entry.d.ts +16 -2
  43. package/dist/worker-entry.js +300 -456
  44. package/dist/worker-host.d.ts +174 -0
  45. package/dist/worker-host.js +536 -0
  46. package/dist/worker-protocol.d.ts +173 -61
  47. package/dist/worker-protocol.js +7 -16
  48. package/package.json +45 -112
  49. package/src/apply.ts +435 -0
  50. package/src/blob.ts +333 -0
  51. package/src/bun-database.ts +75 -0
  52. package/src/client.ts +2247 -277
  53. package/src/content-type.ts +2 -0
  54. package/src/database.ts +63 -1389
  55. package/src/encryption.ts +123 -0
  56. package/src/errors.ts +11 -265
  57. package/src/http.ts +254 -0
  58. package/src/index.ts +25 -20
  59. package/src/invalidation.ts +128 -0
  60. package/src/leader-lock.ts +68 -0
  61. package/src/multi-tab.ts +550 -0
  62. package/src/node-database.ts +180 -0
  63. package/src/outbox.ts +206 -0
  64. package/src/schema.ts +397 -0
  65. package/src/state.ts +126 -0
  66. package/src/transport.ts +52 -0
  67. package/src/wasm-database.ts +279 -0
  68. package/src/window.ts +0 -0
  69. package/src/worker-entry.ts +391 -545
  70. package/src/worker-host.ts +800 -0
  71. package/src/worker-protocol.ts +204 -99
  72. package/dist/auth-leases.d.ts +0 -11
  73. package/dist/auth-leases.d.ts.map +0 -1
  74. package/dist/auth-leases.js +0 -140
  75. package/dist/auth-leases.js.map +0 -1
  76. package/dist/blob-limits.d.ts +0 -15
  77. package/dist/blob-limits.d.ts.map +0 -1
  78. package/dist/blob-limits.js +0 -66
  79. package/dist/blob-limits.js.map +0 -1
  80. package/dist/bridge-client.d.ts +0 -69
  81. package/dist/bridge-client.d.ts.map +0 -1
  82. package/dist/bridge-client.js +0 -282
  83. package/dist/bridge-client.js.map +0 -1
  84. package/dist/client-config.d.ts +0 -6
  85. package/dist/client-config.d.ts.map +0 -1
  86. package/dist/client-config.js +0 -18
  87. package/dist/client-config.js.map +0 -1
  88. package/dist/client.d.ts.map +0 -1
  89. package/dist/client.js.map +0 -1
  90. package/dist/command-history.d.ts +0 -35
  91. package/dist/command-history.d.ts.map +0 -1
  92. package/dist/command-history.js +0 -378
  93. package/dist/command-history.js.map +0 -1
  94. package/dist/console-diagnostics.d.ts +0 -33
  95. package/dist/console-diagnostics.d.ts.map +0 -1
  96. package/dist/console-diagnostics.js +0 -496
  97. package/dist/console-diagnostics.js.map +0 -1
  98. package/dist/crdt-yjs/index.d.ts +0 -4
  99. package/dist/crdt-yjs/index.d.ts.map +0 -1
  100. package/dist/crdt-yjs/index.js +0 -4
  101. package/dist/crdt-yjs/index.js.map +0 -1
  102. package/dist/crdt-yjs/webview-host-facade.d.ts +0 -126
  103. package/dist/crdt-yjs/webview-host-facade.d.ts.map +0 -1
  104. package/dist/crdt-yjs/webview-host-facade.js +0 -284
  105. package/dist/crdt-yjs/webview-host-facade.js.map +0 -1
  106. package/dist/crdt-yjs/yjs-document-field-adapter.d.ts +0 -153
  107. package/dist/crdt-yjs/yjs-document-field-adapter.d.ts.map +0 -1
  108. package/dist/crdt-yjs/yjs-document-field-adapter.js +0 -406
  109. package/dist/crdt-yjs/yjs-document-field-adapter.js.map +0 -1
  110. package/dist/crdt-yjs/yjs-prosemirror-bridge.d.ts +0 -73
  111. package/dist/crdt-yjs/yjs-prosemirror-bridge.d.ts.map +0 -1
  112. package/dist/crdt-yjs/yjs-prosemirror-bridge.js +0 -169
  113. package/dist/crdt-yjs/yjs-prosemirror-bridge.js.map +0 -1
  114. package/dist/database.d.ts.map +0 -1
  115. package/dist/database.js.map +0 -1
  116. package/dist/diagnostics.d.ts +0 -10
  117. package/dist/diagnostics.d.ts.map +0 -1
  118. package/dist/diagnostics.js +0 -83
  119. package/dist/diagnostics.js.map +0 -1
  120. package/dist/errors.d.ts.map +0 -1
  121. package/dist/errors.js.map +0 -1
  122. package/dist/generated-bridge.d.ts +0 -365
  123. package/dist/generated-bridge.d.ts.map +0 -1
  124. package/dist/generated-bridge.js +0 -250
  125. package/dist/generated-bridge.js.map +0 -1
  126. package/dist/index.d.ts.map +0 -1
  127. package/dist/index.js.map +0 -1
  128. package/dist/mutations.d.ts +0 -72
  129. package/dist/mutations.d.ts.map +0 -1
  130. package/dist/mutations.js +0 -63
  131. package/dist/mutations.js.map +0 -1
  132. package/dist/network.d.ts +0 -3
  133. package/dist/network.d.ts.map +0 -1
  134. package/dist/network.js +0 -17
  135. package/dist/network.js.map +0 -1
  136. package/dist/react/index.d.ts +0 -169
  137. package/dist/react/index.d.ts.map +0 -1
  138. package/dist/react/index.js +0 -628
  139. package/dist/react/index.js.map +0 -1
  140. package/dist/react-native/index.d.ts +0 -35
  141. package/dist/react-native/index.d.ts.map +0 -1
  142. package/dist/react-native/index.js +0 -49
  143. package/dist/react-native/index.js.map +0 -1
  144. package/dist/runtime-contract.d.ts +0 -13
  145. package/dist/runtime-contract.d.ts.map +0 -1
  146. package/dist/runtime-contract.js +0 -24
  147. package/dist/runtime-contract.js.map +0 -1
  148. package/dist/rust-client.d.ts +0 -106
  149. package/dist/rust-client.d.ts.map +0 -1
  150. package/dist/rust-client.js +0 -938
  151. package/dist/rust-client.js.map +0 -1
  152. package/dist/sentry.d.ts +0 -35
  153. package/dist/sentry.d.ts.map +0 -1
  154. package/dist/sentry.js +0 -155
  155. package/dist/sentry.js.map +0 -1
  156. package/dist/sql-safety.d.ts +0 -3
  157. package/dist/sql-safety.d.ts.map +0 -1
  158. package/dist/sql-safety.js +0 -62
  159. package/dist/sql-safety.js.map +0 -1
  160. package/dist/syncular-runtime-artifacts.json +0 -61
  161. package/dist/tauri/index.d.ts +0 -35
  162. package/dist/tauri/index.d.ts.map +0 -1
  163. package/dist/tauri/index.js +0 -114
  164. package/dist/tauri/index.js.map +0 -1
  165. package/dist/types.d.ts +0 -1096
  166. package/dist/types.d.ts.map +0 -1
  167. package/dist/types.js +0 -2
  168. package/dist/types.js.map +0 -1
  169. package/dist/wasm/.syncular-wasm-profile +0 -1
  170. package/dist/wasm/syncular-runtime-artifact.json +0 -21
  171. package/dist/wasm/syncular.d.ts +0 -207
  172. package/dist/wasm/syncular.js +0 -2341
  173. package/dist/wasm/syncular_bg.wasm +0 -0
  174. package/dist/wasm/syncular_bg.wasm.d.ts +0 -97
  175. package/dist/wasm-bindings/runtime-contract.d.ts +0 -22
  176. package/dist/wasm-bindings/runtime-contract.d.ts.map +0 -1
  177. package/dist/wasm-bindings/runtime-contract.js +0 -112
  178. package/dist/wasm-bindings/runtime-contract.js.map +0 -1
  179. package/dist/wasm-core/.syncular-wasm-profile +0 -1
  180. package/dist/wasm-core/syncular-runtime-artifact.json +0 -17
  181. package/dist/wasm-core/syncular.d.ts +0 -162
  182. package/dist/wasm-core/syncular.js +0 -1847
  183. package/dist/wasm-core/syncular_bg.wasm +0 -0
  184. package/dist/wasm-core/syncular_bg.wasm.d.ts +0 -77
  185. package/dist/wasm-perf/.syncular-wasm-profile +0 -1
  186. package/dist/wasm-perf/syncular-runtime-artifact.json +0 -21
  187. package/dist/wasm-perf/syncular.d.ts +0 -207
  188. package/dist/wasm-perf/syncular.js +0 -2341
  189. package/dist/wasm-perf/syncular_bg.wasm +0 -0
  190. package/dist/wasm-perf/syncular_bg.wasm.d.ts +0 -97
  191. package/dist/wasm-runtime.d.ts +0 -23
  192. package/dist/wasm-runtime.d.ts.map +0 -1
  193. package/dist/wasm-runtime.js +0 -69
  194. package/dist/wasm-runtime.js.map +0 -1
  195. package/dist/worker-client.d.ts +0 -123
  196. package/dist/worker-client.d.ts.map +0 -1
  197. package/dist/worker-client.js +0 -1735
  198. package/dist/worker-client.js.map +0 -1
  199. package/dist/worker-entry.d.ts.map +0 -1
  200. package/dist/worker-entry.js.map +0 -1
  201. package/dist/worker-protocol.d.ts.map +0 -1
  202. package/dist/worker-protocol.js.map +0 -1
  203. package/dist/worker-realtime.d.ts +0 -39
  204. package/dist/worker-realtime.d.ts.map +0 -1
  205. package/dist/worker-realtime.js +0 -677
  206. package/dist/worker-realtime.js.map +0 -1
  207. package/src/auth-leases.ts +0 -251
  208. package/src/blob-limits.ts +0 -98
  209. package/src/bridge-client.ts +0 -512
  210. package/src/client-config.ts +0 -29
  211. package/src/command-history.ts +0 -623
  212. package/src/console-diagnostics.ts +0 -617
  213. package/src/crdt-yjs/index.ts +0 -3
  214. package/src/crdt-yjs/webview-host-facade.ts +0 -477
  215. package/src/crdt-yjs/yjs-document-field-adapter.ts +0 -733
  216. package/src/crdt-yjs/yjs-prosemirror-bridge.ts +0 -272
  217. package/src/diagnostics.ts +0 -116
  218. package/src/generated-bridge.ts +0 -741
  219. package/src/mutations.ts +0 -168
  220. package/src/network.ts +0 -32
  221. package/src/react/index.ts +0 -1036
  222. package/src/react-native/index.ts +0 -152
  223. package/src/runtime-contract.ts +0 -48
  224. package/src/rust-client.ts +0 -1491
  225. package/src/sentry.ts +0 -215
  226. package/src/sql-safety.ts +0 -61
  227. package/src/tauri/index.ts +0 -211
  228. package/src/types.ts +0 -1397
  229. package/src/wasm-bindings/generated-wasm-bindings.d.ts +0 -70
  230. package/src/wasm-bindings/runtime-contract.ts +0 -158
  231. package/src/wasm-runtime.ts +0 -145
  232. package/src/worker-client.ts +0 -2289
  233. package/src/worker-realtime.ts +0 -843
@@ -1,623 +0,0 @@
1
- import { randomId } from '@syncular/core';
2
- import {
3
- createMutationsApi,
4
- type MutationReceipt,
5
- type MutationsApi,
6
- type MutationsCommitFn,
7
- type MutationsTx,
8
- type TableMutationsTx,
9
- } from './mutations';
10
- import type {
11
- SyncularSqlClient,
12
- SyncularTableConfigMap,
13
- SyncularUnsafeSqlClient,
14
- } from './types';
15
-
16
- type AnyDb = Record<string, Record<string, unknown>>;
17
- type MutationScope = 'mutations' | 'leasedMutations';
18
- type RowSnapshot = Record<string, unknown> | null;
19
-
20
- interface HistoryRow extends Record<string, unknown> {
21
- id: string;
22
- mutation_scope: MutationScope;
23
- state: 'done' | 'undone';
24
- entries_json: string;
25
- client_commit_id: string;
26
- undo_client_commit_id: string | null;
27
- redo_client_commit_id: string | null;
28
- created_at: number;
29
- updated_at: number;
30
- }
31
-
32
- interface CommandEntry {
33
- table: string;
34
- rowId: string;
35
- before: RowSnapshot;
36
- after: RowSnapshot;
37
- }
38
-
39
- interface PendingCommandEntry {
40
- table: string;
41
- rowId: string;
42
- before: RowSnapshot;
43
- }
44
-
45
- export type SyncularCommandHistoryErrorCode =
46
- | 'sync.command_history_empty'
47
- | 'sync.command_history_conflict'
48
- | 'sync.command_history_storage_unavailable'
49
- | 'sync.command_history_table_unsupported'
50
- | 'sync.command_history_unsafe_field';
51
-
52
- export class SyncularCommandHistoryError extends Error {
53
- readonly code: SyncularCommandHistoryErrorCode;
54
- readonly commandId?: string;
55
-
56
- constructor(
57
- code: SyncularCommandHistoryErrorCode,
58
- message: string,
59
- options: { commandId?: string } = {}
60
- ) {
61
- super(message);
62
- this.name = 'SyncularCommandHistoryError';
63
- this.code = code;
64
- this.commandId = options.commandId;
65
- }
66
- }
67
-
68
- export interface SyncularCommandHistoryReceipt extends MutationReceipt {
69
- commandId: string;
70
- }
71
-
72
- export interface SyncularCommandHistory {
73
- canUndo(): Promise<boolean>;
74
- canRedo(): Promise<boolean>;
75
- undoLast(): Promise<SyncularCommandHistoryReceipt>;
76
- redoLast(): Promise<SyncularCommandHistoryReceipt>;
77
- }
78
-
79
- export interface SyncularCommandHistoryController<DB> {
80
- history: SyncularCommandHistory;
81
- wrapMutations(
82
- mutations: MutationsApi<DB, undefined>,
83
- scope: MutationScope
84
- ): MutationsApi<DB, undefined>;
85
- }
86
-
87
- export interface CreateSyncularCommandHistoryOptions<DB> {
88
- client: SyncularSqlClient & Partial<SyncularUnsafeSqlClient>;
89
- tableConfig: SyncularTableConfigMap;
90
- mutations: MutationsApi<DB, undefined>;
91
- leasedMutations: MutationsApi<DB, undefined>;
92
- nowMs?: () => number;
93
- idFactory?: () => string;
94
- }
95
-
96
- export function createSyncularCommandHistory<DB>(
97
- options: CreateSyncularCommandHistoryOptions<DB>
98
- ): SyncularCommandHistoryController<DB> {
99
- const store = new CommandHistoryStore(options);
100
- const history = new CommandHistory(options, store);
101
-
102
- return {
103
- history,
104
- wrapMutations(mutations, scope) {
105
- return createMutationsApi(createTrackedCommit(mutations, scope, history));
106
- },
107
- };
108
- }
109
-
110
- function createTrackedCommit<DB>(
111
- mutations: MutationsApi<DB, undefined>,
112
- scope: MutationScope,
113
- history: CommandHistory<DB>
114
- ): MutationsCommitFn<DB, void, undefined> {
115
- return async (fn) => {
116
- await history.ensureReady();
117
- const recorder = new PendingCommandRecorder(history);
118
- const { result, commit } = await mutations.$commit(async (tx) =>
119
- fn(createTrackedTx(tx, recorder) as MutationsTx<DB>)
120
- );
121
- await recorder.recordCommitted(scope, commit);
122
- return { result, receipt: commit, meta: undefined };
123
- };
124
- }
125
-
126
- function createTrackedTx<DB>(
127
- tx: MutationsTx<DB>,
128
- recorder: PendingCommandRecorder<DB>
129
- ): MutationsTx<DB> {
130
- const tableCache = new Map<string, TableMutationsTx<AnyDb, string>>();
131
- return new Proxy(
132
- {},
133
- {
134
- get(_target, prop) {
135
- if (prop === 'then') return undefined;
136
- if (typeof prop !== 'string') return undefined;
137
- const cached = tableCache.get(prop);
138
- if (cached) return cached;
139
- const tableTx = tx[prop] as TableMutationsTx<AnyDb, string> | undefined;
140
- if (!tableTx) return undefined;
141
- const tracked = createTrackedTableTx(prop, tableTx, recorder);
142
- tableCache.set(prop, tracked);
143
- return tracked;
144
- },
145
- }
146
- ) as MutationsTx<DB>;
147
- }
148
-
149
- function createTrackedTableTx<DB>(
150
- table: string,
151
- tableTx: TableMutationsTx<AnyDb, string>,
152
- recorder: PendingCommandRecorder<DB>
153
- ): TableMutationsTx<AnyDb, string> {
154
- return {
155
- async insert(values) {
156
- const id = await tableTx.insert(values);
157
- await recorder.track(table, id);
158
- return id;
159
- },
160
- async insertMany(rows) {
161
- const ids = await tableTx.insertMany(rows);
162
- for (const id of ids) await recorder.track(table, id);
163
- return ids;
164
- },
165
- async update(id, patch, options) {
166
- await recorder.track(table, id);
167
- await tableTx.update(id, patch, options);
168
- },
169
- async delete(id, options) {
170
- await recorder.track(table, id);
171
- await tableTx.delete(id, options);
172
- },
173
- async upsert(id, patch, options) {
174
- await recorder.track(table, id);
175
- await tableTx.upsert(id, patch, options);
176
- },
177
- };
178
- }
179
-
180
- class PendingCommandRecorder<DB> {
181
- readonly #entries = new Map<string, PendingCommandEntry>();
182
-
183
- constructor(private readonly history: CommandHistory<DB>) {}
184
-
185
- async track(table: string, rowId: string): Promise<void> {
186
- const key = `${table}\0${rowId}`;
187
- if (this.#entries.has(key)) return;
188
- this.#entries.set(key, {
189
- table,
190
- rowId,
191
- before: await this.history.readRow(table, rowId),
192
- });
193
- }
194
-
195
- async recordCommitted(
196
- scope: MutationScope,
197
- receipt: MutationReceipt
198
- ): Promise<void> {
199
- if (this.#entries.size === 0) return;
200
- const entries: CommandEntry[] = [];
201
- for (const entry of this.#entries.values()) {
202
- const after = await this.history.readRow(entry.table, entry.rowId);
203
- if (sameSnapshot(entry.before, after)) continue;
204
- entries.push({ ...entry, after });
205
- }
206
- if (entries.length === 0) return;
207
- await this.history.record(scope, entries, receipt);
208
- }
209
- }
210
-
211
- class CommandHistory<DB> implements SyncularCommandHistory {
212
- constructor(
213
- private readonly options: CreateSyncularCommandHistoryOptions<DB>,
214
- private readonly store: CommandHistoryStore<DB>
215
- ) {}
216
-
217
- ensureReady(): Promise<void> {
218
- return this.store.ensureReady();
219
- }
220
-
221
- readRow(table: string, rowId: string): Promise<RowSnapshot> {
222
- const config = this.options.tableConfig[table];
223
- if (!config) {
224
- throw new SyncularCommandHistoryError(
225
- 'sync.command_history_table_unsupported',
226
- `Cannot record undo history for unsupported table ${table}`
227
- );
228
- }
229
- return readCurrentRow(
230
- this.options.client,
231
- table,
232
- config.primaryKeyColumn ?? 'id',
233
- rowId
234
- );
235
- }
236
-
237
- record(
238
- scope: MutationScope,
239
- entries: CommandEntry[],
240
- receipt: MutationReceipt
241
- ): Promise<void> {
242
- return this.store.insert(scope, entries, receipt);
243
- }
244
-
245
- async canUndo(): Promise<boolean> {
246
- await this.ensureReady();
247
- return (await this.store.latest('done')) !== null;
248
- }
249
-
250
- async canRedo(): Promise<boolean> {
251
- await this.ensureReady();
252
- return (await this.store.latest('undone')) !== null;
253
- }
254
-
255
- async undoLast(): Promise<SyncularCommandHistoryReceipt> {
256
- await this.ensureReady();
257
- const command = await this.store.latest('done');
258
- if (!command) {
259
- throw new SyncularCommandHistoryError(
260
- 'sync.command_history_empty',
261
- 'There is no Syncular command to undo'
262
- );
263
- }
264
- const entries = decodeEntries(command);
265
- this.assertSafeReplay(command.id, entries);
266
- await this.assertCurrentRows(command.id, entries, 'after');
267
- const commit = await this.applySnapshots(
268
- command.mutation_scope,
269
- [...entries].reverse().map((entry) => ({
270
- table: entry.table,
271
- rowId: entry.rowId,
272
- snapshot: entry.before,
273
- }))
274
- );
275
- await this.store.mark(command.id, 'undone', commit);
276
- return { ...commit, commandId: command.id };
277
- }
278
-
279
- async redoLast(): Promise<SyncularCommandHistoryReceipt> {
280
- await this.ensureReady();
281
- const command = await this.store.latest('undone');
282
- if (!command) {
283
- throw new SyncularCommandHistoryError(
284
- 'sync.command_history_empty',
285
- 'There is no Syncular command to redo'
286
- );
287
- }
288
- const entries = decodeEntries(command);
289
- this.assertSafeReplay(command.id, entries);
290
- await this.assertCurrentRows(command.id, entries, 'before');
291
- const commit = await this.applySnapshots(
292
- command.mutation_scope,
293
- entries.map((entry) => ({
294
- table: entry.table,
295
- rowId: entry.rowId,
296
- snapshot: entry.after,
297
- }))
298
- );
299
- await this.store.mark(command.id, 'done', commit);
300
- return { ...commit, commandId: command.id };
301
- }
302
-
303
- private async assertCurrentRows(
304
- commandId: string,
305
- entries: readonly CommandEntry[],
306
- expected: 'before' | 'after'
307
- ): Promise<void> {
308
- for (const entry of entries) {
309
- const config = this.options.tableConfig[entry.table];
310
- if (!config) {
311
- throw new SyncularCommandHistoryError(
312
- 'sync.command_history_table_unsupported',
313
- `Cannot replay undo history for unsupported table ${entry.table}`,
314
- { commandId }
315
- );
316
- }
317
- const current = await this.readRow(entry.table, entry.rowId);
318
- if (!sameReplaySnapshot(config, current, entry[expected])) {
319
- throw new SyncularCommandHistoryError(
320
- 'sync.command_history_conflict',
321
- `Cannot ${expected === 'after' ? 'undo' : 'redo'} Syncular command ${commandId}; ${entry.table}.${entry.rowId} changed since the command was recorded`,
322
- { commandId }
323
- );
324
- }
325
- }
326
- }
327
-
328
- private assertSafeReplay(
329
- commandId: string,
330
- entries: readonly CommandEntry[]
331
- ): void {
332
- for (const entry of entries) {
333
- const config = this.options.tableConfig[entry.table];
334
- if (!config) {
335
- throw new SyncularCommandHistoryError(
336
- 'sync.command_history_table_unsupported',
337
- `Cannot replay undo history for unsupported table ${entry.table}`,
338
- { commandId }
339
- );
340
- }
341
- const unsafeFields = unsafeChangedFields(config, entry);
342
- if (unsafeFields.length > 0) {
343
- throw new SyncularCommandHistoryError(
344
- 'sync.command_history_unsafe_field',
345
- `Cannot replay Syncular command ${commandId}; ${entry.table}.${entry.rowId} changed unsafe fields: ${unsafeFields.join(', ')}`,
346
- { commandId }
347
- );
348
- }
349
- }
350
- }
351
-
352
- private async applySnapshots(
353
- scope: MutationScope,
354
- snapshots: Array<{ table: string; rowId: string; snapshot: RowSnapshot }>
355
- ): Promise<MutationReceipt> {
356
- const mutations =
357
- scope === 'leasedMutations'
358
- ? this.options.leasedMutations
359
- : this.options.mutations;
360
- const { commit } = await mutations.$commit(async (tx) => {
361
- for (const snapshot of snapshots) {
362
- const table = tx[snapshot.table] as
363
- | TableMutationsTx<AnyDb, string>
364
- | undefined;
365
- if (!table) {
366
- throw new SyncularCommandHistoryError(
367
- 'sync.command_history_table_unsupported',
368
- `Cannot apply undo history for unsupported table ${snapshot.table}`
369
- );
370
- }
371
- if (snapshot.snapshot === null) {
372
- await table.delete(snapshot.rowId);
373
- } else {
374
- await table.upsert(
375
- snapshot.rowId,
376
- this.mutationPayloadForSnapshot(snapshot.table, snapshot.snapshot)
377
- );
378
- }
379
- }
380
- });
381
- return commit;
382
- }
383
-
384
- private mutationPayloadForSnapshot(
385
- table: string,
386
- snapshot: Record<string, unknown>
387
- ): Record<string, unknown> {
388
- const config = this.options.tableConfig[table];
389
- if (!config) {
390
- throw new SyncularCommandHistoryError(
391
- 'sync.command_history_table_unsupported',
392
- `Cannot apply undo history for unsupported table ${table}`
393
- );
394
- }
395
- const payload = { ...snapshot };
396
- delete payload[config.primaryKeyColumn ?? 'id'];
397
- if (config.serverVersionColumn) delete payload[config.serverVersionColumn];
398
- for (const field of config.crdtYjsFields ?? []) {
399
- delete payload[field.stateColumn];
400
- }
401
- return payload;
402
- }
403
- }
404
-
405
- class CommandHistoryStore<DB> {
406
- #ready: Promise<void> | undefined;
407
-
408
- constructor(
409
- private readonly options: CreateSyncularCommandHistoryOptions<DB>
410
- ) {}
411
-
412
- ensureReady(): Promise<void> {
413
- this.#ready ??= this.#ensureReady();
414
- return this.#ready;
415
- }
416
-
417
- async insert(
418
- scope: MutationScope,
419
- entries: readonly CommandEntry[],
420
- receipt: MutationReceipt
421
- ): Promise<void> {
422
- await this.ensureReady();
423
- const now = this.now();
424
- const id = this.options.idFactory?.() ?? `cmd_${randomId()}`;
425
- const client = this.unsafeClient();
426
- await client.executeUnsafeSql(
427
- "delete from sync_command_history where state = 'undone'"
428
- );
429
- await client.executeUnsafeSql(
430
- `insert into sync_command_history (
431
- id,
432
- mutation_scope,
433
- state,
434
- entries_json,
435
- client_commit_id,
436
- created_at,
437
- updated_at
438
- ) values (?, ?, 'done', ?, ?, ?, ?)`,
439
- [id, scope, JSON.stringify(entries), receipt.clientCommitId, now, now]
440
- );
441
- }
442
-
443
- async latest(state: 'done' | 'undone'): Promise<HistoryRow | null> {
444
- await this.ensureReady();
445
- const result = await this.options.client.executeSql<HistoryRow>(
446
- `select id, mutation_scope, state, entries_json, client_commit_id,
447
- undo_client_commit_id, redo_client_commit_id, created_at, updated_at
448
- from sync_command_history
449
- where state = ?
450
- order by updated_at desc, created_at desc, id desc
451
- limit 1`,
452
- [state]
453
- );
454
- return result.rows[0] ?? null;
455
- }
456
-
457
- async mark(
458
- id: string,
459
- state: 'done' | 'undone',
460
- receipt: MutationReceipt
461
- ): Promise<void> {
462
- await this.ensureReady();
463
- const replayColumn =
464
- state === 'undone' ? 'undo_client_commit_id' : 'redo_client_commit_id';
465
- await this.unsafeClient().executeUnsafeSql(
466
- `update sync_command_history
467
- set state = ?, updated_at = ?, ${replayColumn} = ?
468
- where id = ?`,
469
- [state, this.now(), receipt.clientCommitId, id]
470
- );
471
- }
472
-
473
- async #ensureReady(): Promise<void> {
474
- const client = this.unsafeClient();
475
- await client.executeUnsafeSql(
476
- `create table if not exists sync_command_history (
477
- id text primary key,
478
- mutation_scope text not null,
479
- state text not null check (state in ('done', 'undone')),
480
- entries_json text not null,
481
- client_commit_id text not null,
482
- undo_client_commit_id text null,
483
- redo_client_commit_id text null,
484
- created_at integer not null,
485
- updated_at integer not null
486
- )`
487
- );
488
- await client.executeUnsafeSql(
489
- `create index if not exists idx_sync_command_history_state_updated
490
- on sync_command_history (state, updated_at, created_at)`
491
- );
492
- }
493
-
494
- private unsafeClient(): SyncularUnsafeSqlClient {
495
- const client = this.options.client;
496
- if (typeof client.executeUnsafeSql === 'function') {
497
- return client as SyncularUnsafeSqlClient;
498
- }
499
- throw new SyncularCommandHistoryError(
500
- 'sync.command_history_storage_unavailable',
501
- 'Syncular command history requires internal SQLite write access'
502
- );
503
- }
504
-
505
- private now(): number {
506
- return Math.trunc(this.options.nowMs?.() ?? Date.now());
507
- }
508
- }
509
-
510
- async function readCurrentRow(
511
- client: SyncularSqlClient,
512
- table: string,
513
- idColumn: string,
514
- rowId: string
515
- ): Promise<RowSnapshot> {
516
- const result = await client.executeSql(
517
- `select * from ${quoteIdentifier(table)} where ${quoteIdentifier(idColumn)} = ? limit 1`,
518
- [rowId]
519
- );
520
- const row = result.rows[0];
521
- return row ? normalizeSnapshot(row) : null;
522
- }
523
-
524
- function decodeEntries(row: HistoryRow): CommandEntry[] {
525
- const entries = JSON.parse(row.entries_json) as CommandEntry[];
526
- if (!Array.isArray(entries)) {
527
- throw new SyncularCommandHistoryError(
528
- 'sync.command_history_conflict',
529
- `Syncular command history row ${row.id} is malformed`,
530
- { commandId: row.id }
531
- );
532
- }
533
- return entries;
534
- }
535
-
536
- function normalizeSnapshot(
537
- row: Record<string, unknown>
538
- ): Record<string, unknown> {
539
- return Object.fromEntries(
540
- Object.entries(row).sort(([a], [b]) => a.localeCompare(b))
541
- );
542
- }
543
-
544
- function sameSnapshot(left: RowSnapshot, right: RowSnapshot): boolean {
545
- return stableJson(left) === stableJson(right);
546
- }
547
-
548
- function sameReplaySnapshot(
549
- config: SyncularTableConfigMap[string],
550
- left: RowSnapshot,
551
- right: RowSnapshot
552
- ): boolean {
553
- return (
554
- stableJson(replayComparableSnapshot(config, left)) ===
555
- stableJson(replayComparableSnapshot(config, right))
556
- );
557
- }
558
-
559
- function replayComparableSnapshot(
560
- config: SyncularTableConfigMap[string],
561
- snapshot: RowSnapshot
562
- ): RowSnapshot {
563
- if (snapshot === null) return null;
564
- const comparable = { ...snapshot };
565
- if (config.serverVersionColumn) delete comparable[config.serverVersionColumn];
566
- for (const field of config.crdtYjsFields ?? []) {
567
- delete comparable[field.stateColumn];
568
- }
569
- return comparable;
570
- }
571
-
572
- function unsafeChangedFields(
573
- config: SyncularTableConfigMap[string],
574
- entry: CommandEntry
575
- ): string[] {
576
- const rowLifecycleReplay = entry.before === null || entry.after === null;
577
- const unsafeFields = new Set<string>();
578
- for (const column of config.blobColumns ?? []) unsafeFields.add(column);
579
- for (const field of config.encryptedFields ?? [])
580
- unsafeFields.add(field.field);
581
- if (!rowLifecycleReplay) {
582
- for (const field of config.crdtYjsFields ?? []) {
583
- unsafeFields.add(field.field);
584
- unsafeFields.add(field.stateColumn);
585
- }
586
- }
587
-
588
- const changed: string[] = [];
589
- for (const field of unsafeFields) {
590
- const before = entry.before?.[field];
591
- const after = entry.after?.[field];
592
- if (
593
- stableJson(nullishToNull(before)) === stableJson(nullishToNull(after))
594
- ) {
595
- continue;
596
- }
597
- if (rowLifecycleReplay && before == null && after == null) continue;
598
- changed.push(field);
599
- }
600
- return changed;
601
- }
602
-
603
- function nullishToNull(value: unknown): unknown {
604
- return value == null ? null : value;
605
- }
606
-
607
- function stableJson(value: unknown): string {
608
- return JSON.stringify(sortValue(value));
609
- }
610
-
611
- function sortValue(value: unknown): unknown {
612
- if (Array.isArray(value)) return value.map(sortValue);
613
- if (!value || typeof value !== 'object') return value;
614
- return Object.fromEntries(
615
- Object.entries(value as Record<string, unknown>)
616
- .sort(([a], [b]) => a.localeCompare(b))
617
- .map(([key, nested]) => [key, sortValue(nested)])
618
- );
619
- }
620
-
621
- function quoteIdentifier(identifier: string): string {
622
- return `"${identifier.replaceAll('"', '""')}"`;
623
- }