@abloatai/humans 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (404) hide show
  1. package/README.md +52 -0
  2. package/dist/Ablo.d.ts +208 -0
  3. package/dist/Ablo.js +120 -0
  4. package/dist/client.d.ts +317 -0
  5. package/dist/client.js +13 -0
  6. package/dist/core.d.ts +35 -0
  7. package/dist/core.js +48 -0
  8. package/dist/humans.d.ts +28 -0
  9. package/dist/humans.js +34 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +6 -0
  12. package/dist/local/BaseSyncedStore.d.ts +807 -0
  13. package/dist/local/BaseSyncedStore.js +1516 -0
  14. package/dist/local/Database.d.ts +322 -0
  15. package/dist/local/Database.js +1589 -0
  16. package/dist/local/InstanceCache.d.ts +255 -0
  17. package/dist/local/InstanceCache.js +1263 -0
  18. package/dist/local/LazyReferenceCollection.d.ts +177 -0
  19. package/dist/local/LazyReferenceCollection.js +461 -0
  20. package/dist/local/Model.d.ts +475 -0
  21. package/dist/local/Model.js +950 -0
  22. package/dist/local/ModelRegistry.d.ts +225 -0
  23. package/dist/local/ModelRegistry.js +539 -0
  24. package/dist/local/NetworkMonitor.d.ts +28 -0
  25. package/dist/local/NetworkMonitor.js +79 -0
  26. package/dist/local/RuntimeContext.d.ts +52 -0
  27. package/dist/local/RuntimeContext.js +80 -0
  28. package/dist/local/SyncClient.d.ts +516 -0
  29. package/dist/local/SyncClient.js +1754 -0
  30. package/dist/local/adapters/alwaysOnline.d.ts +14 -0
  31. package/dist/local/adapters/alwaysOnline.js +17 -0
  32. package/dist/local/adapters/inMemoryStorage.d.ts +37 -0
  33. package/dist/local/adapters/inMemoryStorage.js +122 -0
  34. package/dist/local/client/clientPrelude.d.ts +52 -0
  35. package/dist/local/client/clientPrelude.js +60 -0
  36. package/dist/local/client/consoleLogger.d.ts +35 -0
  37. package/dist/local/client/consoleLogger.js +44 -0
  38. package/dist/local/client/createInternalComponents.d.ts +50 -0
  39. package/dist/local/client/createInternalComponents.js +98 -0
  40. package/dist/local/client/createModelProxy.d.ts +248 -0
  41. package/dist/local/client/createModelProxy.js +880 -0
  42. package/dist/local/client/modelRegistration.d.ts +10 -0
  43. package/dist/local/client/modelRegistration.js +316 -0
  44. package/dist/local/client/options.d.ts +440 -0
  45. package/dist/local/client/options.js +7 -0
  46. package/dist/local/client/reactiveEngine.d.ts +53 -0
  47. package/dist/local/client/reactiveEngine.js +705 -0
  48. package/dist/local/client/resourceTypes.d.ts +12 -0
  49. package/dist/local/client/resourceTypes.js +10 -0
  50. package/dist/local/client/schemaConfig.d.ts +44 -0
  51. package/dist/local/client/schemaConfig.js +185 -0
  52. package/dist/local/client/storeCluster.d.ts +46 -0
  53. package/dist/local/client/storeCluster.js +133 -0
  54. package/dist/local/client/storeLifecycle.d.ts +61 -0
  55. package/dist/local/client/storeLifecycle.js +236 -0
  56. package/dist/local/client/validateAbloOptions.d.ts +42 -0
  57. package/dist/local/client/validateAbloOptions.js +43 -0
  58. package/dist/local/client/wsMutationExecutor.d.ts +27 -0
  59. package/dist/local/client/wsMutationExecutor.js +72 -0
  60. package/dist/local/context.d.ts +42 -0
  61. package/dist/local/context.js +81 -0
  62. package/dist/local/coordination/ClaimLog.d.ts +26 -0
  63. package/dist/local/coordination/ClaimLog.js +32 -0
  64. package/dist/local/interfaces/index.d.ts +311 -0
  65. package/dist/local/interfaces/index.js +9 -0
  66. package/dist/local/localModelContract.d.ts +14 -0
  67. package/dist/local/localModelContract.js +1 -0
  68. package/dist/local/logPosition.d.ts +31 -0
  69. package/dist/local/logPosition.js +53 -0
  70. package/dist/local/mutationPersistence.d.ts +6 -0
  71. package/dist/local/mutationPersistence.js +1 -0
  72. package/dist/local/mutators/RecordingMutation.d.ts +36 -0
  73. package/dist/local/mutators/RecordingMutation.js +182 -0
  74. package/dist/local/mutators/Transaction.d.ts +40 -0
  75. package/dist/local/mutators/Transaction.js +58 -0
  76. package/dist/local/mutators/UndoManager.d.ts +258 -0
  77. package/dist/local/mutators/UndoManager.js +665 -0
  78. package/dist/local/mutators/defineMutators.d.ts +60 -0
  79. package/dist/local/mutators/defineMutators.js +18 -0
  80. package/dist/local/mutators/inverseOp.d.ts +126 -0
  81. package/dist/local/mutators/inverseOp.js +71 -0
  82. package/dist/local/mutators/mutateActions.d.ts +45 -0
  83. package/dist/local/mutators/mutateActions.js +105 -0
  84. package/dist/local/mutators/readerActions.d.ts +33 -0
  85. package/dist/local/mutators/readerActions.js +57 -0
  86. package/dist/local/mutators/undoApply.d.ts +51 -0
  87. package/dist/local/mutators/undoApply.js +117 -0
  88. package/dist/local/persistence.d.ts +7 -0
  89. package/dist/local/persistence.js +9 -0
  90. package/dist/local/query/QueryProcessor.d.ts +75 -0
  91. package/dist/local/query/QueryProcessor.js +255 -0
  92. package/dist/local/query/client.d.ts +64 -0
  93. package/dist/local/query/client.js +138 -0
  94. package/dist/local/query/types.d.ts +85 -0
  95. package/dist/local/query/types.js +16 -0
  96. package/dist/local/schema/serialize.d.ts +1 -0
  97. package/dist/local/schema/serialize.js +1 -0
  98. package/dist/local/store/queryApi.d.ts +13 -0
  99. package/dist/local/store/queryApi.js +35 -0
  100. package/dist/local/storeContract.d.ts +145 -0
  101. package/dist/local/storeContract.js +12 -0
  102. package/dist/local/stores/DatabaseManager.d.ts +112 -0
  103. package/dist/local/stores/DatabaseManager.js +400 -0
  104. package/dist/local/stores/ObjectStore.d.ts +115 -0
  105. package/dist/local/stores/ObjectStore.js +393 -0
  106. package/dist/local/stores/ObjectStoreContract.d.ts +38 -0
  107. package/dist/local/stores/ObjectStoreContract.js +1 -0
  108. package/dist/local/stores/StoreManager.d.ts +114 -0
  109. package/dist/local/stores/StoreManager.js +304 -0
  110. package/dist/local/stores/SyncActionStore.d.ts +99 -0
  111. package/dist/local/stores/SyncActionStore.js +506 -0
  112. package/dist/local/stores/openIDBWithTimeout.d.ts +65 -0
  113. package/dist/local/stores/openIDBWithTimeout.js +153 -0
  114. package/dist/local/stores/persistenceCleanup.d.ts +7 -0
  115. package/dist/local/stores/persistenceCleanup.js +26 -0
  116. package/dist/local/stores/persistenceIdentity.d.ts +27 -0
  117. package/dist/local/stores/persistenceIdentity.js +38 -0
  118. package/dist/local/stores/syncAction.d.ts +26 -0
  119. package/dist/local/stores/syncAction.js +16 -0
  120. package/dist/local/stores/v1PersistenceDeletion.d.ts +8 -0
  121. package/dist/local/stores/v1PersistenceDeletion.js +16 -0
  122. package/dist/local/sync/BootstrapFetcher.d.ts +284 -0
  123. package/dist/local/sync/BootstrapFetcher.js +964 -0
  124. package/dist/local/sync/ConnectionManager.d.ts +8 -0
  125. package/dist/local/sync/ConnectionManager.js +8 -0
  126. package/dist/local/sync/OnDemandLoader.d.ts +231 -0
  127. package/dist/local/sync/OnDemandLoader.js +743 -0
  128. package/dist/local/sync/SubscriptionManager.d.ts +159 -0
  129. package/dist/local/sync/SubscriptionManager.js +243 -0
  130. package/dist/local/sync/SyncWebSocket.d.ts +173 -0
  131. package/dist/local/sync/SyncWebSocket.js +438 -0
  132. package/dist/local/sync/bootstrapApply.d.ts +73 -0
  133. package/dist/local/sync/bootstrapApply.js +73 -0
  134. package/dist/local/sync/commitFrames.d.ts +8 -0
  135. package/dist/local/sync/commitFrames.js +8 -0
  136. package/dist/local/sync/connectionManagerLifecycle.d.ts +23 -0
  137. package/dist/local/sync/connectionManagerLifecycle.js +126 -0
  138. package/dist/local/sync/contextPorts.d.ts +18 -0
  139. package/dist/local/sync/contextPorts.js +31 -0
  140. package/dist/local/sync/createClaimStream.d.ts +64 -0
  141. package/dist/local/sync/createClaimStream.js +475 -0
  142. package/dist/local/sync/createSnapshot.d.ts +29 -0
  143. package/dist/local/sync/createSnapshot.js +116 -0
  144. package/dist/local/sync/credentialLifecycle.d.ts +7 -0
  145. package/dist/local/sync/credentialLifecycle.js +7 -0
  146. package/dist/local/sync/deltaPipeline.d.ts +116 -0
  147. package/dist/local/sync/deltaPipeline.js +357 -0
  148. package/dist/local/sync/groupChange.d.ts +116 -0
  149. package/dist/local/sync/groupChange.js +244 -0
  150. package/dist/local/sync/initialize.d.ts +27 -0
  151. package/dist/local/sync/initialize.js +137 -0
  152. package/dist/local/sync/participants.d.ts +132 -0
  153. package/dist/local/sync/participants.js +342 -0
  154. package/dist/local/sync/persistedPrefix.d.ts +12 -0
  155. package/dist/local/sync/persistedPrefix.js +22 -0
  156. package/dist/local/sync/reconnect.d.ts +23 -0
  157. package/dist/local/sync/reconnect.js +55 -0
  158. package/dist/local/sync/schemaDrift.d.ts +55 -0
  159. package/dist/local/sync/schemaDrift.js +53 -0
  160. package/dist/local/sync/schemas.d.ts +71 -0
  161. package/dist/local/sync/schemas.js +94 -0
  162. package/dist/local/sync/socketEventWiring.d.ts +31 -0
  163. package/dist/local/sync/socketEventWiring.js +130 -0
  164. package/dist/local/sync/syncCursor.d.ts +40 -0
  165. package/dist/local/sync/syncCursor.js +55 -0
  166. package/dist/local/sync/syncPlan.d.ts +54 -0
  167. package/dist/local/sync/syncPlan.js +50 -0
  168. package/dist/local/sync/terminalSessionLifecycle.d.ts +20 -0
  169. package/dist/local/sync/terminalSessionLifecycle.js +50 -0
  170. package/dist/local/sync/wsFrameHandlers.d.ts +8 -0
  171. package/dist/local/sync/wsFrameHandlers.js +8 -0
  172. package/dist/local/transactions/databaseCommitOutbox.d.ts +15 -0
  173. package/dist/local/transactions/databaseCommitOutbox.js +16 -0
  174. package/dist/local/transactions/localMutation.d.ts +10 -0
  175. package/dist/local/transactions/localMutation.js +37 -0
  176. package/dist/local/transactions/mutations/MutationQueue.d.ts +511 -0
  177. package/dist/local/transactions/mutations/MutationQueue.js +1498 -0
  178. package/dist/local/transactions/mutations/MutationStore.d.ts +20 -0
  179. package/dist/local/transactions/mutations/MutationStore.js +53 -0
  180. package/dist/local/transactions/mutations/UnconfirmedWrites.d.ts +82 -0
  181. package/dist/local/transactions/mutations/UnconfirmedWrites.js +104 -0
  182. package/dist/local/transactions/mutations/batchProcessing.d.ts +64 -0
  183. package/dist/local/transactions/mutations/batchProcessing.js +349 -0
  184. package/dist/local/transactions/mutations/coalesceRules.d.ts +58 -0
  185. package/dist/local/transactions/mutations/coalesceRules.js +140 -0
  186. package/dist/local/transactions/mutations/commitApi.d.ts +19 -0
  187. package/dist/local/transactions/mutations/commitApi.js +74 -0
  188. package/dist/local/transactions/mutations/commitLane.d.ts +70 -0
  189. package/dist/local/transactions/mutations/commitLane.js +140 -0
  190. package/dist/local/transactions/mutations/commitLatency.d.ts +52 -0
  191. package/dist/local/transactions/mutations/commitLatency.js +130 -0
  192. package/dist/local/transactions/mutations/commitPayload.d.ts +165 -0
  193. package/dist/local/transactions/mutations/commitPayload.js +152 -0
  194. package/dist/local/transactions/mutations/commitTransport.d.ts +36 -0
  195. package/dist/local/transactions/mutations/commitTransport.js +104 -0
  196. package/dist/local/transactions/mutations/deltaConfirmation.d.ts +63 -0
  197. package/dist/local/transactions/mutations/deltaConfirmation.js +235 -0
  198. package/dist/local/transactions/mutations/durableCommitRestore.d.ts +17 -0
  199. package/dist/local/transactions/mutations/durableCommitRestore.js +95 -0
  200. package/dist/local/transactions/mutations/durableWriteStore.d.ts +14 -0
  201. package/dist/local/transactions/mutations/durableWriteStore.js +12 -0
  202. package/dist/local/transactions/mutations/executionSelection.d.ts +6 -0
  203. package/dist/local/transactions/mutations/executionSelection.js +42 -0
  204. package/dist/local/transactions/mutations/failureHandling.d.ts +16 -0
  205. package/dist/local/transactions/mutations/failureHandling.js +130 -0
  206. package/dist/local/transactions/mutations/failurePolicy.d.ts +13 -0
  207. package/dist/local/transactions/mutations/failurePolicy.js +48 -0
  208. package/dist/local/transactions/mutations/localMutation.d.ts +58 -0
  209. package/dist/local/transactions/mutations/localMutation.js +75 -0
  210. package/dist/local/transactions/mutations/modelOperations.d.ts +44 -0
  211. package/dist/local/transactions/mutations/modelOperations.js +144 -0
  212. package/dist/local/transactions/mutations/mutationPersistence.d.ts +25 -0
  213. package/dist/local/transactions/mutations/mutationPersistence.js +188 -0
  214. package/dist/local/transactions/mutations/pendingDrain.d.ts +33 -0
  215. package/dist/local/transactions/mutations/pendingDrain.js +112 -0
  216. package/dist/local/transactions/mutations/processingScheduler.d.ts +14 -0
  217. package/dist/local/transactions/mutations/processingScheduler.js +24 -0
  218. package/dist/local/transactions/mutations/queueCoalescing.d.ts +13 -0
  219. package/dist/local/transactions/mutations/queueCoalescing.js +35 -0
  220. package/dist/local/transactions/mutations/replayValidation.d.ts +187 -0
  221. package/dist/local/transactions/mutations/replayValidation.js +164 -0
  222. package/dist/local/transactions/reconnectDrain.d.ts +11 -0
  223. package/dist/local/transactions/reconnectDrain.js +13 -0
  224. package/dist/local/utils/mobxSetup.d.ts +53 -0
  225. package/dist/local/utils/mobxSetup.js +330 -0
  226. package/dist/local/views/QueryView.d.ts +79 -0
  227. package/dist/local/views/QueryView.js +218 -0
  228. package/dist/local/views/ViewRegistry.d.ts +20 -0
  229. package/dist/local/views/ViewRegistry.js +57 -0
  230. package/dist/local/views/incrementalView.d.ts +45 -0
  231. package/dist/local/views/incrementalView.js +69 -0
  232. package/dist/plugin.d.ts +285 -0
  233. package/dist/plugin.js +106 -0
  234. package/dist/presenceStream.d.ts +69 -0
  235. package/dist/presenceStream.js +200 -0
  236. package/dist/react/AbloProvider.d.ts +242 -0
  237. package/dist/react/AbloProvider.js +456 -0
  238. package/dist/react/ClientSideSuspense.d.ts +36 -0
  239. package/dist/react/ClientSideSuspense.js +17 -0
  240. package/dist/react/DefaultFallback.d.ts +24 -0
  241. package/dist/react/DefaultFallback.js +43 -0
  242. package/dist/react/context.d.ts +55 -0
  243. package/dist/react/context.js +29 -0
  244. package/dist/react/createAbloReact.d.ts +50 -0
  245. package/dist/react/createAbloReact.js +48 -0
  246. package/dist/react/internalContext.d.ts +33 -0
  247. package/dist/react/internalContext.js +3 -0
  248. package/dist/react/useAblo.d.ts +96 -0
  249. package/dist/react/useAblo.js +120 -0
  250. package/dist/react/useCurrentUserId.d.ts +2 -0
  251. package/dist/react/useCurrentUserId.js +12 -0
  252. package/dist/react/useErrorListener.d.ts +2 -0
  253. package/dist/react/useErrorListener.js +14 -0
  254. package/dist/react/useMutationFailureListener.d.ts +8 -0
  255. package/dist/react/useMutationFailureListener.js +19 -0
  256. package/dist/react/useMutators.d.ts +56 -0
  257. package/dist/react/useMutators.js +84 -0
  258. package/dist/react/useSyncStatus.d.ts +19 -0
  259. package/dist/react/useSyncStatus.js +37 -0
  260. package/dist/react/useUndoScope.d.ts +34 -0
  261. package/dist/react/useUndoScope.js +73 -0
  262. package/dist/react.d.ts +18 -0
  263. package/dist/react.js +14 -0
  264. package/dist/reactRuntime.d.ts +4 -0
  265. package/dist/reactRuntime.js +2 -0
  266. package/dist/surface.d.ts +36 -0
  267. package/dist/surface.js +77 -0
  268. package/dist/useReactive.d.ts +6 -0
  269. package/dist/useReactive.js +43 -0
  270. package/package.json +119 -0
  271. package/src/Ablo.ts +456 -0
  272. package/src/client.ts +374 -0
  273. package/src/core.ts +104 -0
  274. package/src/humans.ts +61 -0
  275. package/src/index.ts +40 -0
  276. package/src/local/BaseSyncedStore.ts +1991 -0
  277. package/src/local/Database.ts +2052 -0
  278. package/src/local/InstanceCache.ts +1503 -0
  279. package/src/local/LazyReferenceCollection.ts +563 -0
  280. package/src/local/Model.ts +1124 -0
  281. package/src/local/ModelRegistry.ts +762 -0
  282. package/src/local/NetworkMonitor.ts +88 -0
  283. package/src/local/RuntimeContext.ts +141 -0
  284. package/src/local/SyncClient.ts +2131 -0
  285. package/src/local/adapters/alwaysOnline.ts +20 -0
  286. package/src/local/adapters/inMemoryStorage.ts +141 -0
  287. package/src/local/client/clientPrelude.ts +112 -0
  288. package/src/local/client/consoleLogger.ts +60 -0
  289. package/src/local/client/createInternalComponents.ts +163 -0
  290. package/src/local/client/createModelProxy.ts +1390 -0
  291. package/src/local/client/modelRegistration.ts +350 -0
  292. package/src/local/client/options.ts +526 -0
  293. package/src/local/client/reactiveEngine.ts +935 -0
  294. package/src/local/client/resourceTypes.ts +37 -0
  295. package/src/local/client/schemaConfig.ts +194 -0
  296. package/src/local/client/storeCluster.ts +172 -0
  297. package/src/local/client/storeLifecycle.ts +343 -0
  298. package/src/local/client/validateAbloOptions.ts +95 -0
  299. package/src/local/client/wsMutationExecutor.ts +110 -0
  300. package/src/local/context.ts +96 -0
  301. package/src/local/coordination/ClaimLog.ts +39 -0
  302. package/src/local/interfaces/index.ts +468 -0
  303. package/src/local/localModelContract.ts +15 -0
  304. package/src/local/logPosition.ts +84 -0
  305. package/src/local/mutationPersistence.ts +7 -0
  306. package/src/local/mutators/RecordingMutation.ts +222 -0
  307. package/src/local/mutators/Transaction.ts +97 -0
  308. package/src/local/mutators/UndoManager.ts +741 -0
  309. package/src/local/mutators/defineMutators.ts +76 -0
  310. package/src/local/mutators/inverseOp.ts +83 -0
  311. package/src/local/mutators/mutateActions.ts +167 -0
  312. package/src/local/mutators/readerActions.ts +99 -0
  313. package/src/local/mutators/undoApply.ts +141 -0
  314. package/src/local/persistence.ts +16 -0
  315. package/src/local/query/QueryProcessor.ts +347 -0
  316. package/src/local/query/client.ts +197 -0
  317. package/src/local/query/types.ts +102 -0
  318. package/src/local/schema/serialize.ts +1 -0
  319. package/src/local/store/queryApi.ts +56 -0
  320. package/src/local/storeContract.ts +146 -0
  321. package/src/local/stores/DatabaseManager.ts +507 -0
  322. package/src/local/stores/ObjectStore.ts +449 -0
  323. package/src/local/stores/ObjectStoreContract.ts +48 -0
  324. package/src/local/stores/StoreManager.ts +388 -0
  325. package/src/local/stores/SyncActionStore.ts +579 -0
  326. package/src/local/stores/openIDBWithTimeout.ts +195 -0
  327. package/src/local/stores/persistenceCleanup.ts +43 -0
  328. package/src/local/stores/persistenceIdentity.ts +83 -0
  329. package/src/local/stores/syncAction.ts +21 -0
  330. package/src/local/stores/v1PersistenceDeletion.ts +21 -0
  331. package/src/local/sync/BootstrapFetcher.ts +1224 -0
  332. package/src/local/sync/ConnectionManager.ts +15 -0
  333. package/src/local/sync/OnDemandLoader.ts +927 -0
  334. package/src/local/sync/SubscriptionManager.ts +300 -0
  335. package/src/local/sync/SyncWebSocket.ts +584 -0
  336. package/src/local/sync/bootstrapApply.ts +130 -0
  337. package/src/local/sync/commitFrames.ts +16 -0
  338. package/src/local/sync/connectionManagerLifecycle.ts +158 -0
  339. package/src/local/sync/contextPorts.ts +37 -0
  340. package/src/local/sync/createClaimStream.ts +668 -0
  341. package/src/local/sync/createSnapshot.ts +160 -0
  342. package/src/local/sync/credentialLifecycle.ts +18 -0
  343. package/src/local/sync/deltaPipeline.ts +473 -0
  344. package/src/local/sync/groupChange.ts +343 -0
  345. package/src/local/sync/initialize.ts +205 -0
  346. package/src/local/sync/participants.ts +564 -0
  347. package/src/local/sync/persistedPrefix.ts +27 -0
  348. package/src/local/sync/reconnect.ts +88 -0
  349. package/src/local/sync/schemaDrift.ts +86 -0
  350. package/src/local/sync/schemas.ts +118 -0
  351. package/src/local/sync/socketEventWiring.ts +196 -0
  352. package/src/local/sync/syncCursor.ts +62 -0
  353. package/src/local/sync/syncPlan.ts +89 -0
  354. package/src/local/sync/terminalSessionLifecycle.ts +66 -0
  355. package/src/local/sync/wsFrameHandlers.ts +20 -0
  356. package/src/local/transactions/databaseCommitOutbox.ts +33 -0
  357. package/src/local/transactions/localMutation.ts +58 -0
  358. package/src/local/transactions/mutations/MutationQueue.ts +1998 -0
  359. package/src/local/transactions/mutations/MutationStore.ts +65 -0
  360. package/src/local/transactions/mutations/UnconfirmedWrites.ts +133 -0
  361. package/src/local/transactions/mutations/batchProcessing.ts +469 -0
  362. package/src/local/transactions/mutations/coalesceRules.ts +192 -0
  363. package/src/local/transactions/mutations/commitApi.ts +97 -0
  364. package/src/local/transactions/mutations/commitLane.ts +191 -0
  365. package/src/local/transactions/mutations/commitLatency.ts +164 -0
  366. package/src/local/transactions/mutations/commitPayload.ts +281 -0
  367. package/src/local/transactions/mutations/commitTransport.ts +174 -0
  368. package/src/local/transactions/mutations/deltaConfirmation.ts +298 -0
  369. package/src/local/transactions/mutations/durableCommitRestore.ts +128 -0
  370. package/src/local/transactions/mutations/durableWriteStore.ts +21 -0
  371. package/src/local/transactions/mutations/executionSelection.ts +42 -0
  372. package/src/local/transactions/mutations/failureHandling.ts +154 -0
  373. package/src/local/transactions/mutations/failurePolicy.ts +61 -0
  374. package/src/local/transactions/mutations/localMutation.ts +135 -0
  375. package/src/local/transactions/mutations/modelOperations.ts +210 -0
  376. package/src/local/transactions/mutations/mutationPersistence.ts +231 -0
  377. package/src/local/transactions/mutations/pendingDrain.ts +160 -0
  378. package/src/local/transactions/mutations/processingScheduler.ts +35 -0
  379. package/src/local/transactions/mutations/queueCoalescing.ts +45 -0
  380. package/src/local/transactions/mutations/replayValidation.ts +192 -0
  381. package/src/local/transactions/reconnectDrain.ts +24 -0
  382. package/src/local/utils/mobxSetup.ts +388 -0
  383. package/src/local/views/QueryView.ts +311 -0
  384. package/src/local/views/ViewRegistry.ts +61 -0
  385. package/src/local/views/incrementalView.ts +92 -0
  386. package/src/plugin.ts +396 -0
  387. package/src/presenceStream.ts +279 -0
  388. package/src/react/AbloProvider.tsx +744 -0
  389. package/src/react/ClientSideSuspense.tsx +57 -0
  390. package/src/react/DefaultFallback.tsx +60 -0
  391. package/src/react/context.ts +89 -0
  392. package/src/react/createAbloReact.ts +116 -0
  393. package/src/react/internalContext.ts +38 -0
  394. package/src/react/useAblo.ts +280 -0
  395. package/src/react/useCurrentUserId.ts +17 -0
  396. package/src/react/useErrorListener.ts +22 -0
  397. package/src/react/useMutationFailureListener.ts +34 -0
  398. package/src/react/useMutators.ts +184 -0
  399. package/src/react/useSyncStatus.ts +42 -0
  400. package/src/react/useUndoScope.ts +143 -0
  401. package/src/react.ts +69 -0
  402. package/src/reactRuntime.ts +10 -0
  403. package/src/surface.ts +106 -0
  404. package/src/useReactive.ts +51 -0
@@ -0,0 +1,807 @@
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 type { RecoveryClass } from '@abloatai/transaction/errorCodes';
14
+ import { ConnectionManager } from './sync/ConnectionManager.js';
15
+ import { SubscriptionManager } from './sync/SubscriptionManager.js';
16
+ import { type ParticipantScope } from './sync/participants.js';
17
+ import type { SyncClient } from './SyncClient.js';
18
+ import type { Database, BootstrapResult, BootstrapRequirements } from './Database.js';
19
+ import type { InstanceCache } from './InstanceCache.js';
20
+ import { ModelRegistry } from './ModelRegistry.js';
21
+ import { SyncWebSocket, type SyncDelta, type SyncGroupChangePayload, type GroupAddedPayload, type GroupRemovedPayload, type BootstrapHint, type BootstrapDataEvent, type PresenceUpdate, type EventMap, type DefaultCollaborationEvents, type SyncWebSocketEventMap } from './sync/SyncWebSocket.js';
22
+ import { QueryProcessor } from './query/QueryProcessor.js';
23
+ import { Model } from './Model.js';
24
+ import type { RuntimeContext } from './RuntimeContext.js';
25
+ import type { AbloPlugin, AppliedChange } from '../plugin.js';
26
+ import { ModelScope } from './InstanceCache.js';
27
+ import type { Schema } from '@abloatai/transaction/schema/schema';
28
+ import type { SyncStatus, LocalMutation } from './storeContract.js';
29
+ import type { AuthCredentialSource } from '@abloatai/transaction/auth/credentialSource';
30
+ import type { ModelData } from '@abloatai/transaction/types/modelData';
31
+ import type { EnrichmentPlanEntry, ForeignKeyIndexSpec } from './sync/syncPlan.js';
32
+ import { type CredentialRefresher } from './sync/credentialLifecycle.js';
33
+ import type { RehydrationStats } from './sync/bootstrapApply.js';
34
+ import type { ParticipantKind } from '@abloatai/transaction/types/participant';
35
+ import type { QueuedMutation } from './transactions/mutations/MutationQueue.js';
36
+ import type { CommitLatencySample } from './transactions/mutations/commitLatency.js';
37
+ /** Constructor type for Model subclasses (accepts abstract classes) */
38
+ export type ModelConstructor<T extends Model> = abstract new (...args: never[]) => T;
39
+ /** Concrete constructor type for instantiation */
40
+ export type ConcreteModelConstructor<T extends Model> = new (data?: any) => T;
41
+ export type { ModelData } from '@abloatai/transaction/types/modelData';
42
+ /** Query result interface */
43
+ export interface QueryResult<T extends Model> {
44
+ data: T[];
45
+ total: number;
46
+ hasMore: boolean;
47
+ fromCache?: boolean;
48
+ }
49
+ export type { ForeignKeyIndexSpec, EnrichmentPlanEntry } from './sync/syncPlan.js';
50
+ /** Configuration for SyncedStore behavior */
51
+ export interface SyncedStoreConfig {
52
+ enableOffline?: boolean;
53
+ enableCache?: boolean;
54
+ enableTelemetry?: boolean;
55
+ /**
56
+ * Wire message types to surface as collaboration events, e.g.
57
+ * `['document:selection', 'document:cursor']`.
58
+ *
59
+ * The vocabulary belongs to the application, not the SDK — these name the
60
+ * application's own concepts, and a schema with no documents should never see
61
+ * them. Defaults to none, so an application opts in by naming the events it
62
+ * actually broadcasts.
63
+ */
64
+ collaborationEvents?: readonly string[];
65
+ /**
66
+ * Declarative enrichment plan consumed by `enrichRelations`. Replaces
67
+ * the subclass override of `enrichRelations` for per-model parent
68
+ * attachment. Merged with schema-derived entries (relations marked
69
+ * `{ enrich: true }` on `belongsTo`).
70
+ */
71
+ enrichmentPlan?: readonly EnrichmentPlanEntry[];
72
+ /**
73
+ * Foreign-key indexes to register on the InstanceCache at construction
74
+ * time. Replaces the subclass override of `registerForeignKeys` for
75
+ * per-model FK registration. Merged with schema-derived entries
76
+ * (relations marked `{ index: true }` on `belongsTo`). Both sets
77
+ * are registered before the legacy `registerForeignKeys()` hook
78
+ * fires, so subclasses can still add more on top.
79
+ */
80
+ foreignKeyIndexes?: readonly ForeignKeyIndexSpec[];
81
+ }
82
+ export type { SyncStatus } from './storeContract.js';
83
+ /** User context for initialization */
84
+ export interface UserContext {
85
+ userId: string;
86
+ organizationId: string;
87
+ /** Authenticated data-plane coordinates used to isolate local persistence. */
88
+ projectId?: string | null;
89
+ environment?: 'sandbox' | 'production' | null;
90
+ sandboxId?: string | null;
91
+ role?: string;
92
+ teamIds?: string[];
93
+ /** Participant kind on the wire. Default 'user' for browser
94
+ * sessions; 'agent' for headless bots / worker processes. The
95
+ * store routes this to SyncWebSocket so the WS URL carries
96
+ * `kind=agent` and the server applies capability-token auth. */
97
+ kind?: ParticipantKind;
98
+ /** Restricted (`rk_`) API key for `kind: 'agent'` — the agent's
99
+ * bearer credential. Sent in the `ablo.bearer.<token>` WebSocket
100
+ * subprotocol, never in the URL. */
101
+ capabilityToken?: string;
102
+ /** Server-authoritative sync groups, supplied by auth/capability
103
+ * exchange. The SDK does not invent org/user/default groups; app
104
+ * structure comes from schema-declared scopes and server-issued
105
+ * authorization. */
106
+ syncGroups?: readonly string[];
107
+ /**
108
+ * How aggressively this participant should pull baseline state at
109
+ * startup.
110
+ *
111
+ * - `'full'` (default): pull every delta in scope before `ready()`
112
+ * resolves. The standard browser/user replica behavior.
113
+ * - `'none'`: open the WebSocket and process live deltas only.
114
+ * Reads go through `model.get()` / filtered subscriptions
115
+ * backfilled by `Covering` deltas. Suitable for transactional
116
+ * participants — agent-worker, video-pipeline, routine runners —
117
+ * that don't need a local replica of the org's tenant plane.
118
+ */
119
+ bootstrapMode?: 'full' | 'none';
120
+ }
121
+ /** Smart sync options */
122
+ export interface SmartSyncOptions {
123
+ maxDeltasBeforeBootstrap?: number;
124
+ maxBootstrapSize?: number;
125
+ batchingDelay?: number;
126
+ maxBatchSize?: number;
127
+ }
128
+ export type { RehydrationStats } from './sync/bootstrapApply.js';
129
+ /**
130
+ * Bootstrap retry configuration.
131
+ *
132
+ * There is deliberately no overall timeout here. How long one attempt may run
133
+ * is not a policy this layer gets to invent — it is a property of the fetcher's
134
+ * watchdogs, read from `BootstrapFetcher.budgetMs`. A second number kept here
135
+ * would only be able to disagree with them, which is exactly what it used to do.
136
+ */
137
+ export declare const BOOTSTRAP_CONFIG: {
138
+ readonly MAX_RETRY_ATTEMPTS: 3;
139
+ readonly RETRY_DELAY_MS: 500;
140
+ };
141
+ export { ModelScope };
142
+ export type { SyncDelta, SyncGroupChangePayload, GroupAddedPayload, GroupRemovedPayload, BootstrapHint, BootstrapDataEvent, PresenceUpdate, };
143
+ export { deriveSyncPlanFromSchema } from './sync/syncPlan.js';
144
+ /**
145
+ * The abstract base class that application-specific sync stores extend. It
146
+ * carries the injected collaborators, the observable sync status, and the
147
+ * orchestration for initialization, delta processing, bootstrap, and the
148
+ * read and write API. A subclass supplies its own domain behavior by
149
+ * overriding the protected extension points defined here and by typing its
150
+ * collaboration events through the generic parameter.
151
+ *
152
+ * A subclass must call `super(dependencies, config)` and then set up its own
153
+ * MobX observables.
154
+ *
155
+ * Generic over `TCollaboration` — an app-defined event map for real-time
156
+ * collaboration events (cursors, selections, presence beyond the core set).
157
+ * Subclasses pass their own event map to get typed `subscribe()` calls on
158
+ * the underlying SyncWebSocket without casts:
159
+ *
160
+ * @example
161
+ * interface EditorEvents {
162
+ * 'document:selection': [SelectionEvent];
163
+ * 'document:cursor': [CursorEvent];
164
+ * }
165
+ * class EditorStore extends BaseSyncedStore<EditorEvents> {
166
+ * subscribeToCursor(handler: (e: CursorEvent) => void) {
167
+ * return this.syncWebSocket.subscribe('document:cursor', handler);
168
+ * }
169
+ * }
170
+ */
171
+ export declare class BaseSyncedStore<TCollaboration extends EventMap<TCollaboration> = DefaultCollaborationEvents, TSchema extends Schema = Schema> {
172
+ syncStatus: SyncStatus;
173
+ /** The owning client's runtime; the module-global bridge when constructed directly. */
174
+ protected readonly runtime: RuntimeContext;
175
+ /** The installed plugins the delta pipeline dispatches stage handlers to. */
176
+ protected readonly stagePlugins: readonly AbloPlugin[];
177
+ protected readonly syncClient: SyncClient;
178
+ protected readonly database: Database;
179
+ protected readonly objectPool: InstanceCache;
180
+ protected readonly modelRegistry: ModelRegistry;
181
+ protected readonly auth?: AuthCredentialSource;
182
+ /**
183
+ * Schema the store was constructed with. Used by the schema-typed
184
+ * `create(key, data)` factory and model self-healing.
185
+ */
186
+ protected readonly schema?: TSchema;
187
+ /**
188
+ * The connection, owned by whoever built this store (ADR 0016 follow-up
189
+ * 3b): the host constructs it and hands it in, the store seeds its late
190
+ * values during `initialize()` and owns the lifecycle from there. One
191
+ * instance for the store's whole lifetime — reconnects replace the socket
192
+ * inside it, never the object.
193
+ */
194
+ protected readonly syncWebSocket: SyncWebSocket<TCollaboration>;
195
+ /**
196
+ * Dynamic read interest (area-of-interest) over the connection's sync
197
+ * groups. Constructed with the connection; the permanent base scopes are
198
+ * seeded in `setupWebSocketSync` once identity resolves.
199
+ */
200
+ protected readonly areaOfInterest: SubscriptionManager;
201
+ /** Sync groups whose current state has been backfilled into the pool
202
+ * (hydrate-on-enter). Cleared when the pool is reset on (re)bootstrap. */
203
+ private readonly hydratedGroups;
204
+ /** In-flight scoped hydrations, keyed by group — single-flights concurrent
205
+ * enters of the same scope so they share one fetch. */
206
+ private readonly hydratingGroups;
207
+ private _syncServerUrl?;
208
+ /** Application-declared collaboration event types; empty unless configured. */
209
+ private _collaborationEvents;
210
+ /**
211
+ * Public accessor for the underlying SyncWebSocket. Used by the
212
+ * factory in `createSyncEngine` to wire the default mutation
213
+ * executor — the executor needs the WS handle to send commit
214
+ * frames, and the factory can't reach `protected` state through
215
+ * normal typing.
216
+ */
217
+ getSyncWebSocket(): SyncWebSocket<TCollaboration>;
218
+ /**
219
+ * Subscribe to pushed frames — deltas, presence updates, claim grants and
220
+ * losses, connection changes, and this store's collaboration events.
221
+ * Durable by construction: the connection object exists for the store's
222
+ * whole lifetime (reconnects replace only the socket inside it), so a
223
+ * subscription made before the first connect starts delivering when the
224
+ * socket opens and keeps delivering across every reconnect. Returns the
225
+ * unsubscribe function.
226
+ */
227
+ subscribe<K extends keyof SyncWebSocketEventMap<TCollaboration>>(event: K, handler: (...args: SyncWebSocketEventMap<TCollaboration>[K]) => void): () => void;
228
+ /**
229
+ * Send a collaboration event (an app-specific real-time message from this
230
+ * store's `TCollaboration` map). A no-op while the connection is down —
231
+ * presence-grade traffic is not queued.
232
+ */
233
+ sendCollaborationEvent<K extends string & keyof TCollaboration>(messageType: K, payload: TCollaboration[K] extends [infer P] ? Omit<P & Record<string, unknown>, 'timestamp'> : never): void;
234
+ private scopeToGroups;
235
+ /**
236
+ * Bring a scope into view and subscribe to its sync groups. With
237
+ * `{ hydrate: true }`, also backfill the groups' current state into the pool
238
+ * once the subscription is active. The order matters: subscribing first
239
+ * guarantees no live delta is missed in the gap before the snapshot lands.
240
+ * Hydration is best-effort — a failed backfill never rejects `enterScope`,
241
+ * and the live delta stream keeps flowing regardless.
242
+ */
243
+ enterScope(scope: ParticipantScope, opts?: {
244
+ hydrate?: boolean;
245
+ }): Promise<void>;
246
+ /**
247
+ * Backfill the current state of `syncGroups` into the pool with a side-effect-free
248
+ * scoped snapshot fetch followed by the version-guarded scoped apply. The call
249
+ * is idempotent (it skips groups already hydrated) and single-flight (concurrent
250
+ * enters of the same group share one fetch). On error the groups are left
251
+ * unmarked, so a later re-enter retries.
252
+ */
253
+ protected hydrateGroups(syncGroups: readonly string[]): Promise<void>;
254
+ /** Leave a scope → its groups go warm (hysteresis), then drop on sweep. */
255
+ leaveScope(scope: ParticipantScope): Promise<void>;
256
+ /** Pin a scope (active claim / prominence) → never warms while pinned. */
257
+ pinScope(scope: ParticipantScope): Promise<void>;
258
+ /** Release a pin → the group transitions to warm rather than dropping. */
259
+ unpinScope(scope: ParticipantScope): Promise<void>;
260
+ protected readonly queryProcessor: QueryProcessor;
261
+ /**
262
+ * Runtime behavior flags only — the schema/config arrays
263
+ * (`enrichmentPlan`, `foreignKeyIndexes`) are consumed at construction
264
+ * time and stored on the instance as `enrichmentPlan` and
265
+ * pool-registered indexes. They don't need to persist on `this.config`.
266
+ */
267
+ protected readonly config: Required<Pick<SyncedStoreConfig, 'enableOffline' | 'enableCache' | 'enableTelemetry'>>;
268
+ protected disposers: (() => void)[];
269
+ protected initialized: boolean;
270
+ protected dataReady: boolean;
271
+ protected userContext: UserContext | null;
272
+ /**
273
+ * Declarative enrichment plan: "for model X, when a delta arrives,
274
+ * read data[foreignKey] and attach the matching parent from the pool
275
+ * as data[relationKey]." Merged from schema-derived + config at
276
+ * construction time. Replaces the `enrichRelations` subclass override
277
+ * pattern.
278
+ */
279
+ protected enrichmentPlan: readonly EnrichmentPlanEntry[];
280
+ protected smartSyncOptions: Required<SmartSyncOptions>;
281
+ protected pendingDeltas: SyncDelta[];
282
+ protected batchTimer: ReturnType<typeof setTimeout> | null;
283
+ protected syncPromise: Promise<void> | null;
284
+ /** Resume/ack cursor — delegates to the shared LogPosition (see
285
+ * logPosition.ts). Advances only after IDB persistence. */
286
+ protected get lastAckedId(): number;
287
+ /** Pool-applied cursor — delegates to the shared LogPosition. */
288
+ protected get highestProcessedSyncId(): number;
289
+ protected bootstrapDeltaQueue: SyncDelta[] | null;
290
+ protected activeBootstrapCount: number;
291
+ /** The live deadline for the bootstrap attempt in flight, if any. */
292
+ private bootstrapDeadlineTimer;
293
+ protected pendingDeletes: Set<string>;
294
+ protected modelTypesHydrated: Set<string>;
295
+ protected modelTypeHydrationInFlight: Map<string, Promise<void>>;
296
+ constructor(dependencies: {
297
+ syncClient: SyncClient;
298
+ database: Database;
299
+ objectPool: InstanceCache;
300
+ modelRegistry: ModelRegistry;
301
+ /**
302
+ * The connection, built by the host. When omitted, the store constructs
303
+ * its own from `url` and the collaboration-event config — the
304
+ * self-contained path subclasses and tests use. Either way the store
305
+ * owns the lifecycle from here: it seeds the late values (identity,
306
+ * read scope, resume cursor) during `initialize()` and releases the
307
+ * first connect.
308
+ */
309
+ syncWebSocket?: SyncWebSocket<TCollaboration>;
310
+ /**
311
+ * Optional schema. When provided, {@link deriveSyncPlanFromSchema} walks
312
+ * the schema's models and relations to auto-populate foreign-key indexes
313
+ * and the enrichment plan from their declarative annotations. Subclasses
314
+ * that register model classes directly can instead pass explicit
315
+ * `config.foreignKeyIndexes` / `config.enrichmentPlan`.
316
+ */
317
+ schema?: TSchema;
318
+ /** Sync server URL for WebSocket connection. Converted to wss:// automatically. */
319
+ url?: string;
320
+ /** Shared bearer credential source for every auth-aware transport. */
321
+ auth?: AuthCredentialSource;
322
+ /** The owning client's runtime. Defaults to the module-global bridge. */
323
+ runtime?: RuntimeContext;
324
+ /**
325
+ * The installed plugins, whose declared stage handlers the delta
326
+ * pipeline dispatches. Empty on direct construction — the store's own
327
+ * apply is then the whole pipeline.
328
+ */
329
+ stagePlugins?: readonly AbloPlugin[];
330
+ }, config?: SyncedStoreConfig);
331
+ /**
332
+ * Register foreign-key indexes for constant-time lookups.
333
+ *
334
+ * This is an override hook. The preferred way to declare a foreign-key
335
+ * index is `config.foreignKeyIndexes` at construction time, or marking the
336
+ * `belongsTo` relation with `{ index: true }` in the schema. The hook fires
337
+ * after the schema-derived and config registrations, so a subclass can
338
+ * layer additional indexes on top.
339
+ */
340
+ protected registerForeignKeys(): void;
341
+ /**
342
+ * Enrich delta data with related models from the InstanceCache.
343
+ *
344
+ * Base implementation walks `this.enrichmentPlan` — entries populated
345
+ * from the schema's `{ enrich: true }` relations and from
346
+ * `config.enrichmentPlan`. Subclasses can still override for bespoke
347
+ * logic, calling `super.enrichRelations(modelName, data)` first to
348
+ * apply the declarative plan before layering on custom work.
349
+ *
350
+ * Enrichment is best-effort: if the parent isn't yet in the pool
351
+ * (e.g., a child delta arrives before its parent in a bootstrap
352
+ * batch), the entry is silently skipped and the data passes through
353
+ * untouched. The next delta for the same child will re-enrich.
354
+ */
355
+ protected enrichRelations(modelName: string, data: ModelData): ModelData;
356
+ /** Check if a model name represents a custom/dynamic entity type. */
357
+ protected isCustomEntity(modelName: string): boolean;
358
+ /** Create a custom entity instance from delta data. Override for domain-specific custom entities. */
359
+ protected createCustomEntity(_modelName: string, _modelId: string, _data: Record<string, unknown>): Model | null;
360
+ /** Called before save for domain-specific validation/self-healing. */
361
+ protected beforeSave(_model: Model): void;
362
+ /** Connection lifecycle event callback — set by subclass to wire connection state machine. */
363
+ protected onConnectionEvent?: (event: string) => void;
364
+ /**
365
+ * Internal connection FSM. Owns network probe + backoff + reconnect
366
+ * orchestration for the default path. Constructed lazily once we
367
+ * have a user context + a WebSocket (see `wireWebSocketEvents`);
368
+ * driven by the `onConnectionEvent` hook AND browser online/offline
369
+ * events it sets up itself.
370
+ *
371
+ * Every consumer gets production-grade offline-to-online recovery
372
+ * out of the box. Subclasses that want their own lifecycle owner
373
+ * can disable this by overriding `createConnectionManager()` to
374
+ * return null.
375
+ */
376
+ protected connectionManager: import('./sync/ConnectionManager.js').ConnectionManager | null;
377
+ /**
378
+ * Access-credential re-mint + proactive pre-roll — extracted to
379
+ * sync/credentialLifecycle.ts. Owns the refresher hook, the single-flight
380
+ * guard, and the browser-only refresh timer / wake listener; talks back
381
+ * through three lazily-resolved callbacks (the ConnectionManager doesn't
382
+ * exist until `setupWebSocketSync`). The `setCredentialRefresher` /
383
+ * `performCredentialRefresh` / `startCredentialLifecycle` methods below
384
+ * are thin delegates so the store's public surface is unchanged.
385
+ */
386
+ private readonly credentialLifecycle;
387
+ /**
388
+ * Listeners registered via `subscribeSessionError()`. Fired when the
389
+ * WebSocket closes with a session-invalid code (1008/4001/4003) or a
390
+ * session-error event is received. Separate from `onConnectionEvent`
391
+ * (which exists for the ConnectionStore FSM) so multiple consumers —
392
+ * typically `<AbloProvider>` and a connection-lifecycle owner — can
393
+ * both react without racing on the single-callback slot.
394
+ */
395
+ protected sessionErrorListeners: Set<(error: Error) => void>;
396
+ private readonly terminalSessionLifecycle;
397
+ /**
398
+ * Subscribe to session-error events. The returned function removes
399
+ * the listener. Safe to call multiple times from different consumers
400
+ * (each gets its own slot in the listener set).
401
+ */
402
+ subscribeSessionError(listener: (error: Error) => void): () => void;
403
+ /**
404
+ * Subscribe to per-mutation failure payloads. Forwarded from the
405
+ * underlying `SyncClient.mutationQueue` so consumers (toast layer,
406
+ * route-level reverted boundaries, telemetry) can react without
407
+ * reaching across the store. Returns an unsubscribe function.
408
+ *
409
+ * Why this lives on the base store rather than SyncClient: the React
410
+ * `<AbloProvider>` binds against this surface, so adding it here
411
+ * keeps the engine's internal wiring private while still giving the
412
+ * SDK a single hook to expose. Mirrors `subscribeSessionError` —
413
+ * same shape, same lifecycle.
414
+ */
415
+ subscribeMutationFailure(listener: (payload: {
416
+ transaction: QueuedMutation;
417
+ error: Error;
418
+ permanent?: boolean;
419
+ }) => void): () => void;
420
+ /**
421
+ * Subscribe to commit round-trip latency. Forwarded from the underlying
422
+ * `SyncClient` for the same reason as `subscribeMutationFailure` — the
423
+ * React provider binds against this surface, so the engine's wiring stays
424
+ * private while the SDK keeps one hook to expose.
425
+ */
426
+ subscribeCommitLatency(listener: (sample: CommitLatencySample) => void): () => void;
427
+ /**
428
+ * Wait for the in-flight transaction for (modelName, modelId) to be
429
+ * confirmed by the server. See `SyncClient.waitForConfirmation` for the
430
+ * lookup contract; resolves immediately if nothing is in flight.
431
+ */
432
+ waitForConfirmation(modelName: string, modelId: string): Promise<void>;
433
+ /**
434
+ * Observe the LOCAL mutation stream for undo recording (see
435
+ * {@link import('./storeContract.js').LocalMutation}). Taps the
436
+ * MutationQueue's `transaction:created` event — fired once per local
437
+ * create/update/delete/archive with `previousData` already captured.
438
+ * Remote/collaborator deltas apply via `applyDeltaBatchToPool` and never
439
+ * emit here, so undo is naturally local-only (you can't undo a teammate).
440
+ */
441
+ subscribeLocalMutations(handler: (mutation: LocalMutation) => void): () => void;
442
+ /**
443
+ * Execute a bootstrap function with timeout protection and automatic retry.
444
+ * Prevents the common issue where bootstrap hangs on startup.
445
+ */
446
+ protected executeBootstrapWithTimeout<T>(bootstrapFn: () => Promise<T>, _context: UserContext, signal?: AbortSignal): Promise<T>;
447
+ /**
448
+ * The outer deadline for one bootstrap attempt.
449
+ *
450
+ * The length is DERIVED from the fetcher's own watchdog budget, not chosen. A
451
+ * chosen number is what broke this: the previous fixed 15s was shorter than a
452
+ * single model chunk's allowance — 20s waiting for response headers plus 15s
453
+ * of stall grace — so on any workspace with one slow model the deadline fired
454
+ * before the watchdogs it was meant to backstop, and every attempt timed out
455
+ * by construction. The watchdogs below are progress-based and already
456
+ * guarantee termination; this deadline exists only for a hang somewhere other
457
+ * than the network, so it must sit above them, and it can only do that
458
+ * reliably by asking them how long they take.
459
+ *
460
+ * Reaching it aborts the work in flight. `Promise.race` merely stops waiting:
461
+ * without the abort the losing bootstrap keeps running, keeps its sockets, and
462
+ * races the retry that replaced it — which is how one page load turned into
463
+ * dozens of overlapping requests.
464
+ */
465
+ protected createBootstrapTimeout(attempt: number): Promise<never>;
466
+ /** Disarm the deadline once its attempt has settled. Load-bearing now that
467
+ * firing it aborts real work: a leftover timer would cancel a later,
468
+ * unrelated bootstrap. */
469
+ private clearBootstrapDeadline;
470
+ /** Reset bootstrap-related state for a clean retry */
471
+ protected resetBootstrapState(): void;
472
+ /** Perform reconnect: bootstrap + WS reconnect. Returns outcome for state machine. */
473
+ performReconnect(): Promise<'success' | 'session_error' | 'network_error'>;
474
+ /**
475
+ * Register the access-credential re-mint hook. Called by the React provider
476
+ * with a thunk that mints a fresh `ek_`/`rk_` (typically its `getToken`).
477
+ * See {@link CredentialLifecycle.setRefresher}.
478
+ */
479
+ setCredentialRefresher(refresher: CredentialRefresher | null): void;
480
+ /**
481
+ * Re-mint the short-lived access credential and push it into the credential
482
+ * source, reporting a tri-state outcome the {@link ConnectionManager} maps to
483
+ * its FSM. Single-flight; no refresher wired ⇒ `'refreshed'` (a no-op
484
+ * re-probe). Full contract on {@link CredentialLifecycle.refresh}.
485
+ */
486
+ performCredentialRefresh(): Promise<'refreshed' | 'session_error' | 'network_error'>;
487
+ /**
488
+ * The authentication-recovery path for HTTP transports, such as the lazy
489
+ * query lane. It runs a single-flight credential re-mint driven by the
490
+ * rejection's recovery class, routing outcomes through the same state
491
+ * machine the WebSocket probe uses. `'retry'` means a fresh credential is
492
+ * now in the credential source and the request should be replayed once.
493
+ * Full contract on {@link CredentialLifecycle.recoverFromAuthRejection}.
494
+ */
495
+ recoverFromAuthRejection(recovery: RecoveryClass): Promise<'retry' | 'stop'>;
496
+ /**
497
+ * Nudge the connection FSM to re-probe with the current credential. Idempotent
498
+ * and safe in any state (ignored while `connected`). Call after pushing a
499
+ * freshly-minted token via `setAuthToken`, or on an OS-wake signal, so a
500
+ * connection parked in `offline` / `backoff` / `auth_blocked` picks the new
501
+ * credential up immediately instead of waiting for the 30s watchdog.
502
+ */
503
+ nudgeReconnect(): void;
504
+ /**
505
+ * Install the client-owned access-credential lifecycle: register `getToken`
506
+ * as the reactive re-mint hook and arm the browser-only proactive refresh
507
+ * (a refresh timer plus an OS-wake re-mint). Idempotent — a second call
508
+ * replaces the first — and torn down on {@link disconnect}. Full rationale
509
+ * on {@link CredentialLifecycle.start}.
510
+ */
511
+ startCredentialLifecycle(getToken: CredentialRefresher, opts?: {
512
+ proactiveInNode?: boolean;
513
+ }): void;
514
+ /** Tear down the proactive credential lifecycle (idempotent). */
515
+ private stopCredentialLifecycle;
516
+ /** Narrow context the group-change leaf talks back through. */
517
+ private groupChangeContext;
518
+ /**
519
+ * Handle an actionType 'G' delta — incremental `{ group, userId }` or
520
+ * legacy `{ addedGroups, removedGroups }` payloads. Full pathway doc on
521
+ * {@link groupChange.handleSyncGroupChange}.
522
+ */
523
+ protected handleSyncGroupChange(delta: SyncDelta): Promise<void>;
524
+ /**
525
+ * Handle an incremental GroupAdded delta — metadata only, no re-bootstrap
526
+ * (covering deltas bring the entities). See {@link groupChange.handleGroupAdded}.
527
+ */
528
+ protected handleGroupAdded(payload: GroupAddedPayload, syncId: number): Promise<void>;
529
+ /**
530
+ * Handle an actionType 'S' (GroupRemoved) delta: for safety, clear the
531
+ * revoked local state and trigger a full re-bootstrap. See
532
+ * {@link groupChange.handleGroupRemoved}.
533
+ */
534
+ protected handleGroupRemoved(delta: SyncDelta): Promise<void>;
535
+ /** Compute new sync groups after applying additions and removals */
536
+ protected computeUpdatedSyncGroups(payload: SyncGroupChangePayload): string[];
537
+ /** Force a full re-bootstrap via connection lifecycle event (no-op for
538
+ * `bootstrapMode: 'none'` participants — see {@link groupChange.forceFullRebootstrap}). */
539
+ protected forceFullRebootstrap(): void;
540
+ /**
541
+ * Single source of truth for the sync-group list this session is
542
+ * subscribed to. Server-issued (`context.syncGroups`) is authoritative.
543
+ * When absent, the SDK subscribes to no explicit groups. Both
544
+ * `checkSyncGroupShrinkage` and `setupWebSocketSync` resolve through
545
+ * here so the WS subscription and the security-critical shrinkage
546
+ * check can never disagree.
547
+ */
548
+ protected resolveSyncGroups(context: UserContext): readonly string[];
549
+ /** Check if sync groups shrank since last session — force full bootstrap if so */
550
+ protected checkSyncGroupShrinkage(): Promise<void>;
551
+ /** Narrow context the bootstrap-apply leaf talks back through. */
552
+ private poolContext;
553
+ /** Apply bootstrap data to the {@link InstanceCache}, removing entities that are no longer present (ghost removal). Pool writes are delegated to {@link SyncClient}. */
554
+ protected applyBootstrapToPool(bootstrapResult: BootstrapResult, protectedIds?: ReadonlySet<string>): RehydrationStats;
555
+ /**
556
+ * Initialize the sync engine with user context.
557
+ * Offline-first: hydrate from IDB → show UI → bootstrap from server in background.
558
+ */
559
+ initialize(context: UserContext, signal?: AbortSignal): Generator<Promise<void | number | boolean | BootstrapRequirements>, {
560
+ success: boolean;
561
+ error?: Error;
562
+ }, void | number | boolean | BootstrapRequirements>;
563
+ /** Background bootstrap — non-blocking, user sees cached data while this runs */
564
+ protected performBackgroundBootstrap(requirements: Awaited<ReturnType<typeof this.database.requiredBootstrap>>, context: UserContext, signal?: AbortSignal): Promise<void>;
565
+ /** Run bootstrap with delta queuing to prevent race conditions */
566
+ protected withDeltaQueuing<T>(fn: () => Promise<T>): Promise<T>;
567
+ /** Collect IDs that must survive ghost removal (added by deltas during bootstrap) */
568
+ protected collectDeltaProtectedIds(preBootstrapIds: ReadonlySet<string>): Set<string>;
569
+ /** Replay deltas queued during bootstrap (atomically, via `applyDeltaFrame`). */
570
+ protected replayQueuedDeltas(): void;
571
+ protected createConnectionManager(kind?: ParticipantKind): ConnectionManager | null;
572
+ /**
573
+ * Disconnect and clean up all resources. Terminal: this means "the client
574
+ * is finished", not "close and reopen later" — the connection object stays
575
+ * assigned but closed, the event wiring is torn down, and nothing
576
+ * re-initializes a disconnected store. (Mid-session closes during recovery
577
+ * go through the connection FSM's `onDisconnectWebSocket`, which closes
578
+ * the transport without touching the store.)
579
+ */
580
+ disconnect(): Promise<void>;
581
+ /** Stop access and await deletion of this identity's local state. */
582
+ purge(): Promise<void>;
583
+ /**
584
+ * Create WebSocket connection and wire all event handlers.
585
+ * Handles: deltas, batches, presence, bootstrap_required, errors, reconnection.
586
+ */
587
+ /**
588
+ * Block until the WebSocket reports a `connected` event, or until
589
+ * `timeoutMs` elapses (returns false on timeout, true on connect).
590
+ * Used by `initialize()` for `bootstrapMode: 'none'` consumers to
591
+ * honor `ready()`'s "WS is connected when this resolves" contract
592
+ * — `setupWebSocketSync` is fire-and-forget on the upgrade, and
593
+ * without an explicit wait the next mutation can race the open.
594
+ *
595
+ * Resolves immediately if the WS is already connected (e.g., warm
596
+ * reconnect after redeploy). Resolves false on timeout rather than
597
+ * throwing so initialize() can complete and let the caller's first
598
+ * mutation attempt surface a clearer error.
599
+ */
600
+ protected waitForWebSocketConnected(timeoutMs: number): Promise<boolean>;
601
+ /**
602
+ * Seed the connection's late values and open it. The socket itself exists
603
+ * from construction; what identity resolution supplies — the participant
604
+ * kind, the credential, the read scope, and the resume cursor — is seeded
605
+ * here, and only then is the held first connect released. A retried
606
+ * `initialize()` after a failed `ready()` re-runs this against the same
607
+ * connection object: the reconnect counter is reset for a clean slate,
608
+ * while the session-error latch deliberately survives (only the
609
+ * credential-expiry recovery clears it).
610
+ */
611
+ protected setupWebSocketSync(context: UserContext, lastSyncId: number): void;
612
+ /**
613
+ * Wire the store's handlers onto the connection. Runs once, at
614
+ * construction — the connection object is stable for the store's
615
+ * lifetime, so the wiring is too.
616
+ */
617
+ protected wireSocketEvents(): void;
618
+ /**
619
+ * Build and start the connection FSM. The `onConnectionEvent` hook is the
620
+ * bridge — WS events fire the hook, the hook forwards into the FSM. Called
621
+ * from `setupWebSocketSync` because the FSM's shape depends on the resolved
622
+ * participant kind (agents get none — see {@link createConnectionManager}).
623
+ */
624
+ private startConnectionManager;
625
+ /** Memoized pipeline context — `enqueueDelta` runs once per delta, so the
626
+ * accessor object is built once and reused (the get/set accessors always
627
+ * read the live host fields). */
628
+ private _deltaPipelineContext;
629
+ private get deltaPipelineContext();
630
+ /**
631
+ * Lands persisted changes in the in-memory pool, with this store's
632
+ * relation enrichment bound. The one apply path: the pipeline's bridge
633
+ * (no plugins installed) and the `humans()` apply handler both call it.
634
+ */
635
+ applyChangesToPool(changes: readonly AppliedChange[]): void;
636
+ /** Get fields that represent meaningful state for deduplication. Override for model-specific fields. */
637
+ protected getStateFields(_modelName: string): string[];
638
+ /** Deduplicate deltas to the same entity — keep meaningful state transitions only */
639
+ protected deduplicateDeltas(deltas: SyncDelta[]): SyncDelta[];
640
+ /** Process incoming delta with smart batching */
641
+ protected processDeltaWithBatching(delta: SyncDelta): void;
642
+ /**
643
+ * Apply a complete, server-delivered delta frame atomically.
644
+ *
645
+ * A `delta_batch` WebSocket event (a reconnect or catch-up replay) already
646
+ * carries the full set of missed deltas. Routing it through the per-delta
647
+ * `processDeltaWithBatching` path would re-chunk it via the live-traffic
648
+ * debounce timer and `maxBatchSize` force-flush, so a 300-delta catch-up
649
+ * would fan out into several separate `flushPendingDeltas` cycles — each its
650
+ * own local write, pool mutation, `models:changed` emit, and re-render, so
651
+ * the UI visibly repaints once per chunk.
652
+ *
653
+ * Instead, this runs the per-delta bookkeeping (deduplication, ack, version
654
+ * vector, watermark, group-change routing, delete cascade) for every delta
655
+ * without scheduling a flush, then flushes once — collapsing the whole frame
656
+ * into a single local write, pool mutation, `models:changed` emit, and
657
+ * re-render. The post-bootstrap replay of deltas queued during bootstrap
658
+ * uses the same path.
659
+ *
660
+ * It is named `applyDeltaFrame`, not `processDeltaBatch`, to avoid confusion
661
+ * with {@link Database.processDeltaBatch} — the lower-level local write this
662
+ * eventually drives through `flushPendingDeltas`.
663
+ */
664
+ protected applyDeltaFrame(deltas: SyncDelta[]): void;
665
+ /**
666
+ * Per-delta bookkeeping + enqueue. Returns `true` when the delta was
667
+ * pushed onto `pendingDeltas` (a regular batchable I/U/C/D delta that a
668
+ * subsequent flush must drain), `false` when it was skipped (dedup),
669
+ * deferred (bootstrap queue), or handled immediately out-of-band (G/S
670
+ * sync-group mutations). Does NOT schedule a flush — callers decide
671
+ * whether to debounce (live) or flush atomically (catch-up frame).
672
+ */
673
+ protected enqueueDelta(delta: SyncDelta, options?: {
674
+ authoritative?: boolean;
675
+ }): boolean;
676
+ /** Debounce a flush for live single-delta traffic. */
677
+ protected scheduleDeltaFlush(): void;
678
+ /**
679
+ * Cancel pending transactions for child entities when a parent is deleted.
680
+ *
681
+ * Uses `pool.getByForeignKey` (O(1) via the FK index registered at
682
+ * schema build time) to find children. The previous implementation did
683
+ * `getByType(ctor).filter(e => e.toJSON()[foreignKey] === parentId)` —
684
+ * a full pool scan per child model + a `toJSON()` allocation per
685
+ * candidate. For a report delete with 10K blocks in the pool, that was
686
+ * 10K toJSON allocations per cascade level. The FK-indexed lookup
687
+ * skips both the scan AND the allocation.
688
+ */
689
+ protected cascadeCancelTransactionsForDeletedParent(parentModelName: string, parentId: string): void;
690
+ /** Flush pending deltas with deduplication. Pool writes are delegated to {@link SyncClient}. */
691
+ protected flushPendingDeltas(): Promise<void>;
692
+ /** Check if a model type is local-only (no sync). Override for domain-specific models. */
693
+ protected isLocalOnlyModel(_modelName: string): boolean;
694
+ /** Validate model against schema before save */
695
+ protected validateModel(model: Model): void;
696
+ /**
697
+ * Save a model (create or update).
698
+ *
699
+ * Accepts any entity shape with `{ id: string }` so consumers can pass the
700
+ * Zod-inferred model types from `Model<Schema, K>` without knowing
701
+ * about the internal `Model` base class. At runtime, every entity reaching
702
+ * this method came through the object pool (via `store.create`, a query
703
+ * accessor, or an optimistic insert) and IS a `Model` instance — the one
704
+ * cast below preserves that invariant inside the SDK.
705
+ */
706
+ save<T extends {
707
+ id: string;
708
+ createdAt?: Date;
709
+ updatedAt?: Date;
710
+ }>(entity: T, options?: {
711
+ skipValidation?: boolean;
712
+ }): Promise<void>;
713
+ /** Save with an atomic server mutation (e.g., createSectionWithBlocks) */
714
+ saveWithAtomicMutation(model: Model, mutation: (gql: unknown) => Promise<unknown>): Promise<void>;
715
+ /** Delete a model. Accepts schema-inferred entity shapes (see `save`). */
716
+ delete<T extends {
717
+ id: string;
718
+ }>(entity: T): Promise<void>;
719
+ /** Archive a model. Accepts schema-inferred entity shapes (see `save`). */
720
+ archive<T extends {
721
+ id: string;
722
+ archivedAt?: Date | null;
723
+ }>(entity: T): Promise<void>;
724
+ /** Unarchive a model. Accepts schema-inferred entity shapes (see `save`). */
725
+ unarchive<T extends {
726
+ id: string;
727
+ archivedAt?: Date | null;
728
+ }>(entity: T): Promise<void>;
729
+ /** Retrieve a single entity by id. Synchronous pool read. */
730
+ retrieve(_modelClass: ModelConstructor<Model>, id: string): Model | undefined;
731
+ /** Find any entity by ID regardless of type */
732
+ findAnyById(id: string): Model | undefined;
733
+ /**
734
+ * Lookup a model by ID alone. Matches the `SyncStoreRef.getById` contract
735
+ * that schema-defined computeds use when they need to resolve a related
736
+ * entity without holding onto its constructor.
737
+ */
738
+ getById(id: string): Model | undefined;
739
+ /**
740
+ * Create a model instance locally, typed via the schema.
741
+ *
742
+ * ```ts
743
+ * const ledger = store.create('ledgers', { name, reportId });
744
+ * // ledger: Ledger | null — no cast needed
745
+ * ```
746
+ *
747
+ * The `typename` arg is the schema key (camelCase plural, e.g.
748
+ * `'ledgers'`); the returned instance has the
749
+ * `Model<Schema, K>` shape including computeds + relation accessors.
750
+ * Wraps `pool.create(...)` — the underlying runtime is unchanged, just
751
+ * type-narrowed.
752
+ */
753
+ create<K extends keyof TSchema['models'] & string>(typename: K, data: Record<string, unknown>): import('@abloatai/transaction/schema/schema').Model<TSchema, K> | null;
754
+ /**
755
+ * Query entry point for callers that hold a {@link Model} constructor and an
756
+ * options object. It filters, orders, and paginates the matching models from
757
+ * the pool. Prefer the schema-typed read surface (`ablo.<model>.list`) where
758
+ * you can, since it infers concrete row types without a class value or cast.
759
+ */
760
+ queryByClass(modelClass: ModelConstructor<Model>, options?: {
761
+ predicate?: (model: Model) => boolean;
762
+ state?: ModelScope;
763
+ orderBy?: keyof Model;
764
+ order?: 'asc' | 'desc';
765
+ limit?: number;
766
+ offset?: number;
767
+ }): QueryResult<Model>;
768
+ /**
769
+ * Get all models of a type. Returns Model[] honestly — callers that need
770
+ * narrow types should use `useAblo((ablo) => ablo.<model>.list(...))`
771
+ * which does proper inference via `Model<S, K>`.
772
+ */
773
+ allModelsOfType(modelClass: ModelConstructor<Model>, scope?: ModelScope): Model[];
774
+ /** Error handler for fire-and-forget flushPendingDeltas calls */
775
+ protected handleFlushError: (error: unknown) => void;
776
+ /** Process a single delta (used for immediate DELETE processing). Override for domain-specific handling. */
777
+ protected processDelta(delta: SyncDelta): Promise<void>;
778
+ /** Handle bootstrap_required event */
779
+ protected handleBootstrapRequired(_hint: BootstrapHint): void;
780
+ /** Handle bootstrap_data event. Override in subclass. */
781
+ protected handleBootstrapData(_data: BootstrapDataEvent): void;
782
+ /** Handle presence_update event. Override in subclass. */
783
+ protected handlePresenceUpdate(_data: PresenceUpdate): void;
784
+ protected incrementPendingChanges(): void;
785
+ protected decrementPendingChanges(): void;
786
+ protected updateSyncStatus(updates: Partial<SyncStatus>): void;
787
+ get pool(): InstanceCache;
788
+ get lastSyncId(): number;
789
+ get isReady(): boolean;
790
+ get isSyncing(): boolean;
791
+ get isOffline(): boolean;
792
+ get isReconnecting(): boolean;
793
+ get isError(): boolean;
794
+ get hasUnsyncedChanges(): boolean;
795
+ /** The SyncWebSocket handle — for collaboration events. */
796
+ get ws(): SyncWebSocket<TCollaboration> | null;
797
+ /** The Database instance — for demand loaders and direct IDB operations. */
798
+ get db(): Database;
799
+ /** The SyncClient instance — for assignment operations and other direct sync actions. */
800
+ get sc(): SyncClient;
801
+ /** The current organization ID — from the last initialize() call. */
802
+ get orgId(): string | undefined;
803
+ /** Count models matching a predicate. */
804
+ count(modelClass: ModelConstructor<Model>, predicate?: (m: Model) => boolean): number;
805
+ /** Get entities by foreign key (used by Model subclasses via Model.store) */
806
+ getByForeignKey(modelName: string, foreignKey: string, id: string): Model[];
807
+ }