@terreno/syncdb 56.0.0-beta.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 (317) hide show
  1. package/README.md +419 -0
  2. package/dist/auth/betterAuthAdapter.d.ts +22 -0
  3. package/dist/auth/betterAuthAdapter.d.ts.map +1 -0
  4. package/dist/auth/betterAuthAdapter.js +181 -0
  5. package/dist/auth/betterAuthAdapter.js.map +1 -0
  6. package/dist/auth/betterAuthAdapter.test.d.ts +2 -0
  7. package/dist/auth/betterAuthAdapter.test.d.ts.map +1 -0
  8. package/dist/auth/betterAuthAdapter.test.js +350 -0
  9. package/dist/auth/betterAuthAdapter.test.js.map +1 -0
  10. package/dist/auth/types.d.ts +42 -0
  11. package/dist/auth/types.d.ts.map +1 -0
  12. package/dist/auth/types.js +9 -0
  13. package/dist/auth/types.js.map +1 -0
  14. package/dist/client.d.ts +246 -0
  15. package/dist/client.d.ts.map +1 -0
  16. package/dist/client.js +1415 -0
  17. package/dist/client.js.map +1 -0
  18. package/dist/client.test.d.ts +2 -0
  19. package/dist/client.test.d.ts.map +1 -0
  20. package/dist/client.test.js +2310 -0
  21. package/dist/client.test.js.map +1 -0
  22. package/dist/crypto/aesGcmCodec.d.ts +33 -0
  23. package/dist/crypto/aesGcmCodec.d.ts.map +1 -0
  24. package/dist/crypto/aesGcmCodec.js +80 -0
  25. package/dist/crypto/aesGcmCodec.js.map +1 -0
  26. package/dist/crypto/aesGcmCodec.test.d.ts +2 -0
  27. package/dist/crypto/aesGcmCodec.test.d.ts.map +1 -0
  28. package/dist/crypto/aesGcmCodec.test.js +83 -0
  29. package/dist/crypto/aesGcmCodec.test.js.map +1 -0
  30. package/dist/crypto/identityCodec.d.ts +7 -0
  31. package/dist/crypto/identityCodec.d.ts.map +1 -0
  32. package/dist/crypto/identityCodec.js +9 -0
  33. package/dist/crypto/identityCodec.js.map +1 -0
  34. package/dist/crypto/keyProviders.d.ts +34 -0
  35. package/dist/crypto/keyProviders.d.ts.map +1 -0
  36. package/dist/crypto/keyProviders.js +102 -0
  37. package/dist/crypto/keyProviders.js.map +1 -0
  38. package/dist/crypto/keyProviders.test.d.ts +2 -0
  39. package/dist/crypto/keyProviders.test.d.ts.map +1 -0
  40. package/dist/crypto/keyProviders.test.js +189 -0
  41. package/dist/crypto/keyProviders.test.js.map +1 -0
  42. package/dist/crypto/types.d.ts +24 -0
  43. package/dist/crypto/types.d.ts.map +1 -0
  44. package/dist/crypto/types.js +8 -0
  45. package/dist/crypto/types.js.map +1 -0
  46. package/dist/debug/debugChannel.d.ts +52 -0
  47. package/dist/debug/debugChannel.d.ts.map +1 -0
  48. package/dist/debug/debugChannel.js +73 -0
  49. package/dist/debug/debugChannel.js.map +1 -0
  50. package/dist/debug/debugChannel.test.d.ts +2 -0
  51. package/dist/debug/debugChannel.test.d.ts.map +1 -0
  52. package/dist/debug/debugChannel.test.js +105 -0
  53. package/dist/debug/debugChannel.test.js.map +1 -0
  54. package/dist/debug/debugLog.d.ts +111 -0
  55. package/dist/debug/debugLog.d.ts.map +1 -0
  56. package/dist/debug/debugLog.js +150 -0
  57. package/dist/debug/debugLog.js.map +1 -0
  58. package/dist/debug/debugLog.test.d.ts +2 -0
  59. package/dist/debug/debugLog.test.d.ts.map +1 -0
  60. package/dist/debug/debugLog.test.js +121 -0
  61. package/dist/debug/debugLog.test.js.map +1 -0
  62. package/dist/index.d.ts +46 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +51 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/isolated/defaultPersisterFactoryNative.isolated.d.ts +2 -0
  67. package/dist/isolated/defaultPersisterFactoryNative.isolated.d.ts.map +1 -0
  68. package/dist/isolated/defaultPersisterFactoryNative.isolated.js +38 -0
  69. package/dist/isolated/defaultPersisterFactoryNative.isolated.js.map +1 -0
  70. package/dist/mutations/conflicts.d.ts +31 -0
  71. package/dist/mutations/conflicts.d.ts.map +1 -0
  72. package/dist/mutations/conflicts.js +73 -0
  73. package/dist/mutations/conflicts.js.map +1 -0
  74. package/dist/mutations/outbox.d.ts +174 -0
  75. package/dist/mutations/outbox.d.ts.map +1 -0
  76. package/dist/mutations/outbox.js +385 -0
  77. package/dist/mutations/outbox.js.map +1 -0
  78. package/dist/mutations/outbox.test.d.ts +2 -0
  79. package/dist/mutations/outbox.test.d.ts.map +1 -0
  80. package/dist/mutations/outbox.test.js +643 -0
  81. package/dist/mutations/outbox.test.js.map +1 -0
  82. package/dist/mutations/resolveConflict.d.ts +32 -0
  83. package/dist/mutations/resolveConflict.d.ts.map +1 -0
  84. package/dist/mutations/resolveConflict.js +101 -0
  85. package/dist/mutations/resolveConflict.js.map +1 -0
  86. package/dist/mutations/resolveConflict.test.d.ts +2 -0
  87. package/dist/mutations/resolveConflict.test.d.ts.map +1 -0
  88. package/dist/mutations/resolveConflict.test.js +282 -0
  89. package/dist/mutations/resolveConflict.test.js.map +1 -0
  90. package/dist/persisters/defaultPersisterFactory.d.ts +9 -0
  91. package/dist/persisters/defaultPersisterFactory.d.ts.map +1 -0
  92. package/dist/persisters/defaultPersisterFactory.js +9 -0
  93. package/dist/persisters/defaultPersisterFactory.js.map +1 -0
  94. package/dist/persisters/defaultPersisterFactory.native.d.ts +10 -0
  95. package/dist/persisters/defaultPersisterFactory.native.d.ts.map +1 -0
  96. package/dist/persisters/defaultPersisterFactory.native.js +44 -0
  97. package/dist/persisters/defaultPersisterFactory.native.js.map +1 -0
  98. package/dist/persisters/defaultPersisterFactory.test.d.ts +2 -0
  99. package/dist/persisters/defaultPersisterFactory.test.d.ts.map +1 -0
  100. package/dist/persisters/defaultPersisterFactory.test.js +177 -0
  101. package/dist/persisters/defaultPersisterFactory.test.js.map +1 -0
  102. package/dist/persisters/defaultPersisterFactory.web.d.ts +17 -0
  103. package/dist/persisters/defaultPersisterFactory.web.d.ts.map +1 -0
  104. package/dist/persisters/defaultPersisterFactory.web.js +65 -0
  105. package/dist/persisters/defaultPersisterFactory.web.js.map +1 -0
  106. package/dist/persisters/encryptedIndexedDbPersister.d.ts +46 -0
  107. package/dist/persisters/encryptedIndexedDbPersister.d.ts.map +1 -0
  108. package/dist/persisters/encryptedIndexedDbPersister.js +171 -0
  109. package/dist/persisters/encryptedIndexedDbPersister.js.map +1 -0
  110. package/dist/persisters/encryptedIndexedDbPersister.test.d.ts +2 -0
  111. package/dist/persisters/encryptedIndexedDbPersister.test.d.ts.map +1 -0
  112. package/dist/persisters/encryptedIndexedDbPersister.test.js +352 -0
  113. package/dist/persisters/encryptedIndexedDbPersister.test.js.map +1 -0
  114. package/dist/persisters/memoryPersister.d.ts +19 -0
  115. package/dist/persisters/memoryPersister.d.ts.map +1 -0
  116. package/dist/persisters/memoryPersister.js +31 -0
  117. package/dist/persisters/memoryPersister.js.map +1 -0
  118. package/dist/persisters/memoryPersister.test.d.ts +2 -0
  119. package/dist/persisters/memoryPersister.test.d.ts.map +1 -0
  120. package/dist/persisters/memoryPersister.test.js +113 -0
  121. package/dist/persisters/memoryPersister.test.js.map +1 -0
  122. package/dist/persisters/types.d.ts +65 -0
  123. package/dist/persisters/types.d.ts.map +1 -0
  124. package/dist/persisters/types.js +2 -0
  125. package/dist/persisters/types.js.map +1 -0
  126. package/dist/react/hooks.d.ts +132 -0
  127. package/dist/react/hooks.d.ts.map +1 -0
  128. package/dist/react/hooks.js +269 -0
  129. package/dist/react/hooks.js.map +1 -0
  130. package/dist/react/hooks.test.d.ts +2 -0
  131. package/dist/react/hooks.test.d.ts.map +1 -0
  132. package/dist/react/hooks.test.js +645 -0
  133. package/dist/react/hooks.test.js.map +1 -0
  134. package/dist/react/index.d.ts +11 -0
  135. package/dist/react/index.d.ts.map +1 -0
  136. package/dist/react/index.js +11 -0
  137. package/dist/react/index.js.map +1 -0
  138. package/dist/react/provider.d.ts +11 -0
  139. package/dist/react/provider.d.ts.map +1 -0
  140. package/dist/react/provider.js +17 -0
  141. package/dist/react/provider.js.map +1 -0
  142. package/dist/storage/idb.d.ts +27 -0
  143. package/dist/storage/idb.d.ts.map +1 -0
  144. package/dist/storage/idb.js +72 -0
  145. package/dist/storage/idb.js.map +1 -0
  146. package/dist/storage/idb.test.d.ts +2 -0
  147. package/dist/storage/idb.test.d.ts.map +1 -0
  148. package/dist/storage/idb.test.js +100 -0
  149. package/dist/storage/idb.test.js.map +1 -0
  150. package/dist/storage/purgeUnknownStream.test.d.ts +2 -0
  151. package/dist/storage/purgeUnknownStream.test.d.ts.map +1 -0
  152. package/dist/storage/purgeUnknownStream.test.js +64 -0
  153. package/dist/storage/purgeUnknownStream.test.js.map +1 -0
  154. package/dist/storage/schema.d.ts +33 -0
  155. package/dist/storage/schema.d.ts.map +1 -0
  156. package/dist/storage/schema.js +92 -0
  157. package/dist/storage/schema.js.map +1 -0
  158. package/dist/storage/store.d.ts +136 -0
  159. package/dist/storage/store.d.ts.map +1 -0
  160. package/dist/storage/store.js +275 -0
  161. package/dist/storage/store.js.map +1 -0
  162. package/dist/storage/store.test.d.ts +2 -0
  163. package/dist/storage/store.test.d.ts.map +1 -0
  164. package/dist/storage/store.test.js +357 -0
  165. package/dist/storage/store.test.js.map +1 -0
  166. package/dist/storage/types.d.ts +146 -0
  167. package/dist/storage/types.d.ts.map +1 -0
  168. package/dist/storage/types.js +32 -0
  169. package/dist/storage/types.js.map +1 -0
  170. package/dist/storage/wipe.d.ts +22 -0
  171. package/dist/storage/wipe.d.ts.map +1 -0
  172. package/dist/storage/wipe.js +43 -0
  173. package/dist/storage/wipe.js.map +1 -0
  174. package/dist/storage/wipe.test.d.ts +2 -0
  175. package/dist/storage/wipe.test.d.ts.map +1 -0
  176. package/dist/storage/wipe.test.js +95 -0
  177. package/dist/storage/wipe.test.js.map +1 -0
  178. package/dist/sync/bootstrap.d.ts +64 -0
  179. package/dist/sync/bootstrap.d.ts.map +1 -0
  180. package/dist/sync/bootstrap.js +160 -0
  181. package/dist/sync/bootstrap.js.map +1 -0
  182. package/dist/sync/bootstrap.test.d.ts +2 -0
  183. package/dist/sync/bootstrap.test.d.ts.map +1 -0
  184. package/dist/sync/bootstrap.test.js +447 -0
  185. package/dist/sync/bootstrap.test.js.map +1 -0
  186. package/dist/sync/cursor.d.ts +67 -0
  187. package/dist/sync/cursor.d.ts.map +1 -0
  188. package/dist/sync/cursor.js +74 -0
  189. package/dist/sync/cursor.js.map +1 -0
  190. package/dist/sync/cursor.test.d.ts +2 -0
  191. package/dist/sync/cursor.test.d.ts.map +1 -0
  192. package/dist/sync/cursor.test.js +73 -0
  193. package/dist/sync/cursor.test.js.map +1 -0
  194. package/dist/sync/deltaApplier.d.ts +30 -0
  195. package/dist/sync/deltaApplier.d.ts.map +1 -0
  196. package/dist/sync/deltaApplier.js +61 -0
  197. package/dist/sync/deltaApplier.js.map +1 -0
  198. package/dist/sync/deltaApplier.test.d.ts +2 -0
  199. package/dist/sync/deltaApplier.test.d.ts.map +1 -0
  200. package/dist/sync/deltaApplier.test.js +212 -0
  201. package/dist/sync/deltaApplier.test.js.map +1 -0
  202. package/dist/sync/entityRepair.d.ts +45 -0
  203. package/dist/sync/entityRepair.d.ts.map +1 -0
  204. package/dist/sync/entityRepair.js +91 -0
  205. package/dist/sync/entityRepair.js.map +1 -0
  206. package/dist/sync/entityRepair.test.d.ts +2 -0
  207. package/dist/sync/entityRepair.test.d.ts.map +1 -0
  208. package/dist/sync/entityRepair.test.js +146 -0
  209. package/dist/sync/entityRepair.test.js.map +1 -0
  210. package/dist/sync/httpChannel.d.ts +74 -0
  211. package/dist/sync/httpChannel.d.ts.map +1 -0
  212. package/dist/sync/httpChannel.js +123 -0
  213. package/dist/sync/httpChannel.js.map +1 -0
  214. package/dist/sync/httpChannel.test.d.ts +2 -0
  215. package/dist/sync/httpChannel.test.d.ts.map +1 -0
  216. package/dist/sync/httpChannel.test.js +215 -0
  217. package/dist/sync/httpChannel.test.js.map +1 -0
  218. package/dist/sync/replayCoordinator.d.ts +212 -0
  219. package/dist/sync/replayCoordinator.d.ts.map +1 -0
  220. package/dist/sync/replayCoordinator.js +1110 -0
  221. package/dist/sync/replayCoordinator.js.map +1 -0
  222. package/dist/sync/replayCoordinator.test.d.ts +2 -0
  223. package/dist/sync/replayCoordinator.test.d.ts.map +1 -0
  224. package/dist/sync/replayCoordinator.test.js +1496 -0
  225. package/dist/sync/replayCoordinator.test.js.map +1 -0
  226. package/dist/sync/socketTransport.d.ts +56 -0
  227. package/dist/sync/socketTransport.d.ts.map +1 -0
  228. package/dist/sync/socketTransport.js +292 -0
  229. package/dist/sync/socketTransport.js.map +1 -0
  230. package/dist/sync/socketTransport.test.d.ts +2 -0
  231. package/dist/sync/socketTransport.test.d.ts.map +1 -0
  232. package/dist/sync/socketTransport.test.js +346 -0
  233. package/dist/sync/socketTransport.test.js.map +1 -0
  234. package/dist/sync/transport.d.ts +80 -0
  235. package/dist/sync/transport.d.ts.map +1 -0
  236. package/dist/sync/transport.js +5 -0
  237. package/dist/sync/transport.js.map +1 -0
  238. package/dist/testing/fakeTransport.d.ts +55 -0
  239. package/dist/testing/fakeTransport.d.ts.map +1 -0
  240. package/dist/testing/fakeTransport.js +139 -0
  241. package/dist/testing/fakeTransport.js.map +1 -0
  242. package/dist/testing/fakeTransport.test.d.ts +2 -0
  243. package/dist/testing/fakeTransport.test.d.ts.map +1 -0
  244. package/dist/testing/fakeTransport.test.js +112 -0
  245. package/dist/testing/fakeTransport.test.js.map +1 -0
  246. package/dist/testing/index.d.ts +13 -0
  247. package/dist/testing/index.d.ts.map +1 -0
  248. package/dist/testing/index.js +13 -0
  249. package/dist/testing/index.js.map +1 -0
  250. package/dist/types.d.ts +271 -0
  251. package/dist/types.d.ts.map +1 -0
  252. package/dist/types.js +9 -0
  253. package/dist/types.js.map +1 -0
  254. package/package.json +71 -0
  255. package/src/auth/betterAuthAdapter.test.ts +455 -0
  256. package/src/auth/betterAuthAdapter.ts +214 -0
  257. package/src/auth/types.ts +49 -0
  258. package/src/client.test.ts +2670 -0
  259. package/src/client.ts +1748 -0
  260. package/src/crypto/aesGcmCodec.test.ts +103 -0
  261. package/src/crypto/aesGcmCodec.ts +98 -0
  262. package/src/crypto/identityCodec.ts +10 -0
  263. package/src/crypto/keyProviders.test.ts +228 -0
  264. package/src/crypto/keyProviders.ts +153 -0
  265. package/src/crypto/types.ts +23 -0
  266. package/src/debug/debugChannel.test.ts +121 -0
  267. package/src/debug/debugChannel.ts +112 -0
  268. package/src/debug/debugLog.test.ts +139 -0
  269. package/src/debug/debugLog.ts +272 -0
  270. package/src/index.ts +157 -0
  271. package/src/isolated/defaultPersisterFactoryNative.isolated.ts +45 -0
  272. package/src/mutations/conflicts.ts +108 -0
  273. package/src/mutations/outbox.test.ts +754 -0
  274. package/src/mutations/outbox.ts +585 -0
  275. package/src/mutations/resolveConflict.test.ts +338 -0
  276. package/src/mutations/resolveConflict.ts +115 -0
  277. package/src/persisters/defaultPersisterFactory.native.ts +53 -0
  278. package/src/persisters/defaultPersisterFactory.test.ts +207 -0
  279. package/src/persisters/defaultPersisterFactory.ts +12 -0
  280. package/src/persisters/defaultPersisterFactory.web.ts +78 -0
  281. package/src/persisters/encryptedIndexedDbPersister.test.ts +381 -0
  282. package/src/persisters/encryptedIndexedDbPersister.ts +218 -0
  283. package/src/persisters/memoryPersister.test.ts +136 -0
  284. package/src/persisters/memoryPersister.ts +52 -0
  285. package/src/persisters/types.ts +71 -0
  286. package/src/react/hooks.test.tsx +761 -0
  287. package/src/react/hooks.ts +409 -0
  288. package/src/react/index.ts +11 -0
  289. package/src/react/provider.tsx +27 -0
  290. package/src/storage/idb.test.ts +116 -0
  291. package/src/storage/idb.ts +112 -0
  292. package/src/storage/purgeUnknownStream.test.ts +74 -0
  293. package/src/storage/schema.ts +103 -0
  294. package/src/storage/store.test.ts +424 -0
  295. package/src/storage/store.ts +461 -0
  296. package/src/storage/types.ts +159 -0
  297. package/src/storage/wipe.test.ts +111 -0
  298. package/src/storage/wipe.ts +58 -0
  299. package/src/sync/bootstrap.test.ts +486 -0
  300. package/src/sync/bootstrap.ts +217 -0
  301. package/src/sync/cursor.test.ts +84 -0
  302. package/src/sync/cursor.ts +113 -0
  303. package/src/sync/deltaApplier.test.ts +237 -0
  304. package/src/sync/deltaApplier.ts +84 -0
  305. package/src/sync/entityRepair.test.ts +161 -0
  306. package/src/sync/entityRepair.ts +124 -0
  307. package/src/sync/httpChannel.test.ts +265 -0
  308. package/src/sync/httpChannel.ts +220 -0
  309. package/src/sync/replayCoordinator.test.ts +1709 -0
  310. package/src/sync/replayCoordinator.ts +1370 -0
  311. package/src/sync/socketTransport.test.ts +413 -0
  312. package/src/sync/socketTransport.ts +379 -0
  313. package/src/sync/transport.ts +76 -0
  314. package/src/testing/fakeTransport.test.ts +125 -0
  315. package/src/testing/fakeTransport.ts +206 -0
  316. package/src/testing/index.ts +18 -0
  317. package/src/types.ts +284 -0
@@ -0,0 +1,2670 @@
1
+ import "fake-indexeddb/auto";
2
+
3
+ import {describe, expect, it} from "bun:test";
4
+
5
+ import {createSyncDb, type SyncDbConfig} from "./client";
6
+ import {createLocalKeyProvider, DEFAULT_KEY_CACHE_DB_NAME} from "./crypto/keyProviders";
7
+ import {getConflict} from "./mutations/conflicts";
8
+ import {createDefaultPersisterFactory as createWebPersisterFactory} from "./persisters/defaultPersisterFactory.web";
9
+ import {memoryPersisterFactory} from "./persisters/memoryPersister";
10
+ import {idbGet} from "./storage/idb";
11
+ import {SYNC_SCHEMA_VERSION} from "./storage/schema";
12
+ import {CURSORS_TABLE} from "./storage/types";
13
+ import {AuthRequiredError, type HttpChannel} from "./sync/httpChannel";
14
+ import {createFakeTransport, type FakeTransport} from "./testing/fakeTransport";
15
+ import type {AuthProvider, SyncDelta, SyncSnapshotResponse, SyncStreamInfo} from "./types";
16
+
17
+ let nameCounter = 0;
18
+ const uniqueName = (): string => {
19
+ nameCounter += 1;
20
+ return `client-test-${nameCounter}`;
21
+ };
22
+
23
+ const flush = async (): Promise<void> => {
24
+ await new Promise((resolve) => setTimeout(resolve, 5));
25
+ };
26
+
27
+ interface FakeAuth {
28
+ provider: AuthProvider;
29
+ setUserId: (userId: string | null) => void;
30
+ emitAuthChange: () => void;
31
+ }
32
+
33
+ const makeAuthProvider = (initialUserId: string | null = "u1"): FakeAuth => {
34
+ const listeners = new Set<() => void>();
35
+ const state = {userId: initialUserId};
36
+ return {
37
+ emitAuthChange: (): void => {
38
+ for (const listener of listeners) {
39
+ listener();
40
+ }
41
+ },
42
+ provider: {
43
+ getToken: async () => "token",
44
+ getUserId: async () => state.userId,
45
+ onAuthChange: (callback: () => void): (() => void) => {
46
+ listeners.add(callback);
47
+ return () => {
48
+ listeners.delete(callback);
49
+ };
50
+ },
51
+ },
52
+ setUserId: (userId: string | null): void => {
53
+ state.userId = userId;
54
+ },
55
+ };
56
+ };
57
+
58
+ /** The single stream the default harness advertises via GET /sync/streams. */
59
+ const DEFAULT_STREAM = "todos|owner:u1";
60
+
61
+ interface FakeChannel {
62
+ channel: HttpChannel;
63
+ state: {
64
+ fetchCount: number;
65
+ streamsCount: number;
66
+ /** Snapshot pages keyed by stream key. */
67
+ pages: Record<string, SyncSnapshotResponse>;
68
+ /** The membership set GET /sync/streams returns; mutate in a test to model join/leave. */
69
+ streams: SyncStreamInfo[];
70
+ /** When set, fetchStreams throws this instead of returning (401/transport tests). */
71
+ streamsError?: Error;
72
+ };
73
+ }
74
+
75
+ /** An empty snapshot page carrying the C1/C7 fields (no more data, no retention gap). */
76
+ const emptyPage = (stream: string, cursor = 0): SyncSnapshotResponse => ({
77
+ cursor,
78
+ entities: [],
79
+ frontierSeq: cursor,
80
+ hasMore: false,
81
+ oldestRetainedSeq: 0,
82
+ stream,
83
+ });
84
+
85
+ const makeChannel = (): FakeChannel => {
86
+ const state: FakeChannel["state"] = {
87
+ fetchCount: 0,
88
+ pages: {},
89
+ streams: [{collection: "todos", stream: DEFAULT_STREAM}],
90
+ streamsCount: 0,
91
+ };
92
+ return {
93
+ channel: {
94
+ fetchEntities: async () => ({entities: []}),
95
+ fetchKeyMaterial: async () => {
96
+ throw new Error("key material not expected in this test");
97
+ },
98
+ fetchSnapshotPage: async ({stream}) => {
99
+ state.fetchCount += 1;
100
+ return state.pages[stream] ?? emptyPage(stream);
101
+ },
102
+ fetchStreams: async () => {
103
+ state.streamsCount += 1;
104
+ if (state.streamsError) {
105
+ throw state.streamsError;
106
+ }
107
+ return state.streams;
108
+ },
109
+ sendMutation: async () => {
110
+ throw new Error("HTTP mutate not expected in this test");
111
+ },
112
+ },
113
+ state,
114
+ };
115
+ };
116
+
117
+ interface Harness {
118
+ auth: FakeAuth;
119
+ transport: FakeTransport;
120
+ http: FakeChannel;
121
+ clock: {value: number};
122
+ config: SyncDbConfig;
123
+ }
124
+
125
+ const makeHarness = (overrides: Partial<SyncDbConfig> = {}): Harness => {
126
+ const auth = makeAuthProvider();
127
+ const transport = createFakeTransport();
128
+ const http = makeChannel();
129
+ const clock = {value: 1_000_000};
130
+ return {
131
+ auth,
132
+ clock,
133
+ config: {
134
+ authProvider: auth.provider,
135
+ collections: ["todos"],
136
+ httpChannel: http.channel,
137
+ name: uniqueName(),
138
+ now: () => clock.value,
139
+ persisterFactory: memoryPersisterFactory,
140
+ reconcileIntervalMs: 0,
141
+ transport,
142
+ ...overrides,
143
+ },
144
+ http,
145
+ transport,
146
+ };
147
+ };
148
+
149
+ const makeDelta = (overrides: Partial<SyncDelta> = {}): SyncDelta => ({
150
+ collection: "todos",
151
+ data: {title: "from server"},
152
+ id: "t1",
153
+ method: "create",
154
+ seq: 1,
155
+ stream: "todos|owner:u1",
156
+ ...overrides,
157
+ });
158
+
159
+ interface ObservableTransport {
160
+ transport: FakeTransport;
161
+ /** connect/disconnect/subscribe calls in the order the client made them. */
162
+ events: string[];
163
+ /**
164
+ * Hold the NEXT connect() open until the returned resolver runs, so a test
165
+ * can act while a reconnect (e.g. a user-switch bounce) is still in flight.
166
+ */
167
+ gateNextConnect: () => () => void;
168
+ }
169
+
170
+ /** Wrap a fake transport to record its lifecycle calls and gate one connect(). */
171
+ const makeObservableTransport = (base: FakeTransport): ObservableTransport => {
172
+ const events: string[] = [];
173
+ let gate: Promise<void> | undefined;
174
+ return {
175
+ events,
176
+ gateNextConnect: (): (() => void) => {
177
+ let release = (): void => {};
178
+ gate = new Promise<void>((resolve) => {
179
+ release = (): void => resolve();
180
+ });
181
+ return release;
182
+ },
183
+ transport: {
184
+ ...base,
185
+ connect: async (): Promise<void> => {
186
+ events.push("connect");
187
+ const pending = gate;
188
+ gate = undefined;
189
+ if (pending !== undefined) {
190
+ await pending;
191
+ }
192
+ await base.connect();
193
+ },
194
+ disconnect: (): void => {
195
+ events.push("disconnect");
196
+ base.disconnect();
197
+ },
198
+ subscribe: (collections: string[]): void => {
199
+ events.push("subscribe");
200
+ base.subscribe(collections);
201
+ },
202
+ },
203
+ };
204
+ };
205
+
206
+ describe("createSyncDb", () => {
207
+ it("requires a transport or a baseUrl", () => {
208
+ const auth = makeAuthProvider();
209
+ expect(() =>
210
+ createSyncDb({authProvider: auth.provider, collections: ["todos"], name: uniqueName()})
211
+ ).toThrow("requires a transport or a baseUrl");
212
+ });
213
+
214
+ it("constructs default socket transport and http channel from baseUrl", () => {
215
+ const auth = makeAuthProvider();
216
+ const client = createSyncDb({
217
+ authProvider: auth.provider,
218
+ baseUrl: "http://127.0.0.1:9",
219
+ collections: ["todos"],
220
+ name: uniqueName(),
221
+ });
222
+ expect(client.getSyncStatus()).toEqual({
223
+ blockedEntities: 0,
224
+ collections: {},
225
+ conflictCount: 0,
226
+ draining: false,
227
+ failedCount: 0,
228
+ isOnline: false,
229
+ isSyncing: false,
230
+ persistence: "durable",
231
+ queuedCount: 0,
232
+ sentThisDrain: 0,
233
+ streams: {},
234
+ totalThisDrain: 0,
235
+ });
236
+ });
237
+
238
+ it("start() rejects without an authenticated user", async () => {
239
+ // startAuthRetryAttempts: 1 disables retrying so this stays instant — the
240
+ // no-retry-attempts contract is tested here; retry behavior is tested below.
241
+ const harness = makeHarness({startAuthRetryAttempts: 1});
242
+ harness.auth.setUserId(null);
243
+ const client = createSyncDb(harness.config);
244
+ await expect(client.start()).rejects.toThrow("requires an authenticated user");
245
+ });
246
+
247
+ it("start() retries auth resolution before giving up", async () => {
248
+ const harness = makeHarness({startAuthRetryAttempts: 3, startAuthRetryDelayMs: 1});
249
+ harness.auth.setUserId(null);
250
+ const client = createSyncDb(harness.config);
251
+
252
+ // Transient failure: getUserId() only resolves on the 2nd attempt — start()
253
+ // should not throw on the first null, matching a host app that calls start()
254
+ // right after its own login flow resolved (see client.ts start() doc).
255
+ let calls = 0;
256
+ const originalGetUserId = harness.config.authProvider.getUserId;
257
+ harness.config.authProvider.getUserId = async () => {
258
+ calls += 1;
259
+ if (calls === 1) {
260
+ return null;
261
+ }
262
+ return originalGetUserId();
263
+ };
264
+ harness.auth.setUserId("retry-user");
265
+
266
+ await client.start();
267
+ expect(calls).toBeGreaterThanOrEqual(2);
268
+ });
269
+
270
+ it("start() rejects when auth never resolves after exhausting retries", async () => {
271
+ const harness = makeHarness({startAuthRetryAttempts: 2, startAuthRetryDelayMs: 1});
272
+ harness.auth.setUserId(null);
273
+ const client = createSyncDb(harness.config);
274
+ await expect(client.start()).rejects.toThrow("requires an authenticated user");
275
+ });
276
+
277
+ it("start() connects, subscribes the collections, and records the user", async () => {
278
+ const harness = makeHarness();
279
+ const client = createSyncDb(harness.config);
280
+ await client.start();
281
+ expect(harness.transport.subscribedCollections).toEqual(["todos"]);
282
+ expect(client.store.getLastUserId()).toBe("u1");
283
+ expect(client.getSyncStatus().isOnline).toBe(true);
284
+ await client.stop();
285
+ });
286
+
287
+ it("start() succeeds when the transport cannot connect (offline start)", async () => {
288
+ const harness = makeHarness();
289
+ const offlineTransport: FakeTransport = {
290
+ ...harness.transport,
291
+ connect: async () => {
292
+ throw new Error("no network");
293
+ },
294
+ };
295
+ const client = createSyncDb({...harness.config, transport: offlineTransport});
296
+ await client.start();
297
+ expect(client.getSyncStatus().isOnline).toBe(false);
298
+ await client.stop();
299
+ });
300
+
301
+ describe("mutate", () => {
302
+ it("throws before start() and for updates/deletes without an id", async () => {
303
+ const harness = makeHarness();
304
+ const client = createSyncDb(harness.config);
305
+ expect(() => client.mutate({collection: "todos", operation: "create"})).toThrow(
306
+ "requires start()"
307
+ );
308
+ await client.start();
309
+ expect(() => client.mutate({collection: "todos", operation: "update"})).toThrow(
310
+ "requires an id"
311
+ );
312
+ expect(() => client.mutate({collection: "todos", operation: "delete"})).toThrow(
313
+ "requires an id"
314
+ );
315
+ await client.stop();
316
+ });
317
+
318
+ it("applies creates optimistically and immediately", async () => {
319
+ const harness = makeHarness();
320
+ // Hold replies so the pre-ack state is observable.
321
+ harness.transport.setDefaultResponder(async () => {
322
+ await flush();
323
+ throw new Error("offline");
324
+ });
325
+ const client = createSyncDb(harness.config);
326
+ await client.start();
327
+
328
+ const {id, mutationId} = client.mutate({
329
+ collection: "todos",
330
+ data: {title: "buy milk"},
331
+ operation: "create",
332
+ });
333
+ const entity = client.store.getEntity({collection: "todos", id});
334
+ expect(entity?.data).toEqual({title: "buy milk"});
335
+ expect(entity?.pendingMutationId).toBe(mutationId);
336
+ expect(entity?.seq).toBe(0);
337
+ expect(["inFlight", "queued"]).toContain(
338
+ client.outbox.getMutation({mutationId})?.status ?? "missing"
339
+ );
340
+ await client.stop();
341
+ });
342
+
343
+ it("acked mutations clear pendingMutationId and stamp the server seq", async () => {
344
+ const harness = makeHarness();
345
+ harness.transport.respondWithAck({seq: 11});
346
+ const client = createSyncDb(harness.config);
347
+ await client.start();
348
+
349
+ const {id} = client.mutate({collection: "todos", data: {title: "x"}, operation: "create"});
350
+ await flush();
351
+ const entity = client.store.getEntity({collection: "todos", id});
352
+ expect(entity?.pendingMutationId).toBeUndefined();
353
+ expect(entity?.seq).toBe(11);
354
+ expect(client.getSyncStatus().queuedCount).toBe(0);
355
+ await client.stop();
356
+ });
357
+
358
+ it("updates merge into the existing entity data", async () => {
359
+ const harness = makeHarness();
360
+ const client = createSyncDb(harness.config);
361
+ await client.start();
362
+ client.store.upsertEntity({
363
+ collection: "todos",
364
+ data: {completed: false, title: "old"},
365
+ id: "t1",
366
+ seq: 3,
367
+ });
368
+
369
+ const {mutationId} = client.mutate({
370
+ collection: "todos",
371
+ data: {title: "new"},
372
+ id: "t1",
373
+ operation: "update",
374
+ });
375
+ expect(client.store.getEntity({collection: "todos", id: "t1"})?.data).toEqual({
376
+ completed: false,
377
+ title: "new",
378
+ });
379
+ // baseVersion carries the entity's last known seq.
380
+ expect(client.outbox.getMutation({mutationId})?.baseVersion).toBe(3);
381
+ await client.stop();
382
+ });
383
+
384
+ it("deletes tombstone locally while keeping the last data", async () => {
385
+ const harness = makeHarness();
386
+ harness.transport.setDefaultResponder(() => {
387
+ throw new Error("offline");
388
+ });
389
+ const client = createSyncDb(harness.config);
390
+ await client.start();
391
+ client.store.upsertEntity({collection: "todos", data: {title: "bye"}, id: "t1", seq: 2});
392
+
393
+ const {mutationId} = client.mutate({collection: "todos", id: "t1", operation: "delete"});
394
+ const tombstone = client.store.getEntity({collection: "todos", id: "t1"});
395
+ expect(tombstone?.deleted).toBe(true);
396
+ expect(tombstone?.data).toEqual({title: "bye"});
397
+ expect(tombstone?.pendingMutationId).toBe(mutationId);
398
+ // Deleted entities disappear from default list reads.
399
+ expect(client.store.listEntities({collection: "todos"})).toEqual([]);
400
+ await client.stop();
401
+ });
402
+ });
403
+
404
+ it("applies transport deltas to the local store", async () => {
405
+ const harness = makeHarness();
406
+ const client = createSyncDb(harness.config);
407
+ await client.start();
408
+
409
+ harness.transport.deliverDelta(makeDelta());
410
+ expect(client.store.getEntity({collection: "todos", id: "t1"})?.data).toEqual({
411
+ title: "from server",
412
+ });
413
+ expect(client.getSyncStatus().streams["todos|owner:u1"]).toBe(1);
414
+ await client.stop();
415
+ });
416
+
417
+ describe("reconcile triggers", () => {
418
+ it("reconciles and replays when the transport (re)connects", async () => {
419
+ const harness = makeHarness();
420
+ const client = createSyncDb(harness.config);
421
+ await client.start();
422
+ await flush();
423
+ const baseline = harness.http.state.fetchCount;
424
+ expect(baseline).toBeGreaterThanOrEqual(1);
425
+
426
+ harness.transport.setConnected(false);
427
+ harness.transport.setConnected(true);
428
+ await flush();
429
+ expect(harness.http.state.fetchCount).toBe(baseline + 1);
430
+ await client.stop();
431
+ });
432
+
433
+ it("rate-limits seq-jump reconciles per stream", async () => {
434
+ const harness = makeHarness();
435
+ const client = createSyncDb(harness.config);
436
+ await client.start();
437
+ await flush();
438
+ const baseline = harness.http.state.fetchCount;
439
+
440
+ // First jump (seq 10 with cursor 0) triggers a reconcile.
441
+ harness.transport.deliverDelta(makeDelta({id: "a", seq: 10}));
442
+ await flush();
443
+ expect(harness.http.state.fetchCount).toBe(baseline + 1);
444
+
445
+ // A second jump on the same stream inside the window is suppressed.
446
+ harness.transport.deliverDelta(makeDelta({id: "b", seq: 20}));
447
+ await flush();
448
+ expect(harness.http.state.fetchCount).toBe(baseline + 1);
449
+
450
+ // A jump on a different stream is rate-limited independently.
451
+ harness.transport.deliverDelta(makeDelta({id: "c", seq: 10, stream: "todos|owner:other"}));
452
+ await flush();
453
+ expect(harness.http.state.fetchCount).toBe(baseline + 2);
454
+
455
+ // After the per-stream window elapses the same stream may reconcile again.
456
+ harness.clock.value += 30_000;
457
+ harness.transport.deliverDelta(makeDelta({id: "d", seq: 40}));
458
+ await flush();
459
+ expect(harness.http.state.fetchCount).toBe(baseline + 3);
460
+ await client.stop();
461
+ });
462
+
463
+ it("non-jump deltas never trigger a reconcile", async () => {
464
+ const harness = makeHarness();
465
+ const client = createSyncDb(harness.config);
466
+ await client.start();
467
+ await flush();
468
+ const baseline = harness.http.state.fetchCount;
469
+ harness.transport.deliverDelta(makeDelta({seq: 1}));
470
+ await flush();
471
+ expect(harness.http.state.fetchCount).toBe(baseline);
472
+ await client.stop();
473
+ });
474
+
475
+ it("runs the periodic reconcile timer and stops it on stop()", async () => {
476
+ const harness = makeHarness({reconcileIntervalMs: 20});
477
+ const client = createSyncDb(harness.config);
478
+ await client.start();
479
+ await flush();
480
+ const baseline = harness.http.state.fetchCount;
481
+ await new Promise((resolve) => setTimeout(resolve, 70));
482
+ const afterTimer = harness.http.state.fetchCount;
483
+ expect(afterTimer).toBeGreaterThan(baseline);
484
+
485
+ await client.stop();
486
+ await new Promise((resolve) => setTimeout(resolve, 50));
487
+ expect(harness.http.state.fetchCount).toBe(afterTimer);
488
+ });
489
+
490
+ it("reconcile() is a no-op without an http channel", async () => {
491
+ const harness = makeHarness({httpChannel: undefined});
492
+ const client = createSyncDb({...harness.config, httpChannel: undefined});
493
+ await client.start();
494
+ await expect(client.reconcile()).resolves.toBeUndefined();
495
+ await client.stop();
496
+ });
497
+ });
498
+
499
+ describe("stream discovery, join & leave (C2)", () => {
500
+ it("join: a newly-returned stream is bootstrapped from 0 and recorded as known", async () => {
501
+ const harness = makeHarness();
502
+ const joined = "todos|tenant:org1";
503
+ // Server advertises the default owner stream plus a new tenant stream, and serves a
504
+ // one-entity page for the joined stream.
505
+ harness.http.state.streams = [
506
+ {collection: "todos", stream: DEFAULT_STREAM},
507
+ {collection: "todos", stream: joined},
508
+ ];
509
+ harness.http.state.pages[joined] = {
510
+ cursor: 4,
511
+ entities: [{data: {title: "tenant doc"}, deleted: false, id: "tj", seq: 4}],
512
+ frontierSeq: 4,
513
+ hasMore: false,
514
+ oldestRetainedSeq: 0,
515
+ stream: joined,
516
+ };
517
+ const client = createSyncDb(harness.config);
518
+ await client.start();
519
+ await flush();
520
+
521
+ expect(client.store.getKnownStreams().sort()).toEqual([DEFAULT_STREAM, joined].sort());
522
+ expect(client.store.getEntity({collection: "todos", id: "tj"})?.data).toEqual({
523
+ title: "tenant doc",
524
+ });
525
+ await client.stop();
526
+ });
527
+
528
+ it("ignores streams for collections the client is not configured to sync", async () => {
529
+ // A backend can host more collections than this client subscribes to (e.g. a
530
+ // tenant-scoped `projects` stream exposed to org members while this app only
531
+ // syncs `todos`). Discovery must skip the unconfigured stream instead of trying
532
+ // to bootstrap it into a store with no `projects` table (which previously threw
533
+ // "Unknown collection projects" and failed the whole reconcile).
534
+ const harness = makeHarness();
535
+ const unconfigured = "projects|tenant:org1";
536
+ harness.http.state.streams = [
537
+ {collection: "todos", stream: DEFAULT_STREAM},
538
+ {collection: "projects", stream: unconfigured},
539
+ ];
540
+ harness.http.state.pages[unconfigured] = {
541
+ cursor: 1,
542
+ entities: [{data: {title: "a project"}, deleted: false, id: "p1", seq: 1}],
543
+ frontierSeq: 1,
544
+ hasMore: false,
545
+ oldestRetainedSeq: 0,
546
+ stream: unconfigured,
547
+ };
548
+ const client = createSyncDb(harness.config);
549
+ await client.start();
550
+ await flush();
551
+
552
+ // The configured todos stream is bootstrapped and known; the projects stream is
553
+ // neither known nor bootstrapped, and reconcile did not throw.
554
+ expect(client.store.getKnownStreams()).toContain(DEFAULT_STREAM);
555
+ expect(client.store.getKnownStreams()).not.toContain(unconfigured);
556
+ expect(client.getSyncStatus().paused).toBeUndefined();
557
+ await client.stop();
558
+ });
559
+
560
+ it("leave (HTTP 200): a stream absent from the server set is purged locally", async () => {
561
+ const harness = makeHarness();
562
+ const leaving = "todos|tenant:org1";
563
+ // First discovery advertises both streams so org1 becomes known and its entity lands.
564
+ harness.http.state.streams = [
565
+ {collection: "todos", stream: DEFAULT_STREAM},
566
+ {collection: "todos", stream: leaving},
567
+ ];
568
+ harness.http.state.pages[leaving] = {
569
+ cursor: 2,
570
+ entities: [{data: {title: "org doc"}, deleted: false, id: "og", seq: 2}],
571
+ frontierSeq: 2,
572
+ hasMore: false,
573
+ oldestRetainedSeq: 0,
574
+ stream: leaving,
575
+ };
576
+ const client = createSyncDb(harness.config);
577
+ await client.start();
578
+ await flush();
579
+ expect(client.store.getEntity({collection: "todos", id: "og"})?.data).toEqual({
580
+ title: "org doc",
581
+ });
582
+ expect(client.store.getKnownStreams()).toContain(leaving);
583
+
584
+ // Membership changes: org1 is gone. A successful (HTTP 200) discovery purges it.
585
+ harness.http.state.streams = [{collection: "todos", stream: DEFAULT_STREAM}];
586
+ await client.reconcile();
587
+ await flush();
588
+
589
+ expect(client.store.getEntity({collection: "todos", id: "og"})).toBeUndefined();
590
+ expect(client.store.getKnownStreams()).not.toContain(leaving);
591
+ await client.stop();
592
+ });
593
+
594
+ it("leave under 401 (INV-2): NO purge, auth-pause, local data intact", async () => {
595
+ const harness = makeHarness();
596
+ const stream = "todos|tenant:org1";
597
+ harness.http.state.streams = [
598
+ {collection: "todos", stream: DEFAULT_STREAM},
599
+ {collection: "todos", stream},
600
+ ];
601
+ harness.http.state.pages[stream] = {
602
+ cursor: 2,
603
+ entities: [{data: {title: "org doc"}, deleted: false, id: "og", seq: 2}],
604
+ frontierSeq: 2,
605
+ hasMore: false,
606
+ oldestRetainedSeq: 0,
607
+ stream,
608
+ };
609
+ const client = createSyncDb(harness.config);
610
+ await client.start();
611
+ await flush();
612
+ expect(client.store.getEntity({collection: "todos", id: "og"})).toBeDefined();
613
+
614
+ // A 401 during discovery is NOT a membership change: pause, purge NOTHING.
615
+ harness.http.state.streamsError = new AuthRequiredError();
616
+ await client.reconcile();
617
+ await flush();
618
+
619
+ expect(client.getSyncStatus().paused).toBe("auth");
620
+ expect(client.store.getEntity({collection: "todos", id: "og"})?.data).toEqual({
621
+ title: "org doc",
622
+ });
623
+ expect(client.store.getKnownStreams()).toContain(stream);
624
+ await client.stop();
625
+ });
626
+
627
+ it("transport error during discovery: NO purge, data intact (not a membership change)", async () => {
628
+ const harness = makeHarness();
629
+ const stream = "todos|tenant:org1";
630
+ harness.http.state.streams = [
631
+ {collection: "todos", stream: DEFAULT_STREAM},
632
+ {collection: "todos", stream},
633
+ ];
634
+ harness.http.state.pages[stream] = {
635
+ cursor: 1,
636
+ entities: [{data: {x: 1}, deleted: false, id: "og", seq: 1}],
637
+ frontierSeq: 1,
638
+ hasMore: false,
639
+ oldestRetainedSeq: 0,
640
+ stream,
641
+ };
642
+ const client = createSyncDb(harness.config);
643
+ await client.start();
644
+ await flush();
645
+ expect(client.store.getEntity({collection: "todos", id: "og"})).toBeDefined();
646
+
647
+ harness.http.state.streamsError = new Error("network down");
648
+ // reconcile rethrows a transport error; the client's warn() wrapper swallows it, but
649
+ // either way no purge happens and the pause state is NOT auth.
650
+ await client.reconcile().catch(() => {});
651
+ await flush();
652
+
653
+ expect(client.store.getEntity({collection: "todos", id: "og"})).toBeDefined();
654
+ expect(client.store.getKnownStreams()).toContain(stream);
655
+ expect(client.getSyncStatus().paused).toBeUndefined();
656
+ await client.stop();
657
+ });
658
+
659
+ it("legacy migration: a snapshot:{collection} cursor is dropped and streams re-bootstrap", async () => {
660
+ const harness = makeHarness();
661
+ harness.http.state.pages[DEFAULT_STREAM] = {
662
+ cursor: 3,
663
+ entities: [{data: {title: "fresh"}, deleted: false, id: "f1", seq: 3}],
664
+ frontierSeq: 3,
665
+ hasMore: false,
666
+ oldestRetainedSeq: 0,
667
+ stream: DEFAULT_STREAM,
668
+ };
669
+ const client = createSyncDb(harness.config);
670
+ // Seed a legacy snapshot cursor + a stale known-stream entry BEFORE start(), as a
671
+ // deployed client would hold. (The store is shared with the client instance.)
672
+ client.store.raw.setRow(CURSORS_TABLE, "snapshot:todos", {seq: 42, updatedAt: "old"});
673
+ client.store.addKnownStream({collection: "todos", stream: "todos|owner:stale"});
674
+
675
+ await client.start();
676
+ await flush();
677
+
678
+ // The legacy pseudo-cursor is gone...
679
+ expect(client.store.raw.hasRow(CURSORS_TABLE, "snapshot:todos")).toBe(false);
680
+ // ...and the streams were re-bootstrapped from the current membership set.
681
+ expect(client.store.getEntity({collection: "todos", id: "f1"})?.data).toEqual({
682
+ title: "fresh",
683
+ });
684
+ expect(client.store.getKnownStreams()).toContain(DEFAULT_STREAM);
685
+ await client.stop();
686
+ });
687
+ });
688
+
689
+ describe("wipe-on-user-change", () => {
690
+ it("persists data across restarts for the same user", async () => {
691
+ const name = uniqueName();
692
+ const harness = makeHarness({name});
693
+ const client = createSyncDb(harness.config);
694
+ await client.start();
695
+ client.mutate({collection: "todos", data: {title: "persisted"}, operation: "create"});
696
+ await flush();
697
+ await client.stop();
698
+
699
+ const second = makeHarness({name});
700
+ const reopened = createSyncDb(second.config);
701
+ await reopened.start();
702
+ expect(reopened.store.listEntities({collection: "todos"})).toHaveLength(1);
703
+ expect(reopened.store.getLastUserId()).toBe("u1");
704
+ await reopened.stop();
705
+ });
706
+
707
+ it("wipes entities, outbox, cursors, and conflicts when the user changes", async () => {
708
+ const name = uniqueName();
709
+ const harness = makeHarness({name});
710
+ harness.transport.setDefaultResponder(() => {
711
+ throw new Error("offline");
712
+ });
713
+ const client = createSyncDb(harness.config);
714
+ await client.start();
715
+ client.mutate({collection: "todos", data: {title: "secret"}, operation: "create"});
716
+ harness.transport.deliverDelta(makeDelta({id: "t9", seq: 2}));
717
+ await flush();
718
+ await client.stop();
719
+
720
+ const second = makeHarness({name});
721
+ second.auth.setUserId("u2");
722
+ const nextClient = createSyncDb(second.config);
723
+ await nextClient.start();
724
+ expect(nextClient.store.listEntities({collection: "todos", includeDeleted: true})).toEqual(
725
+ []
726
+ );
727
+ expect(nextClient.outbox.listQueued({userId: "u1"})).toEqual([]);
728
+ // u1's delta had advanced this stream's cursor to 2; the wipe reset it. (The row
729
+ // itself is back because this harness serves the same stream key to every user, so
730
+ // u2's own post-wipe bootstrap re-registered it — at seq 0, from scratch.)
731
+ expect(nextClient.getSyncStatus().streams[DEFAULT_STREAM]).toBe(0);
732
+ expect(nextClient.store.getLastUserId()).toBe("u2");
733
+ await nextClient.stop();
734
+ });
735
+
736
+ it("wipes and replays on an in-session auth user switch", async () => {
737
+ const harness = makeHarness();
738
+ const client = createSyncDb(harness.config);
739
+ await client.start();
740
+ client.store.upsertEntity({collection: "todos", data: {title: "mine"}, id: "t1", seq: 1});
741
+
742
+ harness.auth.setUserId("u2");
743
+ harness.auth.emitAuthChange();
744
+ await flush();
745
+ expect(client.store.listEntities({collection: "todos"})).toEqual([]);
746
+ expect(client.store.getLastUserId()).toBe("u2");
747
+ await client.stop();
748
+ });
749
+
750
+ it("an auth change for the same user replays queued mutations", async () => {
751
+ const harness = makeHarness();
752
+ harness.transport.setDefaultResponder(() => {
753
+ throw new Error("offline");
754
+ });
755
+ const client = createSyncDb(harness.config);
756
+ await client.start();
757
+ const {id} = client.mutate({collection: "todos", data: {title: "x"}, operation: "create"});
758
+ await flush();
759
+ expect(client.getSyncStatus().queuedCount).toBe(1);
760
+
761
+ // The failed send armed a jittered transport-failure backoff (A3,
762
+ // unlimited retries) — advance past its cap so the retry is eligible
763
+ // again before the auth-change replay trigger runs.
764
+ harness.clock.value += 30_000;
765
+ harness.transport.setDefaultResponder();
766
+ harness.auth.emitAuthChange();
767
+ await flush();
768
+ expect(client.getSyncStatus().queuedCount).toBe(0);
769
+ expect(client.store.getEntity({collection: "todos", id})?.pendingMutationId).toBeUndefined();
770
+ await client.stop();
771
+ });
772
+
773
+ it("bounces the transport (disconnect, reconnect, resubscribe) on a different-user login", async () => {
774
+ const harness = makeHarness();
775
+ const observable = makeObservableTransport(harness.transport);
776
+ harness.config.transport = observable.transport;
777
+ const client = createSyncDb(harness.config);
778
+ await client.start();
779
+ await flush();
780
+ observable.events.length = 0;
781
+
782
+ harness.auth.setUserId("u2");
783
+ harness.auth.emitAuthChange();
784
+ await flush();
785
+
786
+ expect(observable.events).toEqual(["disconnect", "connect", "subscribe"]);
787
+ expect(client.getSyncStatus().isOnline).toBe(true);
788
+ await client.stop();
789
+ });
790
+
791
+ it("never applies a delta from the stale connection while a user-switch bounce is in flight", async () => {
792
+ const harness = makeHarness();
793
+ const observable = makeObservableTransport(harness.transport);
794
+ harness.config.transport = observable.transport;
795
+ const client = createSyncDb(harness.config);
796
+ await client.start();
797
+ await flush();
798
+
799
+ const releaseConnect = observable.gateNextConnect();
800
+ harness.auth.setUserId("u2");
801
+ harness.auth.emitAuthChange();
802
+ await flush();
803
+
804
+ // The wipe has run and the reconnect is still in flight: a delta the OLD
805
+ // user's socket flushes now must never land in the new user's store.
806
+ harness.transport.deliverDelta(makeDelta({id: "stale-u1", seq: 7}));
807
+ expect(client.store.getEntity({collection: "todos", id: "stale-u1"})).toBeUndefined();
808
+
809
+ releaseConnect();
810
+ await flush();
811
+
812
+ // The rebound handler applies deltas arriving on the new connection.
813
+ harness.transport.deliverDelta(makeDelta({id: "fresh-u2", seq: 1}));
814
+ expect(client.store.getEntity({collection: "todos", id: "fresh-u2"})).toBeDefined();
815
+ expect(client.store.getEntity({collection: "todos", id: "stale-u1"})).toBeUndefined();
816
+ await client.stop();
817
+ });
818
+
819
+ it("does not bounce the transport on a same-user re-auth", async () => {
820
+ const harness = makeHarness();
821
+ const observable = makeObservableTransport(harness.transport);
822
+ harness.config.transport = observable.transport;
823
+ const client = createSyncDb(harness.config);
824
+ await client.start();
825
+ await flush();
826
+ observable.events.length = 0;
827
+
828
+ harness.auth.emitAuthChange();
829
+ await flush();
830
+
831
+ expect(observable.events).toEqual([]);
832
+ expect(client.getSyncStatus().isOnline).toBe(true);
833
+ await client.stop();
834
+ });
835
+
836
+ it("disconnects without reconnecting on logout", async () => {
837
+ const harness = makeHarness();
838
+ const observable = makeObservableTransport(harness.transport);
839
+ harness.config.transport = observable.transport;
840
+ const client = createSyncDb(harness.config);
841
+ await client.start();
842
+ await flush();
843
+ observable.events.length = 0;
844
+
845
+ harness.auth.setUserId(null);
846
+ harness.auth.emitAuthChange();
847
+ await flush();
848
+
849
+ expect(observable.events).toEqual(["disconnect"]);
850
+ expect(client.getSyncStatus().isOnline).toBe(false);
851
+ await client.stop();
852
+ });
853
+
854
+ it("a signed-out auth change clears the current user without wiping", async () => {
855
+ const harness = makeHarness();
856
+ const client = createSyncDb(harness.config);
857
+ await client.start();
858
+ client.store.upsertEntity({collection: "todos", data: {title: "kept"}, id: "t1"});
859
+
860
+ harness.auth.setUserId(null);
861
+ harness.auth.emitAuthChange();
862
+ await flush();
863
+ expect(client.store.listEntities({collection: "todos"})).toHaveLength(1);
864
+ expect(() => client.mutate({collection: "todos", operation: "create"})).toThrow(
865
+ "requires start()"
866
+ );
867
+ await client.stop();
868
+ });
869
+ });
870
+
871
+ describe("simulated offline (goOffline/goOnline)", () => {
872
+ it("mutate while offline applies locally, queues, and reports offline", async () => {
873
+ const harness = makeHarness();
874
+ const client = createSyncDb(harness.config);
875
+ await client.start();
876
+ let statusChanges = 0;
877
+ const unsubscribe = client.onStatusChange(() => {
878
+ statusChanges += 1;
879
+ });
880
+
881
+ client.goOffline();
882
+ expect(client.getSyncStatus().isOnline).toBe(false);
883
+ expect(statusChanges).toBe(1);
884
+
885
+ const {id, mutationId} = client.mutate({
886
+ collection: "todos",
887
+ data: {title: "offline milk run"},
888
+ operation: "create",
889
+ });
890
+ await flush();
891
+ const entity = client.store.getEntity({collection: "todos", id});
892
+ expect(entity?.data).toEqual({title: "offline milk run"});
893
+ expect(entity?.pendingMutationId).toBe(mutationId);
894
+ expect(client.outbox.getMutation({mutationId})?.status).toBe("queued");
895
+ expect(client.getSyncStatus().queuedCount).toBe(1);
896
+ // Nothing is sent while offline — not even via the HTTP fallback.
897
+ expect(harness.transport.sentMutations).toHaveLength(0);
898
+
899
+ unsubscribe();
900
+ await client.stop();
901
+ });
902
+
903
+ it("goOnline reconnects and replays the queued mutation", async () => {
904
+ const harness = makeHarness();
905
+ const client = createSyncDb(harness.config);
906
+ await client.start();
907
+
908
+ client.goOffline();
909
+ const {id} = client.mutate({
910
+ collection: "todos",
911
+ data: {title: "queued"},
912
+ operation: "create",
913
+ });
914
+ await flush();
915
+ expect(client.getSyncStatus().queuedCount).toBe(1);
916
+
917
+ await client.goOnline();
918
+ await flush();
919
+ expect(client.getSyncStatus().isOnline).toBe(true);
920
+ expect(client.getSyncStatus().queuedCount).toBe(0);
921
+ expect(harness.transport.sentMutations).toHaveLength(1);
922
+ expect(client.store.getEntity({collection: "todos", id})?.pendingMutationId).toBeUndefined();
923
+ await client.stop();
924
+ });
925
+
926
+ it("goOffline/goOnline are idempotent and record debug transitions", async () => {
927
+ const harness = makeHarness({debug: true});
928
+ const client = createSyncDb(harness.config);
929
+ await client.start();
930
+
931
+ // A no-op goOnline while already online must not double-connect.
932
+ await client.goOnline();
933
+ expect(client.getSyncStatus().isOnline).toBe(true);
934
+
935
+ client.goOffline();
936
+ client.goOffline();
937
+ expect(client.getSyncStatus().isOnline).toBe(false);
938
+ await client.goOnline();
939
+ await flush();
940
+ expect(client.getSyncStatus().isOnline).toBe(true);
941
+
942
+ const types = client.debug?.getEvents().map((event) => event.type) ?? [];
943
+ expect(types).toContain("disconnect");
944
+ expect(types.filter((type) => type === "connect").length).toBeGreaterThanOrEqual(2);
945
+ await client.stop();
946
+ });
947
+
948
+ it("the periodic timer pauses while offline and resumes on goOnline", async () => {
949
+ const harness = makeHarness({reconcileIntervalMs: 20});
950
+ const client = createSyncDb(harness.config);
951
+ await client.start();
952
+ await flush();
953
+
954
+ client.goOffline();
955
+ const baseline = harness.http.state.fetchCount;
956
+ await new Promise((resolve) => setTimeout(resolve, 60));
957
+ expect(harness.http.state.fetchCount).toBe(baseline);
958
+
959
+ await client.goOnline();
960
+ await new Promise((resolve) => setTimeout(resolve, 60));
961
+ expect(harness.http.state.fetchCount).toBeGreaterThan(baseline);
962
+ await client.stop();
963
+ });
964
+ });
965
+
966
+ describe("conflicts", () => {
967
+ it("records conflicts from nacks and resolves them via the client", async () => {
968
+ const harness = makeHarness();
969
+ const client = createSyncDb(harness.config);
970
+ await client.start();
971
+ client.store.upsertEntity({collection: "todos", data: {title: "old"}, id: "t1", seq: 2});
972
+ harness.transport.respondWithNack({
973
+ code: "conflict",
974
+ serverDoc: {title: "server wins"},
975
+ serverSeq: 7,
976
+ });
977
+
978
+ const {mutationId} = client.mutate({
979
+ collection: "todos",
980
+ data: {title: "mine"},
981
+ id: "t1",
982
+ operation: "update",
983
+ });
984
+ await flush();
985
+ expect(client.getSyncStatus().conflictCount).toBe(1);
986
+ expect(getConflict({mutationId, store: client.store})?.serverSeq).toBe(7);
987
+
988
+ client.resolveConflict({mutationId, strategy: "useServer"});
989
+ expect(client.getSyncStatus().conflictCount).toBe(0);
990
+ expect(client.store.getEntity({collection: "todos", id: "t1"})?.data).toEqual({
991
+ title: "server wins",
992
+ });
993
+ await client.stop();
994
+ });
995
+
996
+ // Task 9.12: an edit-vs-server-delete conflict resolved `useServer` must
997
+ // leave a tombstone. A live row holding null data would keep showing up in
998
+ // every list read (what useQuery/useEntityIds read) as an empty entity.
999
+ it("useServer on a server-deleted conflict leaves a tombstone, not a ghost row (9.12)", async () => {
1000
+ const harness = makeHarness();
1001
+ const client = createSyncDb(harness.config);
1002
+ await client.start();
1003
+ client.store.upsertEntity({collection: "todos", data: {title: "old"}, id: "t1", seq: 2});
1004
+ // The server reports a real seq with no document at it: deleted, hard-
1005
+ // deleted, or moved out of this client's scope.
1006
+ harness.transport.respondWithNack({code: "conflict", serverSeq: 7});
1007
+
1008
+ const {mutationId} = client.mutate({
1009
+ collection: "todos",
1010
+ data: {title: "mine"},
1011
+ id: "t1",
1012
+ operation: "update",
1013
+ });
1014
+ await flush();
1015
+ client.resolveConflict({mutationId, strategy: "useServer"});
1016
+
1017
+ const entity = client.store.getEntity({collection: "todos", id: "t1"});
1018
+ expect(entity?.deleted).toBe(true);
1019
+ expect(entity?.seq).toBe(7);
1020
+ expect(client.store.listEntities({collection: "todos"})).toHaveLength(0);
1021
+ await client.stop();
1022
+ });
1023
+
1024
+ it("getSyncStatus attributes conflicts and failures to their collection", async () => {
1025
+ const harness = makeHarness();
1026
+ const client = createSyncDb(harness.config);
1027
+ await client.start();
1028
+ client.store.upsertEntity({collection: "todos", data: {title: "old"}, id: "t1", seq: 2});
1029
+ harness.transport.respondWithNack({
1030
+ code: "conflict",
1031
+ serverDoc: {title: "server wins"},
1032
+ serverSeq: 7,
1033
+ });
1034
+ const {mutationId} = client.mutate({
1035
+ collection: "todos",
1036
+ data: {title: "mine"},
1037
+ id: "t1",
1038
+ operation: "update",
1039
+ });
1040
+ await flush();
1041
+
1042
+ harness.transport.respondWithNack({code: "validation", message: "bad data"});
1043
+ client.mutate({collection: "todos", data: {title: "bad"}, operation: "create"});
1044
+ await flush();
1045
+
1046
+ expect(client.getSyncStatus().collections).toEqual({
1047
+ todos: {conflictCount: 1, failedCount: 1, queuedCount: 0},
1048
+ });
1049
+
1050
+ client.resolveConflict({mutationId, strategy: "useServer"});
1051
+ expect(client.getSyncStatus().collections).toEqual({
1052
+ todos: {conflictCount: 0, failedCount: 1, queuedCount: 0},
1053
+ });
1054
+ await client.stop();
1055
+ });
1056
+
1057
+ it("getSyncStatus omits healthy collections from the breakdown", async () => {
1058
+ const harness = makeHarness();
1059
+ const client = createSyncDb(harness.config);
1060
+ await client.start();
1061
+ client.mutate({collection: "todos", data: {title: "fine"}, operation: "create"});
1062
+ await flush();
1063
+
1064
+ expect(client.getSyncStatus().collections).toEqual({});
1065
+ await client.stop();
1066
+ });
1067
+ });
1068
+
1069
+ describe("batched drain (B3/B4/B5)", () => {
1070
+ it("sends multiple queued mutations as a single batch via the socket transport", async () => {
1071
+ const harness = makeHarness();
1072
+ const client = createSyncDb(harness.config);
1073
+ await client.start();
1074
+ harness.transport.setConnected(true);
1075
+ await flush();
1076
+
1077
+ // Enqueue directly (bypassing mutate()'s own per-call replay trigger,
1078
+ // which would otherwise start draining synchronously — up to its first
1079
+ // real await — before the second/third mutation exist, since each
1080
+ // mutate() call's fire-and-forget replayOutbox() can independently
1081
+ // observe the queue as it existed at that instant instead of all three
1082
+ // landing in the same batch) so a single replayOutbox() call sees all
1083
+ // three together deterministically.
1084
+ client.outbox.enqueue({
1085
+ args: {title: "a"},
1086
+ collection: "todos",
1087
+ entityId: "e1",
1088
+ operation: "create",
1089
+ userId: "u1",
1090
+ });
1091
+ client.outbox.enqueue({
1092
+ args: {title: "b"},
1093
+ collection: "todos",
1094
+ entityId: "e2",
1095
+ operation: "create",
1096
+ userId: "u1",
1097
+ });
1098
+ client.outbox.enqueue({
1099
+ args: {title: "c"},
1100
+ collection: "todos",
1101
+ entityId: "e3",
1102
+ operation: "create",
1103
+ userId: "u1",
1104
+ });
1105
+ await client.replayOutbox();
1106
+
1107
+ expect(harness.transport.sentBatches.length).toBeGreaterThanOrEqual(1);
1108
+ expect(harness.transport.sentBatches.flat()).toHaveLength(3);
1109
+ expect(client.getSyncStatus().queuedCount).toBe(0);
1110
+ await client.stop();
1111
+ });
1112
+
1113
+ it("re-probes batch support on reconnect after a batch-unsupported determination", async () => {
1114
+ const harness = makeHarness();
1115
+ harness.transport.setBatchResponder(() => ({type: "unsupported"}));
1116
+ const client = createSyncDb(harness.config);
1117
+ await client.start();
1118
+ harness.transport.setConnected(true);
1119
+ await flush();
1120
+
1121
+ client.outbox.enqueue({
1122
+ args: {title: "a"},
1123
+ collection: "todos",
1124
+ entityId: "e1",
1125
+ operation: "create",
1126
+ userId: "u1",
1127
+ });
1128
+ client.outbox.enqueue({
1129
+ args: {title: "b"},
1130
+ collection: "todos",
1131
+ entityId: "e2",
1132
+ operation: "create",
1133
+ userId: "u1",
1134
+ });
1135
+ await client.replayOutbox();
1136
+ expect(client.getSyncStatus().queuedCount).toBe(0);
1137
+ expect(harness.transport.sentMutations).toHaveLength(2);
1138
+
1139
+ harness.transport.setBatchResponder();
1140
+ // A reconnect re-probes batch support.
1141
+ harness.transport.setConnected(false);
1142
+ await flush();
1143
+ harness.transport.setConnected(true);
1144
+ await flush();
1145
+ client.outbox.enqueue({
1146
+ args: {title: "c"},
1147
+ collection: "todos",
1148
+ entityId: "e3",
1149
+ operation: "create",
1150
+ userId: "u1",
1151
+ });
1152
+ client.outbox.enqueue({
1153
+ args: {title: "d"},
1154
+ collection: "todos",
1155
+ entityId: "e4",
1156
+ operation: "create",
1157
+ userId: "u1",
1158
+ });
1159
+ await client.replayOutbox();
1160
+ expect(harness.transport.sentBatches.length).toBeGreaterThanOrEqual(1);
1161
+ await client.stop();
1162
+ });
1163
+
1164
+ it("retryFailed re-enables an entity's successors after a validation failure", async () => {
1165
+ const harness = makeHarness();
1166
+ const client = createSyncDb(harness.config);
1167
+ await client.start();
1168
+ harness.transport.setConnected(true);
1169
+
1170
+ harness.transport.respondWithNack({code: "validation", message: "bad data"});
1171
+ const {id} = client.mutate({collection: "todos", data: {title: "bad"}, operation: "create"});
1172
+ await flush();
1173
+ expect(client.getSyncStatus().failedCount).toBe(1);
1174
+
1175
+ client.mutate({collection: "todos", data: {title: "v2"}, id, operation: "update"});
1176
+ await flush();
1177
+ // The successor is blocked and surfaced, not sent.
1178
+ expect(client.getSyncStatus().blockedEntities).toBe(1);
1179
+ expect(client.getSyncStatus().queuedCount).toBe(1);
1180
+
1181
+ client.retryFailed({entityId: id});
1182
+ await flush();
1183
+ expect(client.getSyncStatus().blockedEntities).toBe(0);
1184
+ expect(client.getSyncStatus().queuedCount).toBe(0);
1185
+ await client.stop();
1186
+ });
1187
+
1188
+ it("getSyncStatus reports draining and drain progress while a replay is in flight", async () => {
1189
+ const harness = makeHarness();
1190
+ let release: (() => void) | undefined;
1191
+ harness.transport.respondWith(async (request) => {
1192
+ await new Promise<void>((resolve) => {
1193
+ release = resolve;
1194
+ });
1195
+ return {ack: {id: request.id ?? "", mutationId: request.mutationId, seq: 1}, type: "ack"};
1196
+ });
1197
+ const client = createSyncDb(harness.config);
1198
+ await client.start();
1199
+ harness.transport.setConnected(true);
1200
+ // Let the startup no-op replay (empty queue) settle before enqueuing,
1201
+ // so the drain this test observes is the one triggered by mutate().
1202
+ await flush();
1203
+
1204
+ client.mutate({collection: "todos", data: {title: "a"}, operation: "create"});
1205
+ await flush();
1206
+ const midDrainStatus = client.getSyncStatus();
1207
+ expect(midDrainStatus.draining).toBe(true);
1208
+ expect(midDrainStatus.totalThisDrain).toBeGreaterThanOrEqual(1);
1209
+
1210
+ release?.();
1211
+ await flush();
1212
+ expect(client.getSyncStatus().draining).toBe(false);
1213
+ await client.stop();
1214
+ });
1215
+
1216
+ it("respects a configured batchSize", async () => {
1217
+ const harness = makeHarness({batchSize: 2});
1218
+ const client = createSyncDb(harness.config);
1219
+ await client.start();
1220
+ harness.transport.setConnected(true);
1221
+ // Let the startup no-op replay (empty queue) settle first.
1222
+ await flush();
1223
+
1224
+ for (let i = 0; i < 5; i++) {
1225
+ client.mutate({collection: "todos", data: {title: `t${i}`}, operation: "create"});
1226
+ }
1227
+ await flush();
1228
+ await flush();
1229
+ // 5 mutations at batchSize 2: two full batches of 2, then a lone
1230
+ // eligible mutation reuses the single-send path (not a batch of one).
1231
+ expect(harness.transport.sentBatches.map((b) => b.length)).toEqual([2, 2]);
1232
+ expect(harness.transport.sentMutations).toHaveLength(1);
1233
+ expect(client.getSyncStatus().queuedCount).toBe(0);
1234
+ await client.stop();
1235
+ });
1236
+
1237
+ it("haltQueueOnConflict config plumbs through to the coordinator: a conflict halts the whole batch", async () => {
1238
+ const harness = makeHarness({haltQueueOnConflict: true});
1239
+ const client = createSyncDb(harness.config);
1240
+ await client.start();
1241
+ harness.transport.setConnected(true);
1242
+ // Let the startup no-op replay (empty queue) settle first.
1243
+ await flush();
1244
+ client.store.upsertEntity({collection: "todos", data: {title: "old"}, id: "t1", seq: 2});
1245
+ client.store.upsertEntity({collection: "todos", data: {title: "other"}, id: "t2"});
1246
+
1247
+ // Enqueue both mutations via the outbox directly (bypassing mutate()'s
1248
+ // own fire-and-forget replay trigger, which would otherwise start
1249
+ // draining synchronously — up to its first real await — before the
1250
+ // second mutation exists, guaranteeing they land in separate chunks)
1251
+ // so a single replayOutbox() call sees both together deterministically.
1252
+ const mutationId = "halt-conflict-t1";
1253
+ client.outbox.enqueue({
1254
+ args: {title: "mine"},
1255
+ baseVersion: 2,
1256
+ collection: "todos",
1257
+ entityId: "t1",
1258
+ mutationId,
1259
+ operation: "update",
1260
+ userId: "u1",
1261
+ });
1262
+ client.outbox.enqueue({
1263
+ args: {title: "other"},
1264
+ collection: "todos",
1265
+ entityId: "t2",
1266
+ mutationId: "halt-conflict-t2",
1267
+ operation: "update",
1268
+ userId: "u1",
1269
+ });
1270
+
1271
+ // Realistic server behavior (B2 stop-on-first-non-ack): t1 is first and
1272
+ // conflicts, so "other" never gets attempted — truncated response.
1273
+ harness.transport.setBatchResponder(() => ({
1274
+ results: [{nack: {code: "conflict", mutationId, serverSeq: 7}, type: "nack"}],
1275
+ type: "results",
1276
+ }));
1277
+ await client.replayOutbox();
1278
+
1279
+ expect(client.getSyncStatus().conflictCount).toBe(1);
1280
+ // The second (distinct-entity) mutation never got a result and never
1281
+ // sent again this pass — haltQueueOnConflict stopped the whole drain.
1282
+ expect(client.getSyncStatus().queuedCount).toBe(1);
1283
+ expect(client.outbox.getMutation({mutationId})?.status).toBe("conflicted");
1284
+ await client.stop();
1285
+ });
1286
+ });
1287
+
1288
+ it("falls back to the HTTP channel for mutations while disconnected", async () => {
1289
+ const harness = makeHarness();
1290
+ const offlineTransport: FakeTransport = {
1291
+ ...harness.transport,
1292
+ connect: async () => {
1293
+ throw new Error("no network");
1294
+ },
1295
+ };
1296
+ let httpMutations = 0;
1297
+ const http: HttpChannel = {
1298
+ fetchEntities: async () => ({entities: []}),
1299
+ fetchKeyMaterial: harness.http.channel.fetchKeyMaterial,
1300
+ fetchSnapshotPage: harness.http.channel.fetchSnapshotPage,
1301
+ fetchStreams: harness.http.channel.fetchStreams,
1302
+ sendMutation: async (request) => {
1303
+ httpMutations += 1;
1304
+ return {ack: {id: request.id ?? "", mutationId: request.mutationId, seq: 5}, type: "ack"};
1305
+ },
1306
+ };
1307
+ const client = createSyncDb({
1308
+ ...harness.config,
1309
+ httpChannel: http,
1310
+ transport: offlineTransport,
1311
+ });
1312
+ await client.start();
1313
+
1314
+ const {id} = client.mutate({collection: "todos", data: {title: "x"}, operation: "create"});
1315
+ await flush();
1316
+ expect(httpMutations).toBe(1);
1317
+ expect(client.store.getEntity({collection: "todos", id})?.seq).toBe(5);
1318
+ await client.stop();
1319
+ });
1320
+
1321
+ it("aggregates sync status", async () => {
1322
+ const harness = makeHarness();
1323
+ harness.transport.setDefaultResponder(() => {
1324
+ throw new Error("offline");
1325
+ });
1326
+ const client = createSyncDb(harness.config);
1327
+ await client.start();
1328
+ expect(client.getSyncStatus().isOnline).toBe(true);
1329
+
1330
+ client.mutate({collection: "todos", data: {title: "a"}, operation: "create"});
1331
+ await flush();
1332
+ const status = client.getSyncStatus();
1333
+ expect(status.queuedCount).toBe(1);
1334
+ expect(status.conflictCount).toBe(0);
1335
+ expect(status.isSyncing).toBe(false);
1336
+
1337
+ harness.transport.setConnected(false);
1338
+ expect(client.getSyncStatus().isOnline).toBe(false);
1339
+ await client.stop();
1340
+ });
1341
+
1342
+ it("stop() disconnects and removes listeners", async () => {
1343
+ const harness = makeHarness();
1344
+ const client = createSyncDb(harness.config);
1345
+ await client.start();
1346
+ await client.stop();
1347
+ expect(client.getSyncStatus().isOnline).toBe(false);
1348
+
1349
+ // Deltas delivered after stop are ignored (listener removed).
1350
+ harness.transport.deliverDelta(makeDelta());
1351
+ expect(client.store.getEntity({collection: "todos", id: "t1"})).toBeUndefined();
1352
+ // Auth changes after stop are ignored too.
1353
+ harness.auth.emitAuthChange();
1354
+ await flush();
1355
+ });
1356
+
1357
+ describe("debug log", () => {
1358
+ it("is undefined by default and present when enabled", async () => {
1359
+ const off = createSyncDb(makeHarness().config);
1360
+ expect(off.debug).toBeUndefined();
1361
+
1362
+ const on = createSyncDb(makeHarness({debug: true}).config);
1363
+ expect(on.debug).toBeDefined();
1364
+ });
1365
+
1366
+ it("records local mutations, inbound deltas, sends and acks", async () => {
1367
+ const harness = makeHarness({debug: true});
1368
+ const client = createSyncDb(harness.config);
1369
+ await client.start();
1370
+
1371
+ client.mutate({collection: "todos", data: {title: "a"}, operation: "create"});
1372
+ await flush();
1373
+ harness.transport.deliverDelta(makeDelta({id: "t9", seq: 1}));
1374
+
1375
+ const types = client.debug?.getEvents().map((e) => e.type) ?? [];
1376
+ expect(types).toContain("mutate");
1377
+ expect(types).toContain("send");
1378
+ expect(types).toContain("ack");
1379
+ expect(types).toContain("delta");
1380
+
1381
+ const mutateEvent = client.debug?.getEvents().find((e) => e.type === "mutate");
1382
+ expect(mutateEvent?.collection).toBe("todos");
1383
+ expect(mutateEvent?.operation).toBe("create");
1384
+
1385
+ // The debug panel shows the create/update body: both the local mutate and
1386
+ // the outbound send carry the request body in `detail.data`.
1387
+ expect(mutateEvent?.detail?.data).toEqual({title: "a"});
1388
+ const sendEvent = client.debug?.getEvents().find((e) => e.type === "send");
1389
+ expect(sendEvent?.detail?.data).toEqual({title: "a"});
1390
+ await client.stop();
1391
+ });
1392
+
1393
+ it("records conflict nacks", async () => {
1394
+ const harness = makeHarness({debug: true});
1395
+ harness.transport.setDefaultResponder((request) => ({
1396
+ nack: {
1397
+ code: "conflict",
1398
+ mutationId: request.mutationId,
1399
+ serverDoc: {title: "server wins"},
1400
+ serverSeq: 7,
1401
+ },
1402
+ type: "nack",
1403
+ }));
1404
+ const client = createSyncDb(harness.config);
1405
+ await client.start();
1406
+
1407
+ client.mutate({collection: "todos", data: {title: "mine"}, operation: "create"});
1408
+ await flush();
1409
+
1410
+ const conflict = client.debug?.getEvents().find((e) => e.type === "conflict");
1411
+ expect(conflict?.ok).toBe(false);
1412
+ expect(conflict?.detail?.serverSeq).toBe(7);
1413
+ // The conflicting create/update body is surfaced so it can be inspected.
1414
+ expect(conflict?.detail?.data).toEqual({title: "mine"});
1415
+ await client.stop();
1416
+ });
1417
+
1418
+ it("skips the debug-only listQueued scan in replayOutbox() when debug is disabled (A3)", async () => {
1419
+ const countListQueuedCalls = async (debug: boolean): Promise<number> => {
1420
+ const harness = makeHarness({debug});
1421
+ const client = createSyncDb(harness.config);
1422
+ await client.start();
1423
+ await flush();
1424
+ const originalListQueued = client.outbox.listQueued;
1425
+ let calls = 0;
1426
+ // biome-ignore lint/suspicious/noExplicitAny: test-only spy shim
1427
+ (client.outbox as any).listQueued = (...args: any[]) => {
1428
+ calls += 1;
1429
+ return originalListQueued(...(args as [{collection?: string; userId: string}]));
1430
+ };
1431
+ await client.replayOutbox();
1432
+ await client.stop();
1433
+ return calls;
1434
+ };
1435
+
1436
+ const withoutDebug = await countListQueuedCalls(false);
1437
+ const withDebug = await countListQueuedCalls(true);
1438
+ // The debug label adds exactly one extra listQueued scan (the drain
1439
+ // itself still calls listQueued to find work) — proving the debug-only
1440
+ // scan is conditional, not unconditional.
1441
+ expect(withDebug).toBe(withoutDebug + 1);
1442
+ });
1443
+ });
1444
+
1445
+ describe("startup recovery (A1)", () => {
1446
+ it("recovers a stranded inFlight row on start(): it replays and the entity receives deltas again", async () => {
1447
+ const name = uniqueName();
1448
+ const harness = makeHarness({name});
1449
+ // Hold every send indefinitely so the mutation is still inFlight when
1450
+ // stop() is called (simulating a crash mid-send, not a clean stop).
1451
+ harness.transport.respondWith(() => new Promise(() => {}));
1452
+ const client = createSyncDb(harness.config);
1453
+ await client.start();
1454
+ const {id, mutationId} = client.mutate({
1455
+ collection: "todos",
1456
+ data: {title: "stranded"},
1457
+ operation: "create",
1458
+ });
1459
+ await flush();
1460
+ expect(client.outbox.getMutation({mutationId})?.status).toBe("inFlight");
1461
+ // stop() itself never repairs outbox state (only start() does) — a
1462
+ // clean stop() here still leaves the row inFlight in persisted content,
1463
+ // standing in for a hard crash that never ran a graceful shutdown.
1464
+ await client.stop();
1465
+
1466
+ const second = makeHarness({name});
1467
+ const reopened = createSyncDb(second.config);
1468
+ await reopened.start();
1469
+ await flush();
1470
+ // Recovered to queued and replayed against the fresh (auto-acking)
1471
+ // transport: the row acks and — per A5 — is pruned immediately, so its
1472
+ // resolution shows up as a successful send, not a lingering outbox row.
1473
+ expect(reopened.outbox.getMutation({mutationId})).toBeUndefined();
1474
+ expect(second.transport.sentMutations.map((m) => m.mutationId)).toContain(mutationId);
1475
+ expect(
1476
+ reopened.store.getEntity({collection: "todos", id})?.pendingMutationId
1477
+ ).toBeUndefined();
1478
+ // The entity's pendingMutationId was released — a subsequent delta applies.
1479
+ second.transport.deliverDelta({
1480
+ collection: "todos",
1481
+ data: {title: "from server"},
1482
+ id,
1483
+ method: "update",
1484
+ seq: 99,
1485
+ stream: "todos|owner:u1",
1486
+ });
1487
+ expect(reopened.store.getEntity({collection: "todos", id})?.data).toEqual({
1488
+ title: "from server",
1489
+ });
1490
+ await reopened.stop();
1491
+ });
1492
+
1493
+ it("clears a stale pendingMutationId for an acked-with-pending row on start()", async () => {
1494
+ const name = uniqueName();
1495
+ const harness = makeHarness({name});
1496
+ const client = createSyncDb(harness.config);
1497
+ await client.start();
1498
+ client.store.upsertEntity({
1499
+ collection: "todos",
1500
+ data: {title: "x"},
1501
+ id: "t1",
1502
+ pendingMutationId: "m1",
1503
+ });
1504
+ client.outbox.enqueue({
1505
+ args: {title: "x"},
1506
+ collection: "todos",
1507
+ entityId: "t1",
1508
+ mutationId: "m1",
1509
+ operation: "create",
1510
+ userId: "u1",
1511
+ });
1512
+ client.outbox.markInFlight({mutationId: "m1"});
1513
+ client.outbox.markAcked({mutationId: "m1"});
1514
+ // Simulate a crash between markAcked and releaseEntity.
1515
+ await flush();
1516
+ await client.stop();
1517
+
1518
+ const second = makeHarness({name});
1519
+ const reopened = createSyncDb(second.config);
1520
+ await reopened.start();
1521
+ expect(
1522
+ reopened.store.getEntity({collection: "todos", id: "t1"})?.pendingMutationId
1523
+ ).toBeUndefined();
1524
+ await reopened.stop();
1525
+ });
1526
+
1527
+ it("writes a missing conflict row for a conflicted mutation on start()", async () => {
1528
+ const name = uniqueName();
1529
+ const harness = makeHarness({name});
1530
+ const client = createSyncDb(harness.config);
1531
+ await client.start();
1532
+ client.store.upsertEntity({
1533
+ collection: "todos",
1534
+ data: {title: "local"},
1535
+ id: "t1",
1536
+ pendingMutationId: "m1",
1537
+ });
1538
+ client.outbox.enqueue({
1539
+ args: {title: "local"},
1540
+ collection: "todos",
1541
+ entityId: "t1",
1542
+ mutationId: "m1",
1543
+ operation: "create",
1544
+ userId: "u1",
1545
+ });
1546
+ client.outbox.markInFlight({mutationId: "m1"});
1547
+ client.outbox.markConflicted({mutationId: "m1"});
1548
+ // Simulate a crash between markConflicted and writeConflict: no row yet.
1549
+ expect(getConflict({mutationId: "m1", store: client.store})).toBeUndefined();
1550
+ await flush();
1551
+ await client.stop();
1552
+
1553
+ const second = makeHarness({name});
1554
+ const reopened = createSyncDb(second.config);
1555
+ await reopened.start();
1556
+ const conflict = getConflict({mutationId: "m1", store: reopened.store});
1557
+ expect(conflict?.entityId).toBe("t1");
1558
+ expect(conflict?.serverSeq).toBe(0);
1559
+ await reopened.stop();
1560
+ });
1561
+
1562
+ // Task 9.11b: a pendingMutationId pointing at a mutation with no `_outbox`
1563
+ // row (pruned, wiped, or lost to a partial persist) freezes the entity —
1564
+ // the delta applier skips it for pending protection and repair refuses to
1565
+ // overwrite it. The startup sweep is the only thing that can release it.
1566
+ it("releases an orphaned pendingMutationId on start() so the entity accepts deltas again (9.11b)", async () => {
1567
+ const name = uniqueName();
1568
+ const harness = makeHarness({name});
1569
+ const client = createSyncDb(harness.config);
1570
+ await client.start();
1571
+ client.store.upsertEntity({
1572
+ collection: "todos",
1573
+ data: {title: "frozen"},
1574
+ id: "t1",
1575
+ pendingMutationId: "row-never-persisted",
1576
+ seq: 4,
1577
+ stream: DEFAULT_STREAM,
1578
+ });
1579
+ await flush();
1580
+ await client.stop();
1581
+
1582
+ const second = makeHarness({name});
1583
+ const reopened = createSyncDb(second.config);
1584
+ await reopened.start();
1585
+ const recovered = reopened.store.getEntity({collection: "todos", id: "t1"});
1586
+ // The persisted row survived the reload with its payload intact — only the
1587
+ // dangling pending lock was dropped.
1588
+ expect(recovered?.data).toEqual({title: "frozen"});
1589
+ expect(recovered?.seq).toBe(4);
1590
+ expect(recovered?.pendingMutationId).toBeUndefined();
1591
+
1592
+ second.transport.deliverDelta(
1593
+ makeDelta({data: {title: "from server"}, id: "t1", method: "update", seq: 9})
1594
+ );
1595
+ const entity = reopened.store.getEntity({collection: "todos", id: "t1"});
1596
+ expect(entity?.data).toEqual({title: "from server"});
1597
+ expect(entity?.seq).toBe(9);
1598
+ await reopened.stop();
1599
+ });
1600
+ });
1601
+
1602
+ // Task 9.11a: a terminal nack leaves optimistic data the server never
1603
+ // accepted. With no concurrent server write the entity's seq never moves, so
1604
+ // snapshot reconcile skips it — the terminal path must mark needs-repair so
1605
+ // the repair fetch pulls canonical state back over the rejected edit.
1606
+ describe("rejected optimistic data (9.11a)", () => {
1607
+ it("converges a validation-nacked entity back to server state", async () => {
1608
+ const harness = makeHarness();
1609
+ harness.http.channel.fetchEntities = async () => ({
1610
+ entities: [{data: {title: "server truth"}, deleted: false, id: "t1", seq: 5}],
1611
+ });
1612
+ const client = createSyncDb(harness.config);
1613
+ await client.start();
1614
+ harness.transport.deliverDelta(
1615
+ makeDelta({data: {title: "server truth"}, id: "t1", method: "create", seq: 5})
1616
+ );
1617
+ harness.transport.setDefaultResponder((request) => ({
1618
+ nack: {code: "validation", message: "title required", mutationId: request.mutationId},
1619
+ type: "nack",
1620
+ }));
1621
+
1622
+ const {mutationId} = client.mutate({
1623
+ collection: "todos",
1624
+ data: {title: "rejected"},
1625
+ id: "t1",
1626
+ operation: "update",
1627
+ });
1628
+ await flush();
1629
+
1630
+ expect(client.outbox.getMutation({mutationId})?.status).toBe("failed");
1631
+ const entity = client.store.getEntity({collection: "todos", id: "t1"});
1632
+ expect(entity?.data).toEqual({title: "server truth"});
1633
+ expect(entity?.seq).toBe(5);
1634
+ expect(entity?.pendingMutationId).toBeUndefined();
1635
+ // The repair landed, so nothing stays marked for a later reconcile pass.
1636
+ expect(client.store.hasNeedsRepair({collection: "todos", entityId: "t1"})).toBe(false);
1637
+ await client.stop();
1638
+ });
1639
+
1640
+ // Editing a doc the server already deleted is the common shape of this: the
1641
+ // update 404s (a terminal `validation` nack, not a conflict — the server
1642
+ // cannot seq-conflict against a document its own read filter hides), so the
1643
+ // repair fetch is what teaches the client the entity is gone.
1644
+ it("converges to a tombstone when the server deleted the entity out from under the edit", async () => {
1645
+ const harness = makeHarness();
1646
+ harness.http.channel.fetchEntities = async () => ({
1647
+ entities: [{data: null, deleted: true, id: "t1", seq: 6}],
1648
+ });
1649
+ const client = createSyncDb(harness.config);
1650
+ await client.start();
1651
+ harness.transport.deliverDelta(
1652
+ makeDelta({data: {title: "server truth"}, id: "t1", method: "create", seq: 5})
1653
+ );
1654
+ harness.transport.setDefaultResponder((request) => ({
1655
+ nack: {code: "validation", message: "not found", mutationId: request.mutationId},
1656
+ type: "nack",
1657
+ }));
1658
+
1659
+ client.mutate({
1660
+ collection: "todos",
1661
+ data: {title: "edited after delete"},
1662
+ id: "t1",
1663
+ operation: "update",
1664
+ });
1665
+ await flush();
1666
+
1667
+ const entity = client.store.getEntity({collection: "todos", id: "t1"});
1668
+ expect(entity?.deleted).toBe(true);
1669
+ expect(entity?.seq).toBe(6);
1670
+ // No ghost row: the edited data never survives as a live entity.
1671
+ expect(client.store.listEntities({collection: "todos"})).toHaveLength(0);
1672
+ await client.stop();
1673
+ });
1674
+
1675
+ it("keeps the needs-repair mark when the repair fetch fails, so a later reconcile retries it", async () => {
1676
+ const harness = makeHarness();
1677
+ harness.http.channel.fetchEntities = async () => {
1678
+ throw new Error("network down");
1679
+ };
1680
+ const client = createSyncDb(harness.config);
1681
+ await client.start();
1682
+ harness.transport.setDefaultResponder((request) => ({
1683
+ nack: {code: "validation", mutationId: request.mutationId},
1684
+ type: "nack",
1685
+ }));
1686
+
1687
+ client.mutate({collection: "todos", data: {title: "rejected"}, operation: "create"});
1688
+ await flush();
1689
+ const [entity] = client.store.listEntities({collection: "todos"});
1690
+ expect(client.store.hasNeedsRepair({collection: "todos", entityId: entity.id})).toBe(true);
1691
+ await client.stop();
1692
+ });
1693
+ });
1694
+
1695
+ describe("outbox hygiene (A5)", () => {
1696
+ it("prunes acked rows after a successful drain pass, driven end-to-end through mutate()", async () => {
1697
+ const harness = makeHarness();
1698
+ harness.transport.respondWithAck({seq: 1});
1699
+ const client = createSyncDb(harness.config);
1700
+ await client.start();
1701
+
1702
+ const {mutationId} = client.mutate({
1703
+ collection: "todos",
1704
+ data: {title: "x"},
1705
+ operation: "create",
1706
+ });
1707
+ await flush();
1708
+ // The mutation acked and was pruned in the same drain pass — no lingering row.
1709
+ expect(client.outbox.getMutation({mutationId})).toBeUndefined();
1710
+ expect(client.getSyncStatus().queuedCount).toBe(0);
1711
+ await client.stop();
1712
+ });
1713
+
1714
+ it("keeps failed rows visible in failedCount until pruned past the retention window", async () => {
1715
+ const harness = makeHarness();
1716
+ harness.transport.setDefaultResponder((request) => ({
1717
+ nack: {code: "validation", mutationId: request.mutationId},
1718
+ type: "nack",
1719
+ }));
1720
+ const client = createSyncDb(harness.config);
1721
+ await client.start();
1722
+ client.mutate({collection: "todos", data: {title: "bad"}, operation: "create"});
1723
+ await flush();
1724
+ expect(client.getSyncStatus().failedCount).toBe(1);
1725
+ await client.stop();
1726
+ });
1727
+ });
1728
+
1729
+ describe("auth-pause pipeline (A4)", () => {
1730
+ /** Force sendMutation through the HTTP channel (offline transport) so AuthRequiredError surfaces. */
1731
+ const makeAuthPauseHarness = (
1732
+ overrides: Partial<SyncDbConfig> = {}
1733
+ ): Harness & {offlineTransport: FakeTransport} => {
1734
+ const harness = makeHarness(overrides);
1735
+ const offlineTransport: FakeTransport = {
1736
+ ...harness.transport,
1737
+ connect: async () => {
1738
+ throw new Error("no network");
1739
+ },
1740
+ };
1741
+ harness.config.transport = offlineTransport;
1742
+ return {...harness, offlineTransport};
1743
+ };
1744
+
1745
+ it("AuthRequiredError from the HTTP channel pauses sync, leaves the outbox untouched, burns zero budget, and fires onAuthRequired once", async () => {
1746
+ const harness = makeAuthPauseHarness();
1747
+ let authRequiredCount = 0;
1748
+ harness.config.onAuthRequired = () => {
1749
+ authRequiredCount += 1;
1750
+ };
1751
+ harness.http.channel.sendMutation = async () => {
1752
+ throw new AuthRequiredError();
1753
+ };
1754
+ const client = createSyncDb(harness.config);
1755
+ await client.start();
1756
+
1757
+ const {mutationId} = client.mutate({
1758
+ collection: "todos",
1759
+ data: {title: "x"},
1760
+ operation: "create",
1761
+ });
1762
+ await flush();
1763
+
1764
+ expect(client.getSyncStatus().paused).toBe("auth");
1765
+ const mutation = client.outbox.getMutation({mutationId});
1766
+ expect(mutation?.status).toBe("queued");
1767
+ expect(mutation?.errorNackCount).toBe(0);
1768
+ expect(authRequiredCount).toBe(1);
1769
+
1770
+ // A second replay trigger while still paused must not re-fire the hook.
1771
+ await client.replayOutbox();
1772
+ expect(authRequiredCount).toBe(1);
1773
+ await client.stop();
1774
+ });
1775
+
1776
+ it("same-user re-auth clears the pause and drains the queue fully, entity converges", async () => {
1777
+ const harness = makeAuthPauseHarness();
1778
+ harness.http.channel.sendMutation = async () => {
1779
+ throw new AuthRequiredError();
1780
+ };
1781
+ const client = createSyncDb(harness.config);
1782
+ await client.start();
1783
+ const {id, mutationId} = client.mutate({
1784
+ collection: "todos",
1785
+ data: {title: "x"},
1786
+ operation: "create",
1787
+ });
1788
+ await flush();
1789
+ expect(client.getSyncStatus().paused).toBe("auth");
1790
+
1791
+ // Re-authenticate as the SAME user with a channel that now works.
1792
+ harness.http.channel.sendMutation = async (request) => ({
1793
+ ack: {id: request.id ?? "", mutationId: request.mutationId, seq: 1},
1794
+ type: "ack",
1795
+ });
1796
+ harness.auth.emitAuthChange();
1797
+ await flush();
1798
+
1799
+ expect(client.getSyncStatus().paused).toBeUndefined();
1800
+ expect(client.getSyncStatus().queuedCount).toBe(0);
1801
+ expect(client.outbox.getMutation({mutationId})).toBeUndefined();
1802
+ expect(client.store.getEntity({collection: "todos", id})?.pendingMutationId).toBeUndefined();
1803
+ await client.stop();
1804
+ });
1805
+
1806
+ it("logout (userId -> undefined) retains local data; a later same-user login drains the queue", async () => {
1807
+ const harness = makeAuthPauseHarness();
1808
+ const client = createSyncDb(harness.config);
1809
+ await client.start();
1810
+ client.store.upsertEntity({collection: "todos", data: {title: "kept"}, id: "t1"});
1811
+
1812
+ harness.auth.setUserId(null);
1813
+ harness.auth.emitAuthChange();
1814
+ await flush();
1815
+ expect(client.store.listEntities({collection: "todos"})).toHaveLength(1);
1816
+ expect(client.getSyncStatus().paused).toBe("auth");
1817
+
1818
+ // Same user comes back — resumes fully, no wipe occurred.
1819
+ harness.auth.setUserId("u1");
1820
+ harness.auth.emitAuthChange();
1821
+ await flush();
1822
+ expect(client.getSyncStatus().paused).toBeUndefined();
1823
+ expect(client.store.listEntities({collection: "todos"})).toHaveLength(1);
1824
+ await client.stop();
1825
+ });
1826
+
1827
+ it("a different-user login still wipes local data (regression)", async () => {
1828
+ const name = uniqueName();
1829
+ const harness = makeAuthPauseHarness({name});
1830
+ const client = createSyncDb(harness.config);
1831
+ await client.start();
1832
+ client.store.upsertEntity({collection: "todos", data: {title: "mine"}, id: "t1", seq: 1});
1833
+
1834
+ harness.auth.setUserId("u2");
1835
+ harness.auth.emitAuthChange();
1836
+ await flush();
1837
+ expect(client.store.listEntities({collection: "todos"})).toEqual([]);
1838
+ expect(client.store.getLastUserId()).toBe("u2");
1839
+ await client.stop();
1840
+ });
1841
+
1842
+ it("no reconcile/snapshot requests are issued while paused", async () => {
1843
+ const harness = makeAuthPauseHarness();
1844
+ harness.http.channel.sendMutation = async () => {
1845
+ throw new AuthRequiredError();
1846
+ };
1847
+ const client = createSyncDb(harness.config);
1848
+ await client.start();
1849
+ client.mutate({collection: "todos", data: {title: "x"}, operation: "create"});
1850
+ await flush();
1851
+ expect(client.getSyncStatus().paused).toBe("auth");
1852
+
1853
+ const baseline = harness.http.state.fetchCount;
1854
+ await client.reconcile();
1855
+ expect(harness.http.state.fetchCount).toBe(baseline);
1856
+ await client.stop();
1857
+ });
1858
+
1859
+ it("betterAuthAdapter's refresh() gets one silent attempt per pause episode, and a successful refresh resumes replay immediately", async () => {
1860
+ const harness = makeAuthPauseHarness();
1861
+ let refreshCalls = 0;
1862
+ let shouldSucceed = false;
1863
+ harness.config.authProvider = {
1864
+ ...harness.auth.provider,
1865
+ refresh: async () => {
1866
+ refreshCalls += 1;
1867
+ if (shouldSucceed) {
1868
+ // A real adapter's refresh() renews the underlying token in place;
1869
+ // simulate that by making the channel work again before reporting success.
1870
+ harness.http.channel.sendMutation = async (request) => ({
1871
+ ack: {id: request.id ?? "", mutationId: request.mutationId, seq: 1},
1872
+ type: "ack",
1873
+ });
1874
+ }
1875
+ return shouldSucceed;
1876
+ },
1877
+ };
1878
+ harness.http.channel.sendMutation = async () => {
1879
+ throw new AuthRequiredError();
1880
+ };
1881
+ const client = createSyncDb(harness.config);
1882
+ await client.start();
1883
+ const {mutationId} = client.mutate({
1884
+ collection: "todos",
1885
+ data: {title: "x"},
1886
+ operation: "create",
1887
+ });
1888
+ await flush();
1889
+ expect(refreshCalls).toBe(1);
1890
+ expect(client.getSyncStatus().paused).toBe("auth");
1891
+
1892
+ // Further replay triggers within the SAME episode never re-attempt refresh.
1893
+ await client.replayOutbox();
1894
+ await client.replayOutbox();
1895
+ expect(refreshCalls).toBe(1);
1896
+
1897
+ // The episode ends via same-user re-auth (not refresh) — the outbox is
1898
+ // still intact and unpaused replay drains it.
1899
+ harness.http.channel.sendMutation = async (request) => ({
1900
+ ack: {id: request.id ?? "", mutationId: request.mutationId, seq: 1},
1901
+ type: "ack",
1902
+ });
1903
+ harness.auth.emitAuthChange();
1904
+ await flush();
1905
+ expect(client.getSyncStatus().paused).toBeUndefined();
1906
+ expect(client.outbox.getMutation({mutationId})).toBeUndefined();
1907
+
1908
+ // A FRESH pause episode (new failing mutation) gets its own refresh
1909
+ // attempt, and this time a successful refresh resumes replay immediately.
1910
+ shouldSucceed = true;
1911
+ harness.http.channel.sendMutation = async () => {
1912
+ throw new AuthRequiredError();
1913
+ };
1914
+ const {mutationId: secondMutationId} = client.mutate({
1915
+ collection: "todos",
1916
+ data: {title: "y"},
1917
+ operation: "create",
1918
+ });
1919
+ await flush();
1920
+ expect(refreshCalls).toBe(2);
1921
+ // The refresh succeeded, so the pause clears and replay retried with the
1922
+ // (now-working) channel rather than staying surfaced to the app.
1923
+ expect(client.getSyncStatus().paused).toBeUndefined();
1924
+ expect(client.outbox.getMutation({mutationId: secondMutationId})).toBeUndefined();
1925
+ await client.stop();
1926
+ });
1927
+
1928
+ it("a refresh resolving a DIFFERENT user never unpauses or replays (INV-2)", async () => {
1929
+ const harness = makeAuthPauseHarness();
1930
+ harness.http.channel.sendMutation = async () => {
1931
+ throw new AuthRequiredError();
1932
+ };
1933
+ // The refresh succeeds, but the session it renewed belongs to another user
1934
+ // (a second tab signed in while this client was paused) — draining u1's
1935
+ // outbox under u2's identity is exactly what INV-2 forbids.
1936
+ harness.config.authProvider = {
1937
+ ...harness.auth.provider,
1938
+ refresh: async () => {
1939
+ harness.auth.setUserId("u2");
1940
+ return true;
1941
+ },
1942
+ };
1943
+ const client = createSyncDb(harness.config);
1944
+ await client.start();
1945
+ const {mutationId} = client.mutate({
1946
+ collection: "todos",
1947
+ data: {title: "x"},
1948
+ operation: "create",
1949
+ });
1950
+ await flush();
1951
+
1952
+ expect(client.getSyncStatus().paused).toBe("auth");
1953
+ expect(client.outbox.getMutation({mutationId})?.status).toBe("queued");
1954
+ await client.stop();
1955
+ });
1956
+
1957
+ // The silent refresh exists to recover a session that expired behind the
1958
+ // app's back. An explicit logout is the auth provider itself reporting "no
1959
+ // user", so there is nothing to refresh — and a refresh that somehow
1960
+ // succeeded could only resolve a user this client is not signed in as.
1961
+ it("does not attempt a silent refresh when the pause came from an explicit logout", async () => {
1962
+ const harness = makeHarness();
1963
+ let refreshCalls = 0;
1964
+ harness.config.authProvider = {
1965
+ ...harness.auth.provider,
1966
+ refresh: async () => {
1967
+ refreshCalls += 1;
1968
+ return true;
1969
+ },
1970
+ };
1971
+ const client = createSyncDb(harness.config);
1972
+ await client.start();
1973
+ await flush();
1974
+
1975
+ harness.auth.setUserId(null);
1976
+ harness.auth.emitAuthChange();
1977
+ await flush();
1978
+
1979
+ expect(client.getSyncStatus().paused).toBe("auth");
1980
+ expect(refreshCalls).toBe(0);
1981
+ await client.stop();
1982
+ });
1983
+
1984
+ it("a 401 surfacing through reconcile attempts exactly one silent refresh per episode", async () => {
1985
+ const harness = makeHarness();
1986
+ let refreshCalls = 0;
1987
+ harness.config.authProvider = {
1988
+ ...harness.auth.provider,
1989
+ refresh: async () => {
1990
+ refreshCalls += 1;
1991
+ return false;
1992
+ },
1993
+ };
1994
+ harness.http.state.streamsError = new AuthRequiredError();
1995
+ const client = createSyncDb(harness.config);
1996
+ await client.start();
1997
+ await flush();
1998
+
1999
+ expect(client.getSyncStatus().paused).toBe("auth");
2000
+ expect(refreshCalls).toBe(1);
2001
+
2002
+ // Every later trigger inside the SAME episode is a no-op for the refresh.
2003
+ await client.reconcile();
2004
+ await client.replayOutbox();
2005
+ await flush();
2006
+ expect(refreshCalls).toBe(1);
2007
+ await client.stop();
2008
+ });
2009
+ });
2010
+
2011
+ describe("socket session re-validation sweep mapping into auth-pause (D1)", () => {
2012
+ it("sync:auth-expired disconnect pauses sync with the outbox intact and zero budget consumed", async () => {
2013
+ const harness = makeHarness();
2014
+ const client = createSyncDb(harness.config);
2015
+ await client.start();
2016
+ harness.transport.setConnected(true);
2017
+ await flush();
2018
+
2019
+ harness.transport.disconnectWithAuthExpired();
2020
+ await flush();
2021
+ expect(client.getSyncStatus().paused).toBe("auth");
2022
+ expect(client.getSyncStatus().isOnline).toBe(false);
2023
+
2024
+ // A mutation enqueued WHILE paused must stay queued untouched — replay
2025
+ // stands down entirely until the pause clears (INV-2).
2026
+ const {mutationId} = client.mutate({
2027
+ collection: "todos",
2028
+ data: {title: "x"},
2029
+ operation: "create",
2030
+ });
2031
+ await flush();
2032
+ const mutation = client.outbox.getMutation({mutationId});
2033
+ expect(mutation?.status).toBe("queued");
2034
+ expect(mutation?.errorNackCount).toBe(0);
2035
+ expect(mutation?.attemptCount).toBe(0);
2036
+ await client.stop();
2037
+ });
2038
+
2039
+ it("a plain disconnect (no auth-expired tag) does NOT enter the auth-pause state", async () => {
2040
+ const harness = makeHarness();
2041
+ const client = createSyncDb(harness.config);
2042
+ await client.start();
2043
+ harness.transport.setConnected(true);
2044
+ await flush();
2045
+
2046
+ harness.transport.setConnected(false);
2047
+ await flush();
2048
+
2049
+ expect(client.getSyncStatus().paused).toBeUndefined();
2050
+ expect(client.getSyncStatus().isOnline).toBe(false);
2051
+ await client.stop();
2052
+ });
2053
+
2054
+ it("same-user re-auth after a sync:auth-expired pause resumes replay with the outbox intact", async () => {
2055
+ const harness = makeHarness();
2056
+ const client = createSyncDb(harness.config);
2057
+ await client.start();
2058
+ harness.transport.setConnected(true);
2059
+ await flush();
2060
+
2061
+ harness.transport.disconnectWithAuthExpired();
2062
+ await flush();
2063
+ expect(client.getSyncStatus().paused).toBe("auth");
2064
+
2065
+ // Enqueued while paused — stays queued (INV-2) until the pause clears.
2066
+ const {id, mutationId} = client.mutate({
2067
+ collection: "todos",
2068
+ data: {title: "x"},
2069
+ operation: "create",
2070
+ });
2071
+ await flush();
2072
+ expect(client.outbox.getMutation({mutationId})?.status).toBe("queued");
2073
+
2074
+ // Same-user re-auth clears the pause; the transport reconnects and drains
2075
+ // the queue fully (the fake transport auto-acks by default).
2076
+ harness.auth.emitAuthChange();
2077
+ harness.transport.setConnected(true);
2078
+ await flush();
2079
+
2080
+ expect(client.getSyncStatus().paused).toBeUndefined();
2081
+ expect(client.outbox.getMutation({mutationId})).toBeUndefined();
2082
+ expect(client.store.getEntity({collection: "todos", id})?.pendingMutationId).toBeUndefined();
2083
+ await client.stop();
2084
+ });
2085
+
2086
+ it("no reconcile/replay is issued while paused from a sync:auth-expired disconnect", async () => {
2087
+ const harness = makeHarness();
2088
+ const client = createSyncDb(harness.config);
2089
+ await client.start();
2090
+ harness.transport.setConnected(true);
2091
+ await flush();
2092
+
2093
+ harness.transport.disconnectWithAuthExpired();
2094
+ await flush();
2095
+ expect(client.getSyncStatus().paused).toBe("auth");
2096
+
2097
+ const baseline = harness.http.state.fetchCount;
2098
+ await client.reconcile();
2099
+ expect(harness.http.state.fetchCount).toBe(baseline);
2100
+ await client.stop();
2101
+ });
2102
+ });
2103
+
2104
+ describe("signOut() (A4)", () => {
2105
+ it("serializes against a concurrent auth change and leaves no destroyed persister behind", async () => {
2106
+ const harness = makeHarness();
2107
+ const client = createSyncDb(harness.config);
2108
+ await client.start();
2109
+ client.store.upsertEntity({collection: "todos", data: {title: "kept"}, id: "t1"});
2110
+
2111
+ // A user switch and a sign-out racing each other: both mutate
2112
+ // currentUserId/persister, so the lifecycle mutex must order them and the
2113
+ // later one must not write state the earlier one already tore down.
2114
+ harness.auth.setUserId("u2");
2115
+ harness.auth.emitAuthChange();
2116
+ const signOutPromise = client.signOut();
2117
+ await signOutPromise;
2118
+ await flush();
2119
+
2120
+ // Sign-out ran last: no current user, and a mutation is rejected until a
2121
+ // fresh start() resolves one again.
2122
+ expect(() => client.mutate({collection: "todos", operation: "create"})).toThrow(
2123
+ "requires start()"
2124
+ );
2125
+ // The client is reusable: start() rebuilds persistence for the new user
2126
+ // rather than reusing the persister signOut() destroyed.
2127
+ await client.start();
2128
+ client.mutate({collection: "todos", data: {title: "after sign out"}, operation: "create"});
2129
+ await flush();
2130
+ expect(client.getSyncStatus().queuedCount).toBe(0);
2131
+ await client.stop();
2132
+ });
2133
+
2134
+ it("clears the current user without wiping when wipeOnSignOut is not set", async () => {
2135
+ const harness = makeHarness();
2136
+ const client = createSyncDb(harness.config);
2137
+ await client.start();
2138
+ client.store.upsertEntity({collection: "todos", data: {title: "kept"}, id: "t1"});
2139
+
2140
+ await client.signOut();
2141
+ expect(client.store.listEntities({collection: "todos"})).toHaveLength(1);
2142
+ expect(() => client.mutate({collection: "todos", operation: "create"})).toThrow(
2143
+ "requires start()"
2144
+ );
2145
+ });
2146
+
2147
+ it("wipes local data when wipeOnSignOut is configured", async () => {
2148
+ const harness = makeHarness({wipeOnSignOut: true});
2149
+ const client = createSyncDb(harness.config);
2150
+ await client.start();
2151
+ client.store.upsertEntity({collection: "todos", data: {title: "gone"}, id: "t1"});
2152
+
2153
+ await client.signOut();
2154
+ expect(client.store.listEntities({collection: "todos", includeDeleted: true})).toEqual([]);
2155
+ });
2156
+
2157
+ it("the wipeOnSignOut wipe also clears the cached derived encryption key (E3f)", async () => {
2158
+ const harness = makeHarness({
2159
+ persisterFactory: createWebPersisterFactory({saveDebounceMs: 0}),
2160
+ wipeOnSignOut: true,
2161
+ });
2162
+ const client = createSyncDb(harness.config);
2163
+ await client.start();
2164
+ await flush();
2165
+ expect(
2166
+ await idbGet<CryptoKey>({databaseName: DEFAULT_KEY_CACHE_DB_NAME, key: "local:local"})
2167
+ ).toBeInstanceOf(CryptoKey);
2168
+
2169
+ await client.signOut();
2170
+
2171
+ expect(
2172
+ await idbGet<CryptoKey>({databaseName: DEFAULT_KEY_CACHE_DB_NAME, key: "local:local"})
2173
+ ).toBeUndefined();
2174
+ });
2175
+ });
2176
+
2177
+ describe("lifecycle serialization (E1)", () => {
2178
+ it("a rapid stop()-then-start() for a new user leaves the new user's persistence working", async () => {
2179
+ const name = uniqueName();
2180
+ const harness = makeHarness({name});
2181
+ const client = createSyncDb(harness.config);
2182
+ await client.start();
2183
+ client.mutate({collection: "todos", data: {title: "user one"}, operation: "create"});
2184
+ await flush();
2185
+
2186
+ // Rapid stop() immediately followed by start() for a DIFFERENT user —
2187
+ // this is the exact interleaving the original bug hit: stop() re-reads
2188
+ // the module-level `persister` after awaiting a debounced save(), and
2189
+ // an interleaved start() for the new user had already replaced it,
2190
+ // destroying the NEW user's persister instead of the old one (leaving
2191
+ // mutate() throwing for the new user). Do NOT await stop() before
2192
+ // calling start() — that's the whole point of "rapid".
2193
+ harness.auth.setUserId("u2");
2194
+ const stopPromise = client.stop();
2195
+ const startPromise = client.start();
2196
+ await Promise.all([stopPromise, startPromise]);
2197
+
2198
+ // The new user's session must be fully functional: mutate() succeeds
2199
+ // and the entity persists through its own persister.
2200
+ const {id, mutationId} = client.mutate({
2201
+ collection: "todos",
2202
+ data: {title: "user two"},
2203
+ operation: "create",
2204
+ });
2205
+ expect(client.store.getEntity({collection: "todos", id})?.data).toEqual({title: "user two"});
2206
+ expect(client.outbox.getMutation({mutationId})).toBeDefined();
2207
+ expect(client.store.getLastUserId()).toBe("u2");
2208
+ await client.stop();
2209
+
2210
+ // Re-opening under the same name for u2 must load what was just
2211
+ // written — proving the persister that survived the race was u2's, not
2212
+ // a destroyed/half-wired one.
2213
+ const reopened = createSyncDb({...harness.config, name});
2214
+ harness.auth.setUserId("u2");
2215
+ await reopened.start();
2216
+ expect(reopened.store.listEntities({collection: "todos"}).map((e) => e.data)).toContainEqual({
2217
+ title: "user two",
2218
+ });
2219
+ await reopened.stop();
2220
+ });
2221
+
2222
+ it("double start() is a no-op: listeners are not double-registered", async () => {
2223
+ const harness = makeHarness();
2224
+ let onDeltaCalls = 0;
2225
+ let onStatusChangeCalls = 0;
2226
+ const countingTransport = {
2227
+ ...harness.transport,
2228
+ onDelta: (callback: (delta: SyncDelta) => void): (() => void) => {
2229
+ onDeltaCalls += 1;
2230
+ return harness.transport.onDelta(callback);
2231
+ },
2232
+ onStatusChange: (
2233
+ callback: (status: {connected: boolean; authExpired?: boolean}) => void
2234
+ ): (() => void) => {
2235
+ onStatusChangeCalls += 1;
2236
+ return harness.transport.onStatusChange(callback);
2237
+ },
2238
+ };
2239
+ const client = createSyncDb({...harness.config, transport: countingTransport});
2240
+ await client.start();
2241
+ expect(onDeltaCalls).toBe(1);
2242
+ expect(onStatusChangeCalls).toBe(1);
2243
+
2244
+ // A second start() while already started must be a no-op — no new
2245
+ // listener registration, no thrown error.
2246
+ await client.start();
2247
+ expect(onDeltaCalls).toBe(1);
2248
+ expect(onStatusChangeCalls).toBe(1);
2249
+
2250
+ // The client is still fully functional (the first start() "won").
2251
+ const {mutationId} = client.mutate({
2252
+ collection: "todos",
2253
+ data: {title: "still works"},
2254
+ operation: "create",
2255
+ });
2256
+ expect(client.outbox.getMutation({mutationId})).toBeDefined();
2257
+ await client.stop();
2258
+ });
2259
+
2260
+ it("stop() disposes the coordinator's armed wake-up timer (A3) so no post-stop send fires", async () => {
2261
+ const harness = makeHarness();
2262
+ harness.transport.setDefaultResponder(() => {
2263
+ throw new Error("transient failure");
2264
+ });
2265
+ const client = createSyncDb(harness.config);
2266
+ await client.start();
2267
+ client.mutate({collection: "todos", data: {title: "x"}, operation: "create"});
2268
+ await flush();
2269
+ // The failed send armed a jittered backoff wake-up timer.
2270
+ expect(client.getSyncStatus().queuedCount).toBe(1);
2271
+
2272
+ await client.stop();
2273
+ const sentBeforeWait = harness.transport.sentMutations.length;
2274
+ // Advance well past any plausible backoff window; if the timer were
2275
+ // still armed post-stop it would fire another send here.
2276
+ await new Promise((resolve) => setTimeout(resolve, 60));
2277
+ expect(harness.transport.sentMutations.length).toBe(sentBeforeWait);
2278
+ });
2279
+ });
2280
+
2281
+ describe("schema versioning (E2)", () => {
2282
+ it("wipes and re-bootstraps when the persisted schemaVersion is stale", async () => {
2283
+ const name = uniqueName();
2284
+ const harness = makeHarness({name});
2285
+ const client = createSyncDb(harness.config);
2286
+ await client.start();
2287
+ client.store.upsertEntity({collection: "todos", data: {title: "v1 data"}, id: "t1", seq: 1});
2288
+ // Simulate a persisted store written under an OLDER schema version.
2289
+ client.store.raw.setValue("schemaVersion", 0);
2290
+ await flush();
2291
+ await client.stop();
2292
+
2293
+ // Seed a snapshot page (keyed by the discovered stream — C2) so the
2294
+ // re-bootstrap after the wipe has something to fetch and the test can
2295
+ // prove it actually ran.
2296
+ const second = makeHarness({name});
2297
+ second.http.state.pages[DEFAULT_STREAM] = {
2298
+ cursor: 5,
2299
+ entities: [{data: {title: "from server"}, deleted: false, id: "server-1", seq: 5}],
2300
+ frontierSeq: 5,
2301
+ hasMore: false,
2302
+ oldestRetainedSeq: 0,
2303
+ stream: DEFAULT_STREAM,
2304
+ };
2305
+ const reopened = createSyncDb(second.config);
2306
+ await reopened.start();
2307
+ await flush();
2308
+
2309
+ // The stale v1 data is gone (wiped, not merged) and the fresh
2310
+ // re-bootstrap populated the store from the server instead.
2311
+ expect(reopened.store.getEntity({collection: "todos", id: "t1"})).toBeUndefined();
2312
+ expect(reopened.store.getEntity({collection: "todos", id: "server-1"})?.data).toEqual({
2313
+ title: "from server",
2314
+ });
2315
+ expect(reopened.store.getSchemaVersion()).toBe(SYNC_SCHEMA_VERSION);
2316
+ await reopened.stop();
2317
+ });
2318
+
2319
+ it("leaves data untouched when the persisted schemaVersion already matches", async () => {
2320
+ const name = uniqueName();
2321
+ const harness = makeHarness({name});
2322
+ const client = createSyncDb(harness.config);
2323
+ await client.start();
2324
+ client.store.upsertEntity({collection: "todos", data: {title: "current"}, id: "t1", seq: 1});
2325
+ await flush();
2326
+ await client.stop();
2327
+
2328
+ const second = makeHarness({name});
2329
+ const reopened = createSyncDb(second.config);
2330
+ await reopened.start();
2331
+ await flush();
2332
+
2333
+ expect(reopened.store.getEntity({collection: "todos", id: "t1"})?.data).toEqual({
2334
+ title: "current",
2335
+ });
2336
+ expect(reopened.store.getSchemaVersion()).toBe(SYNC_SCHEMA_VERSION);
2337
+ await reopened.stop();
2338
+ });
2339
+
2340
+ it("stamps the current schema version on a genuinely fresh store", async () => {
2341
+ const harness = makeHarness();
2342
+ const client = createSyncDb(harness.config);
2343
+ await client.start();
2344
+ expect(client.store.getSchemaVersion()).toBe(SYNC_SCHEMA_VERSION);
2345
+ await client.stop();
2346
+ });
2347
+ });
2348
+
2349
+ describe("persistence failure surfaces (E3)", () => {
2350
+ // These tests exercise the REAL web persister factory (encrypted
2351
+ // IndexedDB) rather than the memoryPersisterFactory default used
2352
+ // elsewhere in this file: under plain bun/Node (no Metro/webpack platform
2353
+ // resolution), importing "./persisters/defaultPersisterFactory" always
2354
+ // resolves to the neutral in-memory fallback, never the `.web.ts`
2355
+ // variant — so `client.ts`'s own E3 hooks (built for that default-factory
2356
+ // branch) are unreachable unless the test supplies the web factory
2357
+ // directly as `persisterFactory`. The client passes its hooks through to
2358
+ // ANY factory via the `hooks` argument (see `PersisterFactory`), so a
2359
+ // directly-supplied web factory still wires up SyncStatus surfacing
2360
+ // exactly as production code would under Metro/webpack.
2361
+ const makeWebPersisterFactory = (
2362
+ overrides: Parameters<typeof createWebPersisterFactory>[0] = {}
2363
+ ): SyncDbConfig["persisterFactory"] =>
2364
+ createWebPersisterFactory({
2365
+ keyProvider: createLocalKeyProvider({cacheDbName: uniqueName()}),
2366
+ saveDebounceMs: 0,
2367
+ ...overrides,
2368
+ });
2369
+
2370
+ it("a quota-exceeded save surfaces persistence: 'error' on SyncStatus", async () => {
2371
+ const harness = makeHarness({
2372
+ persisterFactory: makeWebPersisterFactory({
2373
+ idbSetImpl: async () => {
2374
+ const error = new Error("The quota has been exceeded.");
2375
+ error.name = "QuotaExceededError";
2376
+ throw error;
2377
+ },
2378
+ }),
2379
+ });
2380
+ let statusChanges = 0;
2381
+ const client = createSyncDb(harness.config);
2382
+ const unsubscribe = client.onStatusChange(() => {
2383
+ statusChanges += 1;
2384
+ });
2385
+ // The very first startAutoSave() save already goes through the failing
2386
+ // idbSetImpl, so persistence surfaces "error" immediately on start() —
2387
+ // this is the correct, intentional behavior (a save failure is a save
2388
+ // failure regardless of whether the store was empty or not).
2389
+ await client.start();
2390
+ client.mutate({collection: "todos", data: {title: "x"}, operation: "create"});
2391
+ await flush();
2392
+
2393
+ expect(client.getSyncStatus().persistence).toBe("error");
2394
+ expect(statusChanges).toBeGreaterThan(0);
2395
+ unsubscribe();
2396
+ await client.stop();
2397
+ });
2398
+
2399
+ it("invokes the configured onDecryptFailure hook instead of the default wipe", async () => {
2400
+ const name = uniqueName();
2401
+ const keyProvider = createLocalKeyProvider({cacheDbName: uniqueName()});
2402
+ const harness = makeHarness({
2403
+ name,
2404
+ persisterFactory: createWebPersisterFactory({keyProvider, saveDebounceMs: 0}),
2405
+ });
2406
+ const client = createSyncDb(harness.config);
2407
+ await client.start();
2408
+ client.mutate({collection: "todos", data: {title: "keep"}, operation: "create"});
2409
+ await flush();
2410
+ await client.stop();
2411
+
2412
+ let decryptFailureCalls = 0;
2413
+ const second = makeHarness({
2414
+ name,
2415
+ onDecryptFailure: () => {
2416
+ decryptFailureCalls += 1;
2417
+ },
2418
+ persisterFactory: createWebPersisterFactory({
2419
+ idbGetImpl: async <T>(): Promise<T | undefined> =>
2420
+ new Uint8Array([1, 2, 3, 4, 5]) as unknown as T,
2421
+ keyProvider,
2422
+ saveDebounceMs: 0,
2423
+ }),
2424
+ });
2425
+ const reopened = createSyncDb(second.config);
2426
+ await reopened.start();
2427
+ await flush();
2428
+
2429
+ expect(decryptFailureCalls).toBe(1);
2430
+ await reopened.stop();
2431
+ });
2432
+
2433
+ it("a clean stop() flushes a pending write before destroying the persister", async () => {
2434
+ const name = uniqueName();
2435
+ const keyProvider = createLocalKeyProvider({cacheDbName: uniqueName()});
2436
+ const harness = makeHarness({
2437
+ name,
2438
+ persisterFactory: createWebPersisterFactory({keyProvider, saveDebounceMs: 0}),
2439
+ });
2440
+ const client = createSyncDb(harness.config);
2441
+ await client.start();
2442
+ client.mutate({collection: "todos", data: {title: "before stop"}, operation: "create"});
2443
+ // Let the transaction-triggered autosave settle before stop()'s own
2444
+ // flush — see encryptedIndexedDbPersister.test.ts's
2445
+ // "destroy() flushes a pending debounced save and writes nothing after"
2446
+ // for the narrower, race-free version of this same guarantee at the
2447
+ // persister level.
2448
+ await flush();
2449
+ await client.stop();
2450
+
2451
+ const reopened = createSyncDb({
2452
+ ...harness.config,
2453
+ persisterFactory: createWebPersisterFactory({keyProvider, saveDebounceMs: 0}),
2454
+ });
2455
+ await reopened.start();
2456
+ await flush();
2457
+ expect(
2458
+ reopened.store.listEntities({collection: "todos"}).map((entity) => entity.data)
2459
+ ).toContainEqual({title: "before stop"});
2460
+ await reopened.stop();
2461
+ });
2462
+
2463
+ it("a different-user login clears the cached derived encryption key (E3f)", async () => {
2464
+ // No custom keyProvider/cacheDbName here: `client.ts`'s different-user
2465
+ // wipe path clears `DEFAULT_KEY_CACHE_DB_NAME` specifically (the
2466
+ // default local key provider's cache database), so this test must
2467
+ // exercise that exact default. The test builds the web persister
2468
+ // factory directly (bypassing client.ts's own userId-aware factory
2469
+ // construction — see the describe-level comment on why), so the
2470
+ // cached key's scope key is "local:local" (no userId override) rather
2471
+ // than the "local:{userId}" shape client.ts's own default path uses;
2472
+ // either way it lives in the same DEFAULT_KEY_CACHE_DB_NAME database
2473
+ // client.ts wipes.
2474
+ const harness = makeHarness({
2475
+ persisterFactory: createWebPersisterFactory({saveDebounceMs: 0}),
2476
+ });
2477
+ const client = createSyncDb(harness.config);
2478
+ await client.start();
2479
+ await flush();
2480
+ // The default local key provider derives and caches a key on first use
2481
+ // (during the initial autoload/autosave above).
2482
+ expect(
2483
+ await idbGet<CryptoKey>({databaseName: DEFAULT_KEY_CACHE_DB_NAME, key: "local:local"})
2484
+ ).toBeInstanceOf(CryptoKey);
2485
+
2486
+ harness.auth.setUserId("u2");
2487
+ harness.auth.emitAuthChange();
2488
+ await flush();
2489
+
2490
+ expect(
2491
+ await idbGet<CryptoKey>({databaseName: DEFAULT_KEY_CACHE_DB_NAME, key: "local:local"})
2492
+ ).toBeUndefined();
2493
+ await client.stop();
2494
+ });
2495
+ });
2496
+
2497
+ describe("client-side tombstone compaction (E5)", () => {
2498
+ it("a successful reconcile compacts tombstones older than the retention window", async () => {
2499
+ const harness = makeHarness({tombstoneRetentionMs: 90 * 24 * 60 * 60 * 1_000});
2500
+ const client = createSyncDb(harness.config);
2501
+ await client.start();
2502
+ await flush();
2503
+
2504
+ // A tombstone applied via a delta, stamped at the current (mocked) clock time.
2505
+ harness.transport.deliverDelta({
2506
+ collection: "todos",
2507
+ deleted: true,
2508
+ id: "old-tombstone",
2509
+ method: "delete",
2510
+ seq: 1,
2511
+ stream: "todos|owner:u1",
2512
+ });
2513
+ expect(client.store.getEntity({collection: "todos", id: "old-tombstone"})?.deleted).toBe(
2514
+ true
2515
+ );
2516
+
2517
+ // Advance the clock past the retention window, then trigger a
2518
+ // reconcile (which must succeed for compaction to run at all).
2519
+ harness.clock.value += 91 * 24 * 60 * 60 * 1_000;
2520
+ await client.reconcile();
2521
+
2522
+ expect(client.store.getEntity({collection: "todos", id: "old-tombstone"})).toBeUndefined();
2523
+ await client.stop();
2524
+ });
2525
+
2526
+ it("does not compact tombstones still within the retention window", async () => {
2527
+ const harness = makeHarness({tombstoneRetentionMs: 90 * 24 * 60 * 60 * 1_000});
2528
+ const client = createSyncDb(harness.config);
2529
+ await client.start();
2530
+ await flush();
2531
+
2532
+ harness.transport.deliverDelta({
2533
+ collection: "todos",
2534
+ deleted: true,
2535
+ id: "fresh-tombstone",
2536
+ method: "delete",
2537
+ seq: 1,
2538
+ stream: "todos|owner:u1",
2539
+ });
2540
+
2541
+ harness.clock.value += 5 * 24 * 60 * 60 * 1_000;
2542
+ await client.reconcile();
2543
+
2544
+ expect(client.store.getEntity({collection: "todos", id: "fresh-tombstone"})?.deleted).toBe(
2545
+ true
2546
+ );
2547
+ await client.stop();
2548
+ });
2549
+
2550
+ it("tombstoneRetentionMs: 0 disables compaction entirely", async () => {
2551
+ const harness = makeHarness({tombstoneRetentionMs: 0});
2552
+ const client = createSyncDb(harness.config);
2553
+ await client.start();
2554
+ await flush();
2555
+
2556
+ harness.transport.deliverDelta({
2557
+ collection: "todos",
2558
+ deleted: true,
2559
+ id: "never-compacted",
2560
+ method: "delete",
2561
+ seq: 1,
2562
+ stream: "todos|owner:u1",
2563
+ });
2564
+
2565
+ harness.clock.value += 365 * 24 * 60 * 60 * 1_000;
2566
+ await client.reconcile();
2567
+
2568
+ expect(client.store.getEntity({collection: "todos", id: "never-compacted"})?.deleted).toBe(
2569
+ true
2570
+ );
2571
+ await client.stop();
2572
+ });
2573
+ });
2574
+
2575
+ describe("lifecycle hygiene (9.25)", () => {
2576
+ it("refuses to delete an id the local store has never seen", async () => {
2577
+ const harness = makeHarness();
2578
+ const client = createSyncDb(harness.config);
2579
+ await client.start();
2580
+ await flush();
2581
+
2582
+ expect(() => client.mutate({collection: "todos", id: "ghost", operation: "delete"})).toThrow(
2583
+ /no such entity in the local store/
2584
+ );
2585
+ // No phantom tombstone, and no doomed mutation queued behind it.
2586
+ expect(client.store.getEntity({collection: "todos", id: "ghost"})).toBeUndefined();
2587
+ expect(client.getSyncStatus().queuedCount).toBe(0);
2588
+ await client.stop();
2589
+ });
2590
+
2591
+ it("writes exactly one tombstone row for a delete and keeps the previous data", async () => {
2592
+ const harness = makeHarness();
2593
+ const client = createSyncDb(harness.config);
2594
+ await client.start();
2595
+ await flush();
2596
+
2597
+ const {id} = client.mutate({
2598
+ collection: "todos",
2599
+ data: {title: "doomed"},
2600
+ operation: "create",
2601
+ });
2602
+ client.mutate({collection: "todos", id, operation: "delete"});
2603
+
2604
+ const entity = client.store.getEntity<{title: string}>({collection: "todos", id});
2605
+ expect(entity?.deleted).toBe(true);
2606
+ expect(entity?.data?.title).toBe("doomed");
2607
+ expect(client.store.raw.getCell("todos", id, "deletedAt")).toBeTruthy();
2608
+ await client.stop();
2609
+ });
2610
+
2611
+ it("coalesces concurrent reconcile calls into a single stream discovery", async () => {
2612
+ const harness = makeHarness();
2613
+ const client = createSyncDb(harness.config);
2614
+ await client.start();
2615
+ await flush();
2616
+ const streamsBefore = harness.http.state.streamsCount;
2617
+
2618
+ const first = client.reconcile();
2619
+ const second = client.reconcile();
2620
+ expect(second).toBe(first);
2621
+ await Promise.all([first, second]);
2622
+
2623
+ expect(harness.http.state.streamsCount).toBe(streamsBefore + 1);
2624
+ // Once the shared pass settles, the next trigger starts a fresh one.
2625
+ await client.reconcile();
2626
+ expect(harness.http.state.streamsCount).toBe(streamsBefore + 2);
2627
+ await client.stop();
2628
+ });
2629
+
2630
+ it("closes the debug BroadcastChannel on stop and re-opens it on start", async () => {
2631
+ const globalScope = globalThis as unknown as {BroadcastChannel?: unknown};
2632
+ const original = globalScope.BroadcastChannel;
2633
+ const channels: Array<{name: string; closed: boolean}> = [];
2634
+ class FakeBroadcastChannel {
2635
+ onmessage: ((event: {data: unknown}) => void) | null = null;
2636
+ private readonly record: {name: string; closed: boolean};
2637
+ constructor(name: string) {
2638
+ this.record = {closed: false, name};
2639
+ channels.push(this.record);
2640
+ }
2641
+ postMessage(): void {}
2642
+ close(): void {
2643
+ this.record.closed = true;
2644
+ }
2645
+ }
2646
+ globalScope.BroadcastChannel = FakeBroadcastChannel;
2647
+ try {
2648
+ const harness = makeHarness({debug: true});
2649
+ const client = createSyncDb(harness.config);
2650
+ await client.start();
2651
+ await flush();
2652
+ expect(channels.length).toBe(1);
2653
+ expect(channels[0].closed).toBe(false);
2654
+
2655
+ await client.stop();
2656
+ expect(channels[0].closed).toBe(true);
2657
+
2658
+ // A restarted client mirrors again rather than going silent.
2659
+ await client.start();
2660
+ await flush();
2661
+ expect(channels.length).toBe(2);
2662
+ expect(channels[1].closed).toBe(false);
2663
+ await client.stop();
2664
+ expect(channels[1].closed).toBe(true);
2665
+ } finally {
2666
+ globalScope.BroadcastChannel = original;
2667
+ }
2668
+ });
2669
+ });
2670
+ });