@abloatai/ablo 0.36.0 → 0.37.1

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 (597) hide show
  1. package/AGENTS.md +2 -2
  2. package/CHANGELOG.md +55 -2014
  3. package/NOTICE +2 -2
  4. package/README.md +45 -63
  5. package/assets/banner.png +0 -0
  6. package/dist/auth.d.ts +2 -0
  7. package/dist/auth.d.ts.map +1 -0
  8. package/dist/auth.js +2 -0
  9. package/dist/auth.js.map +1 -0
  10. package/dist/client.d.ts +3 -0
  11. package/dist/client.d.ts.map +1 -0
  12. package/dist/client.js +3 -0
  13. package/dist/client.js.map +1 -0
  14. package/dist/coordination.d.ts +2 -0
  15. package/dist/coordination.d.ts.map +1 -0
  16. package/dist/coordination.js +2 -0
  17. package/dist/coordination.js.map +1 -0
  18. package/dist/index.d.ts +3 -114
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +3 -163
  21. package/dist/index.js.map +1 -0
  22. package/dist/react.d.ts +4 -0
  23. package/dist/react.d.ts.map +1 -0
  24. package/dist/react.js +3 -0
  25. package/dist/react.js.map +1 -0
  26. package/dist/schema.d.ts +2 -0
  27. package/dist/schema.d.ts.map +1 -0
  28. package/dist/schema.js +2 -0
  29. package/dist/schema.js.map +1 -0
  30. package/dist/server.d.ts +2 -0
  31. package/dist/server.d.ts.map +1 -0
  32. package/dist/server.js +2 -0
  33. package/dist/server.js.map +1 -0
  34. package/dist/source-conformance.d.ts +2 -0
  35. package/dist/source-conformance.d.ts.map +1 -0
  36. package/dist/source-conformance.js +2 -0
  37. package/dist/source-conformance.js.map +1 -0
  38. package/dist/source-drizzle.d.ts +2 -0
  39. package/dist/source-drizzle.d.ts.map +1 -0
  40. package/dist/source-drizzle.js +2 -0
  41. package/dist/source-drizzle.js.map +1 -0
  42. package/dist/source-kysely.d.ts +2 -0
  43. package/dist/source-kysely.d.ts.map +1 -0
  44. package/dist/source-kysely.js +2 -0
  45. package/dist/source-kysely.js.map +1 -0
  46. package/dist/source-next.d.ts +2 -0
  47. package/dist/source-next.d.ts.map +1 -0
  48. package/dist/source-next.js +2 -0
  49. package/dist/source-next.js.map +1 -0
  50. package/dist/source.d.ts +2 -0
  51. package/dist/source.d.ts.map +1 -0
  52. package/dist/source.js +2 -0
  53. package/dist/source.js.map +1 -0
  54. package/dist/wire.d.ts +2 -0
  55. package/dist/wire.d.ts.map +1 -0
  56. package/dist/wire.js +2 -0
  57. package/dist/wire.js.map +1 -0
  58. package/docs/agents.md +1 -1
  59. package/docs/api-keys.md +7 -6
  60. package/docs/api.md +10 -10
  61. package/docs/client-behavior.md +5 -5
  62. package/docs/coordination.md +52 -62
  63. package/docs/data-sources.md +1 -1
  64. package/docs/examples/agent-human.md +4 -4
  65. package/docs/examples/ai-sdk-tool.md +1 -1
  66. package/docs/examples/existing-python-backend.md +15 -4
  67. package/docs/examples/nextjs.md +27 -6
  68. package/docs/examples/server-agent.md +2 -2
  69. package/docs/how-it-works.md +4 -4
  70. package/docs/identity.md +2 -1
  71. package/docs/integration-guide.md +24 -13
  72. package/docs/internal/README.md +18 -0
  73. package/docs/internal/agent-fleet-coordination-design.md +171 -0
  74. package/docs/internal/agent-orchestration.md +58 -0
  75. package/docs/internal/commit-identifiers.md +91 -0
  76. package/docs/internal/concurrency-open-decisions.md +37 -0
  77. package/docs/internal/data-source-reverse-channel.md +150 -0
  78. package/docs/internal/per-field-conflict-detection.md +165 -0
  79. package/docs/internal/postgres-replication.md +64 -0
  80. package/docs/internal/serializable-schema.md +119 -0
  81. package/docs/internal/structure.md +32 -0
  82. package/docs/mcp.md +2 -2
  83. package/docs/migration.md +3 -3
  84. package/docs/quickstart.md +2 -2
  85. package/docs/react.md +5 -5
  86. package/docs/schema-contract.md +3 -3
  87. package/docs/sessions.md +91 -37
  88. package/examples/README.md +2 -2
  89. package/examples/data-source/README.md +1 -1
  90. package/examples/data-source/ablo-driver.ts +1 -1
  91. package/examples/data-source/customer-server.ts +1 -1
  92. package/examples/data-source/run.ts +1 -1
  93. package/examples/data-source/schema.ts +1 -1
  94. package/examples/quickstart.ts +2 -2
  95. package/llms.txt +8 -8
  96. package/package.json +63 -166
  97. package/bin/ablo.cjs +0 -39
  98. package/dist/BaseSyncedStore.d.ts +0 -843
  99. package/dist/BaseSyncedStore.js +0 -1971
  100. package/dist/Database.d.ts +0 -323
  101. package/dist/Database.js +0 -1502
  102. package/dist/InstanceCache.d.ts +0 -237
  103. package/dist/InstanceCache.js +0 -1166
  104. package/dist/LazyReferenceCollection.d.ts +0 -177
  105. package/dist/LazyReferenceCollection.js +0 -461
  106. package/dist/Model.d.ts +0 -454
  107. package/dist/Model.js +0 -919
  108. package/dist/ModelRegistry.d.ts +0 -225
  109. package/dist/ModelRegistry.js +0 -539
  110. package/dist/NetworkMonitor.d.ts +0 -28
  111. package/dist/NetworkMonitor.js +0 -79
  112. package/dist/RuntimeContext.d.ts +0 -52
  113. package/dist/RuntimeContext.js +0 -80
  114. package/dist/SyncClient.d.ts +0 -541
  115. package/dist/SyncClient.js +0 -2202
  116. package/dist/adapters/alwaysOnline.d.ts +0 -14
  117. package/dist/adapters/alwaysOnline.js +0 -17
  118. package/dist/adapters/inMemoryStorage.d.ts +0 -31
  119. package/dist/adapters/inMemoryStorage.js +0 -110
  120. package/dist/ai-sdk/coordinatedTool.d.ts +0 -120
  121. package/dist/ai-sdk/coordinatedTool.js +0 -134
  122. package/dist/ai-sdk/coordinationContext.d.ts +0 -46
  123. package/dist/ai-sdk/coordinationContext.js +0 -106
  124. package/dist/ai-sdk/index.d.ts +0 -121
  125. package/dist/ai-sdk/index.js +0 -121
  126. package/dist/ai-sdk/wrap.d.ts +0 -65
  127. package/dist/ai-sdk/wrap.js +0 -39
  128. package/dist/auth/index.d.ts +0 -1
  129. package/dist/auth/index.js +0 -8
  130. package/dist/batching/index.d.ts +0 -55
  131. package/dist/batching/index.js +0 -147
  132. package/dist/client/Ablo.d.ts +0 -231
  133. package/dist/client/Ablo.js +0 -160
  134. package/dist/client/abloClient.d.ts +0 -309
  135. package/dist/client/abloClient.js +0 -13
  136. package/dist/client/clientPrelude.d.ts +0 -52
  137. package/dist/client/clientPrelude.js +0 -60
  138. package/dist/client/consoleLogger.d.ts +0 -35
  139. package/dist/client/consoleLogger.js +0 -44
  140. package/dist/client/coreClient.d.ts +0 -60
  141. package/dist/client/coreClient.js +0 -118
  142. package/dist/client/createInternalComponents.d.ts +0 -50
  143. package/dist/client/createInternalComponents.js +0 -98
  144. package/dist/client/createModelProxy.d.ts +0 -248
  145. package/dist/client/createModelProxy.js +0 -884
  146. package/dist/client/humans.d.ts +0 -69
  147. package/dist/client/humans.js +0 -78
  148. package/dist/client/modelRegistration.d.ts +0 -10
  149. package/dist/client/modelRegistration.js +0 -312
  150. package/dist/client/options.d.ts +0 -461
  151. package/dist/client/options.js +0 -7
  152. package/dist/client/reactiveEngine.d.ts +0 -53
  153. package/dist/client/reactiveEngine.js +0 -688
  154. package/dist/client/resourceTypes.d.ts +0 -12
  155. package/dist/client/resourceTypes.js +0 -10
  156. package/dist/client/schemaConfig.d.ts +0 -44
  157. package/dist/client/schemaConfig.js +0 -185
  158. package/dist/client/storeCluster.d.ts +0 -47
  159. package/dist/client/storeCluster.js +0 -118
  160. package/dist/client/storeLifecycle.d.ts +0 -61
  161. package/dist/client/storeLifecycle.js +0 -231
  162. package/dist/client/validateAbloOptions.d.ts +0 -42
  163. package/dist/client/validateAbloOptions.js +0 -43
  164. package/dist/client/wsMutationExecutor.d.ts +0 -27
  165. package/dist/client/wsMutationExecutor.js +0 -72
  166. package/dist/context.d.ts +0 -42
  167. package/dist/context.js +0 -81
  168. package/dist/coordination/ClaimLog.d.ts +0 -26
  169. package/dist/coordination/ClaimLog.js +0 -32
  170. package/dist/coordination/index.d.ts +0 -1
  171. package/dist/coordination/index.js +0 -8
  172. package/dist/core/index.d.ts +0 -33
  173. package/dist/core/index.js +0 -48
  174. package/dist/docs/catalog.d.ts +0 -72
  175. package/dist/docs/catalog.js +0 -230
  176. package/dist/docs/index.d.ts +0 -10
  177. package/dist/docs/index.js +0 -10
  178. package/dist/environment.d.ts +0 -1
  179. package/dist/environment.js +0 -8
  180. package/dist/interfaces/index.d.ts +0 -311
  181. package/dist/interfaces/index.js +0 -9
  182. package/dist/keys/index.d.ts +0 -1
  183. package/dist/keys/index.js +0 -8
  184. package/dist/mutators/RecordingMutation.d.ts +0 -36
  185. package/dist/mutators/RecordingMutation.js +0 -182
  186. package/dist/mutators/Transaction.d.ts +0 -40
  187. package/dist/mutators/Transaction.js +0 -58
  188. package/dist/mutators/UndoManager.d.ts +0 -258
  189. package/dist/mutators/UndoManager.js +0 -658
  190. package/dist/mutators/defineMutators.d.ts +0 -60
  191. package/dist/mutators/defineMutators.js +0 -18
  192. package/dist/mutators/inverseOp.d.ts +0 -126
  193. package/dist/mutators/inverseOp.js +0 -71
  194. package/dist/mutators/mutateActions.d.ts +0 -45
  195. package/dist/mutators/mutateActions.js +0 -105
  196. package/dist/mutators/readerActions.d.ts +0 -33
  197. package/dist/mutators/readerActions.js +0 -57
  198. package/dist/mutators/undoApply.d.ts +0 -51
  199. package/dist/mutators/undoApply.js +0 -117
  200. package/dist/policy/index.d.ts +0 -21
  201. package/dist/policy/index.js +0 -20
  202. package/dist/query/QueryProcessor.d.ts +0 -75
  203. package/dist/query/QueryProcessor.js +0 -255
  204. package/dist/query/client.d.ts +0 -64
  205. package/dist/query/client.js +0 -138
  206. package/dist/query/types.d.ts +0 -85
  207. package/dist/query/types.js +0 -16
  208. package/dist/react/AbloProvider.d.ts +0 -242
  209. package/dist/react/AbloProvider.js +0 -458
  210. package/dist/react/ClientSideSuspense.d.ts +0 -36
  211. package/dist/react/ClientSideSuspense.js +0 -17
  212. package/dist/react/DefaultFallback.d.ts +0 -24
  213. package/dist/react/DefaultFallback.js +0 -43
  214. package/dist/react/context.d.ts +0 -55
  215. package/dist/react/context.js +0 -29
  216. package/dist/react/createAbloReact.d.ts +0 -56
  217. package/dist/react/createAbloReact.js +0 -51
  218. package/dist/react/index.d.ts +0 -62
  219. package/dist/react/index.js +0 -69
  220. package/dist/react/internalContext.d.ts +0 -33
  221. package/dist/react/internalContext.js +0 -3
  222. package/dist/react/useAblo.d.ts +0 -82
  223. package/dist/react/useAblo.js +0 -120
  224. package/dist/react/useCurrentUserId.d.ts +0 -22
  225. package/dist/react/useCurrentUserId.js +0 -34
  226. package/dist/react/useErrorListener.d.ts +0 -20
  227. package/dist/react/useErrorListener.js +0 -38
  228. package/dist/react/useMutationFailureListener.d.ts +0 -26
  229. package/dist/react/useMutationFailureListener.js +0 -38
  230. package/dist/react/useMutators.d.ts +0 -56
  231. package/dist/react/useMutators.js +0 -84
  232. package/dist/react/useReactive.d.ts +0 -35
  233. package/dist/react/useReactive.js +0 -123
  234. package/dist/react/useSyncStatus.d.ts +0 -59
  235. package/dist/react/useSyncStatus.js +0 -76
  236. package/dist/react/useUndoScope.d.ts +0 -34
  237. package/dist/react/useUndoScope.js +0 -81
  238. package/dist/schema/coordination.d.ts +0 -112
  239. package/dist/schema/coordination.js +0 -133
  240. package/dist/schema/ddl.d.ts +0 -97
  241. package/dist/schema/ddl.js +0 -491
  242. package/dist/schema/ddlLock.d.ts +0 -35
  243. package/dist/schema/ddlLock.js +0 -46
  244. package/dist/schema/diff.d.ts +0 -225
  245. package/dist/schema/diff.js +0 -289
  246. package/dist/schema/generate.d.ts +0 -19
  247. package/dist/schema/generate.js +0 -86
  248. package/dist/schema/index.d.ts +0 -42
  249. package/dist/schema/index.js +0 -80
  250. package/dist/schema/queries.d.ts +0 -201
  251. package/dist/schema/queries.js +0 -144
  252. package/dist/schema/select.d.ts +0 -40
  253. package/dist/schema/select.js +0 -90
  254. package/dist/schema/serialize.d.ts +0 -115
  255. package/dist/schema/serialize.js +0 -265
  256. package/dist/schema/sugar.d.ts +0 -109
  257. package/dist/schema/sugar.js +0 -83
  258. package/dist/schema/syncDeltaRow.d.ts +0 -6
  259. package/dist/schema/syncDeltaRow.js +0 -6
  260. package/dist/server/adapter.d.ts +0 -173
  261. package/dist/server/adapter.js +0 -18
  262. package/dist/server/commit.d.ts +0 -107
  263. package/dist/server/commit.js +0 -1
  264. package/dist/server/index.d.ts +0 -14
  265. package/dist/server/index.js +0 -2
  266. package/dist/server/readConfig.d.ts +0 -80
  267. package/dist/server/readConfig.js +0 -8
  268. package/dist/server/storageMode.d.ts +0 -23
  269. package/dist/server/storageMode.js +0 -17
  270. package/dist/source/adapter.d.ts +0 -83
  271. package/dist/source/adapter.js +0 -24
  272. package/dist/source/adapters/drizzle.d.ts +0 -48
  273. package/dist/source/adapters/drizzle.js +0 -219
  274. package/dist/source/adapters/kysely.d.ts +0 -42
  275. package/dist/source/adapters/kysely.js +0 -205
  276. package/dist/source/adapters/kyselyMutationCore.d.ts +0 -76
  277. package/dist/source/adapters/kyselyMutationCore.js +0 -125
  278. package/dist/source/adapters/memory.d.ts +0 -13
  279. package/dist/source/adapters/memory.js +0 -130
  280. package/dist/source/adapters/prisma.d.ts +0 -63
  281. package/dist/source/adapters/prisma.js +0 -202
  282. package/dist/source/conformance.d.ts +0 -37
  283. package/dist/source/conformance.js +0 -215
  284. package/dist/source/connector.d.ts +0 -95
  285. package/dist/source/connector.js +0 -266
  286. package/dist/source/connectorProtocol.d.ts +0 -154
  287. package/dist/source/connectorProtocol.js +0 -163
  288. package/dist/source/contract.d.ts +0 -195
  289. package/dist/source/contract.js +0 -164
  290. package/dist/source/factory.d.ts +0 -92
  291. package/dist/source/factory.js +0 -286
  292. package/dist/source/idempotency.d.ts +0 -61
  293. package/dist/source/idempotency.js +0 -144
  294. package/dist/source/index.d.ts +0 -23
  295. package/dist/source/index.js +0 -30
  296. package/dist/source/migrations.d.ts +0 -21
  297. package/dist/source/migrations.js +0 -103
  298. package/dist/source/next.d.ts +0 -32
  299. package/dist/source/next.js +0 -25
  300. package/dist/source/pushQueue.d.ts +0 -134
  301. package/dist/source/pushQueue.js +0 -256
  302. package/dist/source/signing.d.ts +0 -92
  303. package/dist/source/signing.js +0 -162
  304. package/dist/source/types.d.ts +0 -401
  305. package/dist/source/types.js +0 -59
  306. package/dist/storeContract.d.ts +0 -145
  307. package/dist/storeContract.js +0 -12
  308. package/dist/stores/DatabaseManager.d.ts +0 -107
  309. package/dist/stores/DatabaseManager.js +0 -388
  310. package/dist/stores/ObjectStore.d.ts +0 -115
  311. package/dist/stores/ObjectStore.js +0 -393
  312. package/dist/stores/ObjectStoreContract.d.ts +0 -38
  313. package/dist/stores/ObjectStoreContract.js +0 -1
  314. package/dist/stores/StoreManager.d.ts +0 -114
  315. package/dist/stores/StoreManager.js +0 -304
  316. package/dist/stores/SyncActionStore.d.ts +0 -99
  317. package/dist/stores/SyncActionStore.js +0 -506
  318. package/dist/stores/openIDBWithTimeout.d.ts +0 -65
  319. package/dist/stores/openIDBWithTimeout.js +0 -153
  320. package/dist/stores/syncAction.d.ts +0 -26
  321. package/dist/stores/syncAction.js +0 -16
  322. package/dist/surface.d.ts +0 -36
  323. package/dist/surface.js +0 -75
  324. package/dist/sync/BootstrapFetcher.d.ts +0 -284
  325. package/dist/sync/BootstrapFetcher.js +0 -964
  326. package/dist/sync/ConnectionManager.d.ts +0 -8
  327. package/dist/sync/ConnectionManager.js +0 -8
  328. package/dist/sync/OnDemandLoader.d.ts +0 -231
  329. package/dist/sync/OnDemandLoader.js +0 -743
  330. package/dist/sync/SubscriptionManager.d.ts +0 -159
  331. package/dist/sync/SubscriptionManager.js +0 -243
  332. package/dist/sync/SyncWebSocket.d.ts +0 -173
  333. package/dist/sync/SyncWebSocket.js +0 -438
  334. package/dist/sync/awaitClaimGrant.d.ts +0 -6
  335. package/dist/sync/awaitClaimGrant.js +0 -6
  336. package/dist/sync/bootstrapApply.d.ts +0 -73
  337. package/dist/sync/bootstrapApply.js +0 -73
  338. package/dist/sync/commitFrames.d.ts +0 -8
  339. package/dist/sync/commitFrames.js +0 -8
  340. package/dist/sync/contextPorts.d.ts +0 -18
  341. package/dist/sync/contextPorts.js +0 -31
  342. package/dist/sync/createClaimStream.d.ts +0 -7
  343. package/dist/sync/createClaimStream.js +0 -7
  344. package/dist/sync/createPresenceStream.d.ts +0 -69
  345. package/dist/sync/createPresenceStream.js +0 -200
  346. package/dist/sync/createSnapshot.d.ts +0 -29
  347. package/dist/sync/createSnapshot.js +0 -118
  348. package/dist/sync/credentialLifecycle.d.ts +0 -7
  349. package/dist/sync/credentialLifecycle.js +0 -7
  350. package/dist/sync/deltaPipeline.d.ts +0 -114
  351. package/dist/sync/deltaPipeline.js +0 -278
  352. package/dist/sync/groupChange.d.ts +0 -116
  353. package/dist/sync/groupChange.js +0 -244
  354. package/dist/sync/participants.d.ts +0 -132
  355. package/dist/sync/participants.js +0 -346
  356. package/dist/sync/persistedPrefix.d.ts +0 -12
  357. package/dist/sync/persistedPrefix.js +0 -22
  358. package/dist/sync/schemaDrift.d.ts +0 -55
  359. package/dist/sync/schemaDrift.js +0 -53
  360. package/dist/sync/schemas.d.ts +0 -71
  361. package/dist/sync/schemas.js +0 -94
  362. package/dist/sync/syncCursor.d.ts +0 -40
  363. package/dist/sync/syncCursor.js +0 -55
  364. package/dist/sync/syncPlan.d.ts +0 -54
  365. package/dist/sync/syncPlan.js +0 -50
  366. package/dist/sync/wsFrameHandlers.d.ts +0 -8
  367. package/dist/sync/wsFrameHandlers.js +0 -8
  368. package/dist/syncLog/contract.d.ts +0 -20
  369. package/dist/syncLog/contract.js +0 -19
  370. package/dist/syncLog/index.d.ts +0 -1
  371. package/dist/syncLog/index.js +0 -1
  372. package/dist/transaction/ablo.d.ts +0 -88
  373. package/dist/transaction/ablo.js +0 -33
  374. package/dist/transaction/auth/apiKey.d.ts +0 -152
  375. package/dist/transaction/auth/apiKey.js +0 -419
  376. package/dist/transaction/auth/bootstrapScope.d.ts +0 -15
  377. package/dist/transaction/auth/bootstrapScope.js +0 -1
  378. package/dist/transaction/auth/capability.d.ts +0 -212
  379. package/dist/transaction/auth/capability.js +0 -224
  380. package/dist/transaction/auth/credentialEndpoint.d.ts +0 -61
  381. package/dist/transaction/auth/credentialEndpoint.js +0 -86
  382. package/dist/transaction/auth/credentialPolicy.d.ts +0 -148
  383. package/dist/transaction/auth/credentialPolicy.js +0 -125
  384. package/dist/transaction/auth/credentialSource.d.ts +0 -30
  385. package/dist/transaction/auth/credentialSource.js +0 -55
  386. package/dist/transaction/auth/hostedEndpoints.d.ts +0 -21
  387. package/dist/transaction/auth/hostedEndpoints.js +0 -21
  388. package/dist/transaction/auth/identity.d.ts +0 -55
  389. package/dist/transaction/auth/identity.js +0 -210
  390. package/dist/transaction/auth/index.d.ts +0 -162
  391. package/dist/transaction/auth/index.js +0 -304
  392. package/dist/transaction/auth/schemas.d.ts +0 -59
  393. package/dist/transaction/auth/schemas.js +0 -85
  394. package/dist/transaction/auth/sessionMint.d.ts +0 -28
  395. package/dist/transaction/auth/sessionMint.js +0 -85
  396. package/dist/transaction/coordination/awaitClaimGrant.d.ts +0 -56
  397. package/dist/transaction/coordination/awaitClaimGrant.js +0 -124
  398. package/dist/transaction/coordination/claimHeartbeatLoop.d.ts +0 -84
  399. package/dist/transaction/coordination/claimHeartbeatLoop.js +0 -108
  400. package/dist/transaction/coordination/claimMeta.d.ts +0 -49
  401. package/dist/transaction/coordination/claimMeta.js +0 -52
  402. package/dist/transaction/coordination/createClaimStream.d.ts +0 -64
  403. package/dist/transaction/coordination/createClaimStream.js +0 -475
  404. package/dist/transaction/coordination/events.d.ts +0 -74
  405. package/dist/transaction/coordination/events.js +0 -7
  406. package/dist/transaction/coordination/index.d.ts +0 -19
  407. package/dist/transaction/coordination/index.js +0 -45
  408. package/dist/transaction/coordination/locator.d.ts +0 -104
  409. package/dist/transaction/coordination/locator.js +0 -102
  410. package/dist/transaction/coordination/schema.d.ts +0 -1536
  411. package/dist/transaction/coordination/schema.js +0 -1177
  412. package/dist/transaction/coordination/targetConflict.d.ts +0 -2
  413. package/dist/transaction/coordination/targetConflict.js +0 -107
  414. package/dist/transaction/coordination/trace.d.ts +0 -78
  415. package/dist/transaction/coordination/trace.js +0 -138
  416. package/dist/transaction/durableWrites.d.ts +0 -62
  417. package/dist/transaction/durableWrites.js +0 -71
  418. package/dist/transaction/environment.d.ts +0 -105
  419. package/dist/transaction/environment.js +0 -108
  420. package/dist/transaction/errorCodes.d.ts +0 -403
  421. package/dist/transaction/errorCodes.js +0 -484
  422. package/dist/transaction/errors.d.ts +0 -428
  423. package/dist/transaction/errors.js +0 -686
  424. package/dist/transaction/footprint.d.ts +0 -111
  425. package/dist/transaction/footprint.js +0 -0
  426. package/dist/transaction/index.d.ts +0 -20
  427. package/dist/transaction/index.js +0 -20
  428. package/dist/transaction/keys/index.d.ts +0 -87
  429. package/dist/transaction/keys/index.js +0 -207
  430. package/dist/transaction/log/syncDeltaRow.d.ts +0 -158
  431. package/dist/transaction/log/syncDeltaRow.js +0 -95
  432. package/dist/transaction/logPosition.d.ts +0 -97
  433. package/dist/transaction/logPosition.js +0 -125
  434. package/dist/transaction/logger.d.ts +0 -16
  435. package/dist/transaction/logger.js +0 -7
  436. package/dist/transaction/observability.d.ts +0 -53
  437. package/dist/transaction/observability.js +0 -19
  438. package/dist/transaction/persistence.d.ts +0 -12
  439. package/dist/transaction/persistence.js +0 -11
  440. package/dist/transaction/plugin.d.ts +0 -285
  441. package/dist/transaction/plugin.js +0 -106
  442. package/dist/transaction/policy/types.d.ts +0 -217
  443. package/dist/transaction/policy/types.js +0 -126
  444. package/dist/transaction/resources/functionalUpdate.d.ts +0 -79
  445. package/dist/transaction/resources/functionalUpdate.js +0 -87
  446. package/dist/transaction/resources/httpResources.d.ts +0 -321
  447. package/dist/transaction/resources/httpResources.js +0 -7
  448. package/dist/transaction/resources/modelOperations.d.ts +0 -427
  449. package/dist/transaction/resources/modelOperations.js +0 -12
  450. package/dist/transaction/resources/mutationOptions.d.ts +0 -66
  451. package/dist/transaction/resources/mutationOptions.js +0 -9
  452. package/dist/transaction/resources/where.d.ts +0 -101
  453. package/dist/transaction/resources/where.js +0 -115
  454. package/dist/transaction/resources/writeOptionsSchema.d.ts +0 -47
  455. package/dist/transaction/resources/writeOptionsSchema.js +0 -73
  456. package/dist/transaction/schema/field.d.ts +0 -120
  457. package/dist/transaction/schema/field.js +0 -265
  458. package/dist/transaction/schema/fieldRef.d.ts +0 -38
  459. package/dist/transaction/schema/fieldRef.js +0 -11
  460. package/dist/transaction/schema/loadStrategy.d.ts +0 -45
  461. package/dist/transaction/schema/loadStrategy.js +0 -46
  462. package/dist/transaction/schema/model.d.ts +0 -379
  463. package/dist/transaction/schema/model.js +0 -123
  464. package/dist/transaction/schema/openapi.d.ts +0 -58
  465. package/dist/transaction/schema/openapi.js +0 -501
  466. package/dist/transaction/schema/relation.d.ts +0 -204
  467. package/dist/transaction/schema/relation.js +0 -104
  468. package/dist/transaction/schema/residency.d.ts +0 -29
  469. package/dist/transaction/schema/residency.js +0 -25
  470. package/dist/transaction/schema/roles.d.ts +0 -249
  471. package/dist/transaction/schema/roles.js +0 -230
  472. package/dist/transaction/schema/schema.d.ts +0 -351
  473. package/dist/transaction/schema/schema.js +0 -325
  474. package/dist/transaction/schema/tenancy.d.ts +0 -139
  475. package/dist/transaction/schema/tenancy.js +0 -190
  476. package/dist/transaction/transactionLayer.d.ts +0 -82
  477. package/dist/transaction/transactionLayer.js +0 -24
  478. package/dist/transaction/transactions/settlement/commitEnvelope.d.ts +0 -143
  479. package/dist/transaction/transactions/settlement/commitEnvelope.js +0 -161
  480. package/dist/transaction/transactions/settlement/httpCommitEnvelope.d.ts +0 -53
  481. package/dist/transaction/transactions/settlement/httpCommitEnvelope.js +0 -207
  482. package/dist/transaction/transactions/settlement/idempotencyKey.d.ts +0 -10
  483. package/dist/transaction/transactions/settlement/idempotencyKey.js +0 -9
  484. package/dist/transaction/transactions/settlement/pendingWrite.d.ts +0 -112
  485. package/dist/transaction/transactions/settlement/pendingWrite.js +0 -20
  486. package/dist/transaction/transport/commitFrames.d.ts +0 -90
  487. package/dist/transaction/transport/commitFrames.js +0 -134
  488. package/dist/transaction/transport/connectionManager.d.ts +0 -215
  489. package/dist/transaction/transport/connectionManager.js +0 -673
  490. package/dist/transaction/transport/credentialLifecycle.d.ts +0 -177
  491. package/dist/transaction/transport/credentialLifecycle.js +0 -324
  492. package/dist/transaction/transport/heartbeat.d.ts +0 -65
  493. package/dist/transaction/transport/heartbeat.js +0 -93
  494. package/dist/transaction/transport/httpClient.d.ts +0 -131
  495. package/dist/transaction/transport/httpClient.js +0 -146
  496. package/dist/transaction/transport/httpOptions.d.ts +0 -33
  497. package/dist/transaction/transport/httpOptions.js +0 -12
  498. package/dist/transaction/transport/httpTransport.d.ts +0 -8
  499. package/dist/transaction/transport/httpTransport.js +0 -1388
  500. package/dist/transaction/transport/networkProbe.d.ts +0 -84
  501. package/dist/transaction/transport/networkProbe.js +0 -207
  502. package/dist/transaction/transport/wsFrameHandlers.d.ts +0 -128
  503. package/dist/transaction/transport/wsFrameHandlers.js +0 -429
  504. package/dist/transaction/transport/wsTransport.d.ts +0 -574
  505. package/dist/transaction/transport/wsTransport.js +0 -1023
  506. package/dist/transaction/types/assertExact.d.ts +0 -17
  507. package/dist/transaction/types/assertExact.js +0 -1
  508. package/dist/transaction/types/global.d.ts +0 -107
  509. package/dist/transaction/types/global.js +0 -40
  510. package/dist/transaction/types/index.d.ts +0 -205
  511. package/dist/transaction/types/index.js +0 -56
  512. package/dist/transaction/types/modelData.d.ts +0 -10
  513. package/dist/transaction/types/modelData.js +0 -9
  514. package/dist/transaction/types/participant.d.ts +0 -20
  515. package/dist/transaction/types/participant.js +0 -10
  516. package/dist/transaction/types/streams.d.ts +0 -550
  517. package/dist/transaction/types/streams.js +0 -11
  518. package/dist/transaction/utils/asyncIterator.d.ts +0 -34
  519. package/dist/transaction/utils/asyncIterator.js +0 -135
  520. package/dist/transaction/utils/duration.d.ts +0 -50
  521. package/dist/transaction/utils/duration.js +0 -77
  522. package/dist/transaction/utils/json.d.ts +0 -57
  523. package/dist/transaction/utils/json.js +0 -276
  524. package/dist/transaction/wire/accountResponses.d.ts +0 -420
  525. package/dist/transaction/wire/accountResponses.js +0 -290
  526. package/dist/transaction/wire/auth.d.ts +0 -56
  527. package/dist/transaction/wire/auth.js +0 -63
  528. package/dist/transaction/wire/bootstrapReason.d.ts +0 -9
  529. package/dist/transaction/wire/bootstrapReason.js +0 -8
  530. package/dist/transaction/wire/claimEvent.d.ts +0 -76
  531. package/dist/transaction/wire/claimEvent.js +0 -73
  532. package/dist/transaction/wire/claims.d.ts +0 -530
  533. package/dist/transaction/wire/claims.js +0 -327
  534. package/dist/transaction/wire/commit.d.ts +0 -603
  535. package/dist/transaction/wire/commit.js +0 -321
  536. package/dist/transaction/wire/delta.d.ts +0 -250
  537. package/dist/transaction/wire/delta.js +0 -147
  538. package/dist/transaction/wire/errorEnvelope.d.ts +0 -72
  539. package/dist/transaction/wire/errorEnvelope.js +0 -123
  540. package/dist/transaction/wire/feedCursor.d.ts +0 -60
  541. package/dist/transaction/wire/feedCursor.js +0 -82
  542. package/dist/transaction/wire/feedEvent.d.ts +0 -204
  543. package/dist/transaction/wire/feedEvent.js +0 -65
  544. package/dist/transaction/wire/frames.d.ts +0 -194
  545. package/dist/transaction/wire/frames.js +0 -50
  546. package/dist/transaction/wire/inboundFrames.d.ts +0 -562
  547. package/dist/transaction/wire/inboundFrames.js +0 -116
  548. package/dist/transaction/wire/index.d.ts +0 -54
  549. package/dist/transaction/wire/index.js +0 -83
  550. package/dist/transaction/wire/listEnvelope.d.ts +0 -37
  551. package/dist/transaction/wire/listEnvelope.js +0 -42
  552. package/dist/transaction/wire/modelMutations.d.ts +0 -31
  553. package/dist/transaction/wire/modelMutations.js +0 -52
  554. package/dist/transaction/wire/modelResponses.d.ts +0 -85
  555. package/dist/transaction/wire/modelResponses.js +0 -43
  556. package/dist/transaction/wire/modelShape.d.ts +0 -78
  557. package/dist/transaction/wire/modelShape.js +0 -74
  558. package/dist/transaction/wire/protocol.d.ts +0 -38
  559. package/dist/transaction/wire/protocol.js +0 -38
  560. package/dist/transaction/wire/protocolVersion.d.ts +0 -73
  561. package/dist/transaction/wire/protocolVersion.js +0 -83
  562. package/dist/transactions/mutations/MutationQueue.d.ts +0 -661
  563. package/dist/transactions/mutations/MutationQueue.js +0 -2807
  564. package/dist/transactions/mutations/MutationStore.d.ts +0 -20
  565. package/dist/transactions/mutations/MutationStore.js +0 -53
  566. package/dist/transactions/mutations/UnconfirmedWrites.d.ts +0 -82
  567. package/dist/transactions/mutations/UnconfirmedWrites.js +0 -104
  568. package/dist/transactions/mutations/coalesceRules.d.ts +0 -58
  569. package/dist/transactions/mutations/coalesceRules.js +0 -140
  570. package/dist/transactions/mutations/commitLatency.d.ts +0 -52
  571. package/dist/transactions/mutations/commitLatency.js +0 -130
  572. package/dist/transactions/mutations/commitOutboxStore.d.ts +0 -28
  573. package/dist/transactions/mutations/commitOutboxStore.js +0 -26
  574. package/dist/transactions/mutations/commitPayload.d.ts +0 -165
  575. package/dist/transactions/mutations/commitPayload.js +0 -152
  576. package/dist/transactions/mutations/deltaConfirmation.d.ts +0 -63
  577. package/dist/transactions/mutations/deltaConfirmation.js +0 -235
  578. package/dist/transactions/mutations/durableWriteStore.d.ts +0 -14
  579. package/dist/transactions/mutations/durableWriteStore.js +0 -12
  580. package/dist/transactions/mutations/optimisticApply.d.ts +0 -49
  581. package/dist/transactions/mutations/optimisticApply.js +0 -65
  582. package/dist/transactions/mutations/replayValidation.d.ts +0 -187
  583. package/dist/transactions/mutations/replayValidation.js +0 -164
  584. package/dist/utils/mobxSetup.d.ts +0 -53
  585. package/dist/utils/mobxSetup.js +0 -330
  586. package/dist/views/QueryView.d.ts +0 -79
  587. package/dist/views/QueryView.js +0 -218
  588. package/dist/views/ViewRegistry.d.ts +0 -20
  589. package/dist/views/ViewRegistry.js +0 -55
  590. package/dist/views/incrementalView.d.ts +0 -45
  591. package/dist/views/incrementalView.js +0 -69
  592. package/dist/webhooks/events.d.ts +0 -43
  593. package/dist/webhooks/events.js +0 -42
  594. package/dist/webhooks/index.d.ts +0 -8
  595. package/dist/webhooks/index.js +0 -8
  596. package/dist/wire/index.d.ts +0 -1
  597. package/dist/wire/index.js +0 -8
@@ -1,1971 +0,0 @@
1
- /**
2
- * The base class that application-specific sync stores extend. It supplies the
3
- * shared orchestration for reads, writes, delta processing, and bootstrap, and
4
- * exports the core types those stores build on.
5
- *
6
- * A subclass adds its own domain behavior — lazy-loaded relations,
7
- * collaboration events, and model enrichment — by overriding the protected
8
- * extension points defined here. The heavy lifting is delegated to injected
9
- * collaborators: {@link SyncClient} owns pool writes and the transaction
10
- * queue, {@link Database} owns local persistence, {@link InstanceCache} holds the
11
- * in-memory models, and {@link ModelRegistry} holds their metadata.
12
- */
13
- import { makeObservable, observable, action, computed, runInAction } from 'mobx';
14
- import { AbloConnectionError, AbloValidationError, toAbloError } from './transaction/errors.js';
15
- import { ConnectionManager } from './sync/ConnectionManager.js';
16
- import { contextLogger, contextSocketObservability } from './sync/contextPorts.js';
17
- import { SubscriptionManager } from './sync/SubscriptionManager.js';
18
- import { resolveParticipantSyncGroups, } from './sync/participants.js';
19
- import { ModelRegistry } from './ModelRegistry.js';
20
- import { PropertyType } from './transaction/types/index.js';
21
- import { SyncWebSocket, } from './sync/SyncWebSocket.js';
22
- import { QueryProcessor } from './query/QueryProcessor.js';
23
- import { Model, rowAsModel } from './Model.js';
24
- import { globalRuntime } from './context.js';
25
- import { AbloSessionError, isAccessCredentialExpiryCloseReason } from './transaction/errors.js';
26
- import { ModelScope } from './InstanceCache.js';
27
- import { LazyReferenceCollection } from './LazyReferenceCollection.js';
28
- import { deriveSyncPlanFromSchema } from './sync/syncPlan.js';
29
- import { CredentialLifecycle } from './sync/credentialLifecycle.js';
30
- import * as groupChange from './sync/groupChange.js';
31
- import * as bootstrapApply from './sync/bootstrapApply.js';
32
- import * as deltaPipeline from './sync/deltaPipeline.js';
33
- /**
34
- * Bootstrap retry configuration.
35
- *
36
- * There is deliberately no overall timeout here. How long one attempt may run
37
- * is not a policy this layer gets to invent — it is a property of the fetcher's
38
- * watchdogs, read from `BootstrapFetcher.budgetMs`. A second number kept here
39
- * would only be able to disagree with them, which is exactly what it used to do.
40
- */
41
- export const BOOTSTRAP_CONFIG = {
42
- MAX_RETRY_ATTEMPTS: 3,
43
- RETRY_DELAY_MS: 500,
44
- };
45
- // Re-export for clean API
46
- export { ModelScope };
47
- // deriveSyncPlanFromSchema derives a sync plan from a schema and is
48
- // re-exported here.
49
- export { deriveSyncPlanFromSchema } from './sync/syncPlan.js';
50
- // ── Base class ──────────────────────────────────────────────────────────────
51
- /**
52
- * The abstract base class that application-specific sync stores extend. It
53
- * carries the injected collaborators, the observable sync status, and the
54
- * orchestration for initialization, delta processing, bootstrap, and the
55
- * read and write API. A subclass supplies its own domain behavior by
56
- * overriding the protected extension points defined here and by typing its
57
- * collaboration events through the generic parameter.
58
- *
59
- * A subclass must call `super(dependencies, config)` and then set up its own
60
- * MobX observables.
61
- *
62
- * Generic over `TCollaboration` — an app-defined event map for real-time
63
- * collaboration events (cursors, selections, presence beyond the core set).
64
- * Subclasses pass their own event map to get typed `subscribe()` calls on
65
- * the underlying SyncWebSocket without casts:
66
- *
67
- * @example
68
- * interface EditorEvents {
69
- * 'document:selection': [SelectionEvent];
70
- * 'document:cursor': [CursorEvent];
71
- * }
72
- * class EditorStore extends BaseSyncedStore<EditorEvents> {
73
- * subscribeToCursor(handler: (e: CursorEvent) => void) {
74
- * return this.syncWebSocket.subscribe('document:cursor', handler);
75
- * }
76
- * }
77
- */
78
- export class BaseSyncedStore {
79
- // ── Observable sync status for UI ──
80
- syncStatus = {
81
- state: 'idle',
82
- progress: 0,
83
- pendingChanges: 0,
84
- isSessionError: false,
85
- };
86
- // ── Injected dependencies ──
87
- /** The owning client's runtime; the module-global bridge when constructed directly. */
88
- runtime;
89
- /** The installed plugins the delta pipeline dispatches stage handlers to. */
90
- stagePlugins;
91
- syncClient;
92
- database;
93
- objectPool;
94
- modelRegistry;
95
- auth;
96
- /**
97
- * Schema the store was constructed with. Used by the schema-typed
98
- * `create(key, data)` factory and model self-healing.
99
- */
100
- schema;
101
- // ── Real-time sync ──
102
- /**
103
- * The connection, owned by whoever built this store (ADR 0016 follow-up
104
- * 3b): the host constructs it and hands it in, the store seeds its late
105
- * values during `initialize()` and owns the lifecycle from there. One
106
- * instance for the store's whole lifetime — reconnects replace the socket
107
- * inside it, never the object.
108
- */
109
- syncWebSocket;
110
- /**
111
- * Dynamic read interest (area-of-interest) over the connection's sync
112
- * groups. Constructed with the connection; the permanent base scopes are
113
- * seeded in `setupWebSocketSync` once identity resolves.
114
- */
115
- areaOfInterest;
116
- /** Sync groups whose current state has been backfilled into the pool
117
- * (hydrate-on-enter). Cleared when the pool is reset on (re)bootstrap. */
118
- hydratedGroups = new Set();
119
- /** In-flight scoped hydrations, keyed by group — single-flights concurrent
120
- * enters of the same scope so they share one fetch. */
121
- hydratingGroups = new Map();
122
- _syncServerUrl;
123
- /** Application-declared collaboration event types; empty unless configured. */
124
- _collaborationEvents = [];
125
- /**
126
- * Public accessor for the underlying SyncWebSocket. Used by the
127
- * factory in `createSyncEngine` to wire the default mutation
128
- * executor — the executor needs the WS handle to send commit
129
- * frames, and the factory can't reach `protected` state through
130
- * normal typing.
131
- */
132
- getSyncWebSocket() {
133
- return this.syncWebSocket;
134
- }
135
- /**
136
- * Subscribe to pushed frames — deltas, presence updates, claim grants and
137
- * losses, connection changes, and this store's collaboration events.
138
- * Durable by construction: the connection object exists for the store's
139
- * whole lifetime (reconnects replace only the socket inside it), so a
140
- * subscription made before the first connect starts delivering when the
141
- * socket opens and keeps delivering across every reconnect. Returns the
142
- * unsubscribe function.
143
- */
144
- subscribe(event, handler) {
145
- return this.syncWebSocket.subscribe(event, handler);
146
- }
147
- /**
148
- * Send a collaboration event (an app-specific real-time message from this
149
- * store's `TCollaboration` map). A no-op while the connection is down —
150
- * presence-grade traffic is not queued.
151
- */
152
- sendCollaborationEvent(messageType, payload) {
153
- this.syncWebSocket.sendCollaborationEvent(messageType, payload);
154
- }
155
- // ── Area-of-interest (dynamic read subscription) ─────────────────
156
- //
157
- // `enterScope`/`leaveScope` move the connection's read interest as the
158
- // user navigates (open or close a record); `pinScope`/`unpinScope`
159
- // express prominence (an active claim keeps a group subscribed). All four
160
- // resolve the scope to sync-group strings through the same resolver the
161
- // claim path uses (`resolveParticipantSyncGroups`), so read interest and
162
- // write claims always agree on the string for a given entity. Before the
163
- // connection opens they record interest without a wire send, and they
164
- // never reject when the transport is offline (see
165
- // {@link SubscriptionManager.reconcile}); the on-connect `resync` pushes
166
- // whatever interest accumulated.
167
- scopeToGroups(scope) {
168
- return resolveParticipantSyncGroups(scope, this.schema);
169
- }
170
- /**
171
- * Bring a scope into view and subscribe to its sync groups. With
172
- * `{ hydrate: true }`, also backfill the groups' current state into the pool
173
- * once the subscription is active. The order matters: subscribing first
174
- * guarantees no live delta is missed in the gap before the snapshot lands.
175
- * Hydration is best-effort — a failed backfill never rejects `enterScope`,
176
- * and the live delta stream keeps flowing regardless.
177
- */
178
- enterScope(scope, opts) {
179
- const groups = this.scopeToGroups(scope);
180
- const subscribed = Promise.all(groups.map((g) => this.areaOfInterest.enter(g))).then(() => undefined);
181
- if (!opts?.hydrate)
182
- return subscribed;
183
- return subscribed.then(() => this.hydrateGroups(groups));
184
- }
185
- /**
186
- * Backfill the current state of `syncGroups` into the pool with a side-effect-free
187
- * scoped snapshot fetch followed by the version-guarded scoped apply. The call
188
- * is idempotent (it skips groups already hydrated) and single-flight (concurrent
189
- * enters of the same group share one fetch). On error the groups are left
190
- * unmarked, so a later re-enter retries.
191
- */
192
- async hydrateGroups(syncGroups) {
193
- const need = syncGroups.filter((g) => !this.hydratedGroups.has(g) && !this.hydratingGroups.has(g));
194
- if (need.length === 0) {
195
- // Nothing new to fetch, but await any in-flight hydration for the
196
- // requested groups so callers can sequence on completion.
197
- await Promise.all(syncGroups
198
- .map((g) => this.hydratingGroups.get(g))
199
- .filter((p) => p !== undefined));
200
- return;
201
- }
202
- const work = (async () => {
203
- try {
204
- const data = await this.database.fetchScopedBootstrapData(need);
205
- this.syncClient.applyBootstrapDataToPool(data, undefined, { scoped: true });
206
- for (const g of need)
207
- this.hydratedGroups.add(g);
208
- }
209
- catch (err) {
210
- this.runtime.logger.debug('[BaseSyncedStore] scoped hydrate failed', {
211
- syncGroups: need,
212
- error: err instanceof Error ? err.message : String(err),
213
- });
214
- // Soft-fail — leave `need` un-hydrated so a re-enter retries.
215
- }
216
- finally {
217
- for (const g of need)
218
- this.hydratingGroups.delete(g);
219
- }
220
- })();
221
- for (const g of need)
222
- this.hydratingGroups.set(g, work);
223
- await work;
224
- }
225
- /** Leave a scope → its groups go warm (hysteresis), then drop on sweep. */
226
- leaveScope(scope) {
227
- return Promise.all(this.scopeToGroups(scope).map((g) => this.areaOfInterest.leave(g))).then(() => undefined);
228
- }
229
- /** Pin a scope (active claim / prominence) → never warms while pinned. */
230
- pinScope(scope) {
231
- return Promise.all(this.scopeToGroups(scope).map((g) => this.areaOfInterest.pin(g))).then(() => undefined);
232
- }
233
- /** Release a pin → the group transitions to warm rather than dropping. */
234
- unpinScope(scope) {
235
- return Promise.all(this.scopeToGroups(scope).map((g) => this.areaOfInterest.unpin(g))).then(() => undefined);
236
- }
237
- // ── Internal helpers ──
238
- queryProcessor;
239
- /**
240
- * Runtime behavior flags only — the schema/config arrays
241
- * (`enrichmentPlan`, `foreignKeyIndexes`) are consumed at construction
242
- * time and stored on the instance as `enrichmentPlan` and
243
- * pool-registered indexes. They don't need to persist on `this.config`.
244
- */
245
- config;
246
- disposers = [];
247
- initialized = false;
248
- dataReady = false;
249
- // ── User context ──
250
- // The identity the consumer supplied to `initialize()`: user id,
251
- // organization id, and optional team ids. Reads are scoped to this
252
- // identity, and the sync-group subscription is derived from it.
253
- userContext = null;
254
- // ── Smart sync ──
255
- /**
256
- * Declarative enrichment plan: "for model X, when a delta arrives,
257
- * read data[foreignKey] and attach the matching parent from the pool
258
- * as data[relationKey]." Merged from schema-derived + config at
259
- * construction time. Replaces the `enrichRelations` subclass override
260
- * pattern.
261
- */
262
- enrichmentPlan = [];
263
- smartSyncOptions;
264
- pendingDeltas = [];
265
- batchTimer = null;
266
- syncPromise = null;
267
- /** Resume/ack cursor — delegates to the shared LogPosition (see
268
- * logPosition.ts). Advances only after IDB persistence. */
269
- get lastAckedId() {
270
- return this.syncClient.position.persisted;
271
- }
272
- /** Pool-applied cursor — delegates to the shared LogPosition. */
273
- get highestProcessedSyncId() {
274
- return this.syncClient.position.applied;
275
- }
276
- // ── Delta queuing during bootstrap ──
277
- bootstrapDeltaQueue = null;
278
- activeBootstrapCount = 0;
279
- /** The live deadline for the bootstrap attempt in flight, if any. */
280
- bootstrapDeadlineTimer = null;
281
- // ── Delete tracking ──
282
- pendingDeletes = new Set();
283
- // ── Model type hydration ──
284
- modelTypesHydrated = new Set();
285
- modelTypeHydrationInFlight = new Map();
286
- constructor(dependencies, config = {}) {
287
- this.runtime = dependencies.runtime ?? globalRuntime;
288
- this.stagePlugins = dependencies.stagePlugins ?? [];
289
- this.syncClient = dependencies.syncClient;
290
- this.database = dependencies.database;
291
- this.objectPool = dependencies.objectPool;
292
- this.modelRegistry = dependencies.modelRegistry;
293
- this.auth = dependencies.auth;
294
- this.schema = dependencies.schema;
295
- this._syncServerUrl = dependencies.url;
296
- this._collaborationEvents = config.collaborationEvents ?? [];
297
- // The connection exists from construction (ADR 0016 follow-up 3b): the
298
- // host hands one in, or the store builds its own. `deferConnect` holds
299
- // it closed until `initialize()` has seeded identity and read scope, so
300
- // nothing can open an unscoped connection in between.
301
- this.syncWebSocket =
302
- dependencies.syncWebSocket ??
303
- new SyncWebSocket({
304
- baseUrl: this._syncServerUrl,
305
- collaborationEvents: [...this._collaborationEvents],
306
- getAuthToken: this.auth?.getAuthToken,
307
- deferConnect: true,
308
- capabilities: {
309
- partialBootstrap: true,
310
- compressedDeltas: true,
311
- streamingBootstrap: true,
312
- batchedDeltas: true,
313
- },
314
- });
315
- this.areaOfInterest = new SubscriptionManager({ transport: this.syncWebSocket });
316
- this.wireSocketEvents();
317
- // QueuedMutation events for pendingChanges tracking — connection-
318
- // independent, wired once for the store's lifetime.
319
- this.disposers.push(this.syncClient.onTransactionEvent('created', () => { this.incrementPendingChanges(); }), this.syncClient.onTransactionEvent('completed', () => { this.decrementPendingChanges(); }), this.syncClient.onTransactionEvent('failed', () => { this.decrementPendingChanges(); }));
320
- // Set this store as the global Model store
321
- Model.setStore(this);
322
- // ── Schema-derived sync plan ───────────────────────────────────────
323
- //
324
- // When a schema is provided, derive foreign-key indexes and the
325
- // enrichment plan from the declarative annotations on its `belongsTo`
326
- // relations. Explicit config fields layer on top, so a subclass can
327
- // pass hardcoded arrays without supplying a full schema.
328
- //
329
- // Order matters: schema-derived entries are registered first and
330
- // config entries second, so that when a caller supplies both, the
331
- // explicit config entries win and are never shadowed by derivation.
332
- const derived = dependencies.schema
333
- ? deriveSyncPlanFromSchema(dependencies.schema)
334
- : { enrichmentPlan: [], foreignKeyIndexes: [] };
335
- const mergedForeignKeyIndexes = [
336
- ...derived.foreignKeyIndexes,
337
- ...(config.foreignKeyIndexes ?? []),
338
- ];
339
- for (const { modelName, fieldName } of mergedForeignKeyIndexes) {
340
- this.objectPool.registerForeignKey(modelName, fieldName);
341
- }
342
- // Override hook — called after schema-driven registration so a subclass
343
- // can add more foreign keys on top of the declarative set.
344
- this.registerForeignKeys();
345
- this.enrichmentPlan = [
346
- ...derived.enrichmentPlan,
347
- ...(config.enrichmentPlan ?? []),
348
- ];
349
- // Set dependencies for LazyReferenceCollection
350
- LazyReferenceCollection.setDependencies(this.database, this.objectPool);
351
- // Apply config defaults
352
- this.config = {
353
- enableOffline: config.enableOffline ?? true,
354
- enableCache: config.enableCache ?? true,
355
- enableTelemetry: config.enableTelemetry ?? false,
356
- };
357
- // Smart sync options
358
- this.smartSyncOptions = {
359
- maxDeltasBeforeBootstrap: 1000,
360
- maxBootstrapSize: 10 * 1024 * 1024,
361
- batchingDelay: 100,
362
- maxBatchSize: 50,
363
- };
364
- // Create internal helpers
365
- this.queryProcessor = new QueryProcessor({
366
- enableCache: this.config.enableCache,
367
- });
368
- // Auto-invalidate query cache when SyncClient modifies the pool.
369
- // Replaces all manual queryProcessor.invalidateCache() calls.
370
- this.syncClient.on('models:changed', (modelNames) => {
371
- for (const name of modelNames) {
372
- this.queryProcessor.invalidateCache(`.*${name}.*`);
373
- }
374
- });
375
- // Make the sync-status fields observable so consumer code can do
376
- // reaction(() => store.isReady, ...)
377
- // observer(() => store.isOffline)
378
- // and actually receive notifications. Without these annotations,
379
- // `syncStatus` and `dataReady` are plain properties, and the derived
380
- // getters (isReady, isSyncing, isOffline, and the rest) never emit
381
- // change signals — so a `reaction` on `store.isReady` would never fire.
382
- makeObservable(this, {
383
- syncStatus: observable,
384
- dataReady: observable,
385
- isReady: computed,
386
- isSyncing: computed,
387
- isOffline: computed,
388
- isReconnecting: computed,
389
- isError: computed,
390
- hasUnsyncedChanges: computed,
391
- });
392
- }
393
- // ── Protected extension points ────────────────────────────────────────────
394
- /**
395
- * Register foreign-key indexes for constant-time lookups.
396
- *
397
- * This is an override hook. The preferred way to declare a foreign-key
398
- * index is `config.foreignKeyIndexes` at construction time, or marking the
399
- * `belongsTo` relation with `{ index: true }` in the schema. The hook fires
400
- * after the schema-derived and config registrations, so a subclass can
401
- * layer additional indexes on top.
402
- */
403
- registerForeignKeys() { }
404
- /**
405
- * Enrich delta data with related models from the InstanceCache.
406
- *
407
- * Base implementation walks `this.enrichmentPlan` — entries populated
408
- * from the schema's `{ enrich: true }` relations and from
409
- * `config.enrichmentPlan`. Subclasses can still override for bespoke
410
- * logic, calling `super.enrichRelations(modelName, data)` first to
411
- * apply the declarative plan before layering on custom work.
412
- *
413
- * Enrichment is best-effort: if the parent isn't yet in the pool
414
- * (e.g., a child delta arrives before its parent in a bootstrap
415
- * batch), the entry is silently skipped and the data passes through
416
- * untouched. The next delta for the same child will re-enrich.
417
- */
418
- enrichRelations(modelName, data) {
419
- for (const entry of this.enrichmentPlan) {
420
- if (entry.modelName !== modelName)
421
- continue;
422
- const fkValue = data[entry.foreignKey];
423
- if (typeof fkValue !== 'string')
424
- continue;
425
- const parent = this.objectPool.get(fkValue);
426
- if (parent) {
427
- data[entry.relationKey] = parent;
428
- }
429
- }
430
- return data;
431
- }
432
- /** Check if a model name represents a custom/dynamic entity type. */
433
- isCustomEntity(modelName) {
434
- return !this.objectPool.registry.getModelByName(modelName);
435
- }
436
- /** Create a custom entity instance from delta data. Override for domain-specific custom entities. */
437
- createCustomEntity(_modelName, _modelId, _data) {
438
- return null;
439
- }
440
- /** Called before save for domain-specific validation/self-healing. */
441
- beforeSave(_model) { }
442
- /** Connection lifecycle event callback — set by subclass to wire connection state machine. */
443
- onConnectionEvent;
444
- /**
445
- * Internal connection FSM. Owns network probe + backoff + reconnect
446
- * orchestration for the default path. Constructed lazily once we
447
- * have a user context + a WebSocket (see `wireWebSocketEvents`);
448
- * driven by the `onConnectionEvent` hook AND browser online/offline
449
- * events it sets up itself.
450
- *
451
- * Every consumer gets production-grade offline-to-online recovery
452
- * out of the box. Subclasses that want their own lifecycle owner
453
- * can disable this by overriding `createConnectionManager()` to
454
- * return null.
455
- */
456
- connectionManager = null;
457
- /**
458
- * Access-credential re-mint + proactive pre-roll — extracted to
459
- * sync/credentialLifecycle.ts. Owns the refresher hook, the single-flight
460
- * guard, and the browser-only refresh timer / wake listener; talks back
461
- * through three lazily-resolved callbacks (the ConnectionManager doesn't
462
- * exist until `setupWebSocketSync`). The `setCredentialRefresher` /
463
- * `performCredentialRefresh` / `startCredentialLifecycle` methods below
464
- * are thin delegates so the store's public surface is unchanged.
465
- */
466
- credentialLifecycle = new CredentialLifecycle({
467
- setAuthToken: (token) => { this.auth?.setAuthToken(token); },
468
- nudgeReconnect: () => { this.nudgeReconnect(); },
469
- reportSessionExpired: () => {
470
- this.connectionManager?.send({ type: 'BOOTSTRAP_FAILED_SESSION' });
471
- },
472
- }, contextLogger);
473
- /**
474
- * Listeners registered via `subscribeSessionError()`. Fired when the
475
- * WebSocket closes with a session-invalid code (1008/4001/4003) or a
476
- * session-error event is received. Separate from `onConnectionEvent`
477
- * (which exists for the ConnectionStore FSM) so multiple consumers —
478
- * typically `<AbloProvider>` and a connection-lifecycle owner — can
479
- * both react without racing on the single-callback slot.
480
- */
481
- sessionErrorListeners = new Set();
482
- /**
483
- * Subscribe to session-error events. The returned function removes
484
- * the listener. Safe to call multiple times from different consumers
485
- * (each gets its own slot in the listener set).
486
- */
487
- subscribeSessionError(listener) {
488
- this.sessionErrorListeners.add(listener);
489
- return () => { this.sessionErrorListeners.delete(listener); };
490
- }
491
- /**
492
- * Subscribe to per-mutation failure payloads. Forwarded from the
493
- * underlying `SyncClient.mutationQueue` so consumers (toast layer,
494
- * route-level reverted boundaries, telemetry) can react without
495
- * reaching across the store. Returns an unsubscribe function.
496
- *
497
- * Why this lives on the base store rather than SyncClient: the React
498
- * `<AbloProvider>` binds against this surface, so adding it here
499
- * keeps the engine's internal wiring private while still giving the
500
- * SDK a single hook to expose. Mirrors `subscribeSessionError` —
501
- * same shape, same lifecycle.
502
- */
503
- subscribeMutationFailure(listener) {
504
- return this.syncClient.onMutationFailure(listener);
505
- }
506
- /**
507
- * Subscribe to commit round-trip latency. Forwarded from the underlying
508
- * `SyncClient` for the same reason as `subscribeMutationFailure` — the
509
- * React provider binds against this surface, so the engine's wiring stays
510
- * private while the SDK keeps one hook to expose.
511
- */
512
- subscribeCommitLatency(listener) {
513
- return this.syncClient.onCommitLatency(listener);
514
- }
515
- /**
516
- * Wait for the in-flight transaction for (modelName, modelId) to be
517
- * confirmed by the server. See `SyncClient.waitForConfirmation` for the
518
- * lookup contract; resolves immediately if nothing is in flight.
519
- */
520
- waitForConfirmation(modelName, modelId) {
521
- return this.syncClient.waitForConfirmation(modelName, modelId);
522
- }
523
- /**
524
- * Observe the LOCAL mutation stream for undo recording (see
525
- * {@link import('./storeContract.js').LocalMutation}). Taps the
526
- * MutationQueue's `transaction:created` event — fired once per local
527
- * create/update/delete/archive with `previousData` already captured.
528
- * Remote/collaborator deltas apply via `applyDeltaBatchToPool` and never
529
- * emit here, so undo is naturally local-only (you can't undo a teammate).
530
- */
531
- subscribeLocalMutations(handler) {
532
- // Tap the MutationQueue directly via `onLocalTransaction`. The previous
533
- // `syncClient.subscribe('transaction:created', …)` route registered the
534
- // handler on SyncClient's OWN emitter, which never fires that event (only
535
- // the queue's emitter does) — so undo recorded nothing. See
536
- // `SyncClient.onLocalTransaction` for the full rationale.
537
- return this.syncClient.onLocalTransaction((tx) => {
538
- if (!tx.modelName || !tx.modelId)
539
- return;
540
- handler({
541
- type: tx.type,
542
- modelName: tx.modelName,
543
- modelId: tx.modelId,
544
- data: tx.data ?? null,
545
- previousData: tx.previousData ?? null,
546
- });
547
- });
548
- }
549
- // ── Bootstrap + Retry ────────────────────────────────────────────────────
550
- /**
551
- * Execute a bootstrap function with timeout protection and automatic retry.
552
- * Prevents the common issue where bootstrap hangs on startup.
553
- */
554
- async executeBootstrapWithTimeout(bootstrapFn, _context, signal) {
555
- let lastError = null;
556
- // An aborted initialize has to stop the transfer, not just stop waiting for
557
- // it. Without this the caller returns while a cold start keeps downloading,
558
- // and those chunks are still in flight when the next initialize begins.
559
- const onCallerAbort = () => { this.database.helper.abort(); };
560
- signal?.addEventListener('abort', onCallerAbort, { once: true });
561
- try {
562
- for (let attempt = 1; attempt <= BOOTSTRAP_CONFIG.MAX_RETRY_ATTEMPTS; attempt++) {
563
- if (signal?.aborted) {
564
- throw new DOMException('Initialization aborted', 'AbortError');
565
- }
566
- // `navigator.onLine === false` is the MDN-reliable "definitely
567
- // offline" signal. Don't use `!navigator.onLine`: Node 22+ exposes
568
- // `globalThis.navigator` with `onLine === undefined`, so the
569
- // negation false-positives every server-side bootstrap (e.g. the
570
- // server-side agent.run dispatch path through `connectAgent`).
571
- if (typeof navigator !== 'undefined' && navigator.onLine === false) {
572
- this.runtime.observability.breadcrumb(`Bootstrap attempt ${attempt} skipped - offline`, 'sync.bootstrap', 'warning');
573
- throw new AbloConnectionError('Bootstrap skipped - device is offline', {
574
- code: 'bootstrap_offline',
575
- });
576
- }
577
- try {
578
- this.runtime.logger.info(`[BaseSyncedStore] Bootstrap attempt ${attempt}/${BOOTSTRAP_CONFIG.MAX_RETRY_ATTEMPTS}`);
579
- const result = (await Promise.race([
580
- bootstrapFn(),
581
- this.createBootstrapTimeout(attempt),
582
- ]));
583
- this.runtime.logger.info('[BaseSyncedStore] Bootstrap completed successfully', { attempt });
584
- return result;
585
- }
586
- catch (error) {
587
- lastError = error;
588
- const isTimeout = error instanceof Error && error.message.includes('timed out');
589
- const isAbort = error instanceof DOMException && error.name === 'AbortError';
590
- const isNetworkError = error instanceof TypeError && error.message.includes('fetch');
591
- if (isAbort)
592
- throw error;
593
- if (AbloSessionError.isSessionError(error))
594
- throw error;
595
- if (isNetworkError && typeof navigator !== 'undefined' && navigator.onLine === false) {
596
- this.runtime.observability.captureBootstrapFailure(error, { type: 'network-offline' });
597
- throw error;
598
- }
599
- this.runtime.observability.breadcrumb(`Bootstrap attempt ${attempt} failed`, 'sync.bootstrap', 'warning', { isTimeout, isNetworkError, willRetry: attempt < BOOTSTRAP_CONFIG.MAX_RETRY_ATTEMPTS });
600
- if (isTimeout && attempt < BOOTSTRAP_CONFIG.MAX_RETRY_ATTEMPTS) {
601
- this.runtime.logger.info('[BaseSyncedStore] Resetting state before bootstrap retry');
602
- this.resetBootstrapState();
603
- await new Promise((resolve) => setTimeout(resolve, BOOTSTRAP_CONFIG.RETRY_DELAY_MS));
604
- }
605
- else if (!isTimeout && attempt < BOOTSTRAP_CONFIG.MAX_RETRY_ATTEMPTS) {
606
- await new Promise((resolve) => setTimeout(resolve, 1000));
607
- }
608
- }
609
- finally {
610
- // Disarm this attempt's deadline the moment it settles — a live timer
611
- // would abort whatever the next attempt puts in flight.
612
- this.clearBootstrapDeadline();
613
- }
614
- }
615
- throw lastError
616
- ? toAbloError(lastError)
617
- : new AbloConnectionError('Bootstrap failed after all retry attempts', {
618
- code: 'bootstrap_fetch_timeout',
619
- });
620
- }
621
- finally {
622
- signal?.removeEventListener('abort', onCallerAbort);
623
- this.clearBootstrapDeadline();
624
- }
625
- }
626
- /**
627
- * The outer deadline for one bootstrap attempt.
628
- *
629
- * The length is DERIVED from the fetcher's own watchdog budget, not chosen. A
630
- * chosen number is what broke this: the previous fixed 15s was shorter than a
631
- * single model chunk's allowance — 20s waiting for response headers plus 15s
632
- * of stall grace — so on any workspace with one slow model the deadline fired
633
- * before the watchdogs it was meant to backstop, and every attempt timed out
634
- * by construction. The watchdogs below are progress-based and already
635
- * guarantee termination; this deadline exists only for a hang somewhere other
636
- * than the network, so it must sit above them, and it can only do that
637
- * reliably by asking them how long they take.
638
- *
639
- * Reaching it aborts the work in flight. `Promise.race` merely stops waiting:
640
- * without the abort the losing bootstrap keeps running, keeps its sockets, and
641
- * races the retry that replaced it — which is how one page load turned into
642
- * dozens of overlapping requests.
643
- */
644
- createBootstrapTimeout(attempt) {
645
- const timeoutMs = this.database.helper.budgetMs;
646
- return new Promise((_, reject) => {
647
- this.clearBootstrapDeadline();
648
- this.bootstrapDeadlineTimer = setTimeout(() => {
649
- this.database.helper.abort();
650
- reject(new AbloConnectionError(`Bootstrap timed out after ${timeoutMs}ms (attempt ${attempt})`, { code: 'bootstrap_fetch_timeout' }));
651
- }, timeoutMs);
652
- });
653
- }
654
- /** Disarm the deadline once its attempt has settled. Load-bearing now that
655
- * firing it aborts real work: a leftover timer would cancel a later,
656
- * unrelated bootstrap. */
657
- clearBootstrapDeadline() {
658
- if (this.bootstrapDeadlineTimer !== null) {
659
- clearTimeout(this.bootstrapDeadlineTimer);
660
- this.bootstrapDeadlineTimer = null;
661
- }
662
- }
663
- /** Reset bootstrap-related state for a clean retry */
664
- resetBootstrapState() {
665
- try {
666
- this.objectPool.clear({ preserveObserved: true });
667
- this.queryProcessor.clearCache();
668
- runInAction(() => { this.dataReady = false; });
669
- this.modelTypesHydrated.clear();
670
- this.modelTypeHydrationInFlight.clear();
671
- // The pool is being wiped + re-bootstrapped, so the scoped-hydrate ledger
672
- // is stale — clear it so re-entered groups backfill again.
673
- this.hydratedGroups.clear();
674
- this.hydratingGroups.clear();
675
- this.runtime.logger.info('[BaseSyncedStore] Bootstrap state reset complete');
676
- }
677
- catch {
678
- this.runtime.observability.breadcrumb('Error resetting bootstrap state', 'sync.bootstrap', 'warning');
679
- }
680
- }
681
- // ── Reconnection ─────────────────────────────────────────────────────────
682
- /** Perform reconnect: bootstrap + WS reconnect. Returns outcome for state machine. */
683
- async performReconnect() {
684
- if (!this.userContext)
685
- return 'network_error';
686
- try {
687
- await this.checkSyncGroupShrinkage();
688
- const requirements = await this.database.requiredBootstrap();
689
- if (requirements.type === 'full' || requirements.lastSyncId === 0) {
690
- this.updateSyncStatus({ state: 'syncing', progress: 0 });
691
- const bootstrapResult = await this.database.bootstrapFromServer(requirements, this.resolveSyncGroups(this.userContext));
692
- this.applyBootstrapToPool(bootstrapResult);
693
- this.dataReady = true;
694
- }
695
- else if (!this.dataReady) {
696
- await this.syncClient.hydrateFromDatabase();
697
- this.dataReady = true;
698
- }
699
- if (!this.syncWebSocket.isConnected()) {
700
- this.syncWebSocket.resetReconnectAttempts();
701
- this.syncWebSocket.connect();
702
- }
703
- this.updateSyncStatus({ state: 'idle', progress: 100 });
704
- return 'success';
705
- }
706
- catch (error) {
707
- this.runtime.observability.captureBootstrapFailure(error, { type: 'connection-store-reconnect' });
708
- if (AbloSessionError.isSessionError(error)) {
709
- this.syncWebSocket.setSessionErrorDetected();
710
- this.syncWebSocket.disconnect();
711
- this.updateSyncStatus({ state: 'error', error: error });
712
- // SECURITY: Clear locally cached data when session is invalid
713
- this.database.clear({ includeWriteJournal: true }).catch(() => { });
714
- this.objectPool.clear();
715
- return 'session_error';
716
- }
717
- if (!this.dataReady && this.objectPool.size === 0) {
718
- try {
719
- await this.syncClient.hydrateFromDatabase();
720
- // Re-read through a local: the guard above narrowed `size` to 0, and
721
- // the compiler carries that narrowing across the await even though
722
- // hydrating is precisely what fills the pool.
723
- const hydratedSize = this.objectPool.size;
724
- if (hydratedSize > 0) {
725
- this.dataReady = true;
726
- this.runtime.logger.info('[BaseSyncedStore] Hydrated from local fallback', {
727
- objectPoolSize: hydratedSize,
728
- });
729
- }
730
- }
731
- catch (fallbackError) {
732
- this.runtime.logger.debug('[BaseSyncedStore] Local fallback failed', {
733
- error: fallbackError.message,
734
- });
735
- }
736
- }
737
- return 'network_error';
738
- }
739
- }
740
- /**
741
- * Register the access-credential re-mint hook. Called by the React provider
742
- * with a thunk that mints a fresh `ek_`/`rk_` (typically its `getToken`).
743
- * See {@link CredentialLifecycle.setRefresher}.
744
- */
745
- setCredentialRefresher(refresher) {
746
- this.credentialLifecycle.setRefresher(refresher);
747
- }
748
- /**
749
- * Re-mint the short-lived access credential and push it into the credential
750
- * source, reporting a tri-state outcome the {@link ConnectionManager} maps to
751
- * its FSM. Single-flight; no refresher wired ⇒ `'refreshed'` (a no-op
752
- * re-probe). Full contract on {@link CredentialLifecycle.refresh}.
753
- */
754
- async performCredentialRefresh() {
755
- return this.credentialLifecycle.refresh();
756
- }
757
- /**
758
- * The authentication-recovery path for HTTP transports, such as the lazy
759
- * query lane. It runs a single-flight credential re-mint driven by the
760
- * rejection's recovery class, routing outcomes through the same state
761
- * machine the WebSocket probe uses. `'retry'` means a fresh credential is
762
- * now in the credential source and the request should be replayed once.
763
- * Full contract on {@link CredentialLifecycle.recoverFromAuthRejection}.
764
- */
765
- async recoverFromAuthRejection(recovery) {
766
- return this.credentialLifecycle.recoverFromAuthRejection(recovery);
767
- }
768
- /**
769
- * Nudge the connection FSM to re-probe with the current credential. Idempotent
770
- * and safe in any state (ignored while `connected`). Call after pushing a
771
- * freshly-minted token via `setAuthToken`, or on an OS-wake signal, so a
772
- * connection parked in `offline` / `backoff` / `auth_blocked` picks the new
773
- * credential up immediately instead of waiting for the 30s watchdog.
774
- */
775
- nudgeReconnect() {
776
- this.connectionManager?.send({ type: 'CREDENTIAL_REFRESHED' });
777
- }
778
- /**
779
- * Install the client-owned access-credential lifecycle: register `getToken`
780
- * as the reactive re-mint hook and arm the browser-only proactive refresh
781
- * (a refresh timer plus an OS-wake re-mint). Idempotent — a second call
782
- * replaces the first — and torn down on {@link disconnect}. Full rationale
783
- * on {@link CredentialLifecycle.start}.
784
- */
785
- startCredentialLifecycle(getToken, opts) {
786
- this.credentialLifecycle.start(getToken, opts);
787
- }
788
- /** Tear down the proactive credential lifecycle (idempotent). */
789
- stopCredentialLifecycle() {
790
- this.credentialLifecycle.stop();
791
- }
792
- // ── Sync group management ────────────────────────────────────────────────
793
- //
794
- // The implementation lives in the sync/groupChange module. The methods
795
- // below are thin protected delegates that keep their signatures, so
796
- // subclass override points still work; the module routes cross-handler
797
- // calls back through `groupChangeContext()` to preserve dynamic dispatch.
798
- /** Narrow context the group-change leaf talks back through. */
799
- groupChangeContext() {
800
- return {
801
- runtime: this.runtime,
802
- database: this.database,
803
- objectPool: this.objectPool,
804
- getSubscribedSyncGroups: () => this.syncWebSocket.getSyncGroups(),
805
- getCurrentSyncGroups: () => this.userContext ? this.resolveSyncGroups(this.userContext) : null,
806
- getBootstrapMode: () => this.userContext?.bootstrapMode,
807
- disconnectWebSocket: () => { this.syncWebSocket.disconnect(); },
808
- emitConnectionEvent: (event) => { this.onConnectionEvent?.(event); },
809
- handleGroupAdded: (payload, syncId) => this.handleGroupAdded(payload, syncId),
810
- computeUpdatedSyncGroups: (payload) => this.computeUpdatedSyncGroups(payload),
811
- forceFullRebootstrap: () => { this.forceFullRebootstrap(); },
812
- };
813
- }
814
- /**
815
- * Handle an actionType 'G' delta — incremental `{ group, userId }` or
816
- * legacy `{ addedGroups, removedGroups }` payloads. Full pathway doc on
817
- * {@link groupChange.handleSyncGroupChange}.
818
- */
819
- async handleSyncGroupChange(delta) {
820
- return groupChange.handleSyncGroupChange(this.groupChangeContext(), delta);
821
- }
822
- /**
823
- * Handle an incremental GroupAdded delta — metadata only, no re-bootstrap
824
- * (covering deltas bring the entities). See {@link groupChange.handleGroupAdded}.
825
- */
826
- async handleGroupAdded(payload, syncId) {
827
- return groupChange.handleGroupAdded(this.groupChangeContext(), payload, syncId);
828
- }
829
- /**
830
- * Handle an actionType 'S' (GroupRemoved) delta: for safety, clear the
831
- * revoked local state and trigger a full re-bootstrap. See
832
- * {@link groupChange.handleGroupRemoved}.
833
- */
834
- async handleGroupRemoved(delta) {
835
- return groupChange.handleGroupRemoved(this.groupChangeContext(), delta);
836
- }
837
- /** Compute new sync groups after applying additions and removals */
838
- computeUpdatedSyncGroups(payload) {
839
- return groupChange.computeUpdatedSyncGroups(this.groupChangeContext(), payload);
840
- }
841
- /** Force a full re-bootstrap via connection lifecycle event (no-op for
842
- * `bootstrapMode: 'none'` participants — see {@link groupChange.forceFullRebootstrap}). */
843
- forceFullRebootstrap() {
844
- groupChange.forceFullRebootstrap(this.groupChangeContext());
845
- }
846
- /**
847
- * Single source of truth for the sync-group list this session is
848
- * subscribed to. Server-issued (`context.syncGroups`) is authoritative.
849
- * When absent, the SDK subscribes to no explicit groups. Both
850
- * `checkSyncGroupShrinkage` and `setupWebSocketSync` resolve through
851
- * here so the WS subscription and the security-critical shrinkage
852
- * check can never disagree.
853
- */
854
- resolveSyncGroups(context) {
855
- return groupChange.resolveSyncGroups(context);
856
- }
857
- /** Check if sync groups shrank since last session — force full bootstrap if so */
858
- async checkSyncGroupShrinkage() {
859
- return groupChange.checkSyncGroupShrinkage(this.groupChangeContext());
860
- }
861
- // ── Bootstrap apply ──────────────────────────────────────────────────────
862
- //
863
- // The implementation lives in the sync/bootstrapApply module. The protected
864
- // delegates below keep their signatures and subclass overridability; the
865
- // module talks back through `poolContext()`, with enrichment pre-bound to
866
- // `this.enrichRelations` so that override point still applies.
867
- /** Narrow context the bootstrap-apply leaf talks back through. */
868
- poolContext() {
869
- const store = this;
870
- return {
871
- runtime: this.runtime,
872
- applyDeltaBatchToPool: (results) => {
873
- this.syncClient.applyDeltaBatchToPool(results, (name, data) => this.enrichRelations(name, data));
874
- },
875
- applyBootstrapDataToPool: (bootstrapData, protectedIds) => this.syncClient.applyBootstrapDataToPool(bootstrapData, protectedIds),
876
- getPoolSize: () => this.objectPool.size,
877
- getAllPoolIds: () => this.objectPool.getAllIds(),
878
- get bootstrapDeltaQueue() { return store.bootstrapDeltaQueue; },
879
- set bootstrapDeltaQueue(queue) { store.bootstrapDeltaQueue = queue; },
880
- applyDeltaFrame: (deltas) => { this.applyDeltaFrame(deltas); },
881
- };
882
- }
883
- /** Apply bootstrap data to the {@link InstanceCache}, removing entities that are no longer present (ghost removal). Pool writes are delegated to {@link SyncClient}. */
884
- applyBootstrapToPool(bootstrapResult, protectedIds) {
885
- return bootstrapApply.applyBootstrapToPool(this.poolContext(), bootstrapResult, protectedIds);
886
- }
887
- // ── Initialize + Lifecycle ───────────────────────────────────────────────
888
- /**
889
- * Initialize the sync engine with user context.
890
- * Offline-first: hydrate from IDB → show UI → bootstrap from server in background.
891
- */
892
- *initialize(context, signal) {
893
- if (this.initialized)
894
- return { success: true };
895
- this.userContext = context;
896
- try {
897
- this.updateSyncStatus({ state: 'syncing', progress: 0 });
898
- // The commit outbox and offline mutation journal live in IndexedDB.
899
- // Open it before SyncClient restores either one; reading first used to
900
- // make persistence silently look empty on every cold start.
901
- yield this.database.open(context.userId, context.organizationId);
902
- // Propagate identity only after storage is ready, then restore sealed
903
- // requests before accepting fresh mutations.
904
- yield this.syncClient.initialize(context.userId, context.organizationId);
905
- // Hydrate from IndexedDB (fast, cached data)
906
- let hasLocalData = false;
907
- try {
908
- yield this.syncClient.hydrateFromDatabase();
909
- hasLocalData = this.objectPool.size > 0;
910
- }
911
- catch (hydrateError) {
912
- this.runtime.logger.debug('[sync-engine] IDB hydration failed', { error: hydrateError });
913
- this.runtime.observability.captureBootstrapFailure(hydrateError, { type: 'hydration-from-idb' });
914
- }
915
- // Get sync baseline for WebSocket
916
- const lastSyncId = (yield this.database.getLastSyncId());
917
- this.syncClient.position.advancePersisted(lastSyncId || 0);
918
- // If local data available, show UI immediately
919
- if (hasLocalData) {
920
- this.dataReady = true;
921
- this.initialized = true;
922
- this.updateSyncStatus({ state: 'syncing', progress: 50 });
923
- }
924
- // Setup WebSocket
925
- this.setupWebSocketSync(context, lastSyncId);
926
- // Bootstrap from server if needed.
927
- //
928
- // `bootstrapMode: 'none'` participants (agent-worker, headless
929
- // task runners) skip baseline replication — they read via
930
- // `model.retrieve()` round-trips and rely on covering deltas
931
- // from filtered subscriptions to populate the pool lazily. The
932
- // WS is already open by `setupWebSocketSync` above, so live
933
- // delta flow works regardless of this branch.
934
- const requirements = (yield this.database.requiredBootstrap());
935
- if (context.bootstrapMode === 'none') {
936
- this.runtime.logger.info('[BaseSyncedStore] Bootstrap skipped (bootstrapMode=none)', { kind: context.kind ?? 'user' });
937
- // `setupWebSocketSync` above creates the SyncWebSocket and
938
- // initiates the upgrade, but it does NOT await the 'connected'
939
- // event — it returns synchronously after wiring listeners.
940
- // For bootstrapMode='none' consumers (agent-worker, headless
941
- // task runners), this branch is the entire body of initialize()
942
- // after the WS is set up, so `ready()` would otherwise resolve
943
- // while the WS is still in 'connecting' state. The very next
944
- // `commits.create` then throws "SyncWebSocket not connected".
945
- //
946
- // For bootstrapMode='full' consumers we don't need this await:
947
- // `executeBootstrapWithTimeout` below sends the bootstrap RPC
948
- // which inherently requires the WS to be open, so it surfaces
949
- // a connection error if the upgrade hasn't completed.
950
- //
951
- // 5s bound is generous (typical connect is <100ms); past that
952
- // we return anyway and let the next commit attempt fail loudly
953
- // rather than block initialize() forever.
954
- yield this.waitForWebSocketConnected(5000);
955
- }
956
- else if (requirements.type !== 'local') {
957
- if (hasLocalData) {
958
- // Background bootstrap — don't block UI. The method captures its own
959
- // operational failures; this backstop covers escapes from the
960
- // delta-queue replay in withDeltaQueuing's finally (and the error
961
- // handler itself), which would otherwise vanish unhandled.
962
- void this.performBackgroundBootstrap(requirements, context, signal).catch((error) => {
963
- this.runtime.observability.captureBootstrapFailure(error, {
964
- type: 'background-orchestration',
965
- });
966
- });
967
- }
968
- else {
969
- // First load — must wait for server data
970
- yield this.executeBootstrapWithTimeout(async () => {
971
- await this.database.bootstrapFromServer(requirements, this.resolveSyncGroups(context));
972
- }, context, signal);
973
- yield this.syncClient.hydrateFromDatabase();
974
- this.dataReady = true;
975
- this.initialized = true;
976
- }
977
- }
978
- if (!this.initialized)
979
- this.initialized = true;
980
- if (!this.dataReady) {
981
- this.dataReady = true;
982
- }
983
- this.updateSyncStatus({ state: 'idle', progress: 100 });
984
- return { success: true };
985
- }
986
- catch (error) {
987
- const isAbort = error instanceof DOMException && error.name === 'AbortError';
988
- if (isAbort) {
989
- this.dataReady = false;
990
- this.initialized = false;
991
- this.updateSyncStatus({ state: 'idle', progress: 0 });
992
- return { success: false, error: error };
993
- }
994
- const isSession = AbloSessionError.isSessionError(error);
995
- this.runtime.observability.captureBootstrapFailure(error, { type: 'initialize' });
996
- if (isSession) {
997
- this.syncWebSocket.setSessionErrorDetected();
998
- this.syncWebSocket.disconnect();
999
- this.updateSyncStatus({ state: 'error', error: error });
1000
- return { success: false, error: error };
1001
- }
1002
- // Fallback: show local data if available
1003
- if (this.objectPool.size === 0) {
1004
- try {
1005
- yield this.syncClient.hydrateFromDatabase();
1006
- }
1007
- catch { }
1008
- }
1009
- if (this.objectPool.size > 0) {
1010
- this.dataReady = true;
1011
- this.initialized = true;
1012
- this.updateSyncStatus(this.syncWebSocket.isConnected()
1013
- ? { state: 'idle', progress: 100 }
1014
- : { state: 'offline', offlineSince: new Date() });
1015
- return { success: true };
1016
- }
1017
- this.updateSyncStatus({ state: 'error', error: error });
1018
- return { success: false, error: error };
1019
- }
1020
- }
1021
- /** Background bootstrap — non-blocking, user sees cached data while this runs */
1022
- async performBackgroundBootstrap(requirements, context, signal) {
1023
- await this.withDeltaQueuing(async () => {
1024
- try {
1025
- const preBootstrapIds = new Set(this.objectPool.getAllIds());
1026
- const bootstrapResult = await this.database.bootstrapFromServer(requirements, this.resolveSyncGroups(context));
1027
- const deltaProtectedIds = this.collectDeltaProtectedIds(preBootstrapIds);
1028
- this.applyBootstrapToPool(bootstrapResult, deltaProtectedIds);
1029
- this.updateSyncStatus({ state: 'idle', progress: 100 });
1030
- }
1031
- catch (error) {
1032
- this.runtime.logger.debug('[sync-engine] Background bootstrap failed', {
1033
- error: error instanceof Error ? error.message : String(error),
1034
- cause: error,
1035
- });
1036
- this.runtime.observability.captureBootstrapFailure(error, { type: 'background' });
1037
- if (AbloSessionError.isSessionError(error)) {
1038
- this.syncWebSocket.setSessionErrorDetected();
1039
- this.syncWebSocket.disconnect();
1040
- this.updateSyncStatus({ state: 'error', error: error });
1041
- }
1042
- else if (!this.syncWebSocket.isConnected()) {
1043
- this.updateSyncStatus({ state: 'offline', offlineSince: new Date() });
1044
- }
1045
- }
1046
- });
1047
- }
1048
- /** Run bootstrap with delta queuing to prevent race conditions */
1049
- async withDeltaQueuing(fn) {
1050
- this.activeBootstrapCount++;
1051
- if (this.bootstrapDeltaQueue === null)
1052
- this.bootstrapDeltaQueue = [];
1053
- try {
1054
- return await fn();
1055
- }
1056
- finally {
1057
- this.activeBootstrapCount--;
1058
- if (this.activeBootstrapCount === 0)
1059
- this.replayQueuedDeltas();
1060
- }
1061
- }
1062
- /** Collect IDs that must survive ghost removal (added by deltas during bootstrap) */
1063
- collectDeltaProtectedIds(preBootstrapIds) {
1064
- return bootstrapApply.collectDeltaProtectedIds(this.poolContext(), preBootstrapIds);
1065
- }
1066
- /** Replay deltas queued during bootstrap (atomically, via `applyDeltaFrame`). */
1067
- replayQueuedDeltas() {
1068
- bootstrapApply.replayQueuedDeltas(this.poolContext());
1069
- }
1070
- /**
1071
- * Factory for the internal `ConnectionManager`. Override to return
1072
- * `null` in subclasses that own their own connection lifecycle
1073
- * (tests, headless runners, custom FSM wrappers). Default builds a
1074
- * manager scoped to `_syncServerUrl` with production backoff.
1075
- *
1076
- * **Agent participants get `null`.** The FSM is wired around browser
1077
- * events (`visibilitychange`, `online`/`offline`, watchdog) which are
1078
- * meaningful for human-facing tabs and meaningless for headless agent
1079
- * processes. On agent hosts the FSM has no event source to drive
1080
- * recovery — and worse, its `offline` entry action calls
1081
- * `syncWebSocket.disconnect()` which sets `isManualClose=true` and
1082
- * cancels the reconnect that `SyncWebSocket.onclose` had just
1083
- * scheduled. The two recovery systems fight and the browser-only one
1084
- * wins by destroying the Node-compatible one's work. Returning `null`
1085
- * for agents leaves `SyncWebSocket`'s exponential-backoff
1086
- * `scheduleReconnect()` as the sole recovery path — which is correct
1087
- * for server-side agents whether they run on Node, Bun, Deno, or
1088
- * inside a Docker container with no `window`.
1089
- *
1090
- * Why gate on `kind` and not `typeof window`: env detection by global
1091
- * existence is fragile (SSR polyfills, jsdom, sandboxed hosts). The
1092
- * participant kind is the actual semantic axis — "is this a human-
1093
- * driven session" vs "is this a server agent". The latter never has
1094
- * a tab to lose focus or a network adapter to wake up.
1095
- */
1096
- createConnectionManager(kind) {
1097
- if (kind === 'agent')
1098
- return null;
1099
- return new ConnectionManager({
1100
- baseUrl: this._syncServerUrl,
1101
- getAuthToken: () => this.auth?.getAuthToken() ?? this.syncWebSocket.getAuthToken() ?? null,
1102
- logger: contextLogger,
1103
- observability: contextSocketObservability,
1104
- });
1105
- }
1106
- /**
1107
- * Disconnect and clean up all resources. Terminal: this means "the client
1108
- * is finished", not "close and reopen later" — the connection object stays
1109
- * assigned but closed, the event wiring is torn down, and nothing
1110
- * re-initializes a disconnected store. (Mid-session closes during recovery
1111
- * go through the connection FSM's `onDisconnectWebSocket`, which closes
1112
- * the transport without touching the store.)
1113
- */
1114
- async disconnect() {
1115
- this.stopCredentialLifecycle();
1116
- if (this.batchTimer) {
1117
- clearTimeout(this.batchTimer);
1118
- this.batchTimer = null;
1119
- }
1120
- this.pendingDeltas = [];
1121
- for (const dispose of this.disposers)
1122
- dispose();
1123
- this.disposers = [];
1124
- if (this.connectionManager) {
1125
- this.connectionManager.dispose();
1126
- this.connectionManager = null;
1127
- }
1128
- try {
1129
- const last = this.syncWebSocket.getLastSyncId();
1130
- if (last > 0)
1131
- await this.database.updateWorkspaceMetadata({ lastSyncId: last });
1132
- }
1133
- catch { }
1134
- this.syncWebSocket.disconnect();
1135
- this.syncClient.disconnect();
1136
- this.queryProcessor.clearCache();
1137
- // Stop the pool's GC interval — the one timer the pool arms itself.
1138
- // Without this a discarded store retains its whole pool via the interval
1139
- // closure (and a Node process without `unref` support can't exit).
1140
- this.objectPool.stopGC();
1141
- this.updateSyncStatus({ state: 'offline' });
1142
- }
1143
- /**
1144
- * Destroy every IndexedDB database owned by the sync engine.
1145
- *
1146
- * First disconnects (releases WebSocket + timers + in-memory caches),
1147
- * then walks `indexedDB.databases()` and deletes any database whose
1148
- * name starts with `ablo_` or `ablo-`. This covers:
1149
- * - `ablo_<hash>` workspace data DBs
1150
- * - `ablo_databases` meta registry
1151
- * - `ablo-sync` offline mutation queue
1152
- *
1153
- * Use case: session expiry (previous-user data must not persist on
1154
- * disk before the next sign-in races into a corrupted state) or
1155
- * explicit user-initiated logout.
1156
- *
1157
- * Best-effort: swallows individual delete errors. Some browsers do
1158
- * not support `indexedDB.databases()` — the method returns without
1159
- * deleting in that case, same behavior as the pre-SDK app code.
1160
- */
1161
- async purge() {
1162
- try {
1163
- await this.disconnect();
1164
- }
1165
- catch { }
1166
- if (typeof indexedDB === 'undefined' || typeof indexedDB.databases !== 'function') {
1167
- return;
1168
- }
1169
- try {
1170
- const dbs = await indexedDB.databases();
1171
- for (const db of dbs) {
1172
- if (!db.name)
1173
- continue;
1174
- if (db.name.startsWith('ablo_') || db.name.startsWith('ablo-')) {
1175
- try {
1176
- indexedDB.deleteDatabase(db.name);
1177
- }
1178
- catch { }
1179
- }
1180
- }
1181
- }
1182
- catch { }
1183
- }
1184
- // ── WebSocket Setup ───────────────────────────────────────────────────────
1185
- /**
1186
- * Create WebSocket connection and wire all event handlers.
1187
- * Handles: deltas, batches, presence, bootstrap_required, errors, reconnection.
1188
- */
1189
- /**
1190
- * Block until the WebSocket reports a `connected` event, or until
1191
- * `timeoutMs` elapses (returns false on timeout, true on connect).
1192
- * Used by `initialize()` for `bootstrapMode: 'none'` consumers to
1193
- * honor `ready()`'s "WS is connected when this resolves" contract
1194
- * — `setupWebSocketSync` is fire-and-forget on the upgrade, and
1195
- * without an explicit wait the next mutation can race the open.
1196
- *
1197
- * Resolves immediately if the WS is already connected (e.g., warm
1198
- * reconnect after redeploy). Resolves false on timeout rather than
1199
- * throwing so initialize() can complete and let the caller's first
1200
- * mutation attempt surface a clearer error.
1201
- */
1202
- async waitForWebSocketConnected(timeoutMs) {
1203
- const ws = this.syncWebSocket;
1204
- if (ws.isConnected())
1205
- return true;
1206
- return new Promise((resolve) => {
1207
- let resolved = false;
1208
- const unsubscribe = ws.subscribe('connected', () => {
1209
- if (resolved)
1210
- return;
1211
- resolved = true;
1212
- unsubscribe();
1213
- clearTimeout(timer);
1214
- resolve(true);
1215
- });
1216
- const timer = setTimeout(() => {
1217
- if (resolved)
1218
- return;
1219
- resolved = true;
1220
- unsubscribe();
1221
- this.runtime.logger.debug(`[BaseSyncedStore] waitForWebSocketConnected timed out after ${timeoutMs}ms — initialize() will return but the next mutation may race the upgrade.`);
1222
- resolve(false);
1223
- }, timeoutMs);
1224
- });
1225
- }
1226
- /**
1227
- * Seed the connection's late values and open it. The socket itself exists
1228
- * from construction; what identity resolution supplies — the participant
1229
- * kind, the credential, the read scope, and the resume cursor — is seeded
1230
- * here, and only then is the held first connect released. A retried
1231
- * `initialize()` after a failed `ready()` re-runs this against the same
1232
- * connection object: the reconnect counter is reset for a clean slate,
1233
- * while the session-error latch deliberately survives (only the
1234
- * credential-expiry recovery clears it).
1235
- */
1236
- setupWebSocketSync(context, lastSyncId) {
1237
- if (!context.userId || !context.organizationId) {
1238
- this.runtime.observability.breadcrumb('Cannot setup WebSocket sync without user context', 'sync.websocket', 'warning');
1239
- return;
1240
- }
1241
- if (context.kind)
1242
- this.syncWebSocket.setKind(context.kind);
1243
- if (context.capabilityToken) {
1244
- this.syncWebSocket.setCapabilityToken(context.capabilityToken);
1245
- }
1246
- const syncGroups = this.resolveSyncGroups(context);
1247
- this.syncWebSocket.setSyncGroups(syncGroups);
1248
- this.syncWebSocket.setLastSyncId(lastSyncId || 0);
1249
- // The permanent base scopes for read interest — same set the connection
1250
- // subscribes to at upgrade, so the two can never disagree.
1251
- this.areaOfInterest.setBaseGroups(syncGroups);
1252
- // ── Connection FSM ────────────────────────────────────────────
1253
- // Instantiate + start the SDK's ConnectionManager so every consumer
1254
- // gets correct online/offline recovery. Guarded: a retried
1255
- // `initialize()` reuses the manager it already started.
1256
- if (!this.connectionManager)
1257
- this.startConnectionManager(context.kind);
1258
- this.syncWebSocket.resetReconnectAttempts();
1259
- this.syncWebSocket.allowConnect();
1260
- this.syncWebSocket.connect();
1261
- }
1262
- /**
1263
- * Wire the store's handlers onto the connection. Runs once, at
1264
- * construction — the connection object is stable for the store's
1265
- * lifetime, so the wiring is too.
1266
- */
1267
- wireSocketEvents() {
1268
- // Connection events → forward to connection lifecycle callback
1269
- const onConnected = this.syncWebSocket.subscribe('connected', () => {
1270
- this.syncClient.markConnected();
1271
- this.onConnectionEvent?.('WS_CONNECTED');
1272
- if (this.dataReady) {
1273
- this.updateSyncStatus({ state: 'idle', offlineSince: undefined });
1274
- }
1275
- else {
1276
- this.updateSyncStatus({ offlineSince: undefined });
1277
- }
1278
- // Re-assert read interest on every (re)connect. After a transient
1279
- // reconnect the socket re-sends its URL groups, but interest may have
1280
- // changed while offline; after a full reconnect the new socket's URL
1281
- // carries only base groups. `resync` re-pushes the current desired set
1282
- // so the server-side index matches what the user is actually viewing.
1283
- void this.areaOfInterest.resync();
1284
- });
1285
- const onDisconnected = this.syncWebSocket.subscribe('disconnected', () => {
1286
- this.syncClient.disconnect();
1287
- this.onConnectionEvent?.('WS_DISCONNECTED');
1288
- this.updateSyncStatus({ state: 'offline', offlineSince: new Date() });
1289
- });
1290
- const onReconnecting = this.syncWebSocket.subscribe('reconnecting', ({ attempt, delay }) => {
1291
- this.runtime.logger.info('[BaseSyncedStore] WebSocket reconnecting', { attempt, delay });
1292
- this.updateSyncStatus({ state: 'reconnecting' });
1293
- });
1294
- // Delta events → feed into processing pipeline
1295
- const onDelta = this.syncWebSocket.subscribe('delta', (delta) => {
1296
- this.processDeltaWithBatching(delta);
1297
- });
1298
- const onDeltaBatch = this.syncWebSocket.subscribe('delta_batch', (deltas) => {
1299
- // A catch-up/reconnect frame is already complete — apply it as ONE
1300
- // atomic flush so the gallery re-renders once, not once per 50-delta
1301
- // chunk. See `applyDeltaFrame`.
1302
- this.applyDeltaFrame(deltas);
1303
- });
1304
- // Bootstrap events
1305
- const onBootstrapRequired = this.syncWebSocket.subscribe('bootstrap_required', (hint) => { this.handleBootstrapRequired(hint); });
1306
- const onBootstrapData = this.syncWebSocket.subscribe('bootstrap_data', (data) => {
1307
- this.handleBootstrapData(data);
1308
- });
1309
- const onPresenceUpdate = this.syncWebSocket.subscribe('presence_update', (data) => {
1310
- this.handlePresenceUpdate(data);
1311
- });
1312
- // Error events
1313
- const onError = this.syncWebSocket.subscribe('error', (error) => {
1314
- if (error.message === 'Network is offline' || error.message === 'WebSocket connection failed') {
1315
- this.updateSyncStatus({ state: 'offline', offlineSince: new Date() });
1316
- }
1317
- else {
1318
- this.updateSyncStatus({ state: 'error', error });
1319
- }
1320
- });
1321
- // Terminal session loss (revocation / the login itself is gone): notify,
1322
- // route the FSM to its terminal state, and clear local data.
1323
- const handleTerminalSessionError = (error) => {
1324
- this.runtime.observability.captureWebSocketError({ context: 'session-error', error: error.message });
1325
- this.onConnectionEvent?.('WS_SESSION_ERROR');
1326
- for (const listener of this.sessionErrorListeners) {
1327
- try {
1328
- listener(error);
1329
- }
1330
- catch { }
1331
- }
1332
- this.updateSyncStatus({ state: 'error', error, isSessionError: true });
1333
- // SECURITY: Clear IndexedDB data on session expiry.
1334
- // When auth is revoked, locally cached data must not persist on disk.
1335
- this.database.clear({ includeWriteJournal: true }).catch((clearErr) => {
1336
- // consumer register: session ended, but cached data may remain on disk
1337
- this.runtime.logger.error('Your session ended, but some locally cached data could not be cleared from this device.');
1338
- this.runtime.logger.debug('[BaseSyncedStore] Failed to clear database on session error', clearErr);
1339
- });
1340
- this.objectPool.clear();
1341
- };
1342
- const onSessionError = this.syncWebSocket.subscribe('session_error', (error) => {
1343
- // WS analog of HTTP's `apikey_expired` (see AbloSessionError.
1344
- // isSessionErrorResponse): the hub's keepalive reaper closes sockets
1345
- // whose SHORT-LIVED access credential (`ek_`/`rk_`) passed its expiry
1346
- // with `4001 credential_expired`. That is re-mintable from the
1347
- // still-valid login — recover silently (un-latch, single-flight
1348
- // re-mint, reconnect) instead of signing out and clearing local data.
1349
- // Only a mint that answers `null` (the login itself is gone) falls
1350
- // through to the terminal path. Without this branch, every credential
1351
- // TTL elapse wedged the socket behind the write-once session latch.
1352
- if (AbloSessionError.isSessionError(error) && isAccessCredentialExpiryCloseReason(error.message)) {
1353
- this.runtime.observability.breadcrumb('WebSocket closed for expired access credential — re-minting', 'sync.websocket', 'warning');
1354
- // Un-latch BEFORE the async mint so the FSM's own recovery
1355
- // (probe → refreshing_credential → reconnect) is never blocked on
1356
- // our .then() ordering.
1357
- this.syncWebSocket.clearSessionError();
1358
- void this.performCredentialRefresh().then((outcome) => {
1359
- if (outcome === 'refreshed') {
1360
- if (this.connectionManager) {
1361
- // Kick a parked FSM; a concurrent probe joins the same
1362
- // single-flight mint, so this never double-mints.
1363
- this.nudgeReconnect();
1364
- }
1365
- else {
1366
- // Agent/system clients have no connection FSM
1367
- // (createConnectionManager returns null for kind 'agent') —
1368
- // reconnect the socket directly; connect() reads the
1369
- // freshly-minted credential from the credential source.
1370
- this.syncWebSocket.resetReconnectAttempts();
1371
- this.syncWebSocket.connect();
1372
- }
1373
- return;
1374
- }
1375
- if (outcome === 'session_error') {
1376
- // The mint endpoint rejected: the long-lived login is gone.
1377
- // Re-latch so writes reject with the permanent session type
1378
- // (see SyncWebSocket.notConnectedError) instead of parking.
1379
- this.syncWebSocket.setSessionErrorDetected();
1380
- handleTerminalSessionError(error);
1381
- }
1382
- // 'network_error' → transient mint failure. The WS_DISCONNECTED
1383
- // that follows this event already put the FSM on its probe/backoff
1384
- // loop, which retries through the same single-flight refresh.
1385
- });
1386
- return;
1387
- }
1388
- handleTerminalSessionError(error);
1389
- });
1390
- // Handshake failed: WS close before open. The HTTP status is hidden
1391
- // behind close code 1006, so we can't tell whether the server rejected
1392
- // auth (401/403) or the connection never reached the server (DNS/TLS/LB).
1393
- // Forward a dedicated event so the connection-lifecycle owner can run
1394
- // an authenticated HTTP probe to disambiguate.
1395
- const onHandshakeFailed = this.syncWebSocket.subscribe('handshake_failed', () => {
1396
- this.onConnectionEvent?.('WS_HANDSHAKE_FAILED');
1397
- this.updateSyncStatus({ state: 'offline', offlineSince: new Date() });
1398
- });
1399
- const onReconnectFailed = this.syncWebSocket.subscribe('reconnect_failed', ({ attempts }) => {
1400
- // consumer register: reconnection exhausted — the app is now offline
1401
- this.runtime.logger.warn('Lost connection to the sync service and could not reconnect. Your app is now offline; changes will sync once the connection is restored.');
1402
- this.runtime.logger.debug('[BaseSyncedStore] WebSocket reconnection gave up', { attempts });
1403
- this.updateSyncStatus({ state: 'reconnecting' });
1404
- });
1405
- this.disposers.push(onConnected, onDisconnected, onReconnecting, onDelta, onDeltaBatch, onBootstrapRequired, onBootstrapData, onPresenceUpdate, onError, onSessionError, onHandshakeFailed, onReconnectFailed, () => { this.areaOfInterest.dispose(); });
1406
- }
1407
- /**
1408
- * Build and start the connection FSM. The `onConnectionEvent` hook is the
1409
- * bridge — WS events fire the hook, the hook forwards into the FSM. Called
1410
- * from `setupWebSocketSync` because the FSM's shape depends on the resolved
1411
- * participant kind (agents get none — see {@link createConnectionManager}).
1412
- */
1413
- startConnectionManager(kind) {
1414
- this.connectionManager = this.createConnectionManager(kind);
1415
- if (this.connectionManager) {
1416
- const manager = this.connectionManager;
1417
- // Preserve any externally-set onConnectionEvent — chain rather
1418
- // than overwrite, so subclasses that wire a secondary consumer
1419
- // still receive events.
1420
- const priorHook = this.onConnectionEvent;
1421
- this.onConnectionEvent = (event) => {
1422
- try {
1423
- priorHook?.(event);
1424
- }
1425
- catch { /* don't let subclass crash the FSM */ }
1426
- switch (event) {
1427
- case 'WS_CONNECTED':
1428
- manager.send({ type: 'WS_CONNECTED' });
1429
- break;
1430
- case 'WS_DISCONNECTED':
1431
- manager.send({ type: 'WS_DISCONNECTED' });
1432
- break;
1433
- case 'WS_SESSION_ERROR':
1434
- manager.send({ type: 'WS_SESSION_ERROR' });
1435
- break;
1436
- case 'WS_HANDSHAKE_FAILED':
1437
- manager.send({ type: 'WS_HANDSHAKE_FAILED' });
1438
- break;
1439
- }
1440
- };
1441
- manager.start({
1442
- onReconnect: () => this.performReconnect(),
1443
- onRefreshCredential: () => this.performCredentialRefresh(),
1444
- onSessionExpired: () => {
1445
- const err = new AbloSessionError('Session expired');
1446
- for (const listener of this.sessionErrorListeners) {
1447
- try {
1448
- listener(err);
1449
- }
1450
- catch { }
1451
- }
1452
- },
1453
- onDisconnectWebSocket: () => {
1454
- this.syncWebSocket.disconnect();
1455
- },
1456
- // Mirror FSM transitions into the visible `syncStatus.state` so
1457
- // the UI can show "Reconnecting…" while the FSM cycles through
1458
- // probing / reconnecting / backoff. Previously these states
1459
- // were opaque to the UI, leaving the sidebar pinned to
1460
- // "offline" for the entire recovery window — exactly the
1461
- // confusing UX the warning log was trying to surface.
1462
- //
1463
- // We only override `state` here; `error` / `progress` / etc.
1464
- // continue to be set by the WebSocket subscription handlers
1465
- // and bootstrap pipeline, which know more than the FSM does.
1466
- onStateChange: (next) => {
1467
- switch (next) {
1468
- case 'connected':
1469
- // Don't clobber an in-flight 'syncing' / 'idle' update
1470
- // that the bootstrap pipeline might be midway through —
1471
- // those handlers run their own `updateSyncStatus`. Only
1472
- // promote out of an offline / reconnecting / error label.
1473
- if (this.syncStatus.state === 'offline' ||
1474
- this.syncStatus.state === 'reconnecting' ||
1475
- this.syncStatus.state === 'error') {
1476
- this.updateSyncStatus({ state: 'idle', offlineSince: undefined });
1477
- }
1478
- break;
1479
- case 'probing_network':
1480
- case 'refreshing_credential':
1481
- case 'reconnecting':
1482
- case 'backoff':
1483
- // Active recovery — the UI should reflect that the FSM
1484
- // is doing work, not that we've given up. (Re-minting a stale
1485
- // access key is just another recovery step, surfaced the same
1486
- // way; the user never sees a credential-level distinction.)
1487
- if (this.syncStatus.state !== 'reconnecting') {
1488
- this.updateSyncStatus({ state: 'reconnecting' });
1489
- }
1490
- break;
1491
- case 'waiting_for_network':
1492
- case 'offline':
1493
- if (this.syncStatus.state !== 'offline') {
1494
- this.updateSyncStatus({
1495
- state: 'offline',
1496
- offlineSince: this.syncStatus.offlineSince ?? new Date(),
1497
- });
1498
- }
1499
- break;
1500
- // 'session_expired' / 'validating_session' are handled by
1501
- // the existing session-error / WS subscription paths.
1502
- }
1503
- },
1504
- });
1505
- }
1506
- }
1507
- // ── Delta processing pipeline ─────────────────────────────────────────────
1508
- //
1509
- // The implementation lives in the sync/deltaPipeline module (deduplication,
1510
- // enqueue bookkeeping, debounce, flush). The methods below are thin protected
1511
- // delegates with unchanged signatures, and the module routes every call to a
1512
- // protected override point back through `deltaPipelineContext`, so subclass
1513
- // dynamic dispatch is preserved. `applyDeltaFrame`, the authoritative-apply
1514
- // correctness point, deliberately stays here.
1515
- /** Memoized pipeline context — `enqueueDelta` runs once per delta, so the
1516
- * accessor object is built once and reused (the get/set accessors always
1517
- * read the live host fields). */
1518
- _deltaPipelineContext = null;
1519
- get deltaPipelineContext() {
1520
- if (this._deltaPipelineContext)
1521
- return this._deltaPipelineContext;
1522
- const store = this;
1523
- this._deltaPipelineContext = {
1524
- runtime: this.runtime,
1525
- stagePlugins: this.stagePlugins,
1526
- // Shared pipeline state, backed by the host fields.
1527
- get pendingDeltas() { return store.pendingDeltas; },
1528
- set pendingDeltas(deltas) { store.pendingDeltas = deltas; },
1529
- get batchTimer() { return store.batchTimer; },
1530
- set batchTimer(timer) { store.batchTimer = timer; },
1531
- get bootstrapDeltaQueue() { return store.bootstrapDeltaQueue; },
1532
- get smartSyncOptions() { return store.smartSyncOptions; },
1533
- get highestProcessedSyncId() { return store.highestProcessedSyncId; },
1534
- get lastAckedId() { return store.lastAckedId; },
1535
- // SyncClient position/transaction bookkeeping.
1536
- onDeltaReceived: (syncId, transactionId, correlationId) => {
1537
- this.syncClient.onDeltaReceived(syncId, transactionId, correlationId);
1538
- },
1539
- advanceApplied: (syncId) => { this.syncClient.position.advanceApplied(syncId); },
1540
- advancePersisted: (syncId) => { this.syncClient.position.advancePersisted(syncId); },
1541
- // Persistence + pool writes.
1542
- processDeltaBatch: (deltas) => this.database.processDeltaBatch(deltas),
1543
- applyDeltaBatchToPool: (results) => { this.applyChangesToPool(results); },
1544
- acknowledge: (syncId) => { this.syncWebSocket.acknowledge(syncId); },
1545
- get objectPool() { return store.objectPool; },
1546
- // Dynamic-dispatch hooks — protected override points on this class.
1547
- getStateFields: (modelName) => this.getStateFields(modelName),
1548
- isCustomEntity: (modelName) => this.isCustomEntity(modelName),
1549
- createCustomEntity: (modelName, modelId, data) => this.createCustomEntity(modelName, modelId, data),
1550
- deduplicateDeltas: (deltas) => this.deduplicateDeltas(deltas),
1551
- flushPendingDeltas: () => this.flushPendingDeltas(),
1552
- handleFlushError: (error) => { this.handleFlushError(error); },
1553
- handleSyncGroupChange: (delta) => this.handleSyncGroupChange(delta),
1554
- handleGroupRemoved: (delta) => this.handleGroupRemoved(delta),
1555
- forceFullRebootstrap: () => { this.forceFullRebootstrap(); },
1556
- cascadeCancelTransactionsForDeletedParent: (parentModelName, parentId) => {
1557
- this.cascadeCancelTransactionsForDeletedParent(parentModelName, parentId);
1558
- },
1559
- };
1560
- return this._deltaPipelineContext;
1561
- }
1562
- /**
1563
- * Lands persisted changes in the in-memory pool, with this store's
1564
- * relation enrichment bound. The one apply path: the pipeline's bridge
1565
- * (no plugins installed) and the `humans()` apply handler both call it.
1566
- */
1567
- applyChangesToPool(changes) {
1568
- this.syncClient.applyDeltaBatchToPool(changes, (name, data) => this.enrichRelations(name, data));
1569
- }
1570
- /** Get fields that represent meaningful state for deduplication. Override for model-specific fields. */
1571
- getStateFields(_modelName) {
1572
- return ['status', 'state', 'isActive'];
1573
- }
1574
- /** Deduplicate deltas to the same entity — keep meaningful state transitions only */
1575
- deduplicateDeltas(deltas) {
1576
- return deltaPipeline.deduplicateDeltas(this.deltaPipelineContext, deltas);
1577
- }
1578
- /** Process incoming delta with smart batching */
1579
- processDeltaWithBatching(delta) {
1580
- if (!this.enqueueDelta(delta))
1581
- return;
1582
- this.scheduleDeltaFlush();
1583
- }
1584
- /**
1585
- * Apply a complete, server-delivered delta frame atomically.
1586
- *
1587
- * A `delta_batch` WebSocket event (a reconnect or catch-up replay) already
1588
- * carries the full set of missed deltas. Routing it through the per-delta
1589
- * `processDeltaWithBatching` path would re-chunk it via the live-traffic
1590
- * debounce timer and `maxBatchSize` force-flush, so a 300-delta catch-up
1591
- * would fan out into several separate `flushPendingDeltas` cycles — each its
1592
- * own local write, pool mutation, `models:changed` emit, and re-render, so
1593
- * the UI visibly repaints once per chunk.
1594
- *
1595
- * Instead, this runs the per-delta bookkeeping (deduplication, ack, version
1596
- * vector, watermark, group-change routing, delete cascade) for every delta
1597
- * without scheduling a flush, then flushes once — collapsing the whole frame
1598
- * into a single local write, pool mutation, `models:changed` emit, and
1599
- * re-render. The post-bootstrap replay of deltas queued during bootstrap
1600
- * uses the same path.
1601
- *
1602
- * It is named `applyDeltaFrame`, not `processDeltaBatch`, to avoid confusion
1603
- * with {@link Database.processDeltaBatch} — the lower-level local write this
1604
- * eventually drives through `flushPendingDeltas`.
1605
- */
1606
- applyDeltaFrame(deltas) {
1607
- let enqueuedAny = false;
1608
- for (const delta of deltas) {
1609
- // A delta_batch frame is the server's authoritative, ordered answer to
1610
- // "everything in my stream after cursor C" (reconnect/catch-up replay or
1611
- // post-bootstrap drain). Apply every delta it carries; do not subject it
1612
- // to the live-traffic watermark dedup (`id <= applied`).
1613
- //
1614
- // That watermark is only valid under in-order delivery, and reconnect
1615
- // breaks the assumption: an in-flight live broadcast for a gap delta can
1616
- // land out of order before the catch-up fills the ids below it (e.g. the
1617
- // server acks a write, then the test/client reconnects, then that write's
1618
- // pending broadcast arrives on the fresh socket — id 4 live before the
1619
- // catch-up's [2,3,4]). Applying id 4 advances `applied` to 4, and the
1620
- // watermark would then drop 2 and 3 from the catch-up as "already seen" —
1621
- // a poisoned gap and a cursor that lies (applied=4 with rows 2,3 absent).
1622
- //
1623
- // Re-applying a delta the live path already applied is safe: the
1624
- // downstream `Database.processDeltaBatch` + `SyncClient.applyDeltaBatchToPool`
1625
- // are idempotent (echo detection, no row resurrection, conflict
1626
- // resolution), so the redundant id 4 is a no-op while 2 and 3 land.
1627
- if (this.enqueueDelta(delta, { authoritative: true }))
1628
- enqueuedAny = true;
1629
- }
1630
- if (!enqueuedAny)
1631
- return;
1632
- // Cancel any pending live-traffic timer — the frame is complete, so
1633
- // there is nothing to wait for. Flush everything in one pass.
1634
- if (this.batchTimer) {
1635
- clearTimeout(this.batchTimer);
1636
- this.batchTimer = null;
1637
- }
1638
- void this.flushPendingDeltas().catch(this.handleFlushError);
1639
- }
1640
- /**
1641
- * Per-delta bookkeeping + enqueue. Returns `true` when the delta was
1642
- * pushed onto `pendingDeltas` (a regular batchable I/U/C/D delta that a
1643
- * subsequent flush must drain), `false` when it was skipped (dedup),
1644
- * deferred (bootstrap queue), or handled immediately out-of-band (G/S
1645
- * sync-group mutations). Does NOT schedule a flush — callers decide
1646
- * whether to debounce (live) or flush atomically (catch-up frame).
1647
- */
1648
- enqueueDelta(delta, options = {}) {
1649
- return deltaPipeline.enqueueDelta(this.deltaPipelineContext, delta, options);
1650
- }
1651
- /** Debounce a flush for live single-delta traffic. */
1652
- scheduleDeltaFlush() {
1653
- deltaPipeline.scheduleDeltaFlush(this.deltaPipelineContext);
1654
- }
1655
- /**
1656
- * Cancel pending transactions for child entities when a parent is deleted.
1657
- *
1658
- * Uses `pool.getByForeignKey` (O(1) via the FK index registered at
1659
- * schema build time) to find children. The previous implementation did
1660
- * `getByType(ctor).filter(e => e.toJSON()[foreignKey] === parentId)` —
1661
- * a full pool scan per child model + a `toJSON()` allocation per
1662
- * candidate. For a report delete with 10K blocks in the pool, that was
1663
- * 10K toJSON allocations per cascade level. The FK-indexed lookup
1664
- * skips both the scan AND the allocation.
1665
- */
1666
- cascadeCancelTransactionsForDeletedParent(parentModelName, parentId) {
1667
- const reg = this.objectPool.registry;
1668
- const childModels = reg.getChildModels(parentModelName);
1669
- if (childModels.length === 0)
1670
- return;
1671
- let totalCancelled = 0;
1672
- for (const { childModel, foreignKey } of childModels) {
1673
- const cancelled = this.syncClient.cancelTransactionsByForeignKey(childModel, foreignKey, parentId);
1674
- totalCancelled += cancelled;
1675
- // O(1) FK-index lookup — skips the prior `getByType().filter(toJSON)` scan.
1676
- const children = this.objectPool.getByForeignKey(childModel, foreignKey, parentId);
1677
- for (const child of children) {
1678
- this.cascadeCancelTransactionsForDeletedParent(childModel, child.id);
1679
- }
1680
- }
1681
- if (totalCancelled > 0) {
1682
- this.runtime.logger.info('[BaseSyncedStore] Cascade cancelled orphaned transactions', {
1683
- parentModel: parentModelName,
1684
- parentId: parentId.slice(0, 12),
1685
- totalCancelled,
1686
- });
1687
- }
1688
- }
1689
- /** Flush pending deltas with deduplication. Pool writes are delegated to {@link SyncClient}. */
1690
- async flushPendingDeltas() {
1691
- return deltaPipeline.flushPendingDeltas(this.deltaPipelineContext);
1692
- }
1693
- // ── Core mutations (thin delegation to SyncClient) ────────────────────────
1694
- //
1695
- // This class orchestrates; it does not implement the writes. {@link SyncClient}
1696
- // owns the object-pool operations, the transaction queue, and local writes.
1697
- // This class owns validation, lifecycle hooks, and pending-delete tracking.
1698
- /** Check if a model type is local-only (no sync). Override for domain-specific models. */
1699
- isLocalOnlyModel(_modelName) {
1700
- return false;
1701
- }
1702
- /** Validate model against schema before save */
1703
- validateModel(model) {
1704
- const modelName = model.getModelName();
1705
- const properties = this.modelRegistry.getPropertiesForModel(modelName);
1706
- const modelData = model.toJSON();
1707
- for (const [propName, metadata] of properties) {
1708
- if (metadata.type === PropertyType.referenceModel)
1709
- continue;
1710
- if (metadata.type === PropertyType.ephemeralProperty)
1711
- continue;
1712
- if (!metadata.optional && (modelData[propName] === null || modelData[propName] === undefined)) {
1713
- throw new AbloValidationError(`Required field ${propName} is missing on ${modelName}`, { code: 'model_required_field_missing' });
1714
- }
1715
- }
1716
- }
1717
- /**
1718
- * Save a model (create or update).
1719
- *
1720
- * Accepts any entity shape with `{ id: string }` so consumers can pass the
1721
- * Zod-inferred model types from `Model<Schema, K>` without knowing
1722
- * about the internal `Model` base class. At runtime, every entity reaching
1723
- * this method came through the object pool (via `store.create`, a query
1724
- * accessor, or an optimistic insert) and IS a `Model` instance — the one
1725
- * cast below preserves that invariant inside the SDK.
1726
- */
1727
- async save(entity, options) {
1728
- const model = rowAsModel(entity);
1729
- this.beforeSave(model);
1730
- if (!options?.skipValidation)
1731
- this.validateModel(model);
1732
- if (!model.createdAt)
1733
- model.createdAt = new Date();
1734
- // SyncClient.add/update handles: optimistic pool add, transaction queue, IDB write
1735
- const isCreate = !this.objectPool.get(model.id);
1736
- if (isCreate) {
1737
- model.updatedAt = new Date();
1738
- this.syncClient.add(model);
1739
- }
1740
- else {
1741
- this.syncClient.update(model);
1742
- }
1743
- }
1744
- /** Save with an atomic server mutation (e.g., createSectionWithBlocks) */
1745
- async saveWithAtomicMutation(model, mutation) {
1746
- this.objectPool.add(model, ModelScope.live);
1747
- await mutation(this.syncClient.gql);
1748
- }
1749
- /** Delete a model. Accepts schema-inferred entity shapes (see `save`). */
1750
- async delete(entity) {
1751
- const model = rowAsModel(entity);
1752
- this.pendingDeletes.add(model.id);
1753
- // SyncClient.delete handles: pool remove, transaction queue
1754
- this.syncClient.delete(model);
1755
- }
1756
- /** Archive a model. Accepts schema-inferred entity shapes (see `save`). */
1757
- async archive(entity) {
1758
- const model = rowAsModel(entity);
1759
- model.archivedAt = new Date();
1760
- this.syncClient.archive(model);
1761
- }
1762
- /** Unarchive a model. Accepts schema-inferred entity shapes (see `save`). */
1763
- async unarchive(entity) {
1764
- const model = rowAsModel(entity);
1765
- model.archivedAt = null;
1766
- this.syncClient.update(model);
1767
- }
1768
- // ── Query API ────────────────────────────────────────────────────────────
1769
- // `ablo.<model>.local.retrieve` / `.local.list` is the read surface for
1770
- // application code. Custom mutators read transactionally through
1771
- // `tx.<model>`, backed by `createReaderActions`.
1772
- /** Retrieve a single entity by id. Synchronous pool read. */
1773
- retrieve(_modelClass, id) {
1774
- return this.objectPool.get(id);
1775
- }
1776
- /** Find any entity by ID regardless of type */
1777
- findAnyById(id) {
1778
- return this.objectPool.get(id);
1779
- }
1780
- /**
1781
- * Lookup a model by ID alone. Matches the `SyncStoreRef.getById` contract
1782
- * that schema-defined computeds use when they need to resolve a related
1783
- * entity without holding onto its constructor.
1784
- */
1785
- getById(id) {
1786
- return this.objectPool.get(id);
1787
- }
1788
- /**
1789
- * Create a model instance locally, typed via the schema.
1790
- *
1791
- * ```ts
1792
- * const ledger = store.create('ledgers', { name, reportId });
1793
- * // ledger: Ledger | null — no cast needed
1794
- * ```
1795
- *
1796
- * The `typename` arg is the schema key (camelCase plural, e.g.
1797
- * `'ledgers'`); the returned instance has the
1798
- * `Model<Schema, K>` shape including computeds + relation accessors.
1799
- * Wraps `pool.create(...)` — the underlying runtime is unchanged, just
1800
- * type-narrowed.
1801
- */
1802
- create(typename, data) {
1803
- if (!this.schema) {
1804
- throw new AbloValidationError('store.create requires a schema to be passed to the BaseSyncedStore constructor.', { code: 'store_create_schema_missing' });
1805
- }
1806
- const modelDef = this.schema.models[typename];
1807
- const wireTypename = modelDef?.typename ?? typename;
1808
- // Same boundary-cast idiom used by `createReaderActions.findById` — the
1809
- // runtime instance IS the schema-typed shape (the dynamic class was
1810
- // built from the same Zod shape), TypeScript just can't unify the SDK's
1811
- // static `Model` class with the schema's object-literal type.
1812
- return this.objectPool.create(wireTypename, data);
1813
- }
1814
- /**
1815
- * Query entry point for callers that hold a {@link Model} constructor and an
1816
- * options object. It filters, orders, and paginates the matching models from
1817
- * the pool. Prefer the schema-typed read surface (`ablo.<model>.list`) where
1818
- * you can, since it infers concrete row types without a class value or cast.
1819
- */
1820
- queryByClass(modelClass, options) {
1821
- const modelName = this.objectPool.registry.getModelNameFromConstructor(modelClass);
1822
- if (!modelName)
1823
- return { data: [], total: 0, hasMore: false };
1824
- let allModels = this.objectPool.getByType(modelClass, options?.state ?? ModelScope.live);
1825
- // Filter out pending deletes
1826
- allModels = allModels.filter((m) => !this.pendingDeletes.has(m.id));
1827
- // Apply predicate
1828
- if (options?.predicate) {
1829
- allModels = allModels.filter(options.predicate);
1830
- }
1831
- const total = allModels.length;
1832
- // Apply ordering
1833
- if (options?.orderBy) {
1834
- const field = options.orderBy;
1835
- const dir = options.order === 'desc' ? -1 : 1;
1836
- allModels.sort((a, b) => {
1837
- const av = a.getField(field);
1838
- const bv = b.getField(field);
1839
- if (av == null || bv == null)
1840
- return 0;
1841
- return av < bv ? -dir : av > bv ? dir : 0;
1842
- });
1843
- }
1844
- // Apply pagination
1845
- if (options?.offset)
1846
- allModels = allModels.slice(options.offset);
1847
- const hasMore = options?.limit ? allModels.length > options.limit : false;
1848
- if (options?.limit)
1849
- allModels = allModels.slice(0, options.limit);
1850
- return { data: allModels, total, hasMore };
1851
- }
1852
- /**
1853
- * Get all models of a type. Returns Model[] honestly — callers that need
1854
- * narrow types should use `useAblo((ablo) => ablo.<model>.list(...))`
1855
- * which does proper inference via `Model<S, K>`.
1856
- */
1857
- allModelsOfType(modelClass, scope) {
1858
- return this.objectPool.getByType(modelClass, scope ?? ModelScope.live);
1859
- }
1860
- /** Error handler for fire-and-forget flushPendingDeltas calls */
1861
- handleFlushError = (error) => {
1862
- this.runtime.observability.captureMutationFailure({
1863
- context: 'flush-pending-deltas',
1864
- modelName: 'batch',
1865
- modelId: 'batch',
1866
- error: error instanceof Error ? error : new Error(String(error)),
1867
- });
1868
- this.runtime.logger.debug('[BaseSyncedStore] Delta flush error', {
1869
- error: error instanceof Error ? error.message : String(error),
1870
- });
1871
- };
1872
- /** Process a single delta (used for immediate DELETE processing). Override for domain-specific handling. */
1873
- async processDelta(delta) {
1874
- const dbResult = await this.database.processDelta({
1875
- syncId: delta.id,
1876
- actionType: delta.actionType,
1877
- modelName: delta.modelName,
1878
- modelId: delta.modelId,
1879
- data: typeof delta.data === 'string' ? JSON.parse(delta.data) : delta.data,
1880
- });
1881
- // Track pending deletes for query filtering
1882
- if (dbResult.action === 'remove') {
1883
- this.pendingDeletes.add(dbResult.modelId);
1884
- }
1885
- // Delegate pool writes to SyncClient (auto-invalidates cache via 'models:changed' event)
1886
- this.syncClient.applyDeltaBatchToPool([dbResult], (name, data) => this.enrichRelations(name, data));
1887
- // This path runs after the delta was written to IDB — advance both
1888
- // cursors through the shared position.
1889
- this.syncClient.position.advancePersisted(delta.id);
1890
- }
1891
- /** Handle bootstrap_required event */
1892
- handleBootstrapRequired(_hint) {
1893
- // Subclass implements — triggers background bootstrap
1894
- }
1895
- /** Handle bootstrap_data event. Override in subclass. */
1896
- handleBootstrapData(_data) {
1897
- this.updateSyncStatus({ state: 'syncing' });
1898
- }
1899
- /** Handle presence_update event. Override in subclass. */
1900
- handlePresenceUpdate(_data) { }
1901
- // ── Pending changes tracking ─────────────────────────────────────────────
1902
- incrementPendingChanges() {
1903
- runInAction(() => { this.syncStatus.pendingChanges++; });
1904
- }
1905
- decrementPendingChanges() {
1906
- runInAction(() => {
1907
- if (this.syncStatus.pendingChanges > 0)
1908
- this.syncStatus.pendingChanges--;
1909
- });
1910
- }
1911
- // ── Status helpers ───────────────────────────────────────────────────────
1912
- updateSyncStatus(updates) {
1913
- runInAction(() => {
1914
- Object.assign(this.syncStatus, updates);
1915
- });
1916
- }
1917
- // ── Accessors ─────────────────────────────────────────────────────────────
1918
- get pool() {
1919
- return this.objectPool;
1920
- }
1921
- get lastSyncId() {
1922
- return this.lastAckedId;
1923
- }
1924
- // ── Status convenience getters ──────────────────────────────────────────
1925
- // Thin wrappers over `syncStatus` for consumer ergonomics.
1926
- get isReady() {
1927
- // Ready if: fully synced (idle + 100%) OR local data loaded (dataReady + syncing in background)
1928
- return (this.syncStatus.state === 'idle' && this.syncStatus.progress >= 100)
1929
- || (this.dataReady && this.syncStatus.state === 'syncing');
1930
- }
1931
- get isSyncing() {
1932
- return this.syncStatus.state === 'syncing';
1933
- }
1934
- get isOffline() {
1935
- return this.syncStatus.state === 'offline';
1936
- }
1937
- get isReconnecting() {
1938
- return this.syncStatus.state === 'reconnecting';
1939
- }
1940
- get isError() {
1941
- return this.syncStatus.state === 'error';
1942
- }
1943
- get hasUnsyncedChanges() {
1944
- return this.syncStatus.pendingChanges > 0;
1945
- }
1946
- /** The SyncWebSocket handle — for collaboration events. */
1947
- get ws() {
1948
- return this.syncWebSocket;
1949
- }
1950
- /** The Database instance — for demand loaders and direct IDB operations. */
1951
- get db() {
1952
- return this.database;
1953
- }
1954
- /** The SyncClient instance — for assignment operations and other direct sync actions. */
1955
- get sc() {
1956
- return this.syncClient;
1957
- }
1958
- /** The current organization ID — from the last initialize() call. */
1959
- get orgId() {
1960
- return this.userContext?.organizationId;
1961
- }
1962
- /** Count models matching a predicate. */
1963
- count(modelClass, predicate) {
1964
- const all = this.allModelsOfType(modelClass);
1965
- return predicate ? all.filter(predicate).length : all.length;
1966
- }
1967
- /** Get entities by foreign key (used by Model subclasses via Model.store) */
1968
- getByForeignKey(modelName, foreignKey, id) {
1969
- return this.objectPool.getByForeignKey(modelName, foreignKey, id);
1970
- }
1971
- }