@abloatai/ablo 0.34.1 → 0.35.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 (483) hide show
  1. package/AGENTS.md +2 -1
  2. package/CHANGELOG.md +674 -5
  3. package/README.md +39 -22
  4. package/dist/BaseSyncedStore.d.ts +152 -44
  5. package/dist/BaseSyncedStore.js +300 -184
  6. package/dist/Database.d.ts +9 -24
  7. package/dist/Database.js +37 -22
  8. package/dist/InstanceCache.d.ts +25 -4
  9. package/dist/InstanceCache.js +48 -15
  10. package/dist/LazyReferenceCollection.d.ts +3 -3
  11. package/dist/LazyReferenceCollection.js +4 -4
  12. package/dist/Model.d.ts +6 -6
  13. package/dist/Model.js +10 -10
  14. package/dist/ModelRegistry.d.ts +4 -4
  15. package/dist/ModelRegistry.js +3 -3
  16. package/dist/{SyncEngineContext.d.ts → RuntimeContext.d.ts} +20 -13
  17. package/dist/{SyncEngineContext.js → RuntimeContext.js} +11 -12
  18. package/dist/SyncClient.d.ts +42 -32
  19. package/dist/SyncClient.js +166 -110
  20. package/dist/ai-sdk/coordinatedTool.d.ts +2 -2
  21. package/dist/ai-sdk/coordinatedTool.js +1 -1
  22. package/dist/ai-sdk/coordinationContext.d.ts +2 -2
  23. package/dist/ai-sdk/coordinationContext.js +1 -1
  24. package/dist/ai-sdk/wrap.d.ts +3 -3
  25. package/dist/ai-sdk/wrap.js +2 -2
  26. package/dist/auth/index.d.ts +1 -156
  27. package/dist/auth/index.js +8 -301
  28. package/dist/cli.cjs +3344 -1073
  29. package/dist/client/Ablo.d.ts +42 -287
  30. package/dist/client/Ablo.js +118 -963
  31. package/dist/client/abloClient.d.ts +309 -0
  32. package/dist/client/abloClient.js +13 -0
  33. package/dist/client/clientPrelude.d.ts +52 -0
  34. package/dist/client/clientPrelude.js +60 -0
  35. package/dist/client/consoleLogger.d.ts +2 -2
  36. package/dist/client/coreClient.d.ts +60 -0
  37. package/dist/client/coreClient.js +118 -0
  38. package/dist/client/createInternalComponents.d.ts +4 -4
  39. package/dist/client/createInternalComponents.js +9 -8
  40. package/dist/client/createModelProxy.d.ts +78 -373
  41. package/dist/client/createModelProxy.js +114 -86
  42. package/dist/client/humans.d.ts +48 -0
  43. package/dist/client/humans.js +52 -0
  44. package/dist/client/modelRegistration.d.ts +1 -1
  45. package/dist/client/modelRegistration.js +9 -9
  46. package/dist/client/options.d.ts +73 -17
  47. package/dist/client/reactiveEngine.d.ts +48 -0
  48. package/dist/client/reactiveEngine.js +910 -0
  49. package/dist/client/resourceTypes.d.ts +9 -250
  50. package/dist/client/resourceTypes.js +8 -5
  51. package/dist/client/schemaConfig.d.ts +4 -4
  52. package/dist/client/schemaConfig.js +6 -2
  53. package/dist/client/validateAbloOptions.d.ts +3 -2
  54. package/dist/client/validateAbloOptions.js +1 -1
  55. package/dist/client/wsMutationExecutor.d.ts +3 -3
  56. package/dist/client/wsMutationExecutor.js +3 -3
  57. package/dist/context.d.ts +9 -9
  58. package/dist/context.js +10 -9
  59. package/dist/coordination/ClaimLog.d.ts +26 -0
  60. package/dist/coordination/ClaimLog.js +32 -0
  61. package/dist/coordination/index.d.ts +1 -15
  62. package/dist/coordination/index.js +8 -31
  63. package/dist/core/DatabaseManager.js +1 -1
  64. package/dist/core/QueryView.d.ts +1 -1
  65. package/dist/core/QueryView.js +1 -1
  66. package/dist/core/StoreManager.d.ts +4 -23
  67. package/dist/core/StoreManager.js +5 -55
  68. package/dist/core/index.d.ts +2 -2
  69. package/dist/core/index.js +2 -2
  70. package/dist/core/storeContract.d.ts +2 -2
  71. package/dist/docs/catalog.d.ts +72 -0
  72. package/dist/docs/catalog.js +227 -0
  73. package/dist/docs/index.d.ts +10 -0
  74. package/dist/docs/index.js +10 -0
  75. package/dist/environment.d.ts +1 -40
  76. package/dist/environment.js +8 -37
  77. package/dist/index.d.ts +40 -34
  78. package/dist/index.js +26 -20
  79. package/dist/interfaces/index.d.ts +44 -134
  80. package/dist/keys/index.d.ts +1 -77
  81. package/dist/keys/index.js +8 -190
  82. package/dist/mutators/{RecordingTransaction.d.ts → RecordingMutation.d.ts} +4 -4
  83. package/dist/mutators/{RecordingTransaction.js → RecordingMutation.js} +2 -2
  84. package/dist/mutators/Transaction.d.ts +1 -1
  85. package/dist/mutators/Transaction.js +1 -1
  86. package/dist/mutators/UndoManager.d.ts +6 -6
  87. package/dist/mutators/UndoManager.js +5 -5
  88. package/dist/mutators/defineMutators.d.ts +3 -3
  89. package/dist/mutators/defineMutators.js +1 -1
  90. package/dist/mutators/inverseOp.js +2 -2
  91. package/dist/mutators/mutateActions.d.ts +3 -3
  92. package/dist/mutators/mutateActions.js +1 -1
  93. package/dist/mutators/readerActions.d.ts +1 -1
  94. package/dist/mutators/undoApply.d.ts +1 -1
  95. package/dist/mutators/undoApply.js +1 -1
  96. package/dist/policy/index.d.ts +2 -2
  97. package/dist/policy/index.js +1 -1
  98. package/dist/query/client.d.ts +2 -2
  99. package/dist/query/client.js +4 -4
  100. package/dist/query/types.d.ts +6 -41
  101. package/dist/query/types.js +2 -2
  102. package/dist/react/AbloProvider.d.ts +6 -8
  103. package/dist/react/AbloProvider.js +5 -7
  104. package/dist/react/context.d.ts +1 -1
  105. package/dist/react/context.js +1 -1
  106. package/dist/react/index.d.ts +5 -5
  107. package/dist/react/index.js +3 -3
  108. package/dist/react/internalContext.d.ts +1 -1
  109. package/dist/react/useAblo.d.ts +3 -3
  110. package/dist/react/useAblo.js +1 -1
  111. package/dist/react/useCurrentUserId.js +1 -1
  112. package/dist/react/useErrorListener.js +1 -1
  113. package/dist/react/useMutationFailureListener.d.ts +2 -2
  114. package/dist/react/useMutationFailureListener.js +1 -1
  115. package/dist/react/useMutators.d.ts +3 -3
  116. package/dist/react/useMutators.js +3 -3
  117. package/dist/react/useUndoScope.d.ts +5 -5
  118. package/dist/react/useUndoScope.js +1 -1
  119. package/dist/schema/coordination.d.ts +69 -10
  120. package/dist/schema/coordination.js +86 -9
  121. package/dist/schema/ddl.js +2 -2
  122. package/dist/schema/diff.d.ts +1 -1
  123. package/dist/schema/generate.js +1 -1
  124. package/dist/schema/index.d.ts +10 -10
  125. package/dist/schema/index.js +18 -18
  126. package/dist/schema/queries.d.ts +27 -27
  127. package/dist/schema/queries.js +23 -23
  128. package/dist/schema/select.d.ts +3 -3
  129. package/dist/schema/select.js +3 -3
  130. package/dist/schema/serialize.d.ts +15 -6
  131. package/dist/schema/serialize.js +17 -3
  132. package/dist/schema/sugar.d.ts +6 -7
  133. package/dist/schema/sugar.js +9 -12
  134. package/dist/schema/syncDeltaRow.d.ts +4 -152
  135. package/dist/schema/syncDeltaRow.js +4 -105
  136. package/dist/server/adapter.d.ts +18 -1
  137. package/dist/server/commit.d.ts +10 -16
  138. package/dist/server/index.d.ts +1 -1
  139. package/dist/server/index.js +1 -1
  140. package/dist/server/readConfig.d.ts +1 -1
  141. package/dist/source/adapters/drizzle.d.ts +1 -1
  142. package/dist/source/adapters/drizzle.js +2 -2
  143. package/dist/source/adapters/kysely.d.ts +1 -1
  144. package/dist/source/adapters/kysely.js +1 -1
  145. package/dist/source/adapters/kyselyMutationCore.d.ts +1 -1
  146. package/dist/source/adapters/kyselyMutationCore.js +2 -2
  147. package/dist/source/adapters/memory.js +1 -1
  148. package/dist/source/adapters/prisma.d.ts +8 -3
  149. package/dist/source/adapters/prisma.js +1 -1
  150. package/dist/source/connector.js +1 -1
  151. package/dist/source/connectorProtocol.d.ts +2 -8
  152. package/dist/source/connectorProtocol.js +3 -2
  153. package/dist/source/contract.d.ts +29 -17
  154. package/dist/source/contract.js +27 -22
  155. package/dist/source/factory.d.ts +1 -1
  156. package/dist/source/footprint.d.ts +111 -0
  157. package/dist/source/footprint.js +0 -0
  158. package/dist/source/idempotency.js +2 -2
  159. package/dist/source/index.d.ts +1 -0
  160. package/dist/source/index.js +3 -0
  161. package/dist/source/next.d.ts +1 -1
  162. package/dist/source/signing.d.ts +9 -2
  163. package/dist/source/signing.js +4 -1
  164. package/dist/source/types.d.ts +6 -4
  165. package/dist/source/types.js +1 -1
  166. package/dist/stores/ObjectStore.d.ts +1 -1
  167. package/dist/stores/SyncActionStore.d.ts +1 -1
  168. package/dist/stores/SyncActionStore.js +2 -10
  169. package/dist/stores/syncAction.d.ts +26 -0
  170. package/dist/stores/syncAction.js +16 -0
  171. package/dist/surface.d.ts +3 -3
  172. package/dist/surface.js +6 -4
  173. package/dist/sync/BootstrapFetcher.d.ts +123 -6
  174. package/dist/sync/BootstrapFetcher.js +492 -66
  175. package/dist/sync/ConnectionManager.d.ts +6 -198
  176. package/dist/sync/ConnectionManager.js +6 -677
  177. package/dist/sync/OnDemandLoader.d.ts +2 -2
  178. package/dist/sync/OnDemandLoader.js +60 -21
  179. package/dist/sync/SubscriptionManager.d.ts +13 -2
  180. package/dist/sync/SubscriptionManager.js +23 -5
  181. package/dist/sync/SyncWebSocket.d.ts +27 -510
  182. package/dist/sync/SyncWebSocket.js +76 -954
  183. package/dist/sync/awaitClaimGrant.d.ts +4 -44
  184. package/dist/sync/awaitClaimGrant.js +4 -109
  185. package/dist/sync/commitFrames.d.ts +6 -40
  186. package/dist/sync/commitFrames.js +6 -97
  187. package/dist/sync/contextPorts.d.ts +18 -0
  188. package/dist/sync/contextPorts.js +31 -0
  189. package/dist/sync/createClaimStream.d.ts +5 -49
  190. package/dist/sync/createClaimStream.js +5 -469
  191. package/dist/sync/createPresenceStream.d.ts +26 -4
  192. package/dist/sync/createPresenceStream.js +28 -20
  193. package/dist/sync/createSnapshot.d.ts +2 -2
  194. package/dist/sync/createSnapshot.js +1 -1
  195. package/dist/sync/credentialLifecycle.d.ts +5 -173
  196. package/dist/sync/credentialLifecycle.js +5 -320
  197. package/dist/sync/deltaPipeline.d.ts +1 -1
  198. package/dist/sync/participants.d.ts +5 -4
  199. package/dist/sync/participants.js +29 -22
  200. package/dist/sync/schemaDrift.d.ts +55 -0
  201. package/dist/sync/schemaDrift.js +53 -0
  202. package/dist/sync/schemas.d.ts +21 -32
  203. package/dist/sync/schemas.js +26 -17
  204. package/dist/sync/syncPlan.d.ts +3 -3
  205. package/dist/sync/wsFrameHandlers.d.ts +6 -114
  206. package/dist/sync/wsFrameHandlers.js +6 -392
  207. package/dist/testing/fixtures/bootstrap.d.ts +1 -1
  208. package/dist/testing/fixtures/deltas.d.ts +1 -1
  209. package/dist/testing/fixtures/httpResponses.d.ts +70 -0
  210. package/dist/testing/fixtures/httpResponses.js +90 -0
  211. package/dist/testing/fixtures/models.js +1 -1
  212. package/dist/testing/helpers/wait.js +1 -1
  213. package/dist/testing/mocks/MockMutationExecutor.d.ts +2 -2
  214. package/dist/testing/mocks/MockMutationExecutor.js +8 -14
  215. package/dist/testing/mocks/MockSyncContext.d.ts +11 -11
  216. package/dist/testing/mocks/MockSyncContext.js +10 -9
  217. package/dist/testing/mocks/MockSyncStore.js +1 -1
  218. package/dist/testing/mocks/MockWebSocket.d.ts +2 -2
  219. package/dist/transaction/ablo.d.ts +88 -0
  220. package/dist/transaction/ablo.js +33 -0
  221. package/dist/{client/auth.d.ts → transaction/auth/apiKey.d.ts} +43 -8
  222. package/dist/{client/auth.js → transaction/auth/apiKey.js} +19 -0
  223. package/dist/transaction/auth/bootstrapScope.d.ts +15 -0
  224. package/dist/transaction/auth/bootstrapScope.js +1 -0
  225. package/dist/transaction/auth/capability.d.ts +177 -0
  226. package/dist/transaction/auth/capability.js +199 -0
  227. package/dist/{auth → transaction/auth}/credentialSource.d.ts +8 -1
  228. package/dist/{client → transaction/auth}/identity.d.ts +8 -7
  229. package/dist/{client → transaction/auth}/identity.js +1 -1
  230. package/dist/transaction/auth/index.d.ts +162 -0
  231. package/dist/transaction/auth/index.js +304 -0
  232. package/dist/{auth → transaction/auth}/schemas.d.ts +1 -1
  233. package/dist/{auth → transaction/auth}/schemas.js +13 -13
  234. package/dist/{client → transaction/auth}/sessionMint.d.ts +8 -8
  235. package/dist/{client → transaction/auth}/sessionMint.js +4 -7
  236. package/dist/transaction/coordination/awaitClaimGrant.d.ts +49 -0
  237. package/dist/transaction/coordination/awaitClaimGrant.js +112 -0
  238. package/dist/transaction/coordination/claimMeta.d.ts +49 -0
  239. package/dist/transaction/coordination/claimMeta.js +52 -0
  240. package/dist/transaction/coordination/createClaimStream.d.ts +64 -0
  241. package/dist/transaction/coordination/createClaimStream.js +475 -0
  242. package/dist/transaction/coordination/events.d.ts +74 -0
  243. package/dist/transaction/coordination/events.js +7 -0
  244. package/dist/transaction/coordination/index.d.ts +19 -0
  245. package/dist/transaction/coordination/index.js +44 -0
  246. package/dist/transaction/coordination/locator.d.ts +83 -0
  247. package/dist/transaction/coordination/locator.js +82 -0
  248. package/dist/transaction/coordination/schema.d.ts +1473 -0
  249. package/dist/{coordination → transaction/coordination}/schema.js +490 -55
  250. package/dist/transaction/coordination/targetConflict.d.ts +2 -0
  251. package/dist/transaction/coordination/targetConflict.js +103 -0
  252. package/dist/{coordination → transaction/coordination}/trace.d.ts +7 -18
  253. package/dist/{coordination → transaction/coordination}/trace.js +18 -25
  254. package/dist/transaction/durableWrites.d.ts +62 -0
  255. package/dist/{client → transaction}/durableWrites.js +28 -3
  256. package/dist/transaction/environment.d.ts +105 -0
  257. package/dist/transaction/environment.js +108 -0
  258. package/dist/{errorCodes.d.ts → transaction/errorCodes.d.ts} +11 -11
  259. package/dist/{errorCodes.js → transaction/errorCodes.js} +35 -12
  260. package/dist/{errors.d.ts → transaction/errors.d.ts} +37 -13
  261. package/dist/{errors.js → transaction/errors.js} +85 -16
  262. package/dist/transaction/index.d.ts +20 -0
  263. package/dist/transaction/index.js +20 -0
  264. package/dist/transaction/keys/index.d.ts +87 -0
  265. package/dist/transaction/keys/index.js +207 -0
  266. package/dist/transaction/log/syncDeltaRow.d.ts +158 -0
  267. package/dist/transaction/log/syncDeltaRow.js +95 -0
  268. package/dist/{sync/syncPosition.d.ts → transaction/logPosition.d.ts} +22 -8
  269. package/dist/{sync/syncPosition.js → transaction/logPosition.js} +15 -6
  270. package/dist/transaction/logger.d.ts +16 -0
  271. package/dist/transaction/logger.js +7 -0
  272. package/dist/transaction/observability.d.ts +53 -0
  273. package/dist/transaction/observability.js +19 -0
  274. package/dist/transaction/plugin.d.ts +192 -0
  275. package/dist/transaction/plugin.js +87 -0
  276. package/dist/{policy → transaction/policy}/types.d.ts +3 -3
  277. package/dist/{policy → transaction/policy}/types.js +2 -0
  278. package/dist/transaction/resources/httpResources.d.ts +266 -0
  279. package/dist/transaction/resources/httpResources.js +7 -0
  280. package/dist/transaction/resources/modelOperations.d.ts +319 -0
  281. package/dist/transaction/resources/modelOperations.js +12 -0
  282. package/dist/transaction/resources/mutationOptions.d.ts +66 -0
  283. package/dist/transaction/resources/mutationOptions.js +9 -0
  284. package/dist/transaction/resources/where.d.ts +85 -0
  285. package/dist/transaction/resources/where.js +70 -0
  286. package/dist/{client → transaction/resources}/writeOptionsSchema.d.ts +2 -6
  287. package/dist/{client → transaction/resources}/writeOptionsSchema.js +9 -5
  288. package/dist/{schema → transaction/schema}/field.d.ts +5 -5
  289. package/dist/{schema → transaction/schema}/field.js +5 -5
  290. package/dist/transaction/schema/loadStrategy.d.ts +45 -0
  291. package/dist/transaction/schema/loadStrategy.js +46 -0
  292. package/dist/{schema → transaction/schema}/model.d.ts +50 -35
  293. package/dist/{schema → transaction/schema}/model.js +30 -20
  294. package/dist/transaction/schema/openapi.d.ts +57 -0
  295. package/dist/transaction/schema/openapi.js +340 -0
  296. package/dist/{schema → transaction/schema}/relation.d.ts +14 -14
  297. package/dist/{schema → transaction/schema}/relation.js +7 -7
  298. package/dist/{schema → transaction/schema}/residency.d.ts +0 -9
  299. package/dist/{schema → transaction/schema}/residency.js +0 -5
  300. package/dist/{schema → transaction/schema}/roles.d.ts +5 -5
  301. package/dist/{schema → transaction/schema}/roles.js +5 -5
  302. package/dist/{schema → transaction/schema}/schema.d.ts +12 -10
  303. package/dist/{schema → transaction/schema}/schema.js +4 -3
  304. package/dist/{schema → transaction/schema}/tenancy.d.ts +1 -1
  305. package/dist/{schema → transaction/schema}/tenancy.js +7 -4
  306. package/dist/transaction/transactionLayer.d.ts +82 -0
  307. package/dist/transaction/transactionLayer.js +24 -0
  308. package/dist/{transactions → transaction/transactions/settlement}/commitEnvelope.d.ts +4 -5
  309. package/dist/{transactions → transaction/transactions/settlement}/commitEnvelope.js +9 -13
  310. package/dist/{transactions → transaction/transactions/settlement}/httpCommitEnvelope.d.ts +9 -2
  311. package/dist/{transactions → transaction/transactions/settlement}/httpCommitEnvelope.js +5 -9
  312. package/dist/{transactions/durableWriteStore.d.ts → transaction/transactions/settlement/pendingWrite.d.ts} +10 -36
  313. package/dist/transaction/transactions/settlement/pendingWrite.js +20 -0
  314. package/dist/transaction/transport/commitFrames.d.ts +90 -0
  315. package/dist/transaction/transport/commitFrames.js +134 -0
  316. package/dist/transaction/transport/connectionManager.d.ts +215 -0
  317. package/dist/transaction/transport/connectionManager.js +673 -0
  318. package/dist/transaction/transport/credentialLifecycle.d.ts +177 -0
  319. package/dist/transaction/transport/credentialLifecycle.js +324 -0
  320. package/dist/{sync → transaction/transport}/heartbeat.d.ts +3 -1
  321. package/dist/{sync → transaction/transport}/heartbeat.js +6 -4
  322. package/dist/{client → transaction/transport}/httpClient.d.ts +59 -16
  323. package/dist/{client → transaction/transport}/httpClient.js +5 -5
  324. package/dist/transaction/transport/httpOptions.d.ts +33 -0
  325. package/dist/transaction/transport/httpOptions.js +12 -0
  326. package/dist/{client → transaction/transport}/httpTransport.js +171 -85
  327. package/dist/{sync/NetworkProbe.d.ts → transaction/transport/networkProbe.d.ts} +7 -4
  328. package/dist/{sync/NetworkProbe.js → transaction/transport/networkProbe.js} +14 -13
  329. package/dist/transaction/transport/wsFrameHandlers.d.ts +128 -0
  330. package/dist/transaction/transport/wsFrameHandlers.js +429 -0
  331. package/dist/transaction/transport/wsTransport.d.ts +576 -0
  332. package/dist/transaction/transport/wsTransport.js +1017 -0
  333. package/dist/transaction/types/assertExact.d.ts +17 -0
  334. package/dist/transaction/types/assertExact.js +1 -0
  335. package/dist/{types → transaction/types}/global.d.ts +17 -2
  336. package/dist/{types → transaction/types}/global.js +2 -1
  337. package/dist/{types → transaction/types}/index.d.ts +14 -46
  338. package/dist/{types → transaction/types}/index.js +7 -16
  339. package/dist/{types → transaction/types}/streams.d.ts +63 -45
  340. package/dist/{utils → transaction/utils}/json.d.ts +18 -0
  341. package/dist/transaction/utils/json.js +276 -0
  342. package/dist/transaction/wire/accountResponses.d.ts +351 -0
  343. package/dist/transaction/wire/accountResponses.js +255 -0
  344. package/dist/transaction/wire/auth.d.ts +49 -0
  345. package/dist/transaction/wire/auth.js +57 -0
  346. package/dist/transaction/wire/claimEvent.d.ts +76 -0
  347. package/dist/transaction/wire/claimEvent.js +73 -0
  348. package/dist/transaction/wire/claims.d.ts +463 -0
  349. package/dist/transaction/wire/claims.js +229 -0
  350. package/dist/{wire → transaction/wire}/commit.d.ts +125 -193
  351. package/dist/{wire → transaction/wire}/commit.js +68 -47
  352. package/dist/{wire → transaction/wire}/delta.d.ts +66 -17
  353. package/dist/{wire → transaction/wire}/delta.js +37 -13
  354. package/dist/transaction/wire/errorEnvelope.d.ts +72 -0
  355. package/dist/{wire → transaction/wire}/errorEnvelope.js +36 -5
  356. package/dist/transaction/wire/feedCursor.d.ts +60 -0
  357. package/dist/transaction/wire/feedCursor.js +82 -0
  358. package/dist/transaction/wire/feedEvent.d.ts +177 -0
  359. package/dist/transaction/wire/feedEvent.js +39 -0
  360. package/dist/transaction/wire/frames.d.ts +194 -0
  361. package/dist/transaction/wire/frames.js +50 -0
  362. package/dist/transaction/wire/inboundFrames.d.ts +552 -0
  363. package/dist/transaction/wire/inboundFrames.js +116 -0
  364. package/dist/transaction/wire/index.d.ts +50 -0
  365. package/dist/transaction/wire/index.js +74 -0
  366. package/dist/{wire → transaction/wire}/listEnvelope.d.ts +13 -14
  367. package/dist/transaction/wire/listEnvelope.js +42 -0
  368. package/dist/transaction/wire/modelResponses.d.ts +85 -0
  369. package/dist/transaction/wire/modelResponses.js +43 -0
  370. package/dist/transactions/{TransactionQueue.d.ts → mutations/MutationQueue.d.ts} +79 -38
  371. package/dist/transactions/{TransactionQueue.js → mutations/MutationQueue.js} +110 -59
  372. package/dist/transactions/{TransactionStore.d.ts → mutations/MutationStore.d.ts} +8 -8
  373. package/dist/transactions/{TransactionStore.js → mutations/MutationStore.js} +2 -2
  374. package/dist/transactions/{coalesceRules.d.ts → mutations/coalesceRules.d.ts} +10 -10
  375. package/dist/transactions/{coalesceRules.js → mutations/coalesceRules.js} +1 -1
  376. package/dist/transactions/mutations/commitLatency.d.ts +52 -0
  377. package/dist/transactions/mutations/commitLatency.js +130 -0
  378. package/dist/transactions/{commitOutboxStore.d.ts → mutations/commitOutboxStore.d.ts} +1 -5
  379. package/dist/transactions/{commitOutboxStore.js → mutations/commitOutboxStore.js} +1 -1
  380. package/dist/transactions/{commitPayload.d.ts → mutations/commitPayload.d.ts} +16 -15
  381. package/dist/transactions/{commitPayload.js → mutations/commitPayload.js} +12 -12
  382. package/dist/transactions/{deltaConfirmation.d.ts → mutations/deltaConfirmation.d.ts} +11 -11
  383. package/dist/transactions/{deltaConfirmation.js → mutations/deltaConfirmation.js} +7 -7
  384. package/dist/transactions/mutations/durableWriteStore.d.ts +14 -0
  385. package/dist/transactions/mutations/durableWriteStore.js +12 -0
  386. package/dist/transactions/{optimisticApply.d.ts → mutations/optimisticApply.d.ts} +7 -7
  387. package/dist/transactions/{replayValidation.d.ts → mutations/replayValidation.d.ts} +3 -3
  388. package/dist/transactions/{replayValidation.js → mutations/replayValidation.js} +4 -3
  389. package/dist/utils/mobxSetup.d.ts +1 -1
  390. package/dist/utils/mobxSetup.js +5 -2
  391. package/dist/webhooks/events.d.ts +2 -2
  392. package/dist/wire/index.d.ts +1 -34
  393. package/dist/wire/index.js +8 -49
  394. package/docs/agent-messaging.md +3 -3
  395. package/docs/agents.md +19 -12
  396. package/docs/api-keys.md +8 -4
  397. package/docs/api.md +22 -18
  398. package/docs/audit.md +2 -0
  399. package/docs/cli.md +31 -3
  400. package/docs/client-behavior.md +8 -6
  401. package/docs/concurrency-convention.md +30 -24
  402. package/docs/coordination.md +48 -38
  403. package/docs/data-sources.md +3 -1
  404. package/docs/debugging.md +5 -3
  405. package/docs/deployment.md +267 -0
  406. package/docs/examples/agent-human.md +49 -42
  407. package/docs/examples/ai-sdk-tool.md +69 -44
  408. package/docs/examples/existing-python-backend.md +8 -6
  409. package/docs/examples/nextjs.md +129 -47
  410. package/docs/examples/scoped-agent.md +45 -44
  411. package/docs/examples/server-agent.md +46 -26
  412. package/docs/groups.md +32 -29
  413. package/docs/guarantees.md +4 -2
  414. package/docs/how-it-works.md +9 -7
  415. package/docs/idempotency.md +126 -0
  416. package/docs/identity.md +58 -54
  417. package/docs/index.md +172 -86
  418. package/docs/integration-guide.md +17 -16
  419. package/docs/interaction-model.md +6 -4
  420. package/docs/mcp.md +41 -16
  421. package/docs/migration.md +63 -5
  422. package/docs/operating-on-your-database.md +3 -1
  423. package/docs/projects.md +2 -0
  424. package/docs/quickstart.md +22 -5
  425. package/docs/react.md +12 -10
  426. package/docs/schema-contract.md +5 -3
  427. package/docs/session-settings.md +108 -0
  428. package/docs/sessions.md +3 -1
  429. package/docs/webhooks.md +3 -1
  430. package/llms.txt +47 -17
  431. package/package.json +10 -8
  432. package/dist/agent/Agent.d.ts +0 -366
  433. package/dist/agent/Agent.js +0 -514
  434. package/dist/agent/index.d.ts +0 -115
  435. package/dist/agent/index.js +0 -128
  436. package/dist/agent/session.d.ts +0 -93
  437. package/dist/agent/session.js +0 -149
  438. package/dist/agent/types.d.ts +0 -68
  439. package/dist/agent/types.js +0 -9
  440. package/dist/client/durableWrites.d.ts +0 -21
  441. package/dist/coordination/schema.d.ts +0 -722
  442. package/dist/schema/openapi.d.ts +0 -29
  443. package/dist/schema/openapi.js +0 -124
  444. package/dist/transactions/durableWriteStore.js +0 -30
  445. package/dist/utils/json.js +0 -88
  446. package/dist/wire/errorEnvelope.d.ts +0 -55
  447. package/dist/wire/frames.d.ts +0 -197
  448. package/dist/wire/frames.js +0 -49
  449. package/dist/wire/listEnvelope.js +0 -18
  450. /package/dist/{client → transaction/auth}/credentialEndpoint.d.ts +0 -0
  451. /package/dist/{client → transaction/auth}/credentialEndpoint.js +0 -0
  452. /package/dist/{auth → transaction/auth}/credentialPolicy.d.ts +0 -0
  453. /package/dist/{auth → transaction/auth}/credentialPolicy.js +0 -0
  454. /package/dist/{auth → transaction/auth}/credentialSource.js +0 -0
  455. /package/dist/{client → transaction/auth}/hostedEndpoints.d.ts +0 -0
  456. /package/dist/{client → transaction/auth}/hostedEndpoints.js +0 -0
  457. /package/dist/{client → transaction/coordination}/claimHeartbeatLoop.d.ts +0 -0
  458. /package/dist/{client → transaction/coordination}/claimHeartbeatLoop.js +0 -0
  459. /package/dist/{client → transaction}/persistence.d.ts +0 -0
  460. /package/dist/{client → transaction}/persistence.js +0 -0
  461. /package/dist/{client → transaction/resources}/functionalUpdate.d.ts +0 -0
  462. /package/dist/{client → transaction/resources}/functionalUpdate.js +0 -0
  463. /package/dist/{transactions → transaction/transactions/settlement}/idempotencyKey.d.ts +0 -0
  464. /package/dist/{transactions → transaction/transactions/settlement}/idempotencyKey.js +0 -0
  465. /package/dist/{client → transaction/transport}/httpTransport.d.ts +0 -0
  466. /package/dist/{types → transaction/types}/modelData.d.ts +0 -0
  467. /package/dist/{types → transaction/types}/modelData.js +0 -0
  468. /package/dist/{types → transaction/types}/participant.d.ts +0 -0
  469. /package/dist/{types → transaction/types}/participant.js +0 -0
  470. /package/dist/{types → transaction/types}/streams.js +0 -0
  471. /package/dist/{utils → transaction/utils}/asyncIterator.d.ts +0 -0
  472. /package/dist/{utils → transaction/utils}/asyncIterator.js +0 -0
  473. /package/dist/{utils → transaction/utils}/duration.d.ts +0 -0
  474. /package/dist/{utils → transaction/utils}/duration.js +0 -0
  475. /package/dist/{wire → transaction/wire}/bootstrapReason.d.ts +0 -0
  476. /package/dist/{wire → transaction/wire}/bootstrapReason.js +0 -0
  477. /package/dist/{wire → transaction/wire}/protocol.d.ts +0 -0
  478. /package/dist/{wire → transaction/wire}/protocol.js +0 -0
  479. /package/dist/{wire → transaction/wire}/protocolVersion.d.ts +0 -0
  480. /package/dist/{wire → transaction/wire}/protocolVersion.js +0 -0
  481. /package/dist/transactions/{UnconfirmedWrites.d.ts → mutations/UnconfirmedWrites.d.ts} +0 -0
  482. /package/dist/transactions/{UnconfirmedWrites.js → mutations/UnconfirmedWrites.js} +0 -0
  483. /package/dist/transactions/{optimisticApply.js → mutations/optimisticApply.js} +0 -0
@@ -0,0 +1,1017 @@
1
+ /**
2
+ * The duplex transport: a WebSocket connection to the sync server, extracted
3
+ * out of the reactive engine's `SyncWebSocket` (ADR 0016). It owns the socket
4
+ * lifecycle (connect, reconnect with exponential backoff, disconnect, the
5
+ * application-level heartbeat), sends commits, claims, releases, and
6
+ * subscription updates over the one connection, correlates their
7
+ * acknowledgement frames back to awaiting callers, and dispatches every other
8
+ * inbound frame through {@link dispatchWsFrame}.
9
+ *
10
+ * What it deliberately does not do is materialise: deltas, sync responses,
11
+ * and bootstrap payloads are surfaced through protected frame hooks
12
+ * ({@link handleDelta} and its siblings) whose defaults just emit, so a
13
+ * server-side caller gets the push feed — claim grants, losses, deltas —
14
+ * with no store, no cursor, and no renderer. The reactive engine subclasses
15
+ * this and overrides the hooks with validation, cursor advancement, and
16
+ * bootstrap handling. The membership test (ADR 0016): a caller with no socket
17
+ * loses only push — it polls instead; a caller with no reactive layer loses
18
+ * the local copy it never wanted.
19
+ */
20
+ import { EventEmitter } from 'events';
21
+ import { AbloConnectionError, AbloError, AbloSessionError, AbloValidationError, toAbloError, } from '../errors.js';
22
+ import { updateSubscriptionPayloadSchema } from '../coordination/schema.js';
23
+ import { PROTOCOL_VERSION, WS_CLOSE_PROTOCOL_VERSION } from '../wire/protocolVersion.js';
24
+ import { WS_BEARER_SUBPROTOCOL_PREFIX, WS_SYNC_SUBPROTOCOL, } from '../auth/credentialSource.js';
25
+ import { buildCommitFrame } from './commitFrames.js';
26
+ import { dispatchWsFrame, readWsInboundFrame, } from './wsFrameHandlers.js';
27
+ import { HeartbeatController } from './heartbeat.js';
28
+ import { noopLogger } from '../logger.js';
29
+ import { noopSocketObservability, } from '../observability.js';
30
+ /**
31
+ * Ceiling for the exponential reconnect backoff (`reconnectDelay * 2^n`,
32
+ * ±15% jitter). A client-side setting, not part of the wire contract.
33
+ */
34
+ const MAX_RECONNECT_DELAY_MS = 30_000;
35
+ // ---------------------------------------------------------------------------
36
+ // Consumers pass their own event types as the TCollaboration generic parameter.
37
+ export class WsTransport extends EventEmitter {
38
+ /**
39
+ * Subscribe to events with automatic cleanup.
40
+ * Returns unsubscribe function for clean disposal.
41
+ */
42
+ subscribe(event, handler) {
43
+ this.on(event, handler);
44
+ return () => this.off(event, handler);
45
+ }
46
+ /**
47
+ * Send a collaboration event (app-specific real-time message).
48
+ * The wire format is `{ type: messageType, payload: { ...payload, timestamp } }`.
49
+ */
50
+ sendCollaborationEvent(messageType, payload) {
51
+ if (this.ws?.readyState !== WebSocket.OPEN)
52
+ return;
53
+ this.send({
54
+ type: messageType.replace(/:/g, '_'), // 'document:selection' → 'document_selection' wire format
55
+ payload: { ...payload, timestamp: Date.now() },
56
+ });
57
+ }
58
+ ws = null;
59
+ options;
60
+ /** The transport's reporting ports, shared with the subclassing engine. */
61
+ logger;
62
+ observability;
63
+ onlineStatus;
64
+ reconnectAttempts = 0;
65
+ /** Stop retrying after this many consecutive failures (backoff caps at 30s, so ~7.5 min total) */
66
+ static MAX_RECONNECT_ATTEMPTS = 15;
67
+ reconnectTimer = null;
68
+ /**
69
+ * Application-level heartbeat: ping every 30 seconds and force-close after a
70
+ * 10-second silence. The {@link HeartbeatController} holds the timing and the
71
+ * zombie-socket rationale; the closures below are the only socket access it
72
+ * gets.
73
+ */
74
+ heartbeat;
75
+ isConnecting = false;
76
+ isManualClose = false;
77
+ /** True while the owner still holds the first connection (`deferConnect`).
78
+ * `connect()` is ignored until {@link allowConnect} lifts the hold. */
79
+ connectHeld;
80
+ /** When true, a session error has been detected (from any path — WS close or HTTP bootstrap).
81
+ * Suppresses reconnection and Sentry error capture to avoid cascading noise. */
82
+ _sessionErrorDetected = false;
83
+ /** True once `onopen` has fired at least once on the current socket. Reset each
84
+ * time a new socket is created in `connect()`. Used by `onclose` to detect
85
+ * handshake failures (close before open) — the one signal we have for "the
86
+ * server rejected the upgrade" since browsers hide the HTTP status (e.g.
87
+ * 401) behind the opaque 1006 close code. */
88
+ _everOpened = false;
89
+ /**
90
+ * Diagnostic snapshot of the last connection lifecycle. Persisted across
91
+ * the lifetime of the transport so that any subsequent "not connected"
92
+ * rejection can quote the actual root cause (close code + reason + when)
93
+ * instead of bottoming out at a generic error string. Browser WS code 1006
94
+ * hides the real reason, so we layer on our own signals: `forceCloseReason`
95
+ * captures heartbeat trips / send failures, `everOpened` distinguishes
96
+ * handshake reject from mid-session drop, and `sessionErrorAt` tells us
97
+ * whether reconnect is suppressed.
98
+ */
99
+ lastOpenAt = null;
100
+ lastCloseAt = null;
101
+ lastCloseCode = null;
102
+ lastCloseReason = null;
103
+ lastForceCloseReason = null;
104
+ sessionErrorAt = null;
105
+ /** Registered collaboration event keys (colon format) for dispatch in onmessage */
106
+ collaborationEventTypes;
107
+ /**
108
+ * A minimal session adapter handed to the inbound frame dispatch table
109
+ * ({@link dispatchWsFrame}). It exposes only the members the handlers touch;
110
+ * the closure members read live state so a reassignment here (for example the
111
+ * `pendingSubscriptions` reset on close) cannot strand a handler on a stale
112
+ * reference. Built in the constructor, after the state it captures exists.
113
+ */
114
+ frameSession;
115
+ /**
116
+ * In-flight `commit` mutation requests keyed by clientTxId. Resolved when
117
+ * a matching `mutation_result` frame arrives from the server, or rejected on
118
+ * timeout / disconnect. Lets consumers await a server ack for mutations
119
+ * sent over the same socket that streams deltas.
120
+ */
121
+ pendingMutations = new Map();
122
+ /**
123
+ * In-flight `claim` requests keyed by claimId. Resolved when the matching
124
+ * `claim_ack` arrives, or rejected on timeout or disconnect — the same
125
+ * request/response pattern as `pendingMutations`, multiplexed over the one
126
+ * connection.
127
+ */
128
+ pendingClaims = new Map();
129
+ /**
130
+ * In-flight `update_subscription` frames awaiting `subscription_ack`.
131
+ * A FIFO queue rather than a keyed Map because the wire ack carries no
132
+ * correlation id — the server applies subscription updates in receive
133
+ * order and acks in the same order, so `shift()` on ack matches the
134
+ * oldest pending request. (Read-interest changes are infrequent and
135
+ * usually settle before the next one, so depth is ~1 in practice.)
136
+ */
137
+ pendingSubscriptions = [];
138
+ constructor(options) {
139
+ super();
140
+ // Construct the WebSocket URL from the base server URL.
141
+ const baseUrl = options.baseUrl || options.url || "http://localhost:8080";
142
+ const wsProtocol = baseUrl.startsWith('https') ? 'wss' : 'ws';
143
+ const wsUrl = baseUrl.replace(/^https?/, wsProtocol) + '/api/sync/ws';
144
+ const { logger, observability, onlineStatus, deferConnect, ...connectionOptions } = options;
145
+ this.logger = logger ?? noopLogger;
146
+ this.observability = observability ?? noopSocketObservability;
147
+ this.onlineStatus = onlineStatus ?? { isOnline: () => true };
148
+ this.connectHeld = deferConnect === true;
149
+ this.options = {
150
+ url: wsUrl,
151
+ reconnectDelay: 1000,
152
+ maxReconnectDelay: MAX_RECONNECT_DELAY_MS,
153
+ collaborationEvents: [],
154
+ syncGroups: [],
155
+ lastSyncId: 0,
156
+ userId: '',
157
+ organizationId: '',
158
+ capabilities: {
159
+ partialBootstrap: true,
160
+ compressedDeltas: true,
161
+ streamingBootstrap: true,
162
+ batchedDeltas: true,
163
+ },
164
+ ...connectionOptions,
165
+ };
166
+ this.heartbeat = new HeartbeatController({
167
+ isSocketOpen: () => this.ws?.readyState === WebSocket.OPEN,
168
+ // Optional-chained rather than asserted: the controller only calls
169
+ // this synchronously after `isSocketOpen()`, so `ws` is present.
170
+ sendPing: () => {
171
+ this.ws?.send(JSON.stringify({ type: 'ping' }));
172
+ },
173
+ forceClose: (reason) => { this.forceClose(reason); },
174
+ }, this.observability);
175
+ this.collaborationEventTypes = new Set(options.collaborationEvents ?? []);
176
+ // Session slice for the inbound frame dispatch table — see the field doc on
177
+ // `frameSession` for why reassigned members are exposed through closures
178
+ // instead of captured references. The four materialisation handlers route
179
+ // through the protected hooks, so a subclass's overrides win.
180
+ this.frameSession = {
181
+ emit: (event, ...args) => this.emit(event, ...args),
182
+ logger: this.logger,
183
+ observability: this.observability,
184
+ pendingMutations: this.pendingMutations,
185
+ pendingClaims: this.pendingClaims,
186
+ shiftPendingSubscription: () => this.pendingSubscriptions.shift(),
187
+ options: this.options,
188
+ collaborationEventTypes: this.collaborationEventTypes,
189
+ handleDelta: (delta) => { this.handleDelta(delta); },
190
+ handleSyncResponse: (payload) => { this.handleSyncResponse(payload); },
191
+ handleBootstrapResponse: (payload) => { this.handleBootstrapResponse(payload); },
192
+ handlePresenceUpdate: (message) => {
193
+ this.handlePresenceUpdate(message);
194
+ },
195
+ };
196
+ }
197
+ // ── Materialisation hooks ─────────────────────────────────────────────
198
+ //
199
+ // The frame dispatch routes deltas, sync responses, bootstrap payloads, and
200
+ // presence frames through these protected hooks. The defaults surface the
201
+ // raw push feed as events — enough for a socketed agent that wants claim
202
+ // push and change notifications without a local copy. The reactive engine
203
+ // overrides them with wire validation, cursor advancement, and bootstrap
204
+ // handling; anything it does not override keeps the transport default.
205
+ /**
206
+ * One inbound delta, straight off the wire and unvalidated. The default
207
+ * emits it as-is; the reactive engine's override validates against the
208
+ * canonical delta schema and drops anything malformed before emitting.
209
+ */
210
+ handleDelta(rawDelta) {
211
+ this.emit('delta', rawDelta);
212
+ }
213
+ /** A `sync_response` frame. Meaningless without a resume cursor to advance,
214
+ * so the transport default does nothing. */
215
+ handleSyncResponse(_payload) { }
216
+ /** A `bootstrap_response` frame. Bootstrap is materialisation, so the
217
+ * transport default does nothing. */
218
+ handleBootstrapResponse(_payload) { }
219
+ /**
220
+ * Handles a presence update from the server. The wire frame's payload is
221
+ * forwarded as-is, so every consumer reads the same shape; stripping fields
222
+ * here would drop `kind`, `activity`, `syncGroups`, and `isAgent` for
223
+ * consumers that need them.
224
+ *
225
+ * The wire frame is:
226
+ * { type: 'presence_update', payload: { kind, userId, status,
227
+ * syncGroups, activity, isAgent, timestamp, activeClaims } }
228
+ */
229
+ handlePresenceUpdate(
230
+ // Typed as a partial presence event as well as an envelope, because both
231
+ // shapes genuinely arrive: the server's canonical `{ payload: {...} }`,
232
+ // and legacy pathways (test fixtures) that put the fields at the top
233
+ // level. Declaring the union up front is what lets the fallback below
234
+ // stay a plain read instead of a checked-off cast.
235
+ message) {
236
+ const event =
237
+ // Server canonical path: `{ payload: {...} }`. Some legacy
238
+ // pathways emit fields at the top level (test fixtures) — fall
239
+ // back to reading from the message itself.
240
+ message.payload ?? message;
241
+ this.emit('presence_update', event);
242
+ }
243
+ /**
244
+ * Runs after the socket opens and `connected` is emitted, before the
245
+ * heartbeat starts. The default does nothing; the reactive engine's
246
+ * override runs its open ritual — presence, ack, incremental sync, and the
247
+ * catch-up poll.
248
+ */
249
+ onOpened() { }
250
+ /**
251
+ * Runs inside the close handler, after the socket reference is cleared and
252
+ * before in-flight requests are rejected. The default does nothing; the
253
+ * reactive engine's override stops its catch-up poll.
254
+ */
255
+ onClosed() { }
256
+ /**
257
+ * The resume position sent as the `cursor` query parameter on the upgrade.
258
+ * The transport itself holds no cursor — a bare connection resumes from
259
+ * nothing — so the default is empty; the reactive engine's override supplies
260
+ * its persisted sync cursor.
261
+ */
262
+ resumeCursor() {
263
+ return '';
264
+ }
265
+ /**
266
+ * Mark that a session error has been detected (e.g. 401 from HTTP bootstrap).
267
+ * Suppresses further reconnection attempts and Sentry error capture.
268
+ */
269
+ setSessionErrorDetected() {
270
+ this._sessionErrorDetected = true;
271
+ this.sessionErrorAt = Date.now();
272
+ }
273
+ /**
274
+ * Clear the session-error latch so `connect()` / `scheduleReconnect()`
275
+ * work again. Called by the store's access-credential recovery path when
276
+ * the close was a re-mintable `ek_`/`rk_` expiry (`4001 credential_expired`),
277
+ * not a login loss — see `isAccessCredentialExpiryCloseReason`. Genuine
278
+ * session losses never clear the latch; re-auth builds a fresh client.
279
+ */
280
+ clearSessionError() {
281
+ this._sessionErrorDetected = false;
282
+ this.sessionErrorAt = null;
283
+ }
284
+ /**
285
+ * Lift the `deferConnect` hold. The owner calls this once the connection's
286
+ * identity and read scope are seeded; from then on `connect()` works
287
+ * normally, including every reconnect path.
288
+ */
289
+ allowConnect() {
290
+ this.connectHeld = false;
291
+ }
292
+ /**
293
+ * Connect to the sync engine WebSocket
294
+ */
295
+ connect() {
296
+ if (this.connectHeld) {
297
+ // Deliberately ignored, not queued: the decided answer to "connect()
298
+ // before the host has seeded identity" is a no-op, so an early caller
299
+ // can never open an unscoped connection (see deferConnect).
300
+ this.logger.debug('WebSocket connect ignored — the connection is still held by its host');
301
+ return;
302
+ }
303
+ if (this._sessionErrorDetected) {
304
+ this.logger.debug('WebSocket connect suppressed — session error detected');
305
+ return;
306
+ }
307
+ // CLOSING counts as busy: the socket's close teardown is still in
308
+ // flight and its `onclose` (which runs `scheduleReconnect`) hasn't
309
+ // fired yet. Overwriting `this.ws` mid-teardown is what produced the
310
+ // orphaned-socket race — see the stale-socket guards in
311
+ // `setupEventHandlers`.
312
+ if (this.ws?.readyState === WebSocket.OPEN ||
313
+ this.ws?.readyState === WebSocket.CLOSING ||
314
+ this.isConnecting) {
315
+ this.logger.debug('WebSocket already connected, connecting, or closing');
316
+ return;
317
+ }
318
+ // Note: onlineStatus is advisory — we'll try to connect and let the WebSocket
319
+ // handle failures. The default browser implementation reads navigator.onLine,
320
+ // which is unreliable but the only signal available; in Node it returns true
321
+ // (assume online) so the sidecar/agent path doesn't short-circuit here.
322
+ if (!this.onlineStatus.isOnline()) {
323
+ this.logger.debug('onlineStatus reports offline, but attempting connection anyway');
324
+ }
325
+ this.isConnecting = true;
326
+ this.isManualClose = false;
327
+ // One credential, server-resolved identity. The bearer travels in a
328
+ // `Sec-WebSocket-Protocol` value (built below), not the URL. The server is
329
+ // bearer-only and resolves identity from the verified token; userId and
330
+ // organizationId are never read from URL parameters.
331
+ const params = new URLSearchParams({
332
+ // Intentionally omit lastSyncId, capabilities from URL; these are sent in sync_request
333
+ // and ack messages to avoid stale baselines on reconnect.
334
+ cursor: this.resumeCursor(),
335
+ });
336
+ // Participant kind — defaults to `user` for session connections. Agent
337
+ // runtimes pass `'agent'` so the server's capability-token path activates
338
+ // instead of session auth.
339
+ if (this.options.kind && this.options.kind !== 'user') {
340
+ params.set('kind', this.options.kind);
341
+ }
342
+ // Add sync groups if provided
343
+ this.options.syncGroups.forEach((group) => {
344
+ params.append('syncGroups', group);
345
+ });
346
+ const wsUrl = `${this.options.url}?${params.toString()}`;
347
+ // Carry the bearer in a `Sec-WebSocket-Protocol` value, not the URL. A
348
+ // browser cannot set an Authorization header on a WebSocket, but it can
349
+ // offer subprotocols — and unlike the query string, those do not land in
350
+ // load-balancer access logs, proxies, or browser history. The server reads
351
+ // `ablo.bearer.<token>` and selects the real `ablo.sync.v1` protocol, never
352
+ // echoing the token-bearing value back. The token is the raw `ek_`/`rk_`,
353
+ // which is safe as a subprotocol value (alphanumerics and `_`).
354
+ const authToken = this.resolveAuthToken();
355
+ const protocols = authToken
356
+ ? [`${WS_BEARER_SUBPROTOCOL_PREFIX}${authToken}`, WS_SYNC_SUBPROTOCOL]
357
+ : [WS_SYNC_SUBPROTOCOL];
358
+ try {
359
+ // Reset the handshake flag before wiring the new socket. Each connect()
360
+ // gets its own lifecycle — a prior successful open on a previous socket
361
+ // must not mask a handshake failure on the new one.
362
+ this._everOpened = false;
363
+ this.ws = new WebSocket(wsUrl, protocols);
364
+ this.setupEventHandlers();
365
+ }
366
+ catch (error) {
367
+ // WebSocket constructor can throw if URL is invalid
368
+ const errorMessage = error instanceof Error ? error.message : 'Failed to create WebSocket';
369
+ this.observability.captureWebSocketError({ context: 'create-websocket', error: errorMessage });
370
+ this.isConnecting = false;
371
+ this.emit('error', new AbloConnectionError(errorMessage, { cause: error }));
372
+ this.scheduleReconnect();
373
+ }
374
+ }
375
+ /**
376
+ * Setup WebSocket event handlers
377
+ */
378
+ setupEventHandlers() {
379
+ // Capture the socket this call wires. Every handler below guards on
380
+ // `this.ws === socket` (onclose additionally tolerates a nulled field —
381
+ // see there), so a handler firing late, after `connect()` has replaced the
382
+ // socket, can never clobber the new connection's shared state. Without this
383
+ // guard, an old socket's `onclose` would unconditionally run `this.ws =
384
+ // null; onClosed(); stopHeartbeat()` — a reconnect during close
385
+ // teardown then orphaned the fresh socket (a zombie receiving deltas with
386
+ // no timers and broken send paths).
387
+ const socket = this.ws;
388
+ if (!socket)
389
+ return;
390
+ socket.onopen = () => {
391
+ if (this.ws !== socket)
392
+ return; // stale socket — a newer connect() owns the state
393
+ this.observability.breadcrumb('WebSocket connected', 'sync.websocket', 'info', {
394
+ reconnectAttempts: this.reconnectAttempts,
395
+ });
396
+ this.isConnecting = false;
397
+ this.reconnectAttempts = 0;
398
+ this._everOpened = true;
399
+ this.lastOpenAt = Date.now();
400
+ this.emit('connected');
401
+ // The subclass's open ritual (presence, ack, incremental sync,
402
+ // catch-up poll) runs here, between the `connected` emit and the
403
+ // heartbeat start — the exact position the inline code held before
404
+ // the split.
405
+ this.onOpened();
406
+ // Start the application-level heartbeat (see HeartbeatController).
407
+ this.heartbeat.start();
408
+ };
409
+ socket.onmessage = (event) => {
410
+ if (this.ws !== socket)
411
+ return; // stale socket — drop, don't feed shared state
412
+ try {
413
+ // Untrusted wire input: parse to `unknown`, then narrow through
414
+ // the frame-envelope guard before dispatch. Payload-level
415
+ // validation (deltas etc.) happens per-frame downstream.
416
+ const message = JSON.parse(event.data);
417
+ // Any inbound frame proves the socket is alive — clear the
418
+ // heartbeat-timeout timer so we don't false-trip force-close
419
+ // during normal traffic.
420
+ this.heartbeat.clearHeartbeatTimeout();
421
+ const frame = readWsInboundFrame(message);
422
+ if (!frame) {
423
+ this.logger.debug('[WsTransport] dropped malformed wire frame', {
424
+ received: Array.isArray(message) ? 'array' : typeof message,
425
+ });
426
+ return;
427
+ }
428
+ // Dispatch by frame type (see dispatchWsFrame). The session adapter
429
+ // exposes only the members the handlers touch; keepalives, the older
430
+ // bare-delta form, and collaboration events are all routed there too.
431
+ dispatchWsFrame(this.frameSession, frame);
432
+ }
433
+ catch (error) {
434
+ this.observability.captureWebSocketError({
435
+ context: 'parse-message',
436
+ error: error instanceof Error ? error.message : String(error),
437
+ });
438
+ }
439
+ };
440
+ socket.onerror = (_event) => {
441
+ if (this.ws !== socket)
442
+ return; // stale socket — its errors are no longer ours
443
+ // WebSocket errors are DOM Events, not Error objects
444
+ // Check if we're offline first
445
+ if (!this.onlineStatus.isOnline()) {
446
+ this.observability.breadcrumb('WebSocket error: Network is offline', 'sync.websocket', 'warning');
447
+ this.emit('error', new AbloConnectionError('Network is offline', { code: 'bootstrap_offline' }));
448
+ return;
449
+ }
450
+ // After a session error, suppress error capture — the root cause is
451
+ // already reported. Still emit so the store can update UI state.
452
+ const error = new AbloConnectionError(`WebSocket connection failed`);
453
+ if (!this._sessionErrorDetected) {
454
+ this.observability.captureWebSocketError({
455
+ context: 'connection-error',
456
+ error: error.message,
457
+ });
458
+ }
459
+ this.emit('error', error);
460
+ };
461
+ socket.onclose = (event) => {
462
+ // Stale-socket close: a newer socket already owns the connection
463
+ // state — don't null it, stop its timers, or schedule a duplicate
464
+ // reconnect (the orphaning race this guard exists for). The one
465
+ // deliberate asymmetry vs the other handlers: `this.ws === null`
466
+ // (manual `disconnect()` nulls the field before the close event
467
+ // lands) still runs the full body, so in-flight work is rejected
468
+ // promptly and 'disconnected' reaches consumers — the pre-guard
469
+ // behavior manual close always had.
470
+ if (this.ws !== null && this.ws !== socket)
471
+ return;
472
+ const everOpened = this._everOpened;
473
+ this.lastCloseAt = Date.now();
474
+ this.lastCloseCode = event.code;
475
+ this.lastCloseReason = event.reason || null;
476
+ this.logger.info('WebSocket closed', {
477
+ code: event.code,
478
+ reason: event.reason,
479
+ everOpened,
480
+ reconnectAttempts: this.reconnectAttempts,
481
+ forceCloseReason: this.lastForceCloseReason,
482
+ msSinceOpen: this.lastOpenAt != null ? Date.now() - this.lastOpenAt : null,
483
+ isManualClose: this.isManualClose,
484
+ });
485
+ this.isConnecting = false;
486
+ this.ws = null;
487
+ this.onClosed();
488
+ this.heartbeat.stop();
489
+ // Cancel in-flight mutations — the socket that was carrying them is
490
+ // gone, and the server-side state may or may not have accepted each
491
+ // one. Rejecting promptly is better than hanging the caller forever;
492
+ // higher-level retry belongs to MutationQueue, not here.
493
+ if (this.pendingMutations.size > 0) {
494
+ for (const pending of this.pendingMutations.values()) {
495
+ clearTimeout(pending.timeout);
496
+ // AbloConnectionError → `isPermanentError` treats it as transient,
497
+ // so MutationQueue retries the commit on reconnect rather than
498
+ // rolling it back. `diagnostics` is preserved as a property (the
499
+ // queue's failure log walks the cause chain for it).
500
+ pending.reject(Object.assign(new AbloConnectionError(`WebSocket closed while commit was in flight (code=${event.code}` +
501
+ (event.reason ? ` reason=${event.reason}` : '') +
502
+ (this.lastForceCloseReason
503
+ ? ` forceCloseReason=${this.lastForceCloseReason}`
504
+ : '') +
505
+ ')', { code: 'commit_no_result' }), { diagnostics: this.getConnectionDiagnostics() }));
506
+ }
507
+ this.pendingMutations.clear();
508
+ }
509
+ // Cancel in-flight claims — same rationale. Server-side
510
+ // claims are bound to the connection; a reconnect will need
511
+ // to re-claim. Higher-level retry belongs to whoever holds
512
+ // the participant handle (typically the SDK's claim manager).
513
+ if (this.pendingClaims.size > 0) {
514
+ for (const pending of this.pendingClaims.values()) {
515
+ clearTimeout(pending.timeout);
516
+ pending.reject(new AbloConnectionError(`WebSocket closed while claim was in flight (code=${event.code})`));
517
+ }
518
+ this.pendingClaims.clear();
519
+ }
520
+ // Cancel in-flight subscription updates — the reconnect handshake
521
+ // re-sends `options.syncGroups` (the last acked interest) in the
522
+ // upgrade URL, so a pending change that never acked is simply
523
+ // retried by the caller against the fresh connection.
524
+ if (this.pendingSubscriptions.length > 0) {
525
+ for (const pending of this.pendingSubscriptions) {
526
+ clearTimeout(pending.timeout);
527
+ pending.reject(new AbloConnectionError(`WebSocket closed while update_subscription was in flight (code=${event.code})`));
528
+ }
529
+ this.pendingSubscriptions = [];
530
+ }
531
+ // Protocol-version rejection (4010): terminal. Reconnecting cannot heal a
532
+ // version mismatch — only upgrading the SDK, or rolling the server
533
+ // forward, can — so a blind retry here would loop forever against the
534
+ // same typed close. Surface it and stop.
535
+ if (event.code === WS_CLOSE_PROTOCOL_VERSION) {
536
+ this.observability.captureWebSocketError({
537
+ context: 'protocol-version-close',
538
+ code: event.code,
539
+ reason: event.reason,
540
+ });
541
+ this.emit('protocol_mismatch', event);
542
+ this.emit('disconnected', event);
543
+ return;
544
+ }
545
+ // Check for session-related close codes
546
+ // 1008 = Policy Violation (often auth)
547
+ // 4001 = Unauthorized (custom)
548
+ // 4003 = Forbidden (custom)
549
+ const isSessionClose = event.code === 1008 ||
550
+ event.code === 4001 ||
551
+ event.code === 4003 ||
552
+ AbloSessionError.isSessionError(event.reason || '');
553
+ if (isSessionClose) {
554
+ this._sessionErrorDetected = true;
555
+ this.sessionErrorAt = Date.now();
556
+ this.observability.captureWebSocketError({
557
+ context: 'session-error-close',
558
+ code: event.code,
559
+ reason: event.reason,
560
+ });
561
+ this.emit('session_error', new AbloSessionError(event.reason || 'Session expired', event.code));
562
+ // Don't reconnect from here. For a genuine session loss the user must
563
+ // re-authenticate; for an expired access credential (`credential_expired`)
564
+ // the store's session-error handler re-mints, clears the latch, and
565
+ // drives the reconnect itself.
566
+ this.emit('disconnected', event);
567
+ return;
568
+ }
569
+ // Handshake failure: `onclose` fired before `onopen` ever did, so the
570
+ // server rejected the upgrade (typically 401/403 on a bad cookie, but it
571
+ // could also be a CORS/origin reject or a load-balancer 5xx). The browser
572
+ // hides the HTTP status behind code 1006, so we cannot tell which from
573
+ // here.
574
+ //
575
+ // Emit a dedicated event and skip the internal reconnect — the owner
576
+ // should run an auth-validating HTTP probe to distinguish session expiry
577
+ // from a transient network issue and transition the UI accordingly.
578
+ // Reconnecting blindly is what produced the infinite
579
+ // "offline → reconnecting → offline" loop on stale cookies.
580
+ if (!everOpened && !this.isManualClose) {
581
+ this.observability.captureWebSocketError({
582
+ context: 'handshake-failed-close',
583
+ code: event.code,
584
+ reason: event.reason,
585
+ });
586
+ this.emit('handshake_failed', event);
587
+ this.emit('disconnected', event);
588
+ return;
589
+ }
590
+ this.emit('disconnected', event);
591
+ // Reconnect if not manually closed
592
+ if (!this.isManualClose) {
593
+ this.scheduleReconnect();
594
+ }
595
+ };
596
+ }
597
+ /**
598
+ * Send message to server
599
+ */
600
+ send(message) {
601
+ if (this.ws?.readyState !== WebSocket.OPEN) {
602
+ // Only log at debug level when offline - this is expected behavior, not an error
603
+ if (this.onlineStatus.isOnline()) {
604
+ this.observability.breadcrumb('WebSocket not connected, cannot send message', 'sync.websocket', 'warning');
605
+ }
606
+ else {
607
+ this.logger.debug('WebSocket send skipped - offline');
608
+ }
609
+ return;
610
+ }
611
+ try {
612
+ this.ws.send(JSON.stringify(message));
613
+ }
614
+ catch (error) {
615
+ // Only log as error if we're online - offline send failures are expected
616
+ if (this.onlineStatus.isOnline()) {
617
+ this.observability.captureWebSocketError({
618
+ context: 'send-message',
619
+ error: error instanceof Error ? error.message : String(error),
620
+ });
621
+ }
622
+ else {
623
+ this.logger.debug('WebSocket send failed - offline');
624
+ }
625
+ }
626
+ }
627
+ /**
628
+ * Sends a `commit` mutation request over the existing WebSocket and resolves
629
+ * when the server's `mutation_result` frame comes back with the same
630
+ * `clientTxId`. The wire frame is `{ type: 'commit', payload: { operations,
631
+ * clientTxId } }`.
632
+ *
633
+ * Times out after 15 seconds of silence from the server. The socket may close
634
+ * during an in-flight mutation (a network flap, a server restart); this does
635
+ * not auto-retry — the caller's transaction queue owns retry and offline
636
+ * replay, and the SDK does not duplicate that logic.
637
+ */
638
+ sendCommit(operations, clientTxId, timeoutMs = 15_000, reads, track) {
639
+ if (this.ws?.readyState !== WebSocket.OPEN) {
640
+ return Promise.reject(this.notConnectedError('commit'));
641
+ }
642
+ return new Promise((resolve, reject) => {
643
+ const timeout = setTimeout(() => {
644
+ this.pendingMutations.delete(clientTxId);
645
+ reject(new AbloConnectionError(`commit timed out after ${timeoutMs}ms (clientTxId=${clientTxId})`, { code: 'commit_no_result' }));
646
+ }, timeoutMs);
647
+ this.pendingMutations.set(clientTxId, { resolve, reject, timeout });
648
+ try {
649
+ const frame = buildCommitFrame(operations, clientTxId, reads, track);
650
+ this.ws.send(JSON.stringify(frame));
651
+ }
652
+ catch (error) {
653
+ clearTimeout(timeout);
654
+ this.pendingMutations.delete(clientTxId);
655
+ reject(toAbloError(error));
656
+ }
657
+ });
658
+ }
659
+ /**
660
+ * Send a commit frame without waiting for `mutation_result`.
661
+ *
662
+ * This backs the public `wait: 'queued'` API: the socket accepted the
663
+ * frame for delivery, but the server has not confirmed it yet. The
664
+ * eventual `mutation_result` frame is intentionally ignored by this
665
+ * instance because no pending resolver is registered.
666
+ */
667
+ sendCommitQueued(operations, clientTxId, reads, track) {
668
+ if (this.ws?.readyState !== WebSocket.OPEN) {
669
+ throw this.notConnectedError('commit');
670
+ }
671
+ const frame = buildCommitFrame(operations, clientTxId, reads, track);
672
+ this.ws.send(JSON.stringify(frame));
673
+ }
674
+ /**
675
+ * Activates a participant claim on this connection. One connection can hold
676
+ * several concurrent claims at once, each scoped to a different set of sync
677
+ * groups, so the SDK reuses the existing connection instead of opening a
678
+ * separate socket per scope.
679
+ *
680
+ * Returns a promise that resolves with the server-canonicalized `syncGroups`
681
+ * and effective `ttlSeconds` once `claim_ack` arrives, or rejects with a typed
682
+ * error on a failed ack, a timeout, or a disconnect.
683
+ */
684
+ sendClaim(claimId, syncGroups, options) {
685
+ if (this.ws?.readyState !== WebSocket.OPEN) {
686
+ return Promise.reject(this.notConnectedError('claim'));
687
+ }
688
+ const timeoutMs = options?.timeoutMs ?? 15_000;
689
+ return new Promise((resolve, reject) => {
690
+ const timeout = setTimeout(() => {
691
+ this.pendingClaims.delete(claimId);
692
+ reject(new AbloConnectionError(`claim timed out after ${timeoutMs}ms (claimId=${claimId})`, {
693
+ code: 'wait_for_timeout',
694
+ }));
695
+ }, timeoutMs);
696
+ this.pendingClaims.set(claimId, { resolve, reject, timeout });
697
+ try {
698
+ this.ws.send(JSON.stringify({
699
+ type: 'claim',
700
+ payload: {
701
+ claimId,
702
+ syncGroups: [...syncGroups],
703
+ capabilityToken: options?.capabilityToken,
704
+ ttlSeconds: options?.ttlSeconds,
705
+ },
706
+ }));
707
+ }
708
+ catch (error) {
709
+ clearTimeout(timeout);
710
+ this.pendingClaims.delete(claimId);
711
+ reject(toAbloError(error));
712
+ }
713
+ });
714
+ }
715
+ /**
716
+ * Drop a previously-active claim. Idempotent — `release` is
717
+ * fire-and-forget per the wire contract; the server accepts
718
+ * unknown claimIds silently so disconnect-time release storms
719
+ * never error. No ack is expected.
720
+ *
721
+ * If a claim's send promise is still pending (no claim_ack yet),
722
+ * we reject it locally — the user explicitly chose to release.
723
+ */
724
+ sendRelease(claimId) {
725
+ // Cancel any in-flight claim that hadn't acked yet — the user
726
+ // changed their mind. Without this the timer would eventually
727
+ // reject; doing it now matches the user's claim immediately.
728
+ const pending = this.pendingClaims.get(claimId);
729
+ if (pending) {
730
+ clearTimeout(pending.timeout);
731
+ this.pendingClaims.delete(claimId);
732
+ pending.reject(new AbloError(`claim ${claimId} released before ack`, {
733
+ code: 'claim_wait_aborted',
734
+ httpStatus: 409,
735
+ }));
736
+ }
737
+ if (this.ws?.readyState !== WebSocket.OPEN)
738
+ return;
739
+ try {
740
+ this.ws.send(JSON.stringify({ type: 'release', payload: { claimId } }));
741
+ }
742
+ catch {
743
+ // Idempotent contract — silent failure is acceptable here.
744
+ }
745
+ }
746
+ /**
747
+ * Moves this connection's read interest — replaces the connection-level sync
748
+ * groups mid-session as the user opens and closes entities. This is the
749
+ * area-of-interest navigation primitive: the server fans out deltas only for
750
+ * the groups currently in view, rather than the fixed set chosen at connect.
751
+ *
752
+ * This is a full-set replace: pass the complete new group list, not a delta.
753
+ * Resolves with the server's effective set once `subscription_ack` arrives;
754
+ * rejects (with a typed error) on a scope denial (a restricted `rk_` key
755
+ * requesting a group outside its allowlist), a timeout, or a disconnect. On
756
+ * success the new set is recorded as `options.syncGroups`, so a later reconnect
757
+ * re-subscribes to the current interest rather than the connect-time set.
758
+ *
759
+ * Distinct from {@link sendClaim} (a write claim, per operation, with a TTL):
760
+ * this is the read side, carries no capability token of its own, and is
761
+ * bounded by the connection credential's grant.
762
+ */
763
+ updateSubscription(syncGroups, options) {
764
+ if (this.ws?.readyState !== WebSocket.OPEN) {
765
+ return Promise.reject(this.notConnectedError('update_subscription'));
766
+ }
767
+ const timeoutMs = options?.timeoutMs ?? 15_000;
768
+ return new Promise((resolve, reject) => {
769
+ const entry = {
770
+ resolve,
771
+ reject,
772
+ timeout: setTimeout(() => {
773
+ const idx = this.pendingSubscriptions.indexOf(entry);
774
+ if (idx !== -1)
775
+ this.pendingSubscriptions.splice(idx, 1);
776
+ reject(new AbloConnectionError(`update_subscription timed out after ${timeoutMs}ms`, { code: 'wait_for_timeout' }));
777
+ }, timeoutMs),
778
+ };
779
+ // Check the payload against the schema the server ingests it with, so a
780
+ // malformed sync group fails here — naming the group and the call that
781
+ // asked for it — instead of coming back as a rejection ack a round trip
782
+ // later, detached from the code that caused it.
783
+ const payload = updateSubscriptionPayloadSchema.safeParse({
784
+ syncGroups: [...syncGroups],
785
+ });
786
+ if (!payload.success) {
787
+ clearTimeout(entry.timeout);
788
+ reject(new AbloValidationError(`update_subscription was given a sync group the protocol does not accept: ${payload.error.issues[0]?.message ?? 'unreadable'}. A group is 'default' or 'kind:id'.`, { code: 'malformed_subscription' }));
789
+ return;
790
+ }
791
+ this.pendingSubscriptions.push(entry);
792
+ try {
793
+ this.ws.send(JSON.stringify({ type: 'update_subscription', payload: payload.data }));
794
+ }
795
+ catch (error) {
796
+ clearTimeout(entry.timeout);
797
+ const idx = this.pendingSubscriptions.indexOf(entry);
798
+ if (idx !== -1)
799
+ this.pendingSubscriptions.splice(idx, 1);
800
+ reject(toAbloError(error));
801
+ }
802
+ });
803
+ }
804
+ /**
805
+ * Sets a fixed credential for callers that construct the socket directly. The
806
+ * SDK instead supplies `getAuthToken`, so reconnects read the shared
807
+ * credential source rather than this copied value.
808
+ */
809
+ setCapabilityToken(token) {
810
+ this.options.capabilityToken = token;
811
+ }
812
+ /**
813
+ * Seeds the participant kind after identity resolution. The kind rides the
814
+ * upgrade URL and selects the server's auth path, and on the hosted path it
815
+ * is derived from the credential's scope — known only once identity
816
+ * resolves, after the socket is built. Call before `connect()`.
817
+ */
818
+ setKind(kind) {
819
+ this.options.kind = kind;
820
+ }
821
+ getAuthToken() {
822
+ return this.resolveAuthToken();
823
+ }
824
+ /**
825
+ * Return the credential that will be used by the next WebSocket upgrade.
826
+ * ConnectionManager reads this for HTTP auth probes so visibility/network
827
+ * checks authenticate the same way reconnects do.
828
+ */
829
+ getCapabilityToken() {
830
+ return this.resolveAuthToken();
831
+ }
832
+ resolveAuthToken = () => {
833
+ return this.options.getAuthToken?.()
834
+ ?? this.options.getCapabilityToken?.()
835
+ ?? this.options.capabilityToken;
836
+ };
837
+ /**
838
+ * Schedule reconnection with exponential backoff
839
+ */
840
+ scheduleReconnect() {
841
+ if (this.reconnectTimer) {
842
+ clearTimeout(this.reconnectTimer);
843
+ }
844
+ // Session error means the user needs to re-authenticate — don't reconnect.
845
+ if (this._sessionErrorDetected) {
846
+ return;
847
+ }
848
+ // Don't attempt reconnection while offline. The owning store manages the
849
+ // offline→online transition: it bootstraps first, then calls `connect()`
850
+ // explicitly. Self-reconnecting here would bypass that bootstrap gate and
851
+ // surface stale data.
852
+ if (!this.onlineStatus.isOnline()) {
853
+ this.emit('reconnecting', { attempt: this.reconnectAttempts + 1, delay: 0 });
854
+ return;
855
+ }
856
+ // Give up after MAX_RECONNECT_ATTEMPTS consecutive failures. The user can
857
+ // recover by refreshing, or the store resets the attempt count and
858
+ // reconnects when the network returns.
859
+ if (this.reconnectAttempts >= WsTransport.MAX_RECONNECT_ATTEMPTS) {
860
+ this.emit('reconnect_failed', { attempts: this.reconnectAttempts });
861
+ return;
862
+ }
863
+ // Exponential backoff with ±15% jitter to prevent thundering herd
864
+ const baseDelay = Math.min(this.options.reconnectDelay * Math.pow(2, this.reconnectAttempts), this.options.maxReconnectDelay);
865
+ const jitter = baseDelay * (0.85 + Math.random() * 0.3);
866
+ const delay = Math.round(jitter);
867
+ // Emit reconnecting event so UI can show reconnection status
868
+ this.emit('reconnecting', { attempt: this.reconnectAttempts + 1, delay });
869
+ this.reconnectTimer = setTimeout(() => {
870
+ this.reconnectAttempts++;
871
+ this.connect();
872
+ }, delay);
873
+ }
874
+ /**
875
+ * Reset reconnect attempt counter. Called when network comes back online
876
+ * to allow a fresh reconnect cycle after the max was previously reached.
877
+ */
878
+ resetReconnectAttempts() {
879
+ this.reconnectAttempts = 0;
880
+ }
881
+ /**
882
+ * Disconnect from WebSocket
883
+ */
884
+ disconnect() {
885
+ this.isManualClose = true;
886
+ this.heartbeat.stop();
887
+ if (this.reconnectTimer) {
888
+ clearTimeout(this.reconnectTimer);
889
+ this.reconnectTimer = null;
890
+ }
891
+ if (this.ws) {
892
+ this.ws.close(1000, 'Manual disconnect');
893
+ this.ws = null;
894
+ }
895
+ }
896
+ /**
897
+ * Force-close the socket from the client side using a private 4xxx
898
+ * code. Callers expect `onclose` to fire; that handler runs the
899
+ * existing reconnect / handshake-failed dispatch. Wrapped in
900
+ * try/catch because `close()` on a CLOSING/CLOSED socket throws on
901
+ * some browsers.
902
+ */
903
+ forceClose(reason) {
904
+ if (!this.ws)
905
+ return;
906
+ this.lastForceCloseReason = reason;
907
+ this.logger.debug('[WsTransport] forceClose', {
908
+ reason,
909
+ readyState: this.ws.readyState,
910
+ msSinceOpen: this.lastOpenAt != null ? Date.now() - this.lastOpenAt : null,
911
+ });
912
+ try {
913
+ this.ws.close(4000, reason);
914
+ }
915
+ catch {
916
+ // Already closing / closed — onclose will still fire.
917
+ }
918
+ }
919
+ /**
920
+ * Get connection state
921
+ */
922
+ isConnected() {
923
+ return this.ws?.readyState === WebSocket.OPEN;
924
+ }
925
+ /**
926
+ * Snapshot of recent connection lifecycle state, for diagnostic logs
927
+ * and error messages. Cheap to call (no I/O); safe to log every time
928
+ * a send is rejected so we can attribute "not connected" rejections
929
+ * to the actual root cause (handshake reject vs heartbeat zombie vs
930
+ * session expiry vs explicit close).
931
+ */
932
+ getConnectionDiagnostics() {
933
+ const now = Date.now();
934
+ return {
935
+ readyState: this.ws?.readyState ?? null,
936
+ isConnecting: this.isConnecting,
937
+ isManualClose: this.isManualClose,
938
+ sessionErrorDetected: this._sessionErrorDetected,
939
+ everOpened: this._everOpened,
940
+ reconnectAttempts: this.reconnectAttempts,
941
+ maxReconnectAttempts: WsTransport.MAX_RECONNECT_ATTEMPTS,
942
+ lastOpenAt: this.lastOpenAt,
943
+ lastCloseAt: this.lastCloseAt,
944
+ lastCloseCode: this.lastCloseCode,
945
+ lastCloseReason: this.lastCloseReason,
946
+ lastForceCloseReason: this.lastForceCloseReason,
947
+ sessionErrorAt: this.sessionErrorAt,
948
+ msSinceLastOpen: this.lastOpenAt != null ? now - this.lastOpenAt : null,
949
+ msSinceLastClose: this.lastCloseAt != null ? now - this.lastCloseAt : null,
950
+ };
951
+ }
952
+ /**
953
+ * Build a richly-diagnosed "not connected" error so callers (and the
954
+ * logs they emit) can attribute the rejection. The message embeds the
955
+ * dominant signal in human-readable form; the structured detail is
956
+ * also attached as `error.diagnostics` for log scrapers.
957
+ */
958
+ notConnectedError(action) {
959
+ const d = this.getConnectionDiagnostics();
960
+ // A session-latched socket is not a transient transport hiccup: reconnection
961
+ // is suppressed until re-auth (or the store's credential re-mint clears the
962
+ // latch), so retrying can never succeed. Reject with the permanent session
963
+ // error type — `isPermanentError` surfaces it to the caller as
964
+ // "re-authenticate" instead of parking the write for a reconnect that will
965
+ // never happen.
966
+ if (d.sessionErrorDetected) {
967
+ return Object.assign(new AbloSessionError(`SyncWebSocket not connected — cannot send ${action}: session expired` +
968
+ (d.lastCloseReason ? ` (${d.lastCloseReason})` : '') +
969
+ '; re-authenticate'), { diagnostics: d });
970
+ }
971
+ let detail;
972
+ if (d.isManualClose) {
973
+ detail = 'manual_close';
974
+ }
975
+ else if (d.isConnecting) {
976
+ detail = 'still_connecting';
977
+ }
978
+ else if (!d.everOpened && d.lastCloseAt != null) {
979
+ detail = `handshake_failed code=${d.lastCloseCode}`;
980
+ }
981
+ else if (d.lastForceCloseReason) {
982
+ detail = `force_closed reason=${d.lastForceCloseReason}`;
983
+ }
984
+ else if (d.lastCloseAt != null) {
985
+ detail =
986
+ `closed code=${d.lastCloseCode}` +
987
+ (d.lastCloseReason ? ` reason=${d.lastCloseReason}` : '') +
988
+ (d.msSinceLastClose != null ? ` ${d.msSinceLastClose}ms ago` : '') +
989
+ (d.reconnectAttempts > 0
990
+ ? ` reconnectAttempts=${d.reconnectAttempts}/${d.maxReconnectAttempts}`
991
+ : '');
992
+ }
993
+ else {
994
+ detail = 'never_connected';
995
+ }
996
+ // Typed so it lands in the AbloError hierarchy and `isPermanentError` sees a
997
+ // transient transport failure (retry on reconnect, don't roll back).
998
+ // `diagnostics` stays a property — the queue's failure log walks the cause
999
+ // chain for it.
1000
+ const err = Object.assign(new AbloConnectionError(`SyncWebSocket not connected — cannot send ${action} (${detail})`, { code: 'ws_not_ready' }), { diagnostics: d });
1001
+ return err;
1002
+ }
1003
+ /** Returns the sync groups this connection is subscribed to. */
1004
+ getSyncGroups() {
1005
+ return this.options.syncGroups;
1006
+ }
1007
+ /**
1008
+ * Seeds the connection's read interest — the sync groups the next upgrade
1009
+ * URL carries. The set is already mutable state (`subscription_ack` writes
1010
+ * the acked set back so a reconnect resubscribes to current interest);
1011
+ * this setter is the host's way to seed it once identity resolves, before
1012
+ * the first `connect()`.
1013
+ */
1014
+ setSyncGroups(syncGroups) {
1015
+ this.options.syncGroups = [...syncGroups];
1016
+ }
1017
+ }