@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,1224 @@
1
+ /**
2
+ * Fetches the initial snapshot the sync engine needs before it can go live: the
3
+ * current rows for the requested models plus the sync position from which to
4
+ * resume live updates. It calls the sync server's `/sync/bootstrap` HTTP
5
+ * endpoint, retries transient failures with backoff, and can fall back to a
6
+ * cached snapshot when the device is offline. {@link BootstrapData} is the
7
+ * shape it returns; {@link BootstrapOptions} configures it.
8
+ */
9
+
10
+ export interface BootstrapData {
11
+ type: 'full' | 'partial';
12
+ lastSyncId: number;
13
+ /**
14
+ * Model rows keyed by type name. Each row is opaque at this boundary; the
15
+ * engine asserts the per-model shape against the registered schema when it
16
+ * reduces the rows and writes them to local storage.
17
+ */
18
+ models?: Record<string, unknown[]>;
19
+ deltas?: ValidatedServerDelta[];
20
+ deltaCount?: number;
21
+ /** Model types whose server-side query failed (timeout, RLS error, and the like). */
22
+ failedModels?: string[];
23
+ timestamp: number;
24
+ /**
25
+ * The content hash of the schema the server currently has active for this
26
+ * tenant — the same hash `ablo push` computes. Present once a schema has been
27
+ * pushed. The client compares it against its own `expectedSchemaHash` to warn
28
+ * when the app's schema and the deployed schema have drifted apart.
29
+ */
30
+ schemaHash?: string;
31
+ /**
32
+ * Present when a paged single-model request stopped at its row limit with
33
+ * rows remaining: pass it back as the next page's `cursor`. Absent on the
34
+ * final page, on unpaged responses, and from servers that predate paging.
35
+ */
36
+ nextCursor?: string;
37
+ }
38
+
39
+ export interface BootstrapFetchResult {
40
+ notModified: boolean;
41
+ data?: BootstrapData;
42
+ etag?: string | null;
43
+ }
44
+
45
+ export interface BootstrapOptions {
46
+ /**
47
+ * Full base URL of the sync server's HTTP API, **including the `/api`
48
+ * prefix**. The bootstrap endpoint is appended as `/sync/bootstrap`, so
49
+ * the final request hits `${baseUrl}/sync/bootstrap`.
50
+ *
51
+ * Example: `'http://localhost:8080/api'` → `http://localhost:8080/api/sync/bootstrap`
52
+ *
53
+ * Default: `'http://localhost:8080/api'`.
54
+ */
55
+ baseUrl?: string;
56
+ /**
57
+ * Namespace for the offline bootstrap cache. Most callers leave this unset;
58
+ * the SDK fills it in once authentication has resolved the account scope, so
59
+ * the fallback cache is partitioned per account.
60
+ */
61
+ cacheScope?: string | null;
62
+ /**
63
+ * @deprecated Use `cacheScope`. Retained so code that constructs
64
+ * {@link BootstrapFetcher} directly keeps its cache namespace.
65
+ */
66
+ organizationId?: string;
67
+ syncGroups?: string[];
68
+ maxRetries?: number;
69
+ retryDelay?: number;
70
+ /**
71
+ * How long to wait for the server to START responding (response headers), in
72
+ * milliseconds. Default 20000 (20 seconds).
73
+ *
74
+ * Deliberately NOT a bound on the whole download: a cold-start snapshot can
75
+ * be tens of megabytes, and its transfer time depends on the connection. A
76
+ * healthy download that is actively delivering bytes is never aborted, no
77
+ * matter how long it takes — {@link stallTimeout} guards the body instead.
78
+ */
79
+ fetchTimeout?: number;
80
+ /**
81
+ * The longest quiet gap allowed between body chunks while downloading, in
82
+ * milliseconds. Default 15000 (15 seconds). This is the progress watchdog:
83
+ * it aborts a download whose stream has gone silent (dead connection,
84
+ * hung proxy) without ever penalizing a slow-but-moving transfer.
85
+ */
86
+ stallTimeout?: number;
87
+ /**
88
+ * The model names to request. When set, the server returns only these models
89
+ * and skips the rest. This is derived from each model's `load` strategy: only
90
+ * models loaded instantly (the default) are included. When unset, the server
91
+ * returns every model.
92
+ */
93
+ instantModels?: string[];
94
+ /**
95
+ * Getter for the current credential, read at request time so a refreshed
96
+ * token takes effect without recreating the helper. Preferred over
97
+ * {@link BootstrapFetcher.setAuthToken}.
98
+ */
99
+ getAuthToken?: AuthTokenGetter;
100
+ /** The owning client's runtime. Defaults to the module-global bridge. */
101
+ runtime?: RuntimeContext;
102
+ }
103
+
104
+ import { globalRuntime } from '../context.js';
105
+ import type { RuntimeContext } from '../RuntimeContext.js';
106
+ import { AbloError, AbloSessionError, AbloConnectionError, translateHttpError, toAbloError, isRetryableCode } from '@abloatai/transaction/errors';
107
+ import { withAuthHeaders, type AuthTokenGetter } from '@abloatai/transaction/auth/credentialSource';
108
+ import {
109
+ classifySchemaDrift,
110
+ describeSchemaDrift,
111
+ type ServerSchemaModel,
112
+ } from './schemaDrift.js';
113
+ // SyncObservability replaced by this.runtime.observability
114
+ import { parseBootstrapResponse, type ValidatedServerDelta } from './schemas.js';
115
+
116
+ /**
117
+ * Rows per page for the chunked cold-start bootstrap. Matches the server's
118
+ * hard cap on the `limit` query parameter — asking for more is silently
119
+ * clamped, so this is the largest honest page.
120
+ */
121
+ const PAGE_LIMIT = 5000;
122
+
123
+ /**
124
+ * Runaway guard for the per-model paging loop: a server that keeps returning
125
+ * a `nextCursor` past this many pages is looping, not paginating. At
126
+ * {@link PAGE_LIMIT} rows per page this allows a million rows per model
127
+ * before the loop is declared broken.
128
+ */
129
+ const MAX_PAGES_PER_MODEL = 200;
130
+
131
+ /** How many model chunks a cold start fetches at once. */
132
+ const CHUNK_CONCURRENCY = 3;
133
+
134
+ /**
135
+ * Which cancellation lane a request belongs to. Cancellation targets one lane
136
+ * at a time, so superseding a cold-start bootstrap cannot take down a scoped
137
+ * hydrate-on-enter running beside it: the two answer different questions and
138
+ * neither is a substitute for the other.
139
+ */
140
+ type CancelLane = 'bootstrap' | 'scoped';
141
+
142
+ /**
143
+ * The reason handed to `abort()` when a request is stopped deliberately —
144
+ * superseded by a newer bootstrap, or abandoned because the bootstrap it
145
+ * belonged to had already failed elsewhere.
146
+ */
147
+ const cancelled = (why: string): AbloConnectionError =>
148
+ new AbloConnectionError(why, { code: 'bootstrap_cancelled' });
149
+
150
+ /** Matches by `name` rather than `instanceof`: an abort that crosses a worker
151
+ * boundary is structured-cloned, which drops the prototype. */
152
+ const isAbortError = (value: unknown): boolean =>
153
+ typeof value === 'object' &&
154
+ value !== null &&
155
+ 'name' in value &&
156
+ (value as { name?: unknown }).name === 'AbortError';
157
+
158
+ /**
159
+ * What a failed request should report.
160
+ *
161
+ * A fetch aborted *with a reason* rejects with that exact reason object, so a
162
+ * deliberate cancellation and a watchdog firing both arrive here already typed
163
+ * and pass straight through — which is the whole point of passing one. Only a
164
+ * bare abort needs translating: a signal aborted with no reason, the browser's
165
+ * stop button, a closing tab. That case is the one that genuinely means the
166
+ * transfer died, so it becomes a retryable timeout.
167
+ *
168
+ * The signal's reason is preferred over the thrown value because a pre-aborted
169
+ * signal rejects before any request is made, and because interior code may have
170
+ * wrapped the rejection on its way out.
171
+ */
172
+ function classifyRequestFailure(
173
+ error: unknown,
174
+ controller: AbortController,
175
+ diedMessage: string,
176
+ ): Error {
177
+ const reason: unknown = controller.signal.aborted ? controller.signal.reason : error;
178
+ if (reason instanceof AbloError) return reason;
179
+ if (isAbortError(reason)) {
180
+ return new AbloConnectionError(diedMessage, {
181
+ code: 'bootstrap_fetch_timeout',
182
+ ...(reason instanceof Error ? { cause: reason } : {}),
183
+ });
184
+ }
185
+ return error instanceof Error ? error : new Error(String(error));
186
+ }
187
+
188
+ export class BootstrapFetcher {
189
+ private options: Required<Omit<BootstrapOptions, 'baseUrl' | 'instantModels' | 'organizationId' | 'cacheScope' | 'getAuthToken' | 'runtime'>> & {
190
+ baseUrl: string;
191
+ instantModels?: string[];
192
+ cacheScope: string | null;
193
+ organizationId?: string;
194
+ authToken?: string;
195
+ getAuthToken?: AuthTokenGetter;
196
+ runtime?: RuntimeContext;
197
+ };
198
+
199
+ private readonly runtime: RuntimeContext;
200
+ /**
201
+ * Every in-flight request's controller, tagged with the lane it belongs to. A
202
+ * registry rather than a single field because a chunked cold start runs
203
+ * several model fetches concurrently — aborting one request (its own
204
+ * TTFB/stall watchdog) must never take its siblings down, while
205
+ * {@link abort} takes down all of them.
206
+ */
207
+ private readonly activeControllers = new Map<AbortController, CancelLane>();
208
+ /**
209
+ * Non-scoped bootstraps currently running, keyed by request identity. A
210
+ * second call for the same snapshot joins the one already in flight rather
211
+ * than cancelling and restarting it — see {@link fetchBootstrap}.
212
+ */
213
+ private readonly flights = new Map<string, Promise<BootstrapData>>();
214
+ /** Warn about schema drift at most once per helper. */
215
+ private schemaDriftWarned = false;
216
+
217
+ /**
218
+ * Abort every in-flight request in `lane` — or in every lane when none is
219
+ * given — with an explicit reason.
220
+ *
221
+ * The reason is load-bearing, not decoration. `fetch` rejects with the exact
222
+ * value handed to `abort()`, so passing a typed error is what lets the retry
223
+ * loop below tell a deliberate cancellation apart from a dead connection. A
224
+ * bare `abort()` produces an `AbortError` indistinguishable from the one the
225
+ * browser's stop button produces, and a retry loop that cannot tell them
226
+ * apart re-issues the requests it just killed.
227
+ */
228
+ private cancelActive(reason: AbloError, lane?: CancelLane): void {
229
+ for (const [controller, controllerLane] of this.activeControllers) {
230
+ if (lane !== undefined && controllerLane !== lane) continue;
231
+ controller.abort(reason);
232
+ this.activeControllers.delete(controller);
233
+ }
234
+ }
235
+
236
+ /**
237
+ * The longest a single bootstrap can run before every watchdog below has
238
+ * necessarily fired, derived from those watchdogs rather than guessed. A
239
+ * caller wanting an outer deadline reads this instead of picking a number,
240
+ * so it cannot set one shorter than the work it wraps. A cold start pages
241
+ * through its models {@link CHUNK_CONCURRENCY} at a time; each request may
242
+ * spend `fetchTimeout` waiting for response headers and `stallTimeout`
243
+ * waiting for the next body chunk, and may be retried `maxRetries` times.
244
+ */
245
+ get budgetMs(): number {
246
+ const models = Math.max(this.options.instantModels?.length ?? 1, 1);
247
+ const waves = Math.ceil(models / CHUNK_CONCURRENCY);
248
+ return (
249
+ waves * (this.options.fetchTimeout + this.options.stallTimeout) * this.options.maxRetries
250
+ );
251
+ }
252
+
253
+ get baseUrl(): string {
254
+ return this.options.baseUrl;
255
+ }
256
+
257
+ /**
258
+ * Advisory schema-drift check: compare the server's active schema hash (on the
259
+ * bootstrap response) against the hash this client was built with. A mismatch
260
+ * means the app's schema and the deployed schema have diverged — reads/writes
261
+ * relying on undeployed changes will later fail with an opaque DB constraint
262
+ * error. Warn once, actionably; never throws or blocks the bootstrap.
263
+ *
264
+ * The message names the SERVER it connected to, and spans all three real
265
+ * causes rather than assuming "you forgot to push". Drift most often means the
266
+ * schema was pushed to a different server, project, or environment than this
267
+ * client points at (a bare `ablo push` targets the hosted default; a local app
268
+ * usually reads a local server) — so the first, load-bearing pointer is `ablo
269
+ * status`, which names the exact org/project/environment the key resolves to
270
+ * and the deployed hash, turning "which of these is it?" into one glance. The
271
+ * older "Run `ablo push`" copy sent everyone down one path and confused the
272
+ * common wrong-target and version-skew cases.
273
+ */
274
+ private warnOnSchemaDrift(serverHash: string | undefined): void {
275
+ if (this.schemaDriftWarned || !serverHash) return;
276
+ const clientHash = this.runtime.config.expectedSchemaHash;
277
+ if (!clientHash || clientHash === serverHash) return;
278
+ // A projection (`selectModels`/`omitModels`) hashes its subset, which never
279
+ // equals the full schema a server runs — so it also carries the source
280
+ // schema's hash. Matching that means the client is a faithful subset of the
281
+ // deployed schema: current, not drifted. Only warn when neither matches.
282
+ const sourceHash = this.runtime.config.expectedSourceSchemaHash;
283
+ if (sourceHash && sourceHash === serverHash) return;
284
+ this.schemaDriftWarned = true;
285
+ const org = this.options.organizationId;
286
+ const where = org ? `${this.baseUrl} (org ${org})` : this.baseUrl;
287
+
288
+ // The whole-schema hashes differ — but that alone can't distinguish "the
289
+ // server gained models this build never touches" (fine, say nothing) from
290
+ // "a model this client uses moved" (name it). Resolve the semantic answer
291
+ // from the server's per-model surface before speaking; fall back to the
292
+ // hash message only when that surface is unavailable (older server,
293
+ // network hiccup). Fire-and-forget: never blocks or fails the bootstrap.
294
+ const clientModels = this.runtime.config.expectedModelHashes;
295
+ if (clientModels && Object.keys(clientModels).length > 0) {
296
+ void this.resolveSemanticDrift(clientModels, clientHash, serverHash, where);
297
+ return;
298
+ }
299
+ this.warnWholeHashDrift(clientHash, serverHash, where);
300
+ }
301
+
302
+ /** Fetch the server's per-model schema surface and warn precisely — or stay
303
+ * silent when every model this client declares matches (additive lead). */
304
+ private async resolveSemanticDrift(
305
+ clientModels: Readonly<Record<string, string>>,
306
+ clientHash: string,
307
+ serverHash: string,
308
+ where: string,
309
+ ): Promise<void> {
310
+ try {
311
+ const res = await fetch(`${this.options.baseUrl}/schema`, {
312
+ method: 'GET',
313
+ headers: withAuthHeaders(this.options.getAuthToken, {}, this.options.authToken),
314
+ });
315
+ if (!res.ok) throw new Error(`schema read-back ${res.status}`);
316
+ const body = (await res.json()) as { models?: unknown };
317
+ const models = Array.isArray(body.models)
318
+ ? body.models.flatMap((m): ServerSchemaModel[] => {
319
+ const entry = m as { key?: unknown; hash?: unknown };
320
+ return typeof entry.key === 'string'
321
+ ? [{ key: entry.key, ...(typeof entry.hash === 'string' ? { hash: entry.hash } : {}) }]
322
+ : [];
323
+ })
324
+ : [];
325
+ const finding = classifySchemaDrift(clientModels, models);
326
+ if (finding.kind === 'aligned') return; // additive server lead — not this client's concern
327
+ if (finding.kind !== 'unknown') {
328
+ this.runtime.logger.warn(describeSchemaDrift(finding, where), {
329
+ clientSchemaHash: clientHash,
330
+ serverSchemaHash: serverHash,
331
+ serverUrl: this.baseUrl,
332
+ ...(finding.kind === 'unpushed'
333
+ ? { unpushedModels: finding.models }
334
+ : { changedModels: finding.models, unpushedModels: finding.unpushed }),
335
+ });
336
+ return;
337
+ }
338
+ } catch {
339
+ /* surface unavailable — fall through to the hash message */
340
+ }
341
+ this.warnWholeHashDrift(clientHash, serverHash, where);
342
+ }
343
+
344
+ private warnWholeHashDrift(clientHash: string, serverHash: string, where: string): void {
345
+ const org = this.options.organizationId;
346
+ // Self-brand the message ("Ablo:") rather than rely on the default logger's
347
+ // `[Ablo]` namespace — consumers wiring their own logger (pino, etc.) lose
348
+ // that prefix, and a drift warning that reads like the app's own log is
349
+ // worse than none. The brand tells them at a glance who is talking.
350
+ this.runtime.logger.warn(
351
+ `Ablo: Schema drift — the schema this client was built with (${clientHash}) is not the ` +
352
+ `one active on the server it connected to (${serverHash} at ${where}). Until they match, ` +
353
+ `operations that depend on the difference will fail later with an opaque database error. ` +
354
+ `This is usually one of three things. The schema may have been pushed to a different ` +
355
+ `server, project, or environment than this client points at — run \`ablo status\` to see ` +
356
+ `the exact org, project, and environment your key resolves to, alongside the deployed ` +
357
+ `hash, and confirm they match here. Your local schema may simply not be pushed to this ` +
358
+ `server yet — run \`ablo push\` against it. Or this client and the server may have been ` +
359
+ `built with different Ablo versions, which can hash an identical schema differently — ` +
360
+ `align the versions. This check is advisory and never blocks the connection.`,
361
+ {
362
+ clientSchemaHash: clientHash,
363
+ serverSchemaHash: serverHash,
364
+ serverUrl: this.baseUrl,
365
+ ...(org ? { organizationId: org } : {}),
366
+ },
367
+ );
368
+ }
369
+
370
+ constructor(options: BootstrapOptions) {
371
+ this.runtime = options.runtime ?? globalRuntime;
372
+ // Defaults are spread first; the explicit `baseUrl` then takes precedence,
373
+ // resolved from `options.baseUrl` or the localhost fallback. Callers pass
374
+ // the full base URL, including the `/api` prefix.
375
+ this.options = {
376
+ syncGroups: [],
377
+ maxRetries: 3,
378
+ retryDelay: 1000,
379
+ // Time-to-first-byte bound only. The server currently materializes the
380
+ // whole snapshot before sending headers, so a cold start on a large org
381
+ // legitimately needs more than a "fail fast" allowance here.
382
+ fetchTimeout: 20_000,
383
+ stallTimeout: 15_000,
384
+ ...options,
385
+ baseUrl: options.baseUrl ?? 'http://localhost:8080/api',
386
+ // Reading the deprecated `organizationId` is deliberate: it preserves the
387
+ // cache namespace for callers that still construct BootstrapFetcher
388
+ // directly with the old field instead of `cacheScope`.
389
+ // eslint-disable-next-line @typescript-eslint/no-deprecated
390
+ cacheScope: options.cacheScope ?? options.organizationId ?? null,
391
+ };
392
+
393
+ // Do not clear cache here; keep offline fallback available
394
+ }
395
+
396
+ /**
397
+ * Update the offline-cache namespace once auth has resolved the server-side
398
+ * account scope. This is intentionally not a public organizationId input.
399
+ */
400
+ setCacheScope(cacheScope: string): void {
401
+ if (cacheScope.trim().length === 0) return;
402
+ this.options.cacheScope = cacheScope;
403
+ }
404
+
405
+ setSyncGroups(syncGroups: readonly string[] | undefined): void {
406
+ this.options.syncGroups = [...(syncGroups ?? [])];
407
+ }
408
+
409
+ /**
410
+ * Sets a fixed credential for callers that construct the helper directly.
411
+ * The SDK instead supplies `getAuthToken` and never calls this.
412
+ */
413
+ setAuthToken(authToken: string | undefined): void {
414
+ if (!authToken) {
415
+ delete this.options.authToken;
416
+ return;
417
+ }
418
+ this.options.authToken = authToken;
419
+ }
420
+
421
+ /**
422
+ * Fetch bootstrap data from sync engine with partial bootstrap support
423
+ * @param lastSyncId - Optional: client's current lastSyncId for partial bootstrap
424
+ * @returns Bootstrap data (either full snapshot or delta batch)
425
+ */
426
+ async fetchBootstrap(
427
+ lastSyncId?: number,
428
+ /**
429
+ * A per-call set of sync groups for a scoped hydrate-on-enter. When given,
430
+ * the request uses these groups instead of the configured `syncGroups`, and
431
+ * does so without mutating the shared options, so a concurrent full
432
+ * bootstrap is unaffected. It also bypasses the offline snapshot cache,
433
+ * which holds the full bootstrap and would be a wrong answer to a subset
434
+ * request.
435
+ */
436
+ syncGroupsOverride?: readonly string[],
437
+ ): Promise<BootstrapData> {
438
+ // A scoped hydrate answers a different question than the full bootstrap and
439
+ // runs in its own lane: it never joins one, and is never superseded by one.
440
+ if (syncGroupsOverride) return this.runBootstrap(lastSyncId, syncGroupsOverride);
441
+
442
+ // Single-flight. Three callers reach this independently — first load,
443
+ // background refresh, and reconnect — and before this they raced: each new
444
+ // call cancelled whatever was running and started over, so a socket that
445
+ // reconnected mid-cold-start restarted the whole snapshot, repeatedly. The
446
+ // same request now joins the one in flight instead.
447
+ const key = this.flightKey(lastSyncId);
448
+ const joined = this.flights.get(key);
449
+ if (joined) {
450
+ this.runtime.logger.debug('Joining the bootstrap already in flight', { key });
451
+ return joined;
452
+ }
453
+
454
+ // A request for something else genuinely does supersede: the running one is
455
+ // not the answer being asked for. Retire it from the registry first, so a
456
+ // caller arriving in the same tick cannot join a flight that is dying.
457
+ if (this.flights.size > 0) {
458
+ this.flights.clear();
459
+ this.cancelActive(cancelled('Superseded by a newer bootstrap request'), 'bootstrap');
460
+ }
461
+
462
+ const flight = this.runBootstrap(lastSyncId);
463
+ this.flights.set(key, flight);
464
+ // The cleanup chain is terminated with `catch` so this derived promise can
465
+ // never surface as an unhandled rejection even when every caller handled the
466
+ // failure, and the delete is guarded by identity so a flight registered
467
+ // after a supersede is not evicted by its predecessor's cleanup.
468
+ void flight
469
+ .catch(() => undefined)
470
+ .finally(() => {
471
+ if (this.flights.get(key) === flight) this.flights.delete(key);
472
+ });
473
+ return flight;
474
+ }
475
+
476
+ /**
477
+ * The identity of a bootstrap request: everything that determines its answer.
478
+ * Two calls with the same key are asking the same question, so the second can
479
+ * take the first's result.
480
+ */
481
+ private flightKey(lastSyncId: number | undefined): string {
482
+ return JSON.stringify({
483
+ lastSyncId: lastSyncId !== undefined && lastSyncId > 0 ? lastSyncId : 0,
484
+ syncGroups: [...this.options.syncGroups].sort(),
485
+ models: [...(this.options.instantModels ?? [])].sort(),
486
+ });
487
+ }
488
+
489
+ /** One bootstrap, start to finish. {@link fetchBootstrap} owns whether it runs. */
490
+ private async runBootstrap(
491
+ lastSyncId?: number,
492
+ syncGroupsOverride?: readonly string[],
493
+ ): Promise<BootstrapData> {
494
+ // organizationId omitted — server reads it from auth identity.
495
+ // See `fetchBootstrapWithETag` for the full rationale.
496
+ const params = new URLSearchParams();
497
+
498
+ // Add lastSyncId for partial bootstrap support
499
+ if (lastSyncId !== undefined && lastSyncId > 0) {
500
+ params.append('lastSyncId', lastSyncId.toString());
501
+ }
502
+
503
+ // Add sync groups (per-call override wins over the configured set).
504
+ (syncGroupsOverride ?? this.options.syncGroups).forEach((group) => {
505
+ params.append('syncGroups', group);
506
+ });
507
+
508
+ // Selective bootstrap: only request instant-strategy models.
509
+ // When present, the server skips all other models → smaller payload.
510
+ // When absent, server returns all models (backward compat).
511
+ if (this.options.instantModels && this.options.instantModels.length > 0) {
512
+ params.append('models', this.options.instantModels.join(','));
513
+ }
514
+
515
+ const url = `${this.options.baseUrl}/sync/bootstrap?${params.toString()}`;
516
+
517
+ // If offline, try the cached bootstrap. Skipped for a scoped override: the
518
+ // cache holds the full snapshot, which is not a valid answer to a subset
519
+ // request; a scoped hydrate just soft-fails offline and retries on re-enter.
520
+ //
521
+ // Only an explicit `false` means offline. `navigator.onLine` is *typed*
522
+ // `boolean`, but at runtime it is `boolean | undefined`: Node 21+ exposes a
523
+ // global `navigator` whose `onLine` is `undefined`. Reading `!navigator.onLine`
524
+ // would treat that `undefined` as offline and falsely short-circuit to the
525
+ // (empty, under `persistence: 'memory'`) cache — throwing instead of fetching.
526
+ // Capturing it at its true runtime type keeps the `=== false` honest (and lets
527
+ // the boolean-literal-compare lint rule see the nullable it really is).
528
+ const navigatorOnline: boolean | undefined =
529
+ typeof navigator !== 'undefined' ? navigator.onLine : undefined;
530
+ if (!syncGroupsOverride && navigatorOnline === false) {
531
+ const cached = this.options.cacheScope
532
+ ? this.loadCachedBootstrap(this.options.cacheScope)
533
+ : null;
534
+ if (cached) {
535
+ this.runtime.logger.info('Using cached bootstrap (offline)');
536
+ return cached;
537
+ }
538
+ throw new AbloConnectionError('Offline and no cached bootstrap available', {
539
+ code: 'bootstrap_offline_no_cache',
540
+ });
541
+ }
542
+
543
+ this.runtime.logger.info('Fetching fresh bootstrap data', { url });
544
+
545
+ const lane: CancelLane = syncGroupsOverride ? 'scoped' : 'bootstrap';
546
+
547
+ // Chunk a COLD start by model: each instant model is its own request, so
548
+ // one giant model can't make the whole snapshot undeliverable, and a
549
+ // dropped connection costs one model, not everything. Each chunk is
550
+ // consistent at its own sync position; the merge anchors at the MINIMUM
551
+ // position, and the regular WS catch-up (`sync_request` → delta replay)
552
+ // closes the skew — full-row deltas make the overlapping re-apply
553
+ // convergent. Warm partials, scoped hydrates, and clients without a
554
+ // model list (server returns everything) stay on the single request.
555
+ const instantModels = this.options.instantModels ?? [];
556
+ const chunked =
557
+ (lastSyncId === undefined || lastSyncId <= 0) &&
558
+ !syncGroupsOverride &&
559
+ instantModels.length > 1;
560
+
561
+ try {
562
+ const data = chunked
563
+ ? await this.fetchChunkedBootstrap(instantModels, this.options.syncGroups)
564
+ : await this.fetchWithRetries(url, lane);
565
+
566
+ this.runtime.logger.info('Bootstrap data fetched', {
567
+ type: data.type,
568
+ lastSyncId: data.lastSyncId,
569
+ chunked,
570
+ modelCount: data.models ? Object.keys(data.models).length : 0,
571
+ deltaCount: data.deltaCount ?? 0,
572
+ totalItems: data.models
573
+ ? Object.values(data.models).reduce(
574
+ (sum, arr) => sum + (Array.isArray(arr) ? arr.length : 0),
575
+ 0
576
+ )
577
+ : 0,
578
+ });
579
+
580
+ // Persist for offline fallback
581
+ if (this.options.cacheScope) {
582
+ this.saveCachedBootstrap(this.options.cacheScope, data);
583
+ }
584
+ return data;
585
+ } catch (error) {
586
+ // Session and non-retryable errors already failed fast inside the
587
+ // retry loop; they must ALSO skip the cached fallback (a stale
588
+ // snapshot is not an answer to "your credential is invalid").
589
+ if (AbloSessionError.isSessionError(error)) {
590
+ throw error;
591
+ }
592
+ const ablo = toAbloError(error);
593
+ if (ablo.code && !isRetryableCode(ablo.code)) {
594
+ throw ablo;
595
+ }
596
+
597
+ // Transient failure after exhausting retries → cached fallback.
598
+ const cached = this.options.cacheScope
599
+ ? this.loadCachedBootstrap(this.options.cacheScope)
600
+ : null;
601
+ if (cached) {
602
+ this.runtime.observability.breadcrumb('Bootstrap cache fallback', 'sync.bootstrap', 'warning', {
603
+ error: ablo.message,
604
+ });
605
+ return cached;
606
+ }
607
+ throw ablo;
608
+ }
609
+ }
610
+
611
+ /**
612
+ * One bootstrap URL, fetched with backoff. Session errors and other
613
+ * non-retryable failures throw immediately; only transient failures
614
+ * (5xx, 429, timeouts, network blips) consume attempts. A cancellation is
615
+ * deliberate and therefore non-retryable — it leaves through the same gate.
616
+ */
617
+ private async fetchWithRetries(url: string, lane: CancelLane): Promise<BootstrapData> {
618
+ let lastError: Error | null = null;
619
+ for (let attempt = 0; attempt < this.options.maxRetries; attempt++) {
620
+ try {
621
+ return await this.fetchOnce(url, lane);
622
+ } catch (error) {
623
+ // SessionError should NOT be retried - the session is invalid and needs re-authentication
624
+ if (AbloSessionError.isSessionError(error)) {
625
+ this.runtime.observability.breadcrumb(
626
+ 'Bootstrap session error - redirecting to sign-in',
627
+ 'sync.bootstrap',
628
+ 'warning',
629
+ {
630
+ statusCode: (error).statusCode,
631
+ }
632
+ );
633
+ throw error;
634
+ }
635
+
636
+ // Don't retry NON-retryable errors. A 401/403/4xx auth or client error
637
+ // (api_key_required, jwt_issuer_untrusted, …) will NOT succeed by
638
+ // repeating the same request with the same credential — retrying just
639
+ // hammers the server and floods the console with doomed requests. Only
640
+ // transient failures (5xx, 429, timeouts, network blips, or an
641
+ // unclassified error with no code) flow through to the retry/backoff.
642
+ const ablo = toAbloError(error);
643
+ if (ablo.code && !isRetryableCode(ablo.code)) {
644
+ this.runtime.observability.breadcrumb(
645
+ 'Bootstrap non-retryable error — failing fast',
646
+ 'sync.bootstrap',
647
+ 'warning',
648
+ { code: ablo.code, httpStatus: ablo.httpStatus },
649
+ );
650
+ throw ablo;
651
+ }
652
+
653
+ lastError = error as Error;
654
+ this.runtime.observability.breadcrumb('Bootstrap fetch failed', 'sync.bootstrap', 'warning', {
655
+ attempt: attempt + 1,
656
+ });
657
+
658
+ if (attempt < this.options.maxRetries - 1) {
659
+ await this.delay(this.options.retryDelay * Math.pow(2, attempt));
660
+ }
661
+ }
662
+ }
663
+ throw lastError
664
+ ? toAbloError(lastError)
665
+ : new AbloConnectionError('Failed to fetch bootstrap data', {
666
+ code: 'bootstrap_fetch_timeout',
667
+ });
668
+ }
669
+
670
+ /**
671
+ * Cold-start bootstrap, one request per instant model with a small
672
+ * concurrency cap. Any chunk's terminal failure fails the whole
673
+ * bootstrap (a partial snapshot must never masquerade as a full one)
674
+ * and cancels its siblings.
675
+ */
676
+ private async fetchChunkedBootstrap(
677
+ models: readonly string[],
678
+ syncGroups: readonly string[],
679
+ ): Promise<BootstrapData> {
680
+ this.runtime.logger.info('Bootstrap chunked by model', {
681
+ models: models.length,
682
+ });
683
+
684
+ const queue = [...models];
685
+ const chunks: BootstrapData[] = [];
686
+ // Shared by the concurrent workers below, so it is deliberately re-read
687
+ // after `await` points where a sibling may have set it. Held on an object
688
+ // rather than in a `let`: the guard inside the worker narrows a plain
689
+ // binding to `null` for the rest of the loop body, and the compiler has no
690
+ // way to know a sibling can overwrite it mid-await.
691
+ const firstFailure: { error: Error | null } = { error: null };
692
+
693
+ const worker = async (): Promise<void> => {
694
+ for (;;) {
695
+ const model = queue.shift();
696
+ if (model === undefined || firstFailure.error !== null) return;
697
+ try {
698
+ // Page through the model: each request is bounded to PAGE_LIMIT
699
+ // rows, so no single response grows with the model's size. A
700
+ // server without paging ignores `limit` and returns the whole
701
+ // model with no nextCursor — one page, previous behavior.
702
+ let cursor: string | undefined;
703
+ for (let pageNo = 0; ; pageNo++) {
704
+ if (pageNo >= MAX_PAGES_PER_MODEL) {
705
+ throw new AbloConnectionError(
706
+ `Bootstrap for model "${model}" exceeded ${MAX_PAGES_PER_MODEL} pages — the server keeps returning a next page`,
707
+ { code: 'bootstrap_fetch_timeout' },
708
+ );
709
+ }
710
+ const params = new URLSearchParams();
711
+ syncGroups.forEach((group) => {
712
+ params.append('syncGroups', group);
713
+ });
714
+ params.append('models', model);
715
+ params.append('limit', String(PAGE_LIMIT));
716
+ if (cursor !== undefined) params.append('cursor', cursor);
717
+ const url = `${this.options.baseUrl}/sync/bootstrap?${params.toString()}`;
718
+ const data = await this.fetchWithRetries(url, 'bootstrap');
719
+ chunks.push(data);
720
+ if (data.nextCursor === undefined) break;
721
+ cursor = data.nextCursor;
722
+ }
723
+ } catch (error) {
724
+ // First failure wins — a later sibling's error must not mask it.
725
+ firstFailure.error ??=
726
+ error instanceof Error ? error : new Error(String(error));
727
+ // The siblings are abandoned, not broken: the snapshot they belong to
728
+ // is already lost. Saying so in the abort reason is what keeps each
729
+ // of them from retrying a request nobody is waiting for any more.
730
+ this.cancelActive(
731
+ cancelled(`Abandoned: the bootstrap chunk for "${model}" failed`),
732
+ 'bootstrap',
733
+ );
734
+ return;
735
+ }
736
+ }
737
+ };
738
+
739
+ await Promise.all(
740
+ Array.from({ length: Math.min(CHUNK_CONCURRENCY, models.length) }, worker),
741
+ );
742
+ if (firstFailure.error !== null) throw firstFailure.error;
743
+ return mergeBootstrapChunks(chunks);
744
+ }
745
+
746
+ /**
747
+ * Fetch bootstrap with ETag, returning 304 hints
748
+ */
749
+ async fetchBootstrapWithETag(): Promise<BootstrapFetchResult> {
750
+ // The organization id is intentionally not sent. The server resolves it
751
+ // from the authenticated identity, so the client cannot select or spoof an
752
+ // organization it is not scoped to.
753
+ const params = new URLSearchParams();
754
+ this.options.syncGroups.forEach((g) => { params.append('syncGroups', g); });
755
+ if (this.options.instantModels && this.options.instantModels.length > 0) {
756
+ params.append('models', this.options.instantModels.join(','));
757
+ }
758
+ const url = `${this.options.baseUrl}/sync/bootstrap?${params.toString()}`;
759
+
760
+ // Note: ETag caching is deliberately app-side, not SDK-side. The server
761
+ // still returns an ETag on responses, which is captured below and
762
+ // forwarded to callers via BootstrapFetchResult.etag — apps that want
763
+ // conditional revalidation (If-None-Match) implement it at their own
764
+ // level where they own the cache-key namespace. The 304 branch below
765
+ // remains defensively in place for when a caller enables revalidation.
766
+ const headers = withAuthHeaders(
767
+ this.options.getAuthToken,
768
+ { 'Content-Type': 'application/json' },
769
+ this.options.authToken,
770
+ );
771
+
772
+ const controller = new AbortController();
773
+ this.activeControllers.set(controller, 'bootstrap');
774
+ try {
775
+ return await this.fetchWithETagUsing(url, headers, controller);
776
+ } finally {
777
+ this.activeControllers.delete(controller);
778
+ }
779
+ }
780
+
781
+ private async fetchWithETagUsing(
782
+ url: string,
783
+ headers: Record<string, string>,
784
+ controller: AbortController,
785
+ ): Promise<BootstrapFetchResult> {
786
+ const res = await fetch(url, {
787
+ method: 'GET',
788
+ headers,
789
+ signal: controller.signal,
790
+ });
791
+
792
+ const etag = res.headers.get('ETag');
793
+
794
+ if (res.status === 304) {
795
+ // Log for telemetry
796
+ this.runtime.logger.info('[Bootstrap] 304 Not Modified - using cached data');
797
+ return { notModified: true, etag };
798
+ }
799
+
800
+ if (!res.ok) {
801
+ const bodyText = await res.text().catch(() => '');
802
+ // Map an empty body to undefined so the `??` below falls through to the
803
+ // synthetic message — translateHttpError renders an empty string body as
804
+ // an empty error message, which is useless to the caller.
805
+ let parsed: unknown = bodyText || undefined;
806
+ if (bodyText) {
807
+ try {
808
+ parsed = JSON.parse(bodyText);
809
+ } catch {
810
+ // Keep as string.
811
+ }
812
+ }
813
+ // Translate the canonical envelope first so the server's specific code
814
+ // and message survive (for example `api_key_required` or
815
+ // `jwt_issuer_untrusted`).
816
+ const translated = translateHttpError(
817
+ res.status,
818
+ parsed ?? `Bootstrap fetch failed: ${res.status} ${res.statusText}`,
819
+ res.headers.get('x-request-id') ?? undefined,
820
+ );
821
+ // Only a genuine session or JWT expiry — or a bare auth failure carrying
822
+ // no structured code — should drive the sign-in redirect. A specific auth
823
+ // code like `api_key_required` is not an expired session: signing in again
824
+ // mints the same credential and loops. Surface it as its real typed error
825
+ // instead of a `session_expired` wrapping the stringified body.
826
+ if (
827
+ translated.code === 'session_expired' ||
828
+ translated.code === 'jwt_expired' ||
829
+ ((res.status === 401 || res.status === 403) &&
830
+ translated.code === undefined)
831
+ ) {
832
+ throw new AbloSessionError(translated.message, res.status);
833
+ }
834
+ throw translated;
835
+ }
836
+
837
+ const data: BootstrapData = parseBootstrapResponse(
838
+ await this.readJsonWithStallGuard(res, controller),
839
+ this.runtime,
840
+ );
841
+ this.warnOnSchemaDrift(data.schemaHash);
842
+
843
+ // Persist payload for offline
844
+ try {
845
+ if (this.options.cacheScope) {
846
+ this.saveCachedBootstrap(this.options.cacheScope, data);
847
+ }
848
+ } catch {
849
+ // Offline persistence is best-effort; a failed cache write must not
850
+ // block returning the freshly fetched data.
851
+ }
852
+ this.runtime.logger.info('[Bootstrap] 200 OK - received new data');
853
+ return { notModified: false, data, etag };
854
+ }
855
+
856
+ /**
857
+ * Read a response body as a stream under a progress watchdog: the stall
858
+ * timer re-arms on every chunk, so only a silent stream is aborted — a
859
+ * slow-but-moving download is never killed for total duration. A cold-start
860
+ * snapshot can be tens of megabytes; bounding its total transfer time was
861
+ * what trapped large orgs in an endless full-bootstrap retry loop.
862
+ *
863
+ * Falls back to `response.json()` when the response exposes no readable
864
+ * stream (empty bodies, some test doubles).
865
+ */
866
+ private async readJsonWithStallGuard(
867
+ response: Response,
868
+ controller: AbortController,
869
+ ): Promise<unknown> {
870
+ const body = response.body;
871
+ if (!body) return response.json() as Promise<unknown>;
872
+
873
+ const reader = body.getReader();
874
+ const chunks: Uint8Array[] = [];
875
+ let receivedBytes = 0;
876
+ let stallTimer: ReturnType<typeof setTimeout> | undefined;
877
+
878
+ // The watchdog must not depend on the stream being wired to the fetch
879
+ // signal (that plumbing is implementation-specific), so a stall races a
880
+ // rejection against each read instead of only aborting the controller.
881
+ let stallReject: ((error: Error) => void) | undefined;
882
+ const stalled = new Promise<never>((_, reject) => {
883
+ stallReject = reject;
884
+ });
885
+ // A stall can fire in the microtask gap between two read races; without a
886
+ // standing handler that would surface as an unhandled rejection.
887
+ stalled.catch(() => undefined);
888
+
889
+ const armStallTimer = () => {
890
+ clearTimeout(stallTimer);
891
+ stallTimer = setTimeout(() => {
892
+ this.runtime.observability.breadcrumb(
893
+ 'Bootstrap download stalled',
894
+ 'sync.bootstrap',
895
+ 'warning',
896
+ { receivedBytes, stallTimeoutMs: this.options.stallTimeout },
897
+ );
898
+ const stallError = new AbloConnectionError(
899
+ `Bootstrap download stalled: no data received for ${this.options.stallTimeout}ms (${receivedBytes} bytes arrived before the stream went quiet)`,
900
+ { code: 'bootstrap_fetch_timeout' },
901
+ );
902
+ stallReject?.(stallError);
903
+ // Then tear the transfer down: abort frees the socket under real
904
+ // fetch; cancel unblocks readers on streams not wired to the signal.
905
+ // Both carry the same error, so whichever path wins the race below
906
+ // reports one message rather than two descriptions of one stall.
907
+ controller.abort(stallError);
908
+ void reader.cancel().catch(() => undefined);
909
+ }, this.options.stallTimeout);
910
+ };
911
+
912
+ try {
913
+ armStallTimer();
914
+ for (;;) {
915
+ const { done, value } = await Promise.race([reader.read(), stalled]);
916
+ if (done) break;
917
+ chunks.push(value);
918
+ receivedBytes += value.byteLength;
919
+ armStallTimer();
920
+ }
921
+ } catch (error) {
922
+ throw classifyRequestFailure(
923
+ error,
924
+ controller,
925
+ `Bootstrap download aborted after ${receivedBytes} bytes`,
926
+ );
927
+ } finally {
928
+ clearTimeout(stallTimer);
929
+ }
930
+
931
+ const bytes = new Uint8Array(receivedBytes);
932
+ let offset = 0;
933
+ for (const chunk of chunks) {
934
+ bytes.set(chunk, offset);
935
+ offset += chunk.byteLength;
936
+ }
937
+ return JSON.parse(new TextDecoder().decode(bytes)) as unknown;
938
+ }
939
+
940
+ /**
941
+ * Perform one fetch. The timeout here bounds time to response headers
942
+ * only; the body download is guarded by the stall watchdog in
943
+ * {@link readJsonWithStallGuard}. Superseding an older in-flight
944
+ * bootstrap is the caller's job ({@link fetchBootstrap} cancels the
945
+ * registry) — chunk requests run through here concurrently and must
946
+ * not cancel each other.
947
+ */
948
+ private async fetchOnce(url: string, lane: CancelLane): Promise<BootstrapData> {
949
+ const controller = new AbortController();
950
+ this.activeControllers.set(controller, lane);
951
+ try {
952
+ return await this.fetchOnceWith(url, controller);
953
+ } finally {
954
+ this.activeControllers.delete(controller);
955
+ }
956
+ }
957
+
958
+ private async fetchOnceWith(url: string, controller: AbortController): Promise<BootstrapData> {
959
+ const timeoutId = setTimeout(() => {
960
+ this.runtime.observability.breadcrumb('Bootstrap fetch timeout', 'sync.bootstrap', 'warning', {
961
+ timeoutMs: this.options.fetchTimeout,
962
+ });
963
+ controller.abort(
964
+ new AbloConnectionError(
965
+ `Bootstrap fetch timed out after ${this.options.fetchTimeout}ms waiting for the server to respond`,
966
+ { code: 'bootstrap_fetch_timeout' },
967
+ ),
968
+ );
969
+ }, this.options.fetchTimeout);
970
+
971
+ let response: Response;
972
+ try {
973
+ response = await fetch(url, {
974
+ method: 'GET',
975
+ headers: withAuthHeaders(this.options.getAuthToken, {
976
+ 'Content-Type': 'application/json',
977
+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
978
+ Pragma: 'no-cache',
979
+ }, this.options.authToken),
980
+ signal: controller.signal,
981
+ cache: 'no-store', // Force browser to not cache
982
+ });
983
+ } catch (error) {
984
+ clearTimeout(timeoutId);
985
+ throw classifyRequestFailure(
986
+ error,
987
+ controller,
988
+ 'The bootstrap request was aborted before the server responded',
989
+ );
990
+ }
991
+ clearTimeout(timeoutId);
992
+
993
+ if (!response.ok) {
994
+ const bodyText = await response.text().catch(() => '');
995
+ // Map an empty body to undefined so the `??` below falls through to the
996
+ // synthetic message (see the note on the primary fetch path).
997
+ let parsed: unknown = bodyText || undefined;
998
+ if (bodyText) {
999
+ try {
1000
+ parsed = JSON.parse(bodyText);
1001
+ } catch {
1002
+ // Keep as string.
1003
+ }
1004
+ }
1005
+ // Same code-aware handling as the primary bootstrap fetch: preserve the
1006
+ // server's specific code/message; only a genuine expiry (or a bare,
1007
+ // code-less auth failure) drives the sign-in redirect.
1008
+ const translated = translateHttpError(
1009
+ response.status,
1010
+ parsed ?? `Bootstrap fetch failed: ${response.status} ${response.statusText}`,
1011
+ response.headers.get('x-request-id') ?? undefined,
1012
+ );
1013
+ if (
1014
+ translated.code === 'session_expired' ||
1015
+ translated.code === 'jwt_expired' ||
1016
+ ((response.status === 401 || response.status === 403) &&
1017
+ translated.code === undefined)
1018
+ ) {
1019
+ throw new AbloSessionError(translated.message, response.status);
1020
+ }
1021
+ throw translated;
1022
+ }
1023
+
1024
+ const data = parseBootstrapResponse(await this.readJsonWithStallGuard(response, controller), this.runtime);
1025
+ this.warnOnSchemaDrift(data.schemaHash);
1026
+ // Offline caching happens in `fetchBootstrap` on the assembled result —
1027
+ // caching here would let a single-model chunk overwrite the full snapshot.
1028
+ return data;
1029
+ }
1030
+
1031
+ /**
1032
+ * Fetch a single entity by ID (on-demand self-healing).
1033
+ * Returns `null` for 404 (entity deleted) — this is an expected state, not an error.
1034
+ * Throws for unexpected HTTP errors (5xx, network failures).
1035
+ */
1036
+ async fetchEntity(modelName: string, id: string): Promise<Record<string, unknown> | null> {
1037
+ const url = `${this.options.baseUrl}/sync/entity/${modelName}/${id}`;
1038
+
1039
+ // Uses the same `fetchTimeout` deadline as `performFetch`. A local
1040
+ // AbortController, rather than the shared `this.abortController`, means an
1041
+ // entity self-heal never cancels a concurrent bootstrap fetch.
1042
+ const controller = new AbortController();
1043
+ const timeoutId = setTimeout(() => { controller.abort(); }, this.options.fetchTimeout);
1044
+
1045
+ let response: Response;
1046
+ try {
1047
+ response = await fetch(url, {
1048
+ method: 'GET',
1049
+ headers: withAuthHeaders(this.options.getAuthToken, {
1050
+ 'Content-Type': 'application/json',
1051
+ }, this.options.authToken),
1052
+ signal: controller.signal,
1053
+ });
1054
+ } catch (error) {
1055
+ // Convert abort to the existing typed timeout error (same code as the
1056
+ // bootstrap fetch path) so callers get a retryable connection error.
1057
+ if (error instanceof Error && error.name === 'AbortError') {
1058
+ throw new AbloConnectionError(
1059
+ `Entity fetch timed out after ${this.options.fetchTimeout}ms`,
1060
+ { code: 'bootstrap_fetch_timeout', cause: error },
1061
+ );
1062
+ }
1063
+ throw error;
1064
+ } finally {
1065
+ clearTimeout(timeoutId);
1066
+ }
1067
+
1068
+ if (response.status === 404) {
1069
+ return null;
1070
+ }
1071
+
1072
+ if (!response.ok) {
1073
+ const bodyText = await response.text().catch(() => '');
1074
+ // Map an empty body to undefined so the `??` below falls through to the
1075
+ // synthetic message (see the note on the primary fetch path).
1076
+ let parsed: unknown = bodyText || undefined;
1077
+ if (bodyText) {
1078
+ try {
1079
+ parsed = JSON.parse(bodyText);
1080
+ } catch {
1081
+ // Keep as string.
1082
+ }
1083
+ }
1084
+ throw translateHttpError(
1085
+ response.status,
1086
+ parsed ?? `Entity fetch failed: ${response.status} ${response.statusText}`,
1087
+ response.headers.get('x-request-id') ?? undefined,
1088
+ );
1089
+ }
1090
+
1091
+ return (await response.json()) as Record<string, unknown> | null;
1092
+ }
1093
+
1094
+ // ─────────────────────────────────────────────────────────────────────
1095
+ /**
1096
+ * Clear all cached bootstrap data
1097
+ */
1098
+ clearCache(): void {
1099
+ if (typeof window === 'undefined') return;
1100
+
1101
+ try {
1102
+ // Clear all bootstrap cache keys
1103
+ const keysToRemove: string[] = [];
1104
+ for (let i = 0; i < localStorage.length; i++) {
1105
+ const key = localStorage.key(i);
1106
+ if (key?.startsWith('ablo:bootstrap:') || key?.includes('sync-bootstrap')) {
1107
+ keysToRemove.push(key);
1108
+ }
1109
+ }
1110
+
1111
+ keysToRemove.forEach((key) => {
1112
+ localStorage.removeItem(key);
1113
+ this.runtime.logger.debug('Cleared cache key', { key });
1114
+ });
1115
+ } catch (error) {
1116
+ this.runtime.logger.debug('Failed to clear cache', { error });
1117
+ }
1118
+ }
1119
+
1120
+ // Cache helpers for offline bootstrap
1121
+ private getBootstrapCacheKey(orgId: string): string {
1122
+ return `ablo:bootstrap:${orgId}`;
1123
+ }
1124
+ private saveCachedBootstrap(orgId: string, data: BootstrapData): void {
1125
+ if (typeof window === 'undefined') return;
1126
+ try {
1127
+ localStorage.setItem(this.getBootstrapCacheKey(orgId), JSON.stringify(data));
1128
+ } catch (e) {
1129
+ this.runtime.logger.debug('Failed to cache bootstrap payload', {
1130
+ error: e instanceof Error ? e.message : String(e),
1131
+ });
1132
+ }
1133
+ }
1134
+ private loadCachedBootstrap(orgId: string): BootstrapData | null {
1135
+ if (typeof window === 'undefined') return null;
1136
+ try {
1137
+ const raw = localStorage.getItem(this.getBootstrapCacheKey(orgId));
1138
+ if (!raw) return null;
1139
+ return JSON.parse(raw) as BootstrapData;
1140
+ } catch {
1141
+ return null;
1142
+ }
1143
+ }
1144
+
1145
+ /**
1146
+ * Abort every ongoing bootstrap request (including all chunks of a
1147
+ * chunked cold start). Entity self-heal fetches are unaffected.
1148
+ *
1149
+ * The flight registry is cleared first and synchronously, so a caller that
1150
+ * bootstraps again in the same tick starts a fresh request rather than
1151
+ * joining the one being torn down.
1152
+ */
1153
+ abort(): void {
1154
+ this.flights.clear();
1155
+ this.cancelActive(cancelled('Bootstrap aborted by its caller'));
1156
+ }
1157
+
1158
+ /**
1159
+ * Helper to delay execution
1160
+ */
1161
+ private delay(ms: number): Promise<void> {
1162
+ return new Promise((resolve) => setTimeout(resolve, ms));
1163
+ }
1164
+
1165
+ /**
1166
+ * Get health status of sync engine
1167
+ */
1168
+ async checkHealth(): Promise<boolean> {
1169
+ try {
1170
+ const response = await fetch(`${this.options.baseUrl}/health`, {
1171
+ method: 'GET',
1172
+ signal: AbortSignal.timeout(5000),
1173
+ cache: 'no-store',
1174
+ });
1175
+
1176
+ if (!response.ok) return false;
1177
+
1178
+ const body = (await response.json()) as { status?: unknown };
1179
+ return body.status === 'healthy';
1180
+ } catch {
1181
+ this.runtime.observability.breadcrumb('Health check failed', 'sync.bootstrap', 'warning');
1182
+ return false;
1183
+ }
1184
+ }
1185
+ }
1186
+
1187
+ /**
1188
+ * Assemble per-model chunk responses into one full snapshot.
1189
+ *
1190
+ * Each chunk is internally consistent at its own sync position, and the
1191
+ * positions differ (the chunks were served seconds apart). Anchoring the
1192
+ * merged snapshot at the MINIMUM position turns that skew into an ordinary
1193
+ * "briefly offline client": the WS catch-up replays every delta from the
1194
+ * anchor, and since deltas carry full rows, re-applying one a later chunk
1195
+ * already reflects converges to the same state. Anchoring at anything later
1196
+ * would silently skip deltas for the earliest-fetched models.
1197
+ */
1198
+ export function mergeBootstrapChunks(chunks: readonly BootstrapData[]): BootstrapData {
1199
+ const models: Record<string, unknown[]> = {};
1200
+ const failedModels: string[] = [];
1201
+ let lastSyncId = Number.POSITIVE_INFINITY;
1202
+ let timestamp = 0;
1203
+ let schemaHash: string | undefined;
1204
+
1205
+ for (const chunk of chunks) {
1206
+ // Concatenate per model: pages of one model arrive as separate chunks.
1207
+ for (const [name, rows] of Object.entries(chunk.models ?? {})) {
1208
+ (models[name] ??= []).push(...rows);
1209
+ }
1210
+ if (chunk.failedModels) failedModels.push(...chunk.failedModels);
1211
+ lastSyncId = Math.min(lastSyncId, chunk.lastSyncId);
1212
+ timestamp = Math.max(timestamp, chunk.timestamp);
1213
+ schemaHash ??= chunk.schemaHash;
1214
+ }
1215
+
1216
+ return {
1217
+ type: 'full',
1218
+ lastSyncId: Number.isFinite(lastSyncId) ? lastSyncId : 0,
1219
+ models,
1220
+ ...(failedModels.length > 0 ? { failedModels } : {}),
1221
+ timestamp,
1222
+ ...(schemaHash !== undefined ? { schemaHash } : {}),
1223
+ };
1224
+ }