@powerhousedao/reactor 6.0.0-dev.23 → 6.0.0-dev.230

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 (409) hide show
  1. package/dist/index.d.ts +4544 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +9941 -0
  4. package/dist/index.js.map +1 -0
  5. package/package.json +20 -18
  6. package/dist/src/actions/index.d.ts +0 -24
  7. package/dist/src/actions/index.d.ts.map +0 -1
  8. package/dist/src/actions/index.js +0 -76
  9. package/dist/src/actions/index.js.map +0 -1
  10. package/dist/src/cache/buffer/ring-buffer.d.ts +0 -37
  11. package/dist/src/cache/buffer/ring-buffer.d.ts.map +0 -1
  12. package/dist/src/cache/buffer/ring-buffer.js +0 -69
  13. package/dist/src/cache/buffer/ring-buffer.js.map +0 -1
  14. package/dist/src/cache/document-meta-cache-types.d.ts +0 -114
  15. package/dist/src/cache/document-meta-cache-types.d.ts.map +0 -1
  16. package/dist/src/cache/document-meta-cache-types.js +0 -2
  17. package/dist/src/cache/document-meta-cache-types.js.map +0 -1
  18. package/dist/src/cache/document-meta-cache.d.ts +0 -30
  19. package/dist/src/cache/document-meta-cache.d.ts.map +0 -1
  20. package/dist/src/cache/document-meta-cache.js +0 -128
  21. package/dist/src/cache/document-meta-cache.js.map +0 -1
  22. package/dist/src/cache/index.d.ts +0 -3
  23. package/dist/src/cache/index.d.ts.map +0 -1
  24. package/dist/src/cache/index.js +0 -2
  25. package/dist/src/cache/index.js.map +0 -1
  26. package/dist/src/cache/kysely-operation-index.d.ts +0 -16
  27. package/dist/src/cache/kysely-operation-index.d.ts.map +0 -1
  28. package/dist/src/cache/kysely-operation-index.js +0 -265
  29. package/dist/src/cache/kysely-operation-index.js.map +0 -1
  30. package/dist/src/cache/kysely-write-cache.d.ts +0 -134
  31. package/dist/src/cache/kysely-write-cache.d.ts.map +0 -1
  32. package/dist/src/cache/kysely-write-cache.js +0 -388
  33. package/dist/src/cache/kysely-write-cache.js.map +0 -1
  34. package/dist/src/cache/lru/lru-tracker.d.ts +0 -15
  35. package/dist/src/cache/lru/lru-tracker.d.ts.map +0 -1
  36. package/dist/src/cache/lru/lru-tracker.js +0 -96
  37. package/dist/src/cache/lru/lru-tracker.js.map +0 -1
  38. package/dist/src/cache/operation-index-types.d.ts +0 -51
  39. package/dist/src/cache/operation-index-types.d.ts.map +0 -1
  40. package/dist/src/cache/operation-index-types.js +0 -4
  41. package/dist/src/cache/operation-index-types.js.map +0 -1
  42. package/dist/src/cache/write/interfaces.d.ts +0 -83
  43. package/dist/src/cache/write/interfaces.d.ts.map +0 -1
  44. package/dist/src/cache/write/interfaces.js +0 -2
  45. package/dist/src/cache/write/interfaces.js.map +0 -1
  46. package/dist/src/cache/write-cache-types.d.ts +0 -42
  47. package/dist/src/cache/write-cache-types.d.ts.map +0 -1
  48. package/dist/src/cache/write-cache-types.js +0 -2
  49. package/dist/src/cache/write-cache-types.js.map +0 -1
  50. package/dist/src/client/reactor-client.d.ts +0 -121
  51. package/dist/src/client/reactor-client.d.ts.map +0 -1
  52. package/dist/src/client/reactor-client.js +0 -425
  53. package/dist/src/client/reactor-client.js.map +0 -1
  54. package/dist/src/client/types.d.ts +0 -253
  55. package/dist/src/client/types.d.ts.map +0 -1
  56. package/dist/src/client/types.js +0 -14
  57. package/dist/src/client/types.js.map +0 -1
  58. package/dist/src/core/reactor-builder.d.ts +0 -47
  59. package/dist/src/core/reactor-builder.d.ts.map +0 -1
  60. package/dist/src/core/reactor-builder.js +0 -231
  61. package/dist/src/core/reactor-builder.js.map +0 -1
  62. package/dist/src/core/reactor-client-builder.d.ts +0 -49
  63. package/dist/src/core/reactor-client-builder.d.ts.map +0 -1
  64. package/dist/src/core/reactor-client-builder.js +0 -123
  65. package/dist/src/core/reactor-client-builder.js.map +0 -1
  66. package/dist/src/core/reactor.d.ts +0 -116
  67. package/dist/src/core/reactor.d.ts.map +0 -1
  68. package/dist/src/core/reactor.js +0 -988
  69. package/dist/src/core/reactor.js.map +0 -1
  70. package/dist/src/core/types.d.ts +0 -277
  71. package/dist/src/core/types.d.ts.map +0 -1
  72. package/dist/src/core/types.js +0 -2
  73. package/dist/src/core/types.js.map +0 -1
  74. package/dist/src/core/utils.d.ts +0 -59
  75. package/dist/src/core/utils.d.ts.map +0 -1
  76. package/dist/src/core/utils.js +0 -171
  77. package/dist/src/core/utils.js.map +0 -1
  78. package/dist/src/events/event-bus.d.ts +0 -8
  79. package/dist/src/events/event-bus.d.ts.map +0 -1
  80. package/dist/src/events/event-bus.js +0 -53
  81. package/dist/src/events/event-bus.js.map +0 -1
  82. package/dist/src/events/interfaces.d.ts +0 -27
  83. package/dist/src/events/interfaces.d.ts.map +0 -1
  84. package/dist/src/events/interfaces.js +0 -2
  85. package/dist/src/events/interfaces.js.map +0 -1
  86. package/dist/src/events/types.d.ts +0 -67
  87. package/dist/src/events/types.d.ts.map +0 -1
  88. package/dist/src/events/types.js +0 -28
  89. package/dist/src/events/types.js.map +0 -1
  90. package/dist/src/executor/interfaces.d.ts +0 -49
  91. package/dist/src/executor/interfaces.d.ts.map +0 -1
  92. package/dist/src/executor/interfaces.js +0 -2
  93. package/dist/src/executor/interfaces.js.map +0 -1
  94. package/dist/src/executor/simple-job-executor-manager.d.ts +0 -34
  95. package/dist/src/executor/simple-job-executor-manager.d.ts.map +0 -1
  96. package/dist/src/executor/simple-job-executor-manager.js +0 -233
  97. package/dist/src/executor/simple-job-executor-manager.js.map +0 -1
  98. package/dist/src/executor/simple-job-executor.d.ts +0 -80
  99. package/dist/src/executor/simple-job-executor.d.ts.map +0 -1
  100. package/dist/src/executor/simple-job-executor.js +0 -898
  101. package/dist/src/executor/simple-job-executor.js.map +0 -1
  102. package/dist/src/executor/types.d.ts +0 -93
  103. package/dist/src/executor/types.d.ts.map +0 -1
  104. package/dist/src/executor/types.js +0 -11
  105. package/dist/src/executor/types.js.map +0 -1
  106. package/dist/src/executor/util.d.ts +0 -74
  107. package/dist/src/executor/util.d.ts.map +0 -1
  108. package/dist/src/executor/util.js +0 -184
  109. package/dist/src/executor/util.js.map +0 -1
  110. package/dist/src/index.d.ts +0 -53
  111. package/dist/src/index.d.ts.map +0 -1
  112. package/dist/src/index.js +0 -62
  113. package/dist/src/index.js.map +0 -1
  114. package/dist/src/job-tracker/in-memory-job-tracker.d.ts +0 -25
  115. package/dist/src/job-tracker/in-memory-job-tracker.d.ts.map +0 -1
  116. package/dist/src/job-tracker/in-memory-job-tracker.js +0 -112
  117. package/dist/src/job-tracker/in-memory-job-tracker.js.map +0 -1
  118. package/dist/src/job-tracker/index.d.ts +0 -3
  119. package/dist/src/job-tracker/index.d.ts.map +0 -1
  120. package/dist/src/job-tracker/index.js +0 -2
  121. package/dist/src/job-tracker/index.js.map +0 -1
  122. package/dist/src/job-tracker/interfaces.d.ts +0 -39
  123. package/dist/src/job-tracker/interfaces.d.ts.map +0 -1
  124. package/dist/src/job-tracker/interfaces.js +0 -2
  125. package/dist/src/job-tracker/interfaces.js.map +0 -1
  126. package/dist/src/logging/console.d.ts +0 -23
  127. package/dist/src/logging/console.d.ts.map +0 -1
  128. package/dist/src/logging/console.js +0 -108
  129. package/dist/src/logging/console.js.map +0 -1
  130. package/dist/src/logging/types.d.ts +0 -12
  131. package/dist/src/logging/types.d.ts.map +0 -1
  132. package/dist/src/logging/types.js +0 -2
  133. package/dist/src/logging/types.js.map +0 -1
  134. package/dist/src/processors/index.d.ts +0 -3
  135. package/dist/src/processors/index.d.ts.map +0 -1
  136. package/dist/src/processors/index.js +0 -2
  137. package/dist/src/processors/index.js.map +0 -1
  138. package/dist/src/processors/processor-manager.d.ts +0 -38
  139. package/dist/src/processors/processor-manager.d.ts.map +0 -1
  140. package/dist/src/processors/processor-manager.js +0 -165
  141. package/dist/src/processors/processor-manager.js.map +0 -1
  142. package/dist/src/processors/types.d.ts +0 -63
  143. package/dist/src/processors/types.d.ts.map +0 -1
  144. package/dist/src/processors/types.js +0 -2
  145. package/dist/src/processors/types.js.map +0 -1
  146. package/dist/src/processors/utils.d.ts +0 -10
  147. package/dist/src/processors/utils.d.ts.map +0 -1
  148. package/dist/src/processors/utils.js +0 -59
  149. package/dist/src/processors/utils.js.map +0 -1
  150. package/dist/src/queue/interfaces.d.ts +0 -103
  151. package/dist/src/queue/interfaces.d.ts.map +0 -1
  152. package/dist/src/queue/interfaces.js +0 -2
  153. package/dist/src/queue/interfaces.js.map +0 -1
  154. package/dist/src/queue/job-execution-handle.d.ts +0 -25
  155. package/dist/src/queue/job-execution-handle.d.ts.map +0 -1
  156. package/dist/src/queue/job-execution-handle.js +0 -62
  157. package/dist/src/queue/job-execution-handle.js.map +0 -1
  158. package/dist/src/queue/queue.d.ts +0 -81
  159. package/dist/src/queue/queue.d.ts.map +0 -1
  160. package/dist/src/queue/queue.js +0 -384
  161. package/dist/src/queue/queue.js.map +0 -1
  162. package/dist/src/queue/types.d.ts +0 -73
  163. package/dist/src/queue/types.d.ts.map +0 -1
  164. package/dist/src/queue/types.js +0 -19
  165. package/dist/src/queue/types.js.map +0 -1
  166. package/dist/src/read-models/base-read-model.d.ts +0 -60
  167. package/dist/src/read-models/base-read-model.d.ts.map +0 -1
  168. package/dist/src/read-models/base-read-model.js +0 -143
  169. package/dist/src/read-models/base-read-model.js.map +0 -1
  170. package/dist/src/read-models/coordinator.d.ts +0 -39
  171. package/dist/src/read-models/coordinator.d.ts.map +0 -1
  172. package/dist/src/read-models/coordinator.js +0 -72
  173. package/dist/src/read-models/coordinator.js.map +0 -1
  174. package/dist/src/read-models/document-view.d.ts +0 -24
  175. package/dist/src/read-models/document-view.d.ts.map +0 -1
  176. package/dist/src/read-models/document-view.js +0 -377
  177. package/dist/src/read-models/document-view.js.map +0 -1
  178. package/dist/src/read-models/interfaces.d.ts +0 -29
  179. package/dist/src/read-models/interfaces.d.ts.map +0 -1
  180. package/dist/src/read-models/interfaces.js +0 -2
  181. package/dist/src/read-models/interfaces.js.map +0 -1
  182. package/dist/src/read-models/types.d.ts +0 -47
  183. package/dist/src/read-models/types.d.ts.map +0 -1
  184. package/dist/src/read-models/types.js +0 -2
  185. package/dist/src/read-models/types.js.map +0 -1
  186. package/dist/src/registry/implementation.d.ts +0 -70
  187. package/dist/src/registry/implementation.d.ts.map +0 -1
  188. package/dist/src/registry/implementation.js +0 -216
  189. package/dist/src/registry/implementation.js.map +0 -1
  190. package/dist/src/registry/index.d.ts +0 -3
  191. package/dist/src/registry/index.d.ts.map +0 -1
  192. package/dist/src/registry/index.js +0 -2
  193. package/dist/src/registry/index.js.map +0 -1
  194. package/dist/src/registry/interfaces.d.ts +0 -100
  195. package/dist/src/registry/interfaces.d.ts.map +0 -1
  196. package/dist/src/registry/interfaces.js +0 -2
  197. package/dist/src/registry/interfaces.js.map +0 -1
  198. package/dist/src/shared/awaiter.d.ts +0 -35
  199. package/dist/src/shared/awaiter.d.ts.map +0 -1
  200. package/dist/src/shared/awaiter.js +0 -123
  201. package/dist/src/shared/awaiter.js.map +0 -1
  202. package/dist/src/shared/consistency-tracker.d.ts +0 -48
  203. package/dist/src/shared/consistency-tracker.d.ts.map +0 -1
  204. package/dist/src/shared/consistency-tracker.js +0 -123
  205. package/dist/src/shared/consistency-tracker.js.map +0 -1
  206. package/dist/src/shared/drive-url.d.ts +0 -15
  207. package/dist/src/shared/drive-url.d.ts.map +0 -1
  208. package/dist/src/shared/drive-url.js +0 -17
  209. package/dist/src/shared/drive-url.js.map +0 -1
  210. package/dist/src/shared/errors.d.ts +0 -41
  211. package/dist/src/shared/errors.d.ts.map +0 -1
  212. package/dist/src/shared/errors.js +0 -75
  213. package/dist/src/shared/errors.js.map +0 -1
  214. package/dist/src/shared/factories.d.ts +0 -16
  215. package/dist/src/shared/factories.d.ts.map +0 -1
  216. package/dist/src/shared/factories.js +0 -33
  217. package/dist/src/shared/factories.js.map +0 -1
  218. package/dist/src/shared/types.d.ts +0 -136
  219. package/dist/src/shared/types.d.ts.map +0 -1
  220. package/dist/src/shared/types.js +0 -38
  221. package/dist/src/shared/types.js.map +0 -1
  222. package/dist/src/shared/utils.d.ts +0 -3
  223. package/dist/src/shared/utils.d.ts.map +0 -1
  224. package/dist/src/shared/utils.js +0 -8
  225. package/dist/src/shared/utils.js.map +0 -1
  226. package/dist/src/signer/passthrough-signer.d.ts +0 -12
  227. package/dist/src/signer/passthrough-signer.d.ts.map +0 -1
  228. package/dist/src/signer/passthrough-signer.js +0 -19
  229. package/dist/src/signer/passthrough-signer.js.map +0 -1
  230. package/dist/src/signer/types.d.ts +0 -17
  231. package/dist/src/signer/types.d.ts.map +0 -1
  232. package/dist/src/signer/types.js +0 -2
  233. package/dist/src/signer/types.js.map +0 -1
  234. package/dist/src/storage/consistency-aware-legacy-storage.d.ts +0 -33
  235. package/dist/src/storage/consistency-aware-legacy-storage.d.ts.map +0 -1
  236. package/dist/src/storage/consistency-aware-legacy-storage.js +0 -65
  237. package/dist/src/storage/consistency-aware-legacy-storage.js.map +0 -1
  238. package/dist/src/storage/index.d.ts +0 -4
  239. package/dist/src/storage/index.d.ts.map +0 -1
  240. package/dist/src/storage/index.js +0 -3
  241. package/dist/src/storage/index.js.map +0 -1
  242. package/dist/src/storage/interfaces.d.ts +0 -454
  243. package/dist/src/storage/interfaces.d.ts.map +0 -1
  244. package/dist/src/storage/interfaces.js +0 -19
  245. package/dist/src/storage/interfaces.js.map +0 -1
  246. package/dist/src/storage/kysely/document-indexer.d.ts +0 -28
  247. package/dist/src/storage/kysely/document-indexer.d.ts.map +0 -1
  248. package/dist/src/storage/kysely/document-indexer.js +0 -350
  249. package/dist/src/storage/kysely/document-indexer.js.map +0 -1
  250. package/dist/src/storage/kysely/keyframe-store.d.ts +0 -15
  251. package/dist/src/storage/kysely/keyframe-store.d.ts.map +0 -1
  252. package/dist/src/storage/kysely/keyframe-store.js +0 -64
  253. package/dist/src/storage/kysely/keyframe-store.js.map +0 -1
  254. package/dist/src/storage/kysely/store.d.ts +0 -16
  255. package/dist/src/storage/kysely/store.d.ts.map +0 -1
  256. package/dist/src/storage/kysely/store.js +0 -246
  257. package/dist/src/storage/kysely/store.js.map +0 -1
  258. package/dist/src/storage/kysely/sync-cursor-storage.d.ts +0 -13
  259. package/dist/src/storage/kysely/sync-cursor-storage.d.ts.map +0 -1
  260. package/dist/src/storage/kysely/sync-cursor-storage.js +0 -93
  261. package/dist/src/storage/kysely/sync-cursor-storage.js.map +0 -1
  262. package/dist/src/storage/kysely/sync-remote-storage.d.ts +0 -13
  263. package/dist/src/storage/kysely/sync-remote-storage.d.ts.map +0 -1
  264. package/dist/src/storage/kysely/sync-remote-storage.js +0 -133
  265. package/dist/src/storage/kysely/sync-remote-storage.js.map +0 -1
  266. package/dist/src/storage/kysely/types.d.ts +0 -135
  267. package/dist/src/storage/kysely/types.d.ts.map +0 -1
  268. package/dist/src/storage/kysely/types.js +0 -2
  269. package/dist/src/storage/kysely/types.js.map +0 -1
  270. package/dist/src/storage/migrations/001_create_operation_table.d.ts +0 -3
  271. package/dist/src/storage/migrations/001_create_operation_table.d.ts.map +0 -1
  272. package/dist/src/storage/migrations/001_create_operation_table.js +0 -41
  273. package/dist/src/storage/migrations/001_create_operation_table.js.map +0 -1
  274. package/dist/src/storage/migrations/002_create_keyframe_table.d.ts +0 -3
  275. package/dist/src/storage/migrations/002_create_keyframe_table.d.ts.map +0 -1
  276. package/dist/src/storage/migrations/002_create_keyframe_table.js +0 -27
  277. package/dist/src/storage/migrations/002_create_keyframe_table.js.map +0 -1
  278. package/dist/src/storage/migrations/003_create_document_table.d.ts +0 -3
  279. package/dist/src/storage/migrations/003_create_document_table.d.ts.map +0 -1
  280. package/dist/src/storage/migrations/003_create_document_table.js +0 -10
  281. package/dist/src/storage/migrations/003_create_document_table.js.map +0 -1
  282. package/dist/src/storage/migrations/004_create_document_relationship_table.d.ts +0 -3
  283. package/dist/src/storage/migrations/004_create_document_relationship_table.d.ts.map +0 -1
  284. package/dist/src/storage/migrations/004_create_document_relationship_table.js +0 -35
  285. package/dist/src/storage/migrations/004_create_document_relationship_table.js.map +0 -1
  286. package/dist/src/storage/migrations/005_create_indexer_state_table.d.ts +0 -3
  287. package/dist/src/storage/migrations/005_create_indexer_state_table.d.ts.map +0 -1
  288. package/dist/src/storage/migrations/005_create_indexer_state_table.js +0 -10
  289. package/dist/src/storage/migrations/005_create_indexer_state_table.js.map +0 -1
  290. package/dist/src/storage/migrations/006_create_document_snapshot_table.d.ts +0 -3
  291. package/dist/src/storage/migrations/006_create_document_snapshot_table.d.ts.map +0 -1
  292. package/dist/src/storage/migrations/006_create_document_snapshot_table.js +0 -49
  293. package/dist/src/storage/migrations/006_create_document_snapshot_table.js.map +0 -1
  294. package/dist/src/storage/migrations/007_create_slug_mapping_table.d.ts +0 -3
  295. package/dist/src/storage/migrations/007_create_slug_mapping_table.d.ts.map +0 -1
  296. package/dist/src/storage/migrations/007_create_slug_mapping_table.js +0 -24
  297. package/dist/src/storage/migrations/007_create_slug_mapping_table.js.map +0 -1
  298. package/dist/src/storage/migrations/008_create_view_state_table.d.ts +0 -3
  299. package/dist/src/storage/migrations/008_create_view_state_table.d.ts.map +0 -1
  300. package/dist/src/storage/migrations/008_create_view_state_table.js +0 -10
  301. package/dist/src/storage/migrations/008_create_view_state_table.js.map +0 -1
  302. package/dist/src/storage/migrations/009_create_operation_index_tables.d.ts +0 -3
  303. package/dist/src/storage/migrations/009_create_operation_index_tables.d.ts.map +0 -1
  304. package/dist/src/storage/migrations/009_create_operation_index_tables.js +0 -50
  305. package/dist/src/storage/migrations/009_create_operation_index_tables.js.map +0 -1
  306. package/dist/src/storage/migrations/010_create_sync_tables.d.ts +0 -3
  307. package/dist/src/storage/migrations/010_create_sync_tables.d.ts.map +0 -1
  308. package/dist/src/storage/migrations/010_create_sync_tables.js +0 -43
  309. package/dist/src/storage/migrations/010_create_sync_tables.js.map +0 -1
  310. package/dist/src/storage/migrations/index.d.ts +0 -3
  311. package/dist/src/storage/migrations/index.d.ts.map +0 -1
  312. package/dist/src/storage/migrations/index.js +0 -3
  313. package/dist/src/storage/migrations/index.js.map +0 -1
  314. package/dist/src/storage/migrations/migrator.d.ts +0 -6
  315. package/dist/src/storage/migrations/migrator.d.ts.map +0 -1
  316. package/dist/src/storage/migrations/migrator.js +0 -78
  317. package/dist/src/storage/migrations/migrator.js.map +0 -1
  318. package/dist/src/storage/migrations/run-migrations.d.ts +0 -2
  319. package/dist/src/storage/migrations/run-migrations.d.ts.map +0 -1
  320. package/dist/src/storage/migrations/run-migrations.js +0 -58
  321. package/dist/src/storage/migrations/run-migrations.js.map +0 -1
  322. package/dist/src/storage/migrations/types.d.ts +0 -9
  323. package/dist/src/storage/migrations/types.d.ts.map +0 -1
  324. package/dist/src/storage/migrations/types.js +0 -2
  325. package/dist/src/storage/migrations/types.js.map +0 -1
  326. package/dist/src/storage/txn.d.ts +0 -15
  327. package/dist/src/storage/txn.d.ts.map +0 -1
  328. package/dist/src/storage/txn.js +0 -42
  329. package/dist/src/storage/txn.js.map +0 -1
  330. package/dist/src/subs/default-error-handler.d.ts +0 -13
  331. package/dist/src/subs/default-error-handler.d.ts.map +0 -1
  332. package/dist/src/subs/default-error-handler.js +0 -27
  333. package/dist/src/subs/default-error-handler.js.map +0 -1
  334. package/dist/src/subs/react-subscription-manager.d.ts +0 -45
  335. package/dist/src/subs/react-subscription-manager.d.ts.map +0 -1
  336. package/dist/src/subs/react-subscription-manager.js +0 -185
  337. package/dist/src/subs/react-subscription-manager.js.map +0 -1
  338. package/dist/src/subs/subscription-notification-read-model.d.ts +0 -17
  339. package/dist/src/subs/subscription-notification-read-model.d.ts.map +0 -1
  340. package/dist/src/subs/subscription-notification-read-model.js +0 -62
  341. package/dist/src/subs/subscription-notification-read-model.js.map +0 -1
  342. package/dist/src/subs/types.d.ts +0 -64
  343. package/dist/src/subs/types.d.ts.map +0 -1
  344. package/dist/src/subs/types.js +0 -2
  345. package/dist/src/subs/types.js.map +0 -1
  346. package/dist/src/sync/channels/composite-channel-factory.d.ts +0 -32
  347. package/dist/src/sync/channels/composite-channel-factory.d.ts.map +0 -1
  348. package/dist/src/sync/channels/composite-channel-factory.js +0 -88
  349. package/dist/src/sync/channels/composite-channel-factory.js.map +0 -1
  350. package/dist/src/sync/channels/gql-channel-factory.d.ts +0 -27
  351. package/dist/src/sync/channels/gql-channel-factory.d.ts.map +0 -1
  352. package/dist/src/sync/channels/gql-channel-factory.js +0 -77
  353. package/dist/src/sync/channels/gql-channel-factory.js.map +0 -1
  354. package/dist/src/sync/channels/gql-channel.d.ts +0 -120
  355. package/dist/src/sync/channels/gql-channel.d.ts.map +0 -1
  356. package/dist/src/sync/channels/gql-channel.js +0 -436
  357. package/dist/src/sync/channels/gql-channel.js.map +0 -1
  358. package/dist/src/sync/channels/index.d.ts +0 -6
  359. package/dist/src/sync/channels/index.d.ts.map +0 -1
  360. package/dist/src/sync/channels/index.js +0 -6
  361. package/dist/src/sync/channels/index.js.map +0 -1
  362. package/dist/src/sync/channels/polling-channel.d.ts +0 -39
  363. package/dist/src/sync/channels/polling-channel.d.ts.map +0 -1
  364. package/dist/src/sync/channels/polling-channel.js +0 -72
  365. package/dist/src/sync/channels/polling-channel.js.map +0 -1
  366. package/dist/src/sync/channels/utils.d.ts +0 -30
  367. package/dist/src/sync/channels/utils.d.ts.map +0 -1
  368. package/dist/src/sync/channels/utils.js +0 -96
  369. package/dist/src/sync/channels/utils.js.map +0 -1
  370. package/dist/src/sync/errors.d.ts +0 -10
  371. package/dist/src/sync/errors.d.ts.map +0 -1
  372. package/dist/src/sync/errors.js +0 -17
  373. package/dist/src/sync/errors.js.map +0 -1
  374. package/dist/src/sync/index.d.ts +0 -12
  375. package/dist/src/sync/index.d.ts.map +0 -1
  376. package/dist/src/sync/index.js +0 -9
  377. package/dist/src/sync/index.js.map +0 -1
  378. package/dist/src/sync/interfaces.d.ts +0 -182
  379. package/dist/src/sync/interfaces.d.ts.map +0 -1
  380. package/dist/src/sync/interfaces.js +0 -2
  381. package/dist/src/sync/interfaces.js.map +0 -1
  382. package/dist/src/sync/mailbox.d.ts +0 -21
  383. package/dist/src/sync/mailbox.d.ts.map +0 -1
  384. package/dist/src/sync/mailbox.js +0 -59
  385. package/dist/src/sync/mailbox.js.map +0 -1
  386. package/dist/src/sync/sync-builder.d.ts +0 -19
  387. package/dist/src/sync/sync-builder.d.ts.map +0 -1
  388. package/dist/src/sync/sync-builder.js +0 -39
  389. package/dist/src/sync/sync-builder.js.map +0 -1
  390. package/dist/src/sync/sync-manager.d.ts +0 -37
  391. package/dist/src/sync/sync-manager.d.ts.map +0 -1
  392. package/dist/src/sync/sync-manager.js +0 -267
  393. package/dist/src/sync/sync-manager.js.map +0 -1
  394. package/dist/src/sync/sync-operation.d.ts +0 -28
  395. package/dist/src/sync/sync-operation.d.ts.map +0 -1
  396. package/dist/src/sync/sync-operation.js +0 -63
  397. package/dist/src/sync/sync-operation.js.map +0 -1
  398. package/dist/src/sync/types.d.ts +0 -62
  399. package/dist/src/sync/types.d.ts.map +0 -1
  400. package/dist/src/sync/types.js +0 -16
  401. package/dist/src/sync/types.js.map +0 -1
  402. package/dist/src/sync/utils.d.ts +0 -36
  403. package/dist/src/sync/utils.d.ts.map +0 -1
  404. package/dist/src/sync/utils.js +0 -78
  405. package/dist/src/sync/utils.js.map +0 -1
  406. package/dist/src/utils/reshuffle.d.ts +0 -30
  407. package/dist/src/utils/reshuffle.d.ts.map +0 -1
  408. package/dist/src/utils/reshuffle.js +0 -47
  409. package/dist/src/utils/reshuffle.js.map +0 -1
@@ -0,0 +1,4544 @@
1
+ import { Action, CreateDocumentActionInput, DocumentModelModule, ISigner, Operation, OperationContext, OperationWithContext, OperationWithContext as OperationWithContext$1, PHDocument, PHDocumentState, SignatureVerificationHandler, UpgradeDocumentActionInput, UpgradeManifest, UpgradeReducer, UpgradeTransition, actions as documentActions } from "@powerhousedao/shared/document-model";
2
+ import { DocumentDriveDocument, DriveInput, FolderNode, Node } from "@powerhousedao/shared/document-drive";
3
+ import { ILogger } from "document-model";
4
+ import * as kysely from "kysely";
5
+ import { Generated, Insertable, Kysely, Transaction } from "kysely";
6
+ import { IProcessor, IProcessorHostModule, IProcessorManager, IProcessorManager as IProcessorManager$1, IRelationalDb, ProcessorApp, ProcessorFactory, ProcessorFactory as ProcessorFactory$1, ProcessorFactoryBuilder, ProcessorFilter, ProcessorRecord, ProcessorStatus, RelationalDbProcessor, TrackedProcessor, TrackedProcessor as TrackedProcessor$1, createRelationalDb } from "@powerhousedao/shared/processors";
7
+
8
+ //#region src/attachments/types.d.ts
9
+ /**
10
+ * Content hash of the attachment data. This is the primary identifier.
11
+ * Format is algorithm-dependent, e.g. SHA-256 hex.
12
+ */
13
+ type AttachmentHash = string;
14
+ /**
15
+ * A reference to an attachment, used in document state and action inputs.
16
+ * Format: `attachment://v<version>:<hash>`
17
+ *
18
+ * The version prefix allows changing the hash algorithm, encoding, or
19
+ * length without leaking implementation details into the ref format.
20
+ * Version 1 is defined as SHA-256 hex.
21
+ *
22
+ * Using the hash as the ref makes attachments content-addressable:
23
+ * any peer that has the bytes for a given hash can serve the attachment.
24
+ */
25
+ type AttachmentRef = `attachment://v${number}:${string}`;
26
+ //#endregion
27
+ //#region src/actions/index.d.ts
28
+ /**
29
+ * Creates a CREATE_DOCUMENT action for document creation.
30
+ */
31
+ declare function createDocumentAction(input: CreateDocumentActionInput): Action;
32
+ /**
33
+ * Creates an UPGRADE_DOCUMENT action to set initial document state.
34
+ */
35
+ declare function upgradeDocumentAction(input: UpgradeDocumentActionInput): Action;
36
+ /**
37
+ * Creates a DELETE_DOCUMENT action for document deletion.
38
+ */
39
+ declare function deleteDocumentAction(documentId: string): Action;
40
+ /**
41
+ * Creates an ADD_RELATIONSHIP action to establish a parent-child relationship.
42
+ */
43
+ declare function addRelationshipAction(sourceId: string, targetId: string, relationshipType?: string): Action;
44
+ /**
45
+ * Creates a REMOVE_RELATIONSHIP action to remove a parent-child relationship.
46
+ */
47
+ declare function removeRelationshipAction(sourceId: string, targetId: string, relationshipType?: string): Action;
48
+ //#endregion
49
+ //#region src/queue/types.d.ts
50
+ type JobKind = "mutation" | "load";
51
+ /**
52
+ * State of a job in the queue
53
+ */
54
+ declare enum JobQueueState {
55
+ UNKNOWN = -1,
56
+ PREPROCESSING = 0,
57
+ PENDING = 1,
58
+ READY = 2,
59
+ RUNNING = 3,
60
+ RESOLVED = 4
61
+ }
62
+ /**
63
+ * Interface for a job execution handle
64
+ */
65
+ interface IJobExecutionHandle {
66
+ readonly job: Job;
67
+ readonly state: JobQueueState;
68
+ start(): void;
69
+ complete(): void;
70
+ fail(error: ErrorInfo): void;
71
+ defer(): void;
72
+ }
73
+ /**
74
+ * Represents a job to be executed by the job executor
75
+ */
76
+ type Job = {
77
+ /** Unique identifier for the job */id: string; /** Classification of the job so executors can switch behavior */
78
+ kind: JobKind; /** The document ID this job operates on */
79
+ documentId: string; /** The scope of the operations */
80
+ scope: string; /** The branch of the operations */
81
+ branch: string; /** The actions to be executed (processed sequentially) */
82
+ actions: Action[]; /** Pre-existing operations to import (used for load jobs) */
83
+ operations: Operation[]; /** Timestamp when the job was created */
84
+ createdAt: string; /** The hint for the queue to use for ordering the job */
85
+ queueHint: string[]; /** Number of retry attempts */
86
+ retryCount?: number; /** Maximum number of retries allowed */
87
+ maxRetries?: number; /** Last error if job failed */
88
+ lastError?: ErrorInfo; /** History of all errors from each attempt (ordered) */
89
+ errorHistory: ErrorInfo[]; /** Metadata that flows through the job lifecycle */
90
+ meta: JobMeta;
91
+ };
92
+ /**
93
+ * Event types for the queue system
94
+ */
95
+ declare const QueueEventTypes: {
96
+ readonly JOB_AVAILABLE: 10000;
97
+ };
98
+ /**
99
+ * Event data for job available events
100
+ */
101
+ type JobAvailableEvent = {
102
+ documentId: string;
103
+ scope: string;
104
+ branch: string;
105
+ jobId: string;
106
+ };
107
+ //#endregion
108
+ //#region src/shared/types.d.ts
109
+ /**
110
+ * Information about an error including message and stack trace.
111
+ */
112
+ type ErrorInfo = {
113
+ message: string;
114
+ stack: string;
115
+ };
116
+ /**
117
+ * Describes the status of a shutdown operation.
118
+ */
119
+ type ShutdownStatus = {
120
+ /**
121
+ * True if and only if the system has been shutdown.
122
+ *
123
+ * This value is meant to be polled to determine if the system has been shutdown.
124
+ *
125
+ * In the case of a browser process, the `kill` method should be able to synchronously set this to true.
126
+ *
127
+ * In the case of a server process, a graceful shutdown period should be allowed for the system to finish its work.
128
+ */
129
+ get isShutdown(): boolean;
130
+ /**
131
+ * A promise that resolves when the shutdown process is complete.
132
+ *
133
+ * For server environments, await this promise to ensure all active jobs finish
134
+ * before exiting the process.
135
+ */
136
+ completed: Promise<void>;
137
+ };
138
+ /**
139
+ * Enum that determines deletion propagation.
140
+ */
141
+ declare enum PropagationMode {
142
+ None = "none",
143
+ Cascade = "cascade"
144
+ }
145
+ /**
146
+ * Enum that describes the type of relationship change.
147
+ */
148
+ declare enum RelationshipChangeType {
149
+ Added = "added",
150
+ Removed = "removed"
151
+ }
152
+ /**
153
+ * Batch-specific metadata always present on every job.
154
+ * Single jobs get a unique batchId and batchJobIds of [jobId].
155
+ */
156
+ type BatchMeta = {
157
+ batchId: string;
158
+ batchJobIds: string[];
159
+ };
160
+ /**
161
+ * Metadata that flows through the job lifecycle.
162
+ * Always includes batch fields; callers may add additional properties.
163
+ */
164
+ type JobMeta = BatchMeta & Record<string, unknown>;
165
+ /**
166
+ * Describes the current state of a job.
167
+ */
168
+ type JobInfo = {
169
+ id: string;
170
+ status: JobStatus;
171
+ createdAtUtcIso: string;
172
+ completedAtUtcIso?: string;
173
+ error?: ErrorInfo;
174
+ errorHistory?: ErrorInfo[];
175
+ result?: any;
176
+ /**
177
+ * A token for coordinating reads, only valid once a job reaches COMPLETED.
178
+ */
179
+ consistencyToken: ConsistencyToken;
180
+ /**
181
+ * Metadata that flows through the job lifecycle.
182
+ */
183
+ meta: JobMeta;
184
+ /**
185
+ * The full job object, populated on failure for debugging purposes.
186
+ */
187
+ job?: Job;
188
+ };
189
+ /**
190
+ * Job execution statuses
191
+ */
192
+ declare enum JobStatus {
193
+ /** Job is queued but not yet started */
194
+ PENDING = "PENDING",
195
+ /** Job is currently being executed */
196
+ RUNNING = "RUNNING",
197
+ /** Operations have been written to the operation store (JOB_WRITE_READY event) */
198
+ WRITE_READY = "WRITE_READY",
199
+ /** Read models have finished indexing operations (JOB_READ_READY event) */
200
+ READ_READY = "READ_READY",
201
+ /** Job failed (may be retried) */
202
+ FAILED = "FAILED"
203
+ }
204
+ /**
205
+ * Describe the view of a set of documents. That is, what pieces of the
206
+ * documents are populated.
207
+ */
208
+ type ViewFilter = {
209
+ branch?: string;
210
+ scopes?: string[];
211
+ revision?: number;
212
+ };
213
+ /**
214
+ * Describes filter options for searching documents.
215
+ *
216
+ * Each parameter is treated as an AND condition.
217
+ */
218
+ type SearchFilter = {
219
+ type?: string;
220
+ parentId?: string;
221
+ ids?: string[];
222
+ slugs?: string[];
223
+ };
224
+ /**
225
+ * Describes the options for paging.
226
+ */
227
+ type PagingOptions = {
228
+ cursor: string;
229
+ limit: number;
230
+ };
231
+ /**
232
+ * The paged result.
233
+ */
234
+ type PagedResults<T> = {
235
+ results: T[];
236
+ options: PagingOptions;
237
+ next?: () => Promise<PagedResults<T>>;
238
+ nextCursor?: string;
239
+ totalCount?: number;
240
+ };
241
+ /**
242
+ * A string key in the format `documentId:scope:branch` used to identify a consistency checkpoint.
243
+ */
244
+ type ConsistencyKey = `${string}:${string}:${string}`;
245
+ /**
246
+ * Describes a specific point in a document's operation history.
247
+ */
248
+ type ConsistencyCoordinate = {
249
+ documentId: string;
250
+ scope: string;
251
+ branch: string;
252
+ operationIndex: number;
253
+ };
254
+ /**
255
+ * A token that captures the state of write operations at a point in time.
256
+ * Can be used to ensure read-after-write consistency.
257
+ */
258
+ type ConsistencyToken = {
259
+ version: 1;
260
+ createdAtUtcIso: string;
261
+ coordinates: ConsistencyCoordinate[];
262
+ };
263
+ //#endregion
264
+ //#region src/read-models/interfaces.d.ts
265
+ /**
266
+ * Generic interface for any read model that can index operations.
267
+ * Implementations include IDocumentView, search indices, caches, etc.
268
+ */
269
+ interface IReadModel {
270
+ /**
271
+ * Unique name identifying this read model, used for lookup via getReadModel.
272
+ */
273
+ readonly name: string;
274
+ /**
275
+ * Indexes a list of operations into the read model.
276
+ * This method is called asynchronously when operations are written to the operation store.
277
+ *
278
+ * @param operations - The operations with their context to index
279
+ */
280
+ indexOperations(operations: OperationWithContext$1[]): Promise<void>;
281
+ }
282
+ /**
283
+ * Coordinates read model synchronization with operation writes.
284
+ * Listens to operation events from the event bus and updates all registered read models.
285
+ */
286
+ interface IReadModelCoordinator {
287
+ /**
288
+ * All registered read models (pre-ready and post-ready).
289
+ */
290
+ readonly readModels: IReadModel[];
291
+ /**
292
+ * Start listening for operation events and updating read models.
293
+ */
294
+ start(): void;
295
+ /**
296
+ * Stop listening and clean up subscriptions.
297
+ */
298
+ stop(): void;
299
+ }
300
+ //#endregion
301
+ //#region src/sync/types.d.ts
302
+ declare enum ChannelScheme {
303
+ CONNECT = "connect",
304
+ SWITCHBOARD = "switchboard"
305
+ }
306
+ /**
307
+ * Dynamic JWT token handler for generating authentication tokens per-request.
308
+ * Called with the target URL to enable audience-specific tokens (aud claim).
309
+ * Returns undefined if no authentication is available (e.g., user not logged in).
310
+ */
311
+ type JwtHandler = (url: string) => Promise<string | undefined>;
312
+ /**
313
+ * Controls how a remote drives its polling schedule.
314
+ * - `Auto` (default): the channel runs the configured interval timer in the background.
315
+ * - `Manual`: the channel registers and connects but never ticks on its own.
316
+ * Callers must invoke ISyncManager.triggerPull(name) to fetch.
317
+ */
318
+ declare enum PollBehavior {
319
+ Auto = "auto",
320
+ Manual = "manual"
321
+ }
322
+ type RemoteOptions = {
323
+ /**
324
+ * Stringified UTC timestamp (ms). When set and not `"0"`, outbox operations older
325
+ * than this value are excluded. `"0"` and `undefined` are equivalent and disable
326
+ * the filter, syncing from the beginning of history.
327
+ */
328
+ sinceTimestampUtcMs?: string;
329
+ /**
330
+ * Polling cadence for this remote. Defaults to `PollBehavior.Auto` when omitted.
331
+ */
332
+ pollBehavior?: PollBehavior;
333
+ };
334
+ type RemoteFilter = {
335
+ documentId: string[];
336
+ scope: string[];
337
+ branch: string;
338
+ };
339
+ type RemoteCursor = {
340
+ remoteName: string;
341
+ cursorType: string;
342
+ cursorOrdinal: number;
343
+ lastSyncedAtUtcMs?: number;
344
+ };
345
+ type ChannelMeta = {
346
+ id: string;
347
+ };
348
+ type SyncEnvelopeType = "operations" | "ack";
349
+ type SyncEnvelope = {
350
+ type: SyncEnvelopeType;
351
+ channelMeta: ChannelMeta;
352
+ operations?: OperationWithContext$1[];
353
+ cursor?: RemoteCursor;
354
+ key?: string;
355
+ dependsOn?: string[];
356
+ };
357
+ declare enum SyncOperationStatus {
358
+ Unknown = -1,
359
+ TransportPending = 0,
360
+ ExecutionPending = 1,
361
+ Applied = 2,
362
+ Error = 3
363
+ }
364
+ declare enum ChannelErrorSource {
365
+ None = "none",
366
+ Channel = "channel",
367
+ Inbox = "inbox",
368
+ Outbox = "outbox"
369
+ }
370
+ type SyncOperationErrorType = "SIGNATURE_INVALID" | "HASH_MISMATCH" | "LIBRARY_ERROR" | "MISSING_OPERATIONS" | "EXCESSIVE_SHUFFLE" | "GRACEFUL_ABORT";
371
+ type ChannelHealth = {
372
+ state: "idle" | "running" | "error";
373
+ lastSuccessUtcMs?: number;
374
+ lastFailureUtcMs?: number;
375
+ failureCount: number;
376
+ };
377
+ type ConnectionState = "connecting" | "connected" | "disconnected" | "reconnecting" | "error";
378
+ type ConnectionStateSnapshot = {
379
+ state: ConnectionState;
380
+ failureCount: number;
381
+ lastSuccessUtcMs: number;
382
+ lastFailureUtcMs: number;
383
+ pushBlocked: boolean;
384
+ pushFailureCount: number;
385
+ receivingPages: boolean;
386
+ };
387
+ type ConnectionStateChangedEvent = {
388
+ remoteName: string;
389
+ remoteId: string;
390
+ previous: ConnectionState;
391
+ current: ConnectionState;
392
+ snapshot: ConnectionStateSnapshot;
393
+ };
394
+ type RemoteStatus = {
395
+ push: ChannelHealth;
396
+ pull: ChannelHealth;
397
+ };
398
+ type ChannelConfig = {
399
+ type: string;
400
+ parameters: Record<string, unknown>;
401
+ };
402
+ type RemoteRecord = {
403
+ id: string;
404
+ name: string;
405
+ collectionId: string;
406
+ channelConfig: ChannelConfig;
407
+ filter: RemoteFilter;
408
+ options: RemoteOptions;
409
+ status: RemoteStatus;
410
+ };
411
+ /**
412
+ * Event types for sync lifecycle events.
413
+ * These events track the sync progress of a job's operations to remotes.
414
+ * Uses a separate namespace (20000 range) from ReactorEventTypes (10000 range).
415
+ */
416
+ declare const SyncEventTypes: {
417
+ readonly SYNC_PENDING: 20001;
418
+ readonly SYNC_SUCCEEDED: 20002;
419
+ readonly SYNC_FAILED: 20003;
420
+ readonly DEAD_LETTER_ADDED: 20004;
421
+ readonly CONNECTION_STATE_CHANGED: 20005;
422
+ };
423
+ /**
424
+ * Event emitted when all SyncOperations for a job are queued in outboxes.
425
+ */
426
+ type SyncPendingEvent = {
427
+ jobId: string;
428
+ syncOperationCount: number;
429
+ remoteNames: string[];
430
+ };
431
+ /**
432
+ * Event emitted when all sync operations for a job succeed.
433
+ */
434
+ type SyncSucceededEvent = {
435
+ jobId: string;
436
+ syncOperationCount: number;
437
+ };
438
+ /**
439
+ * Event emitted when at least one sync operation for a job fails.
440
+ */
441
+ type SyncFailedEvent = {
442
+ jobId: string;
443
+ successCount: number;
444
+ failureCount: number;
445
+ errors: Array<{
446
+ remoteName: string;
447
+ documentId: string;
448
+ error: string;
449
+ }>;
450
+ };
451
+ /**
452
+ * Event emitted when a sync operation is moved to dead letter storage.
453
+ */
454
+ type DeadLetterAddedEvent = {
455
+ id: string;
456
+ jobId: string;
457
+ remoteName: string;
458
+ documentId: string;
459
+ errorSource: ChannelErrorSource;
460
+ };
461
+ /**
462
+ * Status of a sync operation result.
463
+ */
464
+ type SyncResultStatus = "succeeded" | "failed";
465
+ /**
466
+ * Error information for a failed sync operation to a specific remote.
467
+ */
468
+ type SyncResultError = {
469
+ remoteName: string;
470
+ documentId: string;
471
+ error: string;
472
+ };
473
+ /**
474
+ * Result of waiting for sync operations to complete for a job.
475
+ * Returned by ISyncManager.waitForSync().
476
+ */
477
+ type SyncResult = {
478
+ jobId: string;
479
+ status: SyncResultStatus;
480
+ syncOperationCount: number;
481
+ successCount: number;
482
+ failureCount: number;
483
+ errors: SyncResultError[];
484
+ };
485
+ //#endregion
486
+ //#region src/storage/interfaces.d.ts
487
+ /**
488
+ * Thrown when an operation with the same identity already exists in the store.
489
+ */
490
+ declare class DuplicateOperationError extends Error {
491
+ constructor(description: string);
492
+ }
493
+ /**
494
+ * Thrown when a concurrent write conflict is detected during an atomic apply.
495
+ */
496
+ declare class OptimisticLockError extends Error {
497
+ constructor(message: string);
498
+ }
499
+ /**
500
+ * Thrown when the caller-provided revision does not match the current
501
+ * stored revision, indicating a stale read.
502
+ */
503
+ declare class RevisionMismatchError extends Error {
504
+ constructor(expected: number, actual: number);
505
+ }
506
+ /**
507
+ * A write transaction passed to {@link IOperationStore.apply}. Accumulates
508
+ * operations that are committed atomically when the callback returns.
509
+ */
510
+ interface AtomicTxn {
511
+ /** Stages one or more operations to be written as part of this transaction. */
512
+ addOperations(...operations: Operation[]): void;
513
+ }
514
+ /**
515
+ * Per-scope revision map for a document, used to reconstruct the header
516
+ * revision field and lastModified timestamp.
517
+ */
518
+ type DocumentRevisions = {
519
+ /** Map of scope to operation index for that scope */revision: Record<string, number>; /** Latest timestamp across revisions */
520
+ latestTimestamp: string;
521
+ };
522
+ /**
523
+ * Append-only store for document operations. Operations are partitioned by
524
+ * (documentId, scope, branch) and ordered by a monotonic revision index.
525
+ */
526
+ interface IOperationStore {
527
+ /**
528
+ * Atomically appends operations for a single document/scope/branch.
529
+ * The provided revision must match the current head; otherwise a
530
+ * {@link RevisionMismatchError} is thrown.
531
+ *
532
+ * @param documentId - The document id
533
+ * @param documentType - The document type identifier
534
+ * @param scope - The operation scope (e.g. "global", "local")
535
+ * @param branch - The branch name
536
+ * @param revision - Expected current revision (optimistic lock)
537
+ * @param fn - Callback that stages operations via {@link AtomicTxn}
538
+ * @param signal - Optional abort signal to cancel the request
539
+ */
540
+ apply(documentId: string, documentType: string, scope: string, branch: string, revision: number, fn: (txn: AtomicTxn) => void | Promise<void>, signal?: AbortSignal): Promise<void>;
541
+ /**
542
+ * Returns operations for a document/scope/branch whose index is greater
543
+ * than the given revision.
544
+ *
545
+ * @param documentId - The document id
546
+ * @param scope - The operation scope
547
+ * @param branch - The branch name
548
+ * @param revision - Return operations after this revision index
549
+ * @param filter - Optional filters (action types, timestamp range)
550
+ * @param paging - Optional paging options for cursor-based pagination
551
+ * @param signal - Optional abort signal to cancel the request
552
+ */
553
+ getSince(documentId: string, scope: string, branch: string, revision: number, filter?: OperationFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
554
+ /**
555
+ * Returns operations across all documents whose auto-increment store id
556
+ * is greater than the given id. Used by read models and sync to catch up
557
+ * on operations they may have missed.
558
+ *
559
+ * @param id - Return operations with store id greater than this value
560
+ * @param paging - Optional paging options for cursor-based pagination
561
+ * @param signal - Optional abort signal to cancel the request
562
+ */
563
+ getSinceId(id: number, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<OperationWithContext$1>>;
564
+ /**
565
+ * Gets operations that may conflict with incoming operations during a load.
566
+ *
567
+ * @param documentId - The document id
568
+ * @param scope - The scope to query
569
+ * @param branch - The branch name
570
+ * @param minTimestamp - Minimum timestamp (inclusive) as ISO string
571
+ * @param paging - Optional paging options for cursor-based pagination
572
+ * @param signal - Optional abort signal to cancel the request
573
+ * @returns Paged results of operations that may conflict
574
+ */
575
+ getConflicting(documentId: string, scope: string, branch: string, minTimestamp: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
576
+ /**
577
+ * Gets the latest operation index for each scope of a document, along with
578
+ * the latest timestamp across all scopes. This is used to efficiently reconstruct
579
+ * the revision map and lastModified timestamp for document headers.
580
+ *
581
+ * @param documentId - The document id
582
+ * @param branch - The branch name
583
+ * @param signal - Optional abort signal to cancel the request
584
+ * @returns Object containing revision map and latest timestamp
585
+ */
586
+ getRevisions(documentId: string, branch: string, signal?: AbortSignal): Promise<DocumentRevisions>;
587
+ }
588
+ /**
589
+ * Stores periodic document snapshots (keyframes) so that document state
590
+ * can be reconstructed without replaying the full operation history.
591
+ */
592
+ interface IKeyframeStore {
593
+ /**
594
+ * Stores a document snapshot at a specific revision.
595
+ *
596
+ * @param documentId - The document id
597
+ * @param scope - The operation scope
598
+ * @param branch - The branch name
599
+ * @param revision - The operation index this snapshot corresponds to
600
+ * @param document - The full document state to persist
601
+ * @param signal - Optional abort signal to cancel the request
602
+ */
603
+ putKeyframe(documentId: string, scope: string, branch: string, revision: number, document: PHDocument, signal?: AbortSignal): Promise<void>;
604
+ /**
605
+ * Finds the keyframe closest to (but not exceeding) the target revision.
606
+ * Returns undefined if no keyframe exists for this document/scope/branch.
607
+ *
608
+ * @param documentId - The document id
609
+ * @param scope - The operation scope
610
+ * @param branch - The branch name
611
+ * @param targetRevision - The desired revision upper bound
612
+ * @param signal - Optional abort signal to cancel the request
613
+ */
614
+ findNearestKeyframe(documentId: string, scope: string, branch: string, targetRevision: number, signal?: AbortSignal): Promise<{
615
+ revision: number;
616
+ document: PHDocument;
617
+ } | undefined>;
618
+ /**
619
+ * Lists all keyframes for a document, optionally filtered by scope and branch.
620
+ *
621
+ * @param documentId - The document id
622
+ * @param scope - Optional scope filter
623
+ * @param branch - Optional branch filter
624
+ * @param signal - Optional abort signal to cancel the request
625
+ */
626
+ listKeyframes(documentId: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<Array<{
627
+ scope: string;
628
+ branch: string;
629
+ revision: number;
630
+ document: PHDocument;
631
+ }>>;
632
+ /**
633
+ * Deletes keyframes for a document. Optionally scoped to a specific
634
+ * scope and/or branch.
635
+ *
636
+ * @param documentId - The document id
637
+ * @param scope - Optional scope filter; omit to delete across all scopes
638
+ * @param branch - Optional branch filter; omit to delete across all branches
639
+ * @param signal - Optional abort signal to cancel the request
640
+ * @returns The number of keyframes deleted
641
+ */
642
+ deleteKeyframes(documentId: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<number>;
643
+ }
644
+ /**
645
+ * Filters applied when reading document state from {@link IDocumentView}.
646
+ */
647
+ interface ViewFilter$1 {
648
+ /** Branch to read from. Defaults to the main branch when omitted. */
649
+ branch?: string;
650
+ /** Scopes to include. When omitted, all scopes are included. */
651
+ scopes?: string[];
652
+ /** Exclude operations originating from this remote name. */
653
+ excludeSourceRemote?: string;
654
+ }
655
+ /**
656
+ * Filter options for querying operations. When multiple filters are provided,
657
+ * they are combined with AND logic.
658
+ */
659
+ interface OperationFilter {
660
+ /** Filter by action types (OR logic within array) */
661
+ actionTypes?: string[];
662
+ /** Filter operations with timestamp >= this value (ISO string) */
663
+ timestampFrom?: string;
664
+ /** Filter operations with timestamp <= this value (ISO string) */
665
+ timestampTo?: string;
666
+ /** Filter operations with index >= this value */
667
+ sinceRevision?: number;
668
+ }
669
+ /**
670
+ * Materialised read model that maintains document snapshots. Snapshots are
671
+ * updated by indexing operations (which must include `resultingState`) and
672
+ * queried with optional consistency tokens for read-after-write guarantees.
673
+ */
674
+ interface IDocumentView extends IReadModel {
675
+ /**
676
+ * Initializes the view.
677
+ */
678
+ init(): Promise<void>;
679
+ /**
680
+ * Indexes a list of operations.
681
+ *
682
+ * @param items - Operations with context. Context MUST include ephemeral
683
+ * `resultingState` for optimization. IDocumentView never rebuilds
684
+ * documents from operations - it always requires resultingState.
685
+ */
686
+ indexOperations(items: OperationWithContext$1[]): Promise<void>;
687
+ /**
688
+ * Blocks until the view has processed the coordinates referenced by the
689
+ * provided consistency token.
690
+ *
691
+ * @param token - Consistency token derived from the originating job
692
+ * @param timeoutMs - Optional timeout window in milliseconds
693
+ * @param signal - Optional abort signal to cancel the wait
694
+ */
695
+ waitForConsistency(token: ConsistencyToken, timeoutMs?: number, signal?: AbortSignal): Promise<void>;
696
+ /**
697
+ * Returns true if and only if the documents exist.
698
+ *
699
+ * @param documentIds - The list of document ids to check.
700
+ * @param consistencyToken - Optional token for read-after-write consistency
701
+ * @param signal - Optional abort signal to cancel the request
702
+ */
703
+ exists(documentIds: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<boolean[]>;
704
+ /**
705
+ * Returns the document with the given id.
706
+ *
707
+ * @param documentId - The id of the document to get.
708
+ * @param view - Optional filter containing branch and scopes information
709
+ * @param consistencyToken - Optional token for read-after-write consistency
710
+ * @param signal - Optional abort signal to cancel the request
711
+ */
712
+ get<TDocument extends PHDocument>(documentId: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
713
+ /**
714
+ * Returns the documents with the given ids.
715
+ *
716
+ * @param documentIds - The list of document ids to get.
717
+ * @param view - Optional filter containing branch and scopes information
718
+ * @param consistencyToken - Optional token for read-after-write consistency
719
+ * @param signal - Optional abort signal to cancel the request
720
+ */
721
+ getMany<TDocument extends PHDocument>(documentIds: string[], view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument[]>;
722
+ /**
723
+ * Returns the document with the given identifier (either id or slug).
724
+ * Throws an error if the identifier matches both an id and a slug that refer to different documents.
725
+ *
726
+ * @param identifier - The id or slug of the document to get.
727
+ * @param view - Optional filter containing branch and scopes information
728
+ * @param consistencyToken - Optional token for read-after-write consistency
729
+ * @param signal - Optional abort signal to cancel the request
730
+ * @throws {Error} If identifier matches both an ID and slug referring to different documents
731
+ */
732
+ getByIdOrSlug<TDocument extends PHDocument>(identifier: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
733
+ /**
734
+ * Finds documents by their document type.
735
+ *
736
+ * @param type - The document type to search for
737
+ * @param view - Optional filter containing branch and scopes information
738
+ * @param paging - Optional paging options for cursor-based pagination
739
+ * @param consistencyToken - Optional token for read-after-write consistency
740
+ * @param signal - Optional abort signal to cancel the request
741
+ */
742
+ findByType(type: string, view?: ViewFilter$1, paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
743
+ /**
744
+ * Resolves a slug to a document ID.
745
+ *
746
+ * @param slug - The slug to resolve
747
+ * @param view - Optional filter containing branch and scopes information
748
+ * @param consistencyToken - Optional token for read-after-write consistency
749
+ * @param signal - Optional abort signal to cancel the request
750
+ * @returns The document ID or undefined if the slug doesn't exist
751
+ */
752
+ resolveSlug(slug: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string | undefined>;
753
+ /**
754
+ * Resolves a list of slugs to document IDs.
755
+ *
756
+ * @param slugs - The list of slugs to resolve.
757
+ * @param view - Optional filter containing branch and scopes information
758
+ * @param consistencyToken - Optional token for read-after-write consistency
759
+ * @param signal - Optional abort signal to cancel the request
760
+ * @returns The list of document IDs
761
+ */
762
+ resolveSlugs(slugs: string[], view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
763
+ /**
764
+ * Resolves an identifier (either id or slug) to a document ID.
765
+ * This is a lightweight alternative to getByIdOrSlug that returns just the ID
766
+ * without fetching the full document.
767
+ *
768
+ * @param identifier - The id or slug to resolve
769
+ * @param view - Optional filter containing branch and scopes information
770
+ * @param consistencyToken - Optional token for read-after-write consistency
771
+ * @param signal - Optional abort signal to cancel the request
772
+ * @returns The document ID
773
+ * @throws {Error} If document not found or identifier matches both an ID and slug referring to different documents
774
+ */
775
+ resolveIdOrSlug(identifier: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string>;
776
+ }
777
+ /**
778
+ * A directed relationship between two documents in the document graph.
779
+ */
780
+ type DocumentRelationship = {
781
+ sourceId: string;
782
+ targetId: string;
783
+ relationshipType: string;
784
+ metadata?: Record<string, unknown>;
785
+ createdAt: Date;
786
+ updatedAt: Date;
787
+ };
788
+ /**
789
+ * A lightweight directed edge in a {@link IDocumentGraph}.
790
+ */
791
+ type DocumentGraphEdge = {
792
+ from: string;
793
+ to: string;
794
+ type: string;
795
+ };
796
+ /**
797
+ * A subgraph of the document relationship graph, returned by traversal
798
+ * queries such as {@link IDocumentIndexer.findAncestors}.
799
+ */
800
+ interface IDocumentGraph {
801
+ nodes: string[];
802
+ edges: DocumentGraphEdge[];
803
+ }
804
+ /**
805
+ * Read model that maintains a directed graph of document relationships.
806
+ * Relationships are created and removed by indexing operations containing
807
+ * ADD_RELATIONSHIP and REMOVE_RELATIONSHIP actions.
808
+ */
809
+ interface IDocumentIndexer extends IReadModel {
810
+ /**
811
+ * Initializes the indexer and catches up on any missed operations.
812
+ */
813
+ init(): Promise<void>;
814
+ /**
815
+ * Indexes a list of operations to update the relationship graph.
816
+ *
817
+ * @param operations - Operations to index. Will process ADD_RELATIONSHIP and
818
+ * REMOVE_RELATIONSHIP operations.
819
+ */
820
+ indexOperations(operations: OperationWithContext$1[]): Promise<void>;
821
+ /**
822
+ * Blocks until the indexer has processed the coordinates referenced by the
823
+ * provided consistency token.
824
+ *
825
+ * @param token - Consistency token derived from the originating job
826
+ * @param timeoutMs - Optional timeout window in milliseconds
827
+ * @param signal - Optional abort signal to cancel the wait
828
+ */
829
+ waitForConsistency(token: ConsistencyToken, timeoutMs?: number, signal?: AbortSignal): Promise<void>;
830
+ /**
831
+ * Returns outgoing relationships from a document.
832
+ *
833
+ * @param documentId - The source document id
834
+ * @param types - Optional filter by relationship types
835
+ * @param consistencyToken - Optional token for read-after-write consistency
836
+ * @param signal - Optional abort signal to cancel the request
837
+ */
838
+ getOutgoing(documentId: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
839
+ /**
840
+ * Returns incoming relationships to a document.
841
+ *
842
+ * @param documentId - The target document id
843
+ * @param types - Optional filter by relationship types
844
+ * @param consistencyToken - Optional token for read-after-write consistency
845
+ * @param signal - Optional abort signal to cancel the request
846
+ */
847
+ getIncoming(documentId: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
848
+ /**
849
+ * Checks if a relationship exists between two documents.
850
+ *
851
+ * @param sourceId - The source document id
852
+ * @param targetId - The target document id
853
+ * @param types - Optional filter by relationship types
854
+ * @param consistencyToken - Optional token for read-after-write consistency
855
+ * @param signal - Optional abort signal to cancel the request
856
+ */
857
+ hasRelationship(sourceId: string, targetId: string, types?: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<boolean>;
858
+ /**
859
+ * Returns all undirected relationships between two documents.
860
+ *
861
+ * @param a - The ID of the first document
862
+ * @param b - The ID of the second document
863
+ * @param types - Optional filter by relationship types
864
+ * @param consistencyToken - Optional token for read-after-write consistency
865
+ * @param signal - Optional abort signal to cancel the request
866
+ */
867
+ getUndirectedRelationships(a: string, b: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
868
+ /**
869
+ * Returns all directed relationships between two documents.
870
+ *
871
+ * @param sourceId - The source document id
872
+ * @param targetId - The target document id
873
+ * @param types - Optional filter by relationship types
874
+ * @param consistencyToken - Optional token for read-after-write consistency
875
+ * @param signal - Optional abort signal to cancel the request
876
+ */
877
+ getDirectedRelationships(sourceId: string, targetId: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
878
+ /**
879
+ * Finds a path from source to target following directed edges.
880
+ *
881
+ * @param sourceId - The source document id
882
+ * @param targetId - The target document id
883
+ * @param types - Optional filter by relationship types
884
+ * @param consistencyToken - Optional token for read-after-write consistency
885
+ * @param signal - Optional abort signal to cancel the request
886
+ * @returns Array of document ids representing the path, or null if no path exists
887
+ */
888
+ findPath(sourceId: string, targetId: string, types?: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[] | null>;
889
+ /**
890
+ * Returns all ancestors of a document in the relationship graph.
891
+ *
892
+ * @param documentId - The document id
893
+ * @param types - Optional filter by relationship types
894
+ * @param consistencyToken - Optional token for read-after-write consistency
895
+ * @param signal - Optional abort signal to cancel the request
896
+ */
897
+ findAncestors(documentId: string, types?: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<IDocumentGraph>;
898
+ /**
899
+ * Returns children of the given parents that have no parents outside
900
+ * the given set. Used by cascade delete to find documents that would
901
+ * be orphaned if all the given parents were deleted.
902
+ *
903
+ * @param parentIds - The set of parent document ids (the deletion set)
904
+ * @param types - Optional filter by relationship types
905
+ * @param signal - Optional abort signal to cancel the request
906
+ */
907
+ getOrphanedChildren(parentIds: string[], types?: string[], signal?: AbortSignal): Promise<string[]>;
908
+ /**
909
+ * Returns all relationship types currently in the system.
910
+ *
911
+ * @param consistencyToken - Optional token for read-after-write consistency
912
+ * @param signal - Optional abort signal to cancel the request
913
+ */
914
+ getRelationshipTypes(consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
915
+ }
916
+ /**
917
+ * Persistent storage for sync remote configurations. Each remote represents
918
+ * a connection to an external system that operations can be synced with.
919
+ */
920
+ interface ISyncRemoteStorage {
921
+ /**
922
+ * Lists all remotes.
923
+ *
924
+ * @param signal - Optional abort signal to cancel the request
925
+ * @returns The remotes
926
+ */
927
+ list(signal?: AbortSignal): Promise<RemoteRecord[]>;
928
+ /**
929
+ * Gets a remote by name.
930
+ *
931
+ * @param name - The name of the remote
932
+ * @param signal - Optional abort signal to cancel the request
933
+ * @returns The remote
934
+ */
935
+ get(name: string, signal?: AbortSignal): Promise<RemoteRecord>;
936
+ /**
937
+ * Upserts a remote.
938
+ *
939
+ * @param remote - The remote to upsert
940
+ * @param signal - Optional abort signal to cancel the request
941
+ * @returns The remote
942
+ */
943
+ upsert(remote: RemoteRecord, signal?: AbortSignal): Promise<void>;
944
+ /**
945
+ * Removes a remote by name.
946
+ *
947
+ * @param name - The name of the remote
948
+ * @param signal - Optional abort signal to cancel the request
949
+ * @returns The remote
950
+ */
951
+ remove(name: string, signal?: AbortSignal): Promise<void>;
952
+ }
953
+ /**
954
+ * Persistent storage for sync cursors that track inbox/outbox progress
955
+ * per remote. Cursors allow sync to resume from where it left off.
956
+ */
957
+ interface ISyncCursorStorage {
958
+ /**
959
+ * Lists all cursors for a remote.
960
+ *
961
+ * @param remoteName - The name of the remote
962
+ * @param signal - Optional abort signal to cancel the request
963
+ * @returns The cursors
964
+ */
965
+ list(remoteName: string, signal?: AbortSignal): Promise<RemoteCursor[]>;
966
+ /**
967
+ * Gets a cursor for a remote.
968
+ *
969
+ * @param remoteName - The name of the remote
970
+ * @param cursorType - The type of cursor ("inbox" or "outbox")
971
+ * @param signal - Optional abort signal to cancel the request
972
+ * @returns The cursor
973
+ */
974
+ get(remoteName: string, cursorType: "inbox" | "outbox", signal?: AbortSignal): Promise<RemoteCursor>;
975
+ /**
976
+ * Upserts a cursor.
977
+ *
978
+ * @param cursor - The cursor to upsert
979
+ * @param signal - Optional abort signal to cancel the request
980
+ * @returns The cursor
981
+ */
982
+ upsert(cursor: RemoteCursor, signal?: AbortSignal): Promise<void>;
983
+ /**
984
+ * Removes a cursor for a remote.
985
+ *
986
+ * @param remoteName - The name of the remote
987
+ * @param signal - Optional abort signal to cancel the request
988
+ * @returns The cursor
989
+ */
990
+ remove(remoteName: string, signal?: AbortSignal): Promise<void>;
991
+ }
992
+ /**
993
+ * Serializable snapshot of a permanently failed SyncOperation.
994
+ */
995
+ type DeadLetterRecord = {
996
+ id: string;
997
+ jobId: string;
998
+ jobDependencies: string[];
999
+ remoteName: string;
1000
+ documentId: string;
1001
+ scopes: string[];
1002
+ branch: string;
1003
+ operations: OperationWithContext$1[];
1004
+ errorSource: ChannelErrorSource;
1005
+ errorMessage: string;
1006
+ };
1007
+ /**
1008
+ * Persists dead-lettered sync operations so they survive reactor restarts.
1009
+ */
1010
+ interface ISyncDeadLetterStorage {
1011
+ /**
1012
+ * Lists dead letters for a remote, ordered by ordinal DESC (newest first).
1013
+ *
1014
+ * @param remoteName - The name of the remote
1015
+ * @param paging - Optional paging options (cursor + limit)
1016
+ * @param signal - Optional abort signal to cancel the request
1017
+ * @returns Paged dead letter records
1018
+ */
1019
+ list(remoteName: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DeadLetterRecord>>;
1020
+ /**
1021
+ * Adds a dead letter. Duplicate ids are silently ignored.
1022
+ *
1023
+ * @param deadLetter - The dead letter record to persist
1024
+ * @param signal - Optional abort signal to cancel the request
1025
+ */
1026
+ add(deadLetter: DeadLetterRecord, signal?: AbortSignal): Promise<void>;
1027
+ /**
1028
+ * Removes a single dead letter by id.
1029
+ *
1030
+ * @param id - The dead letter id
1031
+ * @param signal - Optional abort signal to cancel the request
1032
+ */
1033
+ remove(id: string, signal?: AbortSignal): Promise<void>;
1034
+ /**
1035
+ * Removes all dead letters for a remote.
1036
+ *
1037
+ * @param remoteName - The name of the remote
1038
+ * @param signal - Optional abort signal to cancel the request
1039
+ */
1040
+ removeByRemote(remoteName: string, signal?: AbortSignal): Promise<void>;
1041
+ /**
1042
+ * Returns distinct document IDs that have any dead letter record across all remotes.
1043
+ * Used to populate the quarantine set on startup.
1044
+ *
1045
+ * @param signal - Optional abort signal to cancel the request
1046
+ */
1047
+ listQuarantinedDocumentIds(signal?: AbortSignal): Promise<string[]>;
1048
+ }
1049
+ //#endregion
1050
+ //#region src/cache/operation-index-types.d.ts
1051
+ type OperationIndexEntry = Operation & {
1052
+ ordinal?: number;
1053
+ documentId: string;
1054
+ documentType: string;
1055
+ branch: string;
1056
+ scope: string;
1057
+ sourceRemote: string;
1058
+ };
1059
+ interface IOperationIndexTxn {
1060
+ createCollection(collectionId: string): void;
1061
+ addToCollection(collectionId: string, documentId: string): void;
1062
+ removeFromCollection(collectionId: string, documentId: string): void;
1063
+ write(operations: OperationIndexEntry[]): void;
1064
+ }
1065
+ interface IOperationIndex {
1066
+ start(): IOperationIndexTxn;
1067
+ commit(txn: IOperationIndexTxn, signal?: AbortSignal): Promise<number[]>;
1068
+ find(collectionId: string, cursor?: number, view?: ViewFilter$1, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<OperationIndexEntry>>;
1069
+ /**
1070
+ * Get all operations for a specific document, ordered by ordinal.
1071
+ * Used for retroactive sync when a document is added to a collection.
1072
+ */
1073
+ get(documentId: string, view?: ViewFilter$1, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<OperationIndexEntry>>;
1074
+ getSinceOrdinal(ordinal: number, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<OperationWithContext$1>>;
1075
+ getLatestTimestampForCollection(collectionId: string, signal?: AbortSignal): Promise<string | null>;
1076
+ /**
1077
+ * Get all collection memberships for the given document IDs.
1078
+ * Returns a map of documentId to array of collection IDs.
1079
+ */
1080
+ getCollectionsForDocuments(documentIds: string[]): Promise<Record<string, string[]>>;
1081
+ }
1082
+ declare function driveCollectionId(branch: string, driveId: string): string;
1083
+ //#endregion
1084
+ //#region src/cache/write/interfaces.d.ts
1085
+ /**
1086
+ * IWriteCache is a write-side projection that optimizes document state retrieval
1087
+ * for the job executor. This is separate from IDocumentView (read-side projection) which optimizes
1088
+ * queries and searches.
1089
+ */
1090
+ interface IWriteCache {
1091
+ /**
1092
+ * Retrieves or builds the document at the specified revision.
1093
+ * If targetRevision is not provided, retrieves the latest state.
1094
+ *
1095
+ * @param documentId - The document identifier
1096
+ * @param scope - Operation scope
1097
+ * @param branch - Branch name
1098
+ * @param targetRevision - The exact revision to retrieve (optional, defaults to latest)
1099
+ * @param signal - Optional abort signal to cancel the operation
1100
+ * @returns The complete document at the specified revision
1101
+ *
1102
+ * @example
1103
+ * ```typescript
1104
+ * // Get latest document state
1105
+ * const doc = await cache.getState(docId, 'global', 'main');
1106
+ *
1107
+ * // Get document at specific revision
1108
+ * const doc = await cache.getState(docId, 'global', 'main', 42);
1109
+ * ```
1110
+ */
1111
+ getState(documentId: string, scope: string, branch: string, targetRevision?: number, signal?: AbortSignal): Promise<PHDocument>;
1112
+ /**
1113
+ * Stores a document snapshot in the cache at the specified revision.
1114
+ * Implementations may truncate the stored document (e.g. strip operation
1115
+ * history beyond the last entry per scope, clear clipboard) to bound memory
1116
+ * and copy cost. Callers must not assume that the document returned by a
1117
+ * subsequent getState() call will have a complete operations array; the only
1118
+ * guaranteed invariant is that operations[scope].at(-1) holds the latest
1119
+ * operation index for each scope present in the cached document.
1120
+ *
1121
+ * @param documentId - The document identifier
1122
+ * @param scope - Operation scope
1123
+ * @param branch - Branch name
1124
+ * @param revision - The revision this document represents
1125
+ * @param document - The document to cache
1126
+ *
1127
+ * @example
1128
+ * ```typescript
1129
+ * cache.putState(docId, 'global', 'main', 42, document);
1130
+ * ```
1131
+ */
1132
+ putState(documentId: string, scope: string, branch: string, revision: number, document: PHDocument): void;
1133
+ /**
1134
+ * Invalidates (removes) cached entries for a document stream.
1135
+ *
1136
+ * - If only documentId is provided: invalidates all scopes and branches for that document
1137
+ * - If documentId + scope provided: invalidates all branches for that document and scope
1138
+ * - If all parameters provided: invalidates the specific stream
1139
+ *
1140
+ * @param documentId - The document identifier
1141
+ * @param scope - Optional scope to narrow invalidation
1142
+ * @param branch - Optional branch to narrow invalidation
1143
+ * @returns Number of ring buffers evicted
1144
+ *
1145
+ * @example
1146
+ * ```typescript
1147
+ * // Invalidate all streams for a document
1148
+ * cache.invalidate(docId);
1149
+ *
1150
+ * // Invalidate all branches for a specific scope
1151
+ * cache.invalidate(docId, 'global');
1152
+ *
1153
+ * // Invalidate specific stream
1154
+ * cache.invalidate(docId, 'global', 'main');
1155
+ * ```
1156
+ */
1157
+ invalidate(documentId: string, scope?: string, branch?: string): number;
1158
+ /**
1159
+ * Clears all cached data from the in-memory cache.
1160
+ */
1161
+ clear(): void;
1162
+ /**
1163
+ * Performs startup initialization.
1164
+ */
1165
+ startup(): Promise<void>;
1166
+ /**
1167
+ * Performs graceful shutdown.
1168
+ */
1169
+ shutdown(): Promise<void>;
1170
+ }
1171
+ //#endregion
1172
+ //#region src/events/types.d.ts
1173
+ /**
1174
+ * Describes a function to unsubscribe from an event.
1175
+ */
1176
+ type Unsubscribe = () => void;
1177
+ /**
1178
+ * A subscriber is a function that is called when an event is emitted.
1179
+ *
1180
+ * It is passed the event type and the data.
1181
+ * It can return a promise or a value.
1182
+ * If it returns a promise, the event bus will wait for the promise to resolve before calling the next subscriber.
1183
+ * If it throws an error, the event bus will reject with an aggregate error of all errors.
1184
+ *
1185
+ * @param type - The type of event to emit.
1186
+ * @param data - The data to pass to the subscriber.
1187
+ */
1188
+ type Subscriber = (type: number, data: any) => void | Promise<void>;
1189
+ /**
1190
+ * Custom error class that aggregates multiple errors from event subscribers.
1191
+ */
1192
+ declare class EventBusAggregateError extends Error {
1193
+ readonly errors: any[];
1194
+ constructor(errors: unknown[]);
1195
+ }
1196
+ /**
1197
+ * Event types for reactor lifecycle events.
1198
+ */
1199
+ declare const ReactorEventTypes: {
1200
+ readonly JOB_PENDING: 10001;
1201
+ readonly JOB_RUNNING: 10002;
1202
+ readonly JOB_WRITE_READY: 10003;
1203
+ readonly JOB_READ_READY: 10004;
1204
+ readonly JOB_FAILED: 10005;
1205
+ };
1206
+ /**
1207
+ * Event emitted when a job is registered and waiting to be executed.
1208
+ */
1209
+ type JobPendingEvent = {
1210
+ jobId: string;
1211
+ jobMeta: JobMeta;
1212
+ };
1213
+ /**
1214
+ * Event emitted when a job starts executing.
1215
+ */
1216
+ type JobRunningEvent = {
1217
+ jobId: string;
1218
+ jobMeta: JobMeta;
1219
+ };
1220
+ /**
1221
+ * Event emitted when operations are written to IOperationStore.
1222
+ * Contains the operations directly to avoid round-trip queries.
1223
+ */
1224
+ type JobWriteReadyEvent = {
1225
+ jobId: string;
1226
+ operations: OperationWithContext$1[];
1227
+ jobMeta: JobMeta;
1228
+ /**
1229
+ * Maps documentId to the collection IDs it belongs to.
1230
+ * Used by SyncManager to route operations only to remotes
1231
+ * whose collection contains the document.
1232
+ */
1233
+ collectionMemberships?: Record<string, string[]>;
1234
+ };
1235
+ /**
1236
+ * Event emitted after all read models have finished processing operations.
1237
+ * This event fires after JOB_WRITE_READY and guarantees that:
1238
+ * - All read models (DocumentView, DocumentIndexer, etc.) have indexed the operations
1239
+ * - All consistency trackers have been updated with the new operation indices
1240
+ * - Queries without consistency tokens will now see the updated data
1241
+ *
1242
+ * This event is useful for:
1243
+ * - Test synchronization (knowing when read models are ready)
1244
+ * - Observability (measuring read model latency)
1245
+ * - Event-driven workflows (triggering downstream processes)
1246
+ */
1247
+ type JobReadReadyEvent = {
1248
+ jobId: string;
1249
+ operations: OperationWithContext$1[];
1250
+ };
1251
+ /**
1252
+ * Event emitted when a job fails with an unrecoverable error.
1253
+ * This event allows the JobAwaiter and other subscribers to react to job failures
1254
+ * without polling.
1255
+ */
1256
+ type JobFailedEvent$1 = {
1257
+ jobId: string;
1258
+ error: Error;
1259
+ job?: Job;
1260
+ };
1261
+ //#endregion
1262
+ //#region src/events/interfaces.d.ts
1263
+ /**
1264
+ * Describes an object that manages event subscriptions and emissions.
1265
+ */
1266
+ interface IEventBus {
1267
+ /**
1268
+ * Register a new subscriber.
1269
+ * Order is preserved by pushing to the end of the per-type array.
1270
+ *
1271
+ * @param type - The type of event to subscribe to.
1272
+ * @param subscriber - The subscriber function to call when the event is emitted.
1273
+ *
1274
+ * @returns A function to unsubscribe from the event.
1275
+ */
1276
+ subscribe<K>(type: number, subscriber: (type: number, event: K) => void | Promise<void>): Unsubscribe;
1277
+ /**
1278
+ * Emits an event and waits until **all** subscribers finish.
1279
+ * - Every subscriber present at emit-start is called, in registration order.
1280
+ * - Calls are invoked and settled sequentially.
1281
+ * - If subscribers throw/reject, `emit` rejects with an aggregate error of all errors.
1282
+ *
1283
+ * @param type - The type of event to emit.
1284
+ * @param data - The data to pass to the subscribers.
1285
+ */
1286
+ emit(type: number, data: any): Promise<void>;
1287
+ }
1288
+ //#endregion
1289
+ //#region src/shared/awaiter.d.ts
1290
+ interface IJobAwaiter {
1291
+ /**
1292
+ * Waits for a job to complete: turns a job into a promise.
1293
+ *
1294
+ * @param jobId - The job id or job object
1295
+ * @param signal - Optional abort signal to cancel the request
1296
+ * @returns The result of the job
1297
+ */
1298
+ waitForJob(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
1299
+ /**
1300
+ * Shuts down the job awaiter. This will synchronously reject all pending jobs.
1301
+ */
1302
+ shutdown(): void;
1303
+ }
1304
+ /**
1305
+ * Event-driven implementation of IJobAwaiter.
1306
+ * Subscribes to operation events to detect job completion without polling.
1307
+ */
1308
+ declare class JobAwaiter implements IJobAwaiter {
1309
+ private eventBus;
1310
+ private getJobStatus;
1311
+ private pendingJobs;
1312
+ private unsubscribers;
1313
+ constructor(eventBus: IEventBus, getJobStatus: (jobId: string, signal?: AbortSignal) => Promise<JobInfo>);
1314
+ private subscribeToEvents;
1315
+ shutdown(): void;
1316
+ waitForJob(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
1317
+ private handleWriteReady;
1318
+ private handleReadReady;
1319
+ private handleJobFailed;
1320
+ private checkAndResolveWaiters;
1321
+ }
1322
+ //#endregion
1323
+ //#region src/subs/types.d.ts
1324
+ /**
1325
+ * Error handler for subscription callback errors
1326
+ */
1327
+ interface ISubscriptionErrorHandler {
1328
+ /**
1329
+ * Called when a subscription callback throws an error
1330
+ * @param error - The error that was thrown
1331
+ * @param context - Context about which subscription failed
1332
+ */
1333
+ handleError(error: unknown, context: SubscriptionErrorContext): void;
1334
+ }
1335
+ /**
1336
+ * Context information about a subscription error
1337
+ */
1338
+ interface SubscriptionErrorContext {
1339
+ /** The type of event that was being processed */
1340
+ eventType: "created" | "deleted" | "updated" | "relationshipChanged";
1341
+ /** The subscription ID that failed */
1342
+ subscriptionId: string;
1343
+ /** Optional additional data about the event */
1344
+ eventData?: unknown;
1345
+ }
1346
+ /**
1347
+ * Interface for subscribing to document events in the reactor.
1348
+ */
1349
+ interface IReactorSubscriptionManager {
1350
+ /**
1351
+ * Subscribes to document creation events
1352
+ *
1353
+ * @param callback - Function called when documents are created
1354
+ * @param search - Optional search filter to limit which documents trigger events
1355
+ * @param view - Optional filter containing branch and scopes information
1356
+ * @returns A function that unsubscribes from the events
1357
+ */
1358
+ onDocumentCreated(callback: (result: PagedResults<string>) => void, search?: SearchFilter): () => void;
1359
+ /**
1360
+ * Subscribes to document deletion events
1361
+ *
1362
+ * @param callback - Function called when documents are deleted
1363
+ * @param search - Optional search filter to limit which documents trigger events
1364
+ * @returns A function that unsubscribes from the events
1365
+ */
1366
+ onDocumentDeleted(callback: (documentIds: string[]) => void, search?: SearchFilter): () => void;
1367
+ /**
1368
+ * Subscribes to document state updates
1369
+ *
1370
+ * @param callback - Function called when documents are updated
1371
+ * @param search - Optional search filter to limit which documents trigger events
1372
+ * @param view - Optional filter containing branch and scopes information
1373
+ * @returns A function that unsubscribes from the events
1374
+ */
1375
+ onDocumentStateUpdated(callback: (result: PagedResults<PHDocument>) => void, search?: SearchFilter, view?: ViewFilter): () => void;
1376
+ /**
1377
+ * Subscribes to parent-child relationship change events
1378
+ *
1379
+ * @param callback - Function called when parent-child relationships change
1380
+ * @param search - Optional search filter to limit which documents trigger events
1381
+ * @returns A function that unsubscribes from the events
1382
+ */
1383
+ onRelationshipChanged(callback: (parentId: string, childId: string, changeType: RelationshipChangeType) => void, search?: SearchFilter): () => void;
1384
+ }
1385
+ //#endregion
1386
+ //#region src/client/types.d.ts
1387
+ /**
1388
+ * Describes the types of document changes that can occur.
1389
+ */
1390
+ declare enum DocumentChangeType {
1391
+ Created = "created",
1392
+ Deleted = "deleted",
1393
+ Updated = "updated",
1394
+ ParentAdded = "parent_added",
1395
+ ParentRemoved = "parent_removed",
1396
+ ChildAdded = "child_added",
1397
+ ChildRemoved = "child_removed"
1398
+ }
1399
+ /**
1400
+ * Represents a change event for documents.
1401
+ */
1402
+ type DocumentChangeEvent = {
1403
+ type: DocumentChangeType;
1404
+ documents: PHDocument[];
1405
+ context?: {
1406
+ parentId?: string;
1407
+ childId?: string;
1408
+ };
1409
+ };
1410
+ /**
1411
+ * Options for creating an empty document.
1412
+ */
1413
+ type CreateDocumentOptions = {
1414
+ /** Optional "id" or "slug" of parent document */parentIdentifier?: string; /** Optional version of the document model to use (defaults to latest) */
1415
+ documentModelVersion?: number;
1416
+ };
1417
+ /**
1418
+ * Drive-aware operations grouped under `client.drives`.
1419
+ *
1420
+ * These methods orchestrate the multi-action, multi-document choreography
1421
+ * required to keep a drive's `state.global.nodes` array consistent with the
1422
+ * relationship index and the underlying documents. Use the flat
1423
+ * `IReactorClient` primitives (`get`, `execute`, `find`) for everything that
1424
+ * is not drive-aware.
1425
+ */
1426
+ interface IDriveClient {
1427
+ /**
1428
+ * Creates a new drive document and waits for completion.
1429
+ */
1430
+ create(input: DriveInput, signal?: AbortSignal): Promise<DocumentDriveDocument>;
1431
+ /**
1432
+ * Adds a document to a drive as a single batched operation.
1433
+ *
1434
+ * Issues CREATE_DOCUMENT, UPGRADE_DOCUMENT, ADD_RELATIONSHIP on the new
1435
+ * document and ADD_FILE on the drive in a single dependent batch.
1436
+ */
1437
+ addFile<TDocument extends PHDocument = PHDocument>(driveIdentifier: string, document: PHDocument, parentFolder?: string, signal?: AbortSignal): Promise<TDocument>;
1438
+ /**
1439
+ * Adds a folder node to a drive.
1440
+ */
1441
+ addFolder(driveIdentifier: string, name: string, parentFolder?: string, signal?: AbortSignal): Promise<FolderNode>;
1442
+ /**
1443
+ * Removes a node from a drive. Folder nodes cascade: descendant file
1444
+ * documents are deleted first, then the folder node entry itself.
1445
+ */
1446
+ removeNode(driveIdentifier: string, nodeId: string, signal?: AbortSignal): Promise<void>;
1447
+ /**
1448
+ * Renames a node. Updates both the underlying document header and the
1449
+ * drive's node entry.
1450
+ */
1451
+ renameNode(driveIdentifier: string, nodeId: string, name: string, signal?: AbortSignal): Promise<Node>;
1452
+ /**
1453
+ * Moves a node to a different parent folder within the same drive.
1454
+ * Pass `undefined` to move the node to the drive root.
1455
+ */
1456
+ moveNode(driveIdentifier: string, srcNodeId: string, targetParentFolderId: string | undefined, signal?: AbortSignal): Promise<DocumentDriveDocument>;
1457
+ /**
1458
+ * Copies a node (and its subtree, if it is a folder) within a drive.
1459
+ * Each copied file gets a new id and a duplicated document.
1460
+ */
1461
+ copyNode(driveIdentifier: string, srcNodeId: string, targetParentFolderId: string | undefined, signal?: AbortSignal): Promise<DocumentDriveDocument>;
1462
+ /**
1463
+ * Returns a single node from the drive's `state.global.nodes` array.
1464
+ */
1465
+ getNode(driveIdentifier: string, nodeId: string, signal?: AbortSignal): Promise<Node>;
1466
+ /**
1467
+ * Returns nodes in the drive, optionally filtered to a single parent
1468
+ * folder. Pass `null` to list root-level nodes only.
1469
+ */
1470
+ listNodes(driveIdentifier: string, parentFolder?: string | null, signal?: AbortSignal): Promise<Node[]>;
1471
+ }
1472
+ /**
1473
+ * The ReactorClient interface that wraps lower-level APIs to provide
1474
+ * a simpler interface for document operations.
1475
+ *
1476
+ * Features:
1477
+ * - Wraps Jobs with Promises for easier async handling
1478
+ * - Manages signing of submitted Action objects
1479
+ * - Provides quality-of-life functions for common tasks
1480
+ * - Wraps subscription interface with ViewFilters
1481
+ */
1482
+ interface IReactorClient {
1483
+ /**
1484
+ * Drive-aware operations. See {@link IDriveClient}.
1485
+ */
1486
+ readonly drives: IDriveClient;
1487
+ /**
1488
+ * Retrieves a list of document model modules.
1489
+ *
1490
+ * @param namespace - Optional namespace like "powerhouse" or "sky", defaults to ""
1491
+ * @param paging - Optional pagination options
1492
+ * @param signal - Optional abort signal to cancel the request
1493
+ * @returns List of document model modules
1494
+ */
1495
+ getDocumentModelModules(namespace?: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentModelModule>>;
1496
+ /**
1497
+ * Retrieves a specific document model module by document type.
1498
+ *
1499
+ * @param documentType - The document type identifier
1500
+ * @returns The document model module
1501
+ */
1502
+ getDocumentModelModule(documentType: string): Promise<DocumentModelModule<any>>;
1503
+ /**
1504
+ * Retrieves a specific document by identifier (either id or slug).
1505
+ *
1506
+ * @param identifier - Required, this is the document id or slug
1507
+ * @param view - Optional filter containing branch and scopes information
1508
+ * @param signal - Optional abort signal to cancel the request
1509
+ * @returns The up-to-date PHDocument with scopes and list of child document ids
1510
+ */
1511
+ get<TDocument extends PHDocument>(identifier: string, view?: ViewFilter, signal?: AbortSignal): Promise<TDocument>;
1512
+ /**
1513
+ * Retrieves operations for a document.
1514
+ *
1515
+ * @param documentIdentifier - Required, this is either a document "id" field or a "slug"
1516
+ * @param view - Optional filter containing branch and scopes information
1517
+ * @param filter - Optional filter for actionTypes, timestamps, and revision
1518
+ * @param paging - Optional pagination options
1519
+ * @param signal - Optional abort signal to cancel the request
1520
+ * @returns Paginated list of operations
1521
+ */
1522
+ getOperations(documentIdentifier: string, view?: ViewFilter, filter?: OperationFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
1523
+ /**
1524
+ * Retrieves outgoing relationships of a given type from a source document.
1525
+ *
1526
+ * @param sourceIdentifier - Required, this is either a document "id" field or a "slug"
1527
+ * @param relationshipType - The relationship type to filter by
1528
+ * @param view - Optional filter containing branch and scopes information
1529
+ * @param paging - Optional pagination options
1530
+ * @param signal - Optional abort signal to cancel the request
1531
+ * @returns The target documents and paging cursor
1532
+ */
1533
+ getOutgoingRelationships(sourceIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
1534
+ /**
1535
+ * Retrieves incoming relationships of a given type to a target document.
1536
+ *
1537
+ * @param targetIdentifier - Required, this is either a document "id" field or a "slug"
1538
+ * @param relationshipType - The relationship type to filter by
1539
+ * @param view - Optional filter containing branch and scopes information
1540
+ * @param paging - Optional pagination options
1541
+ * @param signal - Optional abort signal to cancel the request
1542
+ * @returns The source documents and paging cursor
1543
+ */
1544
+ getIncomingRelationships(targetIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
1545
+ /**
1546
+ * Filters documents by criteria and returns a list of them
1547
+ *
1548
+ * @param search - Search filter options (type, parentId, identifiers)
1549
+ * @param view - Optional filter containing branch and scopes information
1550
+ * @param paging - Optional pagination options
1551
+ * @param signal - Optional abort signal to cancel the request
1552
+ * @returns List of documents matching criteria and pagination cursor
1553
+ */
1554
+ find(search: SearchFilter, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
1555
+ /**
1556
+ * Creates a document and waits for completion
1557
+ *
1558
+ * @param document - Document with optional id, slug, parent, model type, and initial state
1559
+ * @param parentIdentifier - Optional "id" or "slug" of parent document
1560
+ * @param signal - Optional abort signal to cancel the request
1561
+ * @returns The created document
1562
+ */
1563
+ create<TDocument extends PHDocument = PHDocument>(document: PHDocument, parentIdentifier?: string, signal?: AbortSignal): Promise<TDocument>;
1564
+ /**
1565
+ * Creates an empty document and waits for completion
1566
+ *
1567
+ * @param documentModelType - Type of document to create
1568
+ * @param options - Optional creation options (parentIdentifier, documentModelVersion)
1569
+ * @param signal - Optional abort signal to cancel the request
1570
+ */
1571
+ createEmpty<TDocument extends PHDocument>(documentModelType: string, options?: CreateDocumentOptions, signal?: AbortSignal): Promise<TDocument>;
1572
+ /**
1573
+ * Creates an empty document in a drive as a single batched operation.
1574
+ * This is more efficient than createEmpty + addFile as it batches all
1575
+ * actions into dependent jobs and waits for them to complete together.
1576
+ *
1577
+ * @deprecated Use {@link IDriveClient.addFile} via `client.drives.addFile`
1578
+ * instead. This method will be removed in a future release.
1579
+ * @param driveId - The drive document id or slug
1580
+ * @param document - The document to create
1581
+ * @param parentFolder - Optional folder id within the drive
1582
+ * @param signal - Optional abort signal to cancel the request
1583
+ * @returns The created document
1584
+ */
1585
+ createDocumentInDrive<TDocument extends PHDocument>(driveId: string, document: PHDocument, parentFolder?: string, signal?: AbortSignal): Promise<TDocument>;
1586
+ /**
1587
+ * Applies a list of actions to a document and waits for completion
1588
+ *
1589
+ * @param documentIdentifier - Target document id or slug
1590
+ * @param branch - Branch to apply actions to
1591
+ * @param actions - List of actions to apply
1592
+ * @param signal - Optional abort signal to cancel the request
1593
+ * @returns The updated document
1594
+ */
1595
+ execute<TDocument extends PHDocument>(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<TDocument>;
1596
+ /**
1597
+ * Submits a list of actions to a document
1598
+ *
1599
+ * @param documentIdentifier - Target document id or slug
1600
+ * @param branch - Branch to apply actions to
1601
+ * @param actions - List of actions to apply
1602
+ * @param signal - Optional abort signal to cancel the request
1603
+ * @returns The job
1604
+ */
1605
+ executeAsync(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<JobInfo>;
1606
+ /**
1607
+ * Renames a document and waits for completion
1608
+ *
1609
+ * @param documentIdentifier - Target document id or slug
1610
+ * @param name - The new name of the document
1611
+ * @param branch - Optional branch to rename the document, defaults to "main"
1612
+ * @param signal - Optional abort signal to cancel the request
1613
+ * @returns The updated document.
1614
+ */
1615
+ rename(documentIdentifier: string, name: string, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1616
+ /**
1617
+ * Adds a relationship between two documents and waits for completion.
1618
+ *
1619
+ * @param sourceIdentifier - Source document id or slug
1620
+ * @param targetIdentifier - Target document id or slug
1621
+ * @param relationshipType - Relationship type identifier
1622
+ * @param branch - Optional branch to add the relationship to, defaults to "main"
1623
+ * @param signal - Optional abort signal to cancel the request
1624
+ * @returns The updated source document
1625
+ */
1626
+ addRelationship(sourceIdentifier: string, targetIdentifier: string, relationshipType: string, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1627
+ /**
1628
+ * Removes a relationship between two documents and waits for completion.
1629
+ *
1630
+ * @param sourceIdentifier - Source document id or slug
1631
+ * @param targetIdentifier - Target document id or slug
1632
+ * @param relationshipType - Relationship type identifier
1633
+ * @param branch - Optional branch to remove the relationship from, defaults to "main"
1634
+ * @param signal - Optional abort signal to cancel the request
1635
+ * @returns The updated source document
1636
+ */
1637
+ removeRelationship(sourceIdentifier: string, targetIdentifier: string, relationshipType: string, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1638
+ /**
1639
+ * Moves a relationship from one source document to another and waits for completion.
1640
+ *
1641
+ * @param sourceParentIdentifier - Source parent document id or slug
1642
+ * @param targetParentIdentifier - Target parent document id or slug
1643
+ * @param targetIdentifier - The target document id or slug
1644
+ * @param relationshipType - Relationship type identifier
1645
+ * @param branch - Optional branch to apply the move to, defaults to "main"
1646
+ * @param signal - Optional abort signal to cancel the request
1647
+ * @returns The updated source and target documents
1648
+ */
1649
+ moveRelationship(sourceParentIdentifier: string, targetParentIdentifier: string, targetIdentifier: string, relationshipType: string, branch?: string, signal?: AbortSignal): Promise<{
1650
+ source: PHDocument;
1651
+ target: PHDocument;
1652
+ }>;
1653
+ /**
1654
+ * Deletes a document and waits for completion
1655
+ *
1656
+ * @param identifier - Document identifier (id or slug)
1657
+ * @param propagate - Optional mode for handling children, CASCADE deletes child documents
1658
+ * @param signal - Optional abort signal to cancel the request
1659
+ * @returns a promise, resolving on deletion confirmation
1660
+ */
1661
+ deleteDocument(identifier: string, propagate?: PropagationMode, signal?: AbortSignal): Promise<void>;
1662
+ /**
1663
+ * Deletes documents and waits for completion
1664
+ *
1665
+ * @param identifiers - Document identifiers (ids or slugs)
1666
+ * @param propagate - Optional mode for handling children, CASCADE deletes child documents
1667
+ * @param signal - Optional abort signal to cancel the request
1668
+ * @returns a promise, resolving on deletion confirmation
1669
+ */
1670
+ deleteDocuments(identifiers: string[], propagate?: PropagationMode, signal?: AbortSignal): Promise<void>;
1671
+ /**
1672
+ * Loads multiple batches of pre-existing operations across documents with dependency management.
1673
+ * Waits for all jobs to complete.
1674
+ *
1675
+ * @param request - Batch load request containing jobs with dependencies
1676
+ * @param signal - Optional abort signal to cancel the request
1677
+ * @returns Map of job keys to completed job information
1678
+ */
1679
+ loadBatch(request: BatchLoadRequest, signal?: AbortSignal): Promise<BatchLoadResult>;
1680
+ /**
1681
+ * Retrieves the status of a job
1682
+ *
1683
+ * @param jobId - The job id
1684
+ * @param signal - Optional abort signal to cancel the request
1685
+ * @returns The job status
1686
+ */
1687
+ getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
1688
+ /**
1689
+ * Waits for a job to complete
1690
+ *
1691
+ * @param jobId - The job id or job object
1692
+ * @param signal - Optional abort signal to cancel the request
1693
+ * @returns The result of the job
1694
+ */
1695
+ waitForJob(jobId: string | JobInfo, signal?: AbortSignal): Promise<JobInfo>;
1696
+ /**
1697
+ * Subscribes to changes for documents matching specified filters
1698
+ *
1699
+ * @param search - Search filter options (type, parentId, identifiers)
1700
+ * @param callback - Function called when documents change with the change event details
1701
+ * @param view - Optional filter containing branch and scopes information
1702
+ * @returns A function that unsubscribes from the changes
1703
+ */
1704
+ subscribe(search: SearchFilter, callback: (event: DocumentChangeEvent) => void, view?: ViewFilter): () => void;
1705
+ }
1706
+ //#endregion
1707
+ //#region src/client/reactor-client.d.ts
1708
+ /**
1709
+ * ReactorClient implementation that wraps lower-level APIs to provide
1710
+ * a simpler interface for document operations.
1711
+ *
1712
+ * Features:
1713
+ * - Wraps Jobs with Promises for easier async handling
1714
+ * - Manages signing of submitted Action objects
1715
+ * - Provides quality-of-life functions for common tasks
1716
+ * - Wraps subscription interface with ViewFilters
1717
+ */
1718
+ declare class ReactorClient implements IReactorClient {
1719
+ private logger;
1720
+ private reactor;
1721
+ private signer;
1722
+ private subscriptionManager;
1723
+ private jobAwaiter;
1724
+ private documentIndexer;
1725
+ private documentView;
1726
+ readonly drives: IDriveClient;
1727
+ constructor(logger: ILogger, reactor: IReactor, signer: ISigner, subscriptionManager: IReactorSubscriptionManager, jobAwaiter: IJobAwaiter, documentIndexer: IDocumentIndexer, documentView: IDocumentView);
1728
+ /**
1729
+ * Retrieves a list of document model modules.
1730
+ */
1731
+ getDocumentModelModules(namespace?: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentModelModule>>;
1732
+ /**
1733
+ * Retrieves a specific document model module by document type.
1734
+ *
1735
+ * @param documentType - The document type identifier
1736
+ * @returns The document model module
1737
+ */
1738
+ getDocumentModelModule(documentType: string): Promise<DocumentModelModule<any>>;
1739
+ /**
1740
+ * Retrieves a specific PHDocument
1741
+ */
1742
+ get<TDocument extends PHDocument>(identifier: string, view?: ViewFilter, signal?: AbortSignal): Promise<TDocument>;
1743
+ /**
1744
+ * Retrieves operations for a document
1745
+ */
1746
+ getOperations(documentIdentifier: string, view?: ViewFilter, filter?: OperationFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
1747
+ private getOperationsWithCompositeCursor;
1748
+ /**
1749
+ * Retrieves outgoing relationships of a given type from a source document.
1750
+ */
1751
+ getOutgoingRelationships(sourceIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
1752
+ /**
1753
+ * Retrieves incoming relationships of a given type to a target document.
1754
+ */
1755
+ getIncomingRelationships(targetIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
1756
+ /**
1757
+ * Filters documents by criteria and returns a list of them
1758
+ */
1759
+ find(search: SearchFilter, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
1760
+ /**
1761
+ * Creates a document and waits for completion
1762
+ */
1763
+ create<TDocument extends PHDocument = PHDocument>(document: PHDocument, parentIdentifier?: string, signal?: AbortSignal): Promise<TDocument>;
1764
+ /**
1765
+ * Creates an empty document and waits for completion
1766
+ */
1767
+ createEmpty<TDocument extends PHDocument>(documentModelType: string, options?: CreateDocumentOptions, signal?: AbortSignal): Promise<TDocument>;
1768
+ /**
1769
+ * Creates an empty document in a drive as a single batched operation.
1770
+ * Delegates to {@link IDriveClient.addFile}.
1771
+ *
1772
+ * @deprecated Use `client.drives.addFile` instead. This method will be
1773
+ * removed in a future release.
1774
+ */
1775
+ createDocumentInDrive<TDocument extends PHDocument>(driveId: string, document: PHDocument, parentFolder?: string, signal?: AbortSignal): Promise<TDocument>;
1776
+ /**
1777
+ * Applies a list of actions to a document and waits for completion
1778
+ */
1779
+ execute<TDocument extends PHDocument>(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<TDocument>;
1780
+ /**
1781
+ * Submits a list of actions to a document
1782
+ */
1783
+ executeAsync(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<JobInfo>;
1784
+ /**
1785
+ * Renames a document and waits for completion
1786
+ */
1787
+ rename(documentIdentifier: string, name: string, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1788
+ /**
1789
+ * Adds multiple documents as children to another and waits for completion
1790
+ */
1791
+ addRelationship(sourceIdentifier: string, targetIdentifier: string, relationshipType: string, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1792
+ /**
1793
+ * Removes a relationship between two documents and waits for completion.
1794
+ */
1795
+ removeRelationship(sourceIdentifier: string, targetIdentifier: string, relationshipType: string, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1796
+ /**
1797
+ * Moves a relationship from one source document to another and waits for completion.
1798
+ */
1799
+ moveRelationship(sourceParentIdentifier: string, targetParentIdentifier: string, targetIdentifier: string, relationshipType: string, branch?: string, signal?: AbortSignal): Promise<{
1800
+ source: PHDocument;
1801
+ target: PHDocument;
1802
+ }>;
1803
+ loadBatch(request: BatchLoadRequest, signal?: AbortSignal): Promise<BatchLoadResult>;
1804
+ /**
1805
+ * Deletes a document and waits for completion
1806
+ */
1807
+ deleteDocument(identifier: string, propagate?: PropagationMode, signal?: AbortSignal): Promise<void>;
1808
+ /**
1809
+ * Deletes documents and waits for completion
1810
+ */
1811
+ deleteDocuments(identifiers: string[], propagate?: PropagationMode, signal?: AbortSignal): Promise<void>;
1812
+ /**
1813
+ * Retrieves the status of a job
1814
+ */
1815
+ getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
1816
+ /**
1817
+ * Waits for a job to complete
1818
+ */
1819
+ waitForJob(jobId: string | JobInfo, signal?: AbortSignal): Promise<JobInfo>;
1820
+ /**
1821
+ * Subscribes to changes for documents matching specified filters
1822
+ */
1823
+ subscribe(search: SearchFilter, callback: (event: DocumentChangeEvent) => void, view?: ViewFilter): () => void;
1824
+ private removeAllIncomingRelationships;
1825
+ }
1826
+ //#endregion
1827
+ //#region src/executor/types.d.ts
1828
+ /**
1829
+ * Represents the result of a job execution
1830
+ */
1831
+ type JobResult = {
1832
+ /** The job that was executed */job: Job; /** Whether the job executed successfully */
1833
+ success: boolean; /** Error if the job failed */
1834
+ error?: Error; /** The operations generated from the actions (if successful) */
1835
+ operations?: Operation[];
1836
+ /**
1837
+ * Operations with context (includes ephemeral resultingState).
1838
+ * Used for emitting to IDocumentView via event bus.
1839
+ */
1840
+ operationsWithContext?: OperationWithContext$1[]; /** Timestamp when the job execution completed */
1841
+ completedAt?: string; /** Duration of job execution in milliseconds */
1842
+ duration?: number; /** Any additional metadata from the execution */
1843
+ metadata?: Record<string, any>;
1844
+ };
1845
+ /**
1846
+ * Configuration options for the job executor
1847
+ */
1848
+ type JobExecutorConfig = {
1849
+ /** Maximum number of conflicting operations to skip when reshuffling. */maxSkipThreshold?: number; /** Maximum number of concurrent jobs to execute */
1850
+ maxConcurrency?: number; /** Maximum time in milliseconds a job can run before being considered timed out */
1851
+ jobTimeoutMs?: number; /** Base delay in milliseconds for exponential backoff retries */
1852
+ retryBaseDelayMs?: number; /** Maximum delay in milliseconds for exponential backoff retries */
1853
+ retryMaxDelayMs?: number;
1854
+ /** Maximum elapsed milliseconds before yielding to the main thread between actions.
1855
+ * Keeps the UI responsive when processing large batches. */
1856
+ yieldDeadlineMs?: number;
1857
+ };
1858
+ /**
1859
+ * Event types for the job executor
1860
+ */
1861
+ declare const JobExecutorEventTypes: {
1862
+ readonly JOB_STARTED: 20000;
1863
+ readonly JOB_COMPLETED: 20001;
1864
+ readonly JOB_FAILED: 20002;
1865
+ readonly EXECUTOR_STARTED: 20003;
1866
+ readonly EXECUTOR_STOPPED: 20004;
1867
+ };
1868
+ /**
1869
+ * Event data for job execution events
1870
+ */
1871
+ type JobStartedEvent = {
1872
+ job: Job;
1873
+ startedAt: string;
1874
+ };
1875
+ type JobCompletedEvent = {
1876
+ job: Job;
1877
+ result: JobResult;
1878
+ };
1879
+ type JobFailedEvent = {
1880
+ job: Job;
1881
+ error: string;
1882
+ willRetry: boolean;
1883
+ retryCount: number;
1884
+ };
1885
+ type ExecutorStartedEvent = {
1886
+ config: JobExecutorConfig;
1887
+ startedAt: string;
1888
+ };
1889
+ type ExecutorStoppedEvent = {
1890
+ stoppedAt: string;
1891
+ graceful: boolean;
1892
+ };
1893
+ /**
1894
+ * Status information for the job executor manager
1895
+ */
1896
+ type ExecutorManagerStatus = {
1897
+ /** Whether the manager is currently running */isRunning: boolean; /** Number of executor instances managed */
1898
+ numExecutors: number; /** Number of jobs currently being processed */
1899
+ activeJobs: number; /** Total number of jobs processed since start */
1900
+ totalJobsProcessed: number;
1901
+ };
1902
+ //#endregion
1903
+ //#region src/executor/interfaces.d.ts
1904
+ /**
1905
+ * Simple interface for executing a job.
1906
+ * A JobExecutor simply takes a job and executes it - nothing more.
1907
+ */
1908
+ interface IJobExecutor {
1909
+ /**
1910
+ * Execute a single job.
1911
+ * @param job - The job to execute
1912
+ * @returns Promise that resolves to the job result
1913
+ */
1914
+ executeJob(job: Job, signal?: AbortSignal): Promise<JobResult>;
1915
+ }
1916
+ /**
1917
+ * Interface for managing multiple job executors.
1918
+ * Listens for 'jobAvailable' events from the event bus, pulls jobs from the queue,
1919
+ * and coordinates the distribution of jobs across multiple executor instances.
1920
+ */
1921
+ interface IJobExecutorManager {
1922
+ /**
1923
+ * Start the executor manager.
1924
+ * Begins listening for 'jobAvailable' events and dispatching to executors.
1925
+ *
1926
+ * @param numExecutors - Number of executor instances to create
1927
+ * @returns Promise that resolves when the manager is started
1928
+ */
1929
+ start(numExecutors: number): Promise<void>;
1930
+ /**
1931
+ * Stop the executor manager.
1932
+ *
1933
+ * @param graceful - Whether to wait for current jobs to complete
1934
+ * @returns Promise that resolves when the manager is stopped
1935
+ */
1936
+ stop(graceful?: boolean): Promise<void>;
1937
+ /**
1938
+ * Get all managed executor instances.
1939
+ *
1940
+ * @returns Array of executor instances
1941
+ */
1942
+ getExecutors(): IJobExecutor[];
1943
+ /**
1944
+ * Get the current status of the manager.
1945
+ *
1946
+ * @returns The current manager status
1947
+ */
1948
+ getStatus(): ExecutorManagerStatus;
1949
+ }
1950
+ //#endregion
1951
+ //#region src/job-tracker/interfaces.d.ts
1952
+ /**
1953
+ * Interface for tracking job lifecycle status.
1954
+ * Maintains job state throughout execution: PENDING → RUNNING → COMPLETED/FAILED.
1955
+ */
1956
+ interface IJobTracker {
1957
+ /**
1958
+ * Register a new job with PENDING status.
1959
+ *
1960
+ * @param jobInfo - The job information to register
1961
+ */
1962
+ registerJob(jobInfo: JobInfo): void;
1963
+ /**
1964
+ * Update a job's status to RUNNING.
1965
+ *
1966
+ * @param jobId - The job ID to mark as running
1967
+ */
1968
+ markRunning(jobId: string): void;
1969
+ /**
1970
+ * Mark a job as failed.
1971
+ *
1972
+ * @param jobId - The job ID to mark as failed
1973
+ * @param error - Error information including message and stack trace
1974
+ * @param job - Optional full job object for debugging purposes
1975
+ */
1976
+ markFailed(jobId: string, error: ErrorInfo, job?: Job): void;
1977
+ /**
1978
+ * Retrieve the current status of a job.
1979
+ *
1980
+ * @param jobId - The job ID to query
1981
+ * @returns The job information, or null if the job is not found
1982
+ */
1983
+ getJobStatus(jobId: string): JobInfo | null;
1984
+ /**
1985
+ * Shutdown the job tracker and clean up resources.
1986
+ * Unsubscribes from all event bus subscriptions.
1987
+ */
1988
+ shutdown(): void;
1989
+ }
1990
+ //#endregion
1991
+ //#region src/queue/interfaces.d.ts
1992
+ /**
1993
+ * Interface for a job queue that manages write operations.
1994
+ * Internally organizes jobs by documentId, scope, and branch to ensure proper ordering.
1995
+ * Emits events to the event bus when new jobs are available for consumption.
1996
+ */
1997
+ interface IQueue {
1998
+ /**
1999
+ * Add a new job to the queue.
2000
+ * Jobs are automatically organized by documentId, scope, and branch internally.
2001
+ * Emits a 'jobAvailable' event to the event bus when the job is queued.
2002
+ * @param job - The job to add to the queue
2003
+ * @returns Promise that resolves when the job is queued
2004
+ */
2005
+ enqueue(job: Job): Promise<void>;
2006
+ /**
2007
+ * Get the next job to execute for a specific document/scope/branch combination.
2008
+ * @param documentId - The document ID to get jobs for
2009
+ * @param scope - The scope to get jobs for
2010
+ * @param branch - The branch to get jobs for
2011
+ * @param signal - Optional abort signal to cancel the request
2012
+ * @returns Promise that resolves to the next job execution handle or null if no jobs available
2013
+ */
2014
+ dequeue(documentId: string, scope: string, branch: string, signal?: AbortSignal): Promise<IJobExecutionHandle | null>;
2015
+ /**
2016
+ * Get the next available job from any queue.
2017
+ * @param signal - Optional abort signal to cancel the request
2018
+ * @returns Promise that resolves to the next job execution handle or null if no jobs available
2019
+ */
2020
+ dequeueNext(signal?: AbortSignal): Promise<IJobExecutionHandle | null>;
2021
+ /**
2022
+ * Get the current size of the queue for a specific document/scope/branch.
2023
+ * @param documentId - The document ID
2024
+ * @param scope - The scope
2025
+ * @param branch - The branch
2026
+ * @returns Promise that resolves to the number of jobs in the queue
2027
+ */
2028
+ size(documentId: string, scope: string, branch: string): Promise<number>;
2029
+ /**
2030
+ * Get the total size of all queues.
2031
+ * @returns Promise that resolves to the total number of jobs across all queues
2032
+ */
2033
+ totalSize(): Promise<number>;
2034
+ /**
2035
+ * Remove a specific job from the queue.
2036
+ * @param jobId - The ID of the job to remove
2037
+ * @returns Promise that resolves to true if job was removed, false if not found
2038
+ */
2039
+ remove(jobId: string): Promise<boolean>;
2040
+ /**
2041
+ * Clear all jobs for a specific document/scope/branch combination.
2042
+ * @param documentId - The document ID
2043
+ * @param scope - The scope
2044
+ * @param branch - The branch
2045
+ * @returns Promise that resolves when the queue is cleared
2046
+ */
2047
+ clear(documentId: string, scope: string, branch: string): Promise<void>;
2048
+ /**
2049
+ * Clear all jobs from all queues.
2050
+ * @returns Promise that resolves when all queues are cleared
2051
+ */
2052
+ clearAll(): Promise<void>;
2053
+ /**
2054
+ * Check if there are any jobs in the queue.
2055
+ * @returns Promise that resolves to true if there are jobs, false otherwise
2056
+ */
2057
+ hasJobs(): Promise<boolean>;
2058
+ /**
2059
+ * Mark a job as completed.
2060
+ * @param jobId - The ID of the job to mark as completed
2061
+ * @returns Promise that resolves when the job is marked as completed
2062
+ */
2063
+ completeJob(jobId: string): Promise<void>;
2064
+ /**
2065
+ * Mark a job as failed.
2066
+ * @param jobId - The ID of the job to mark as failed
2067
+ * @param error - Optional error information
2068
+ * @returns Promise that resolves when the job is marked as failed
2069
+ */
2070
+ failJob(jobId: string, error?: ErrorInfo): Promise<void>;
2071
+ /**
2072
+ * Retry a failed job.
2073
+ * @param jobId - The ID of the job to retry
2074
+ * @param error - Optional error information from the failure
2075
+ * @returns Promise that resolves when the job is requeued for retry
2076
+ */
2077
+ retryJob(jobId: string, error?: ErrorInfo): Promise<void>;
2078
+ /**
2079
+ * Returns true if and only if all jobs have been resolved.
2080
+ */
2081
+ get isDrained(): boolean;
2082
+ /**
2083
+ * Blocks the queue from accepting new jobs.
2084
+ * @param onDrained - Optional callback to call when the queue is drained
2085
+ */
2086
+ block(onDrained?: () => void): void;
2087
+ /**
2088
+ * Unblocks the queue from accepting new jobs.
2089
+ */
2090
+ unblock(): void;
2091
+ }
2092
+ //#endregion
2093
+ //#region src/read-models/types.d.ts
2094
+ interface ViewStateTable {
2095
+ readModelId: string;
2096
+ lastOrdinal: number;
2097
+ lastOperationTimestamp: Generated<Date>;
2098
+ }
2099
+ interface DocumentSnapshotTable {
2100
+ id: Generated<string>;
2101
+ documentId: string;
2102
+ slug: string | null;
2103
+ name: string | null;
2104
+ scope: string;
2105
+ branch: string;
2106
+ content: unknown;
2107
+ documentType: string;
2108
+ lastOperationIndex: number;
2109
+ lastOperationHash: string;
2110
+ lastUpdatedAt: Generated<Date>;
2111
+ snapshotVersion: Generated<number>;
2112
+ identifiers: unknown;
2113
+ metadata: unknown;
2114
+ isDeleted: Generated<boolean>;
2115
+ deletedAt: Date | null;
2116
+ }
2117
+ interface SlugMappingTable {
2118
+ slug: string;
2119
+ documentId: string;
2120
+ scope: string;
2121
+ branch: string;
2122
+ createdAt: Generated<Date>;
2123
+ updatedAt: Generated<Date>;
2124
+ }
2125
+ interface ProcessorCursorTable {
2126
+ processorId: string;
2127
+ factoryId: string;
2128
+ driveId: string;
2129
+ processorIndex: number;
2130
+ lastOrdinal: Generated<number>;
2131
+ status: Generated<string>;
2132
+ lastError: string | null;
2133
+ lastErrorTimestamp: Date | null;
2134
+ createdAt: Generated<Date>;
2135
+ updatedAt: Generated<Date>;
2136
+ }
2137
+ interface DocumentViewDatabase {
2138
+ ViewState: ViewStateTable;
2139
+ DocumentSnapshot: DocumentSnapshotTable;
2140
+ SlugMapping: SlugMappingTable;
2141
+ ProcessorCursor: ProcessorCursorTable;
2142
+ }
2143
+ type InsertableDocumentSnapshot = Insertable<DocumentSnapshotTable>;
2144
+ //#endregion
2145
+ //#region src/registry/interfaces.d.ts
2146
+ type RegistrationResult<T> = {
2147
+ status: "success";
2148
+ item: T;
2149
+ } | {
2150
+ status: "error";
2151
+ item: T;
2152
+ error: Error;
2153
+ };
2154
+ /**
2155
+ * Loader that can asynchronously resolve and return a document model module
2156
+ * for a given document type. Used by the queue to gate CREATE_DOCUMENT jobs
2157
+ * until the required model is available in the registry.
2158
+ */
2159
+ interface IDocumentModelLoader {
2160
+ load(documentType: string): Promise<DocumentModelModule<any>>;
2161
+ }
2162
+ /**
2163
+ * Registry for managing document model modules.
2164
+ * Provides centralized access to document models' reducers, utils, and specifications.
2165
+ * Supports version-aware module storage and upgrade manifest management.
2166
+ */
2167
+ interface IDocumentModelRegistry {
2168
+ /**
2169
+ * Register multiple modules at once.
2170
+ * Modules without a version field default to version 1.
2171
+ * Invalid or duplicate modules are skipped without breaking registration of the remaining modules.
2172
+ *
2173
+ * @param modules Document model modules to register
2174
+ * @returns Array of results, one per module, indicating success or failure
2175
+ */
2176
+ registerModules(...modules: DocumentModelModule<any>[]): RegistrationResult<DocumentModelModule<any>>[];
2177
+ /**
2178
+ * Unregister all versions of the specified document types.
2179
+ *
2180
+ * @param documentTypes The document types to unregister
2181
+ * @returns true if all modules were unregistered, false if any were not found
2182
+ */
2183
+ unregisterModules(...documentTypes: string[]): boolean;
2184
+ /**
2185
+ * Get a specific document model module by document type and optional version.
2186
+ * If version is not specified, returns the latest version.
2187
+ *
2188
+ * @param documentType The document type identifier
2189
+ * @param version Optional version number to retrieve
2190
+ * @returns The document model module
2191
+ * @throws ModuleNotFoundError if the document type or version is not registered
2192
+ */
2193
+ getModule(documentType: string, version?: number): DocumentModelModule<any>;
2194
+ /**
2195
+ * Get all registered document model modules.
2196
+ *
2197
+ * @returns Array of all registered modules
2198
+ */
2199
+ getAllModules(): DocumentModelModule<any>[];
2200
+ /**
2201
+ * Clear all registered modules and upgrade manifests.
2202
+ */
2203
+ clear(): void;
2204
+ /**
2205
+ * Get all supported versions for a document type, sorted in ascending order.
2206
+ *
2207
+ * @param documentType The document type identifier
2208
+ * @returns Array of version numbers sorted ascending
2209
+ * @throws ModuleNotFoundError if no modules are registered for the document type
2210
+ */
2211
+ getSupportedVersions(documentType: string): number[];
2212
+ /**
2213
+ * Get the latest (highest) version number for a document type.
2214
+ *
2215
+ * @param documentType The document type identifier
2216
+ * @returns The highest version number registered for this document type
2217
+ * @throws ModuleNotFoundError if no modules are registered for the document type
2218
+ */
2219
+ getLatestVersion(documentType: string): number;
2220
+ /**
2221
+ * Register upgrade manifests that define upgrade paths between versions.
2222
+ * Invalid or duplicate manifests are skipped without breaking registration of the remaining manifests.
2223
+ *
2224
+ * @param manifests Upgrade manifests to register
2225
+ * @returns Array of results, one per manifest, indicating success or failure
2226
+ */
2227
+ registerUpgradeManifests(...manifests: UpgradeManifest<readonly number[]>[]): RegistrationResult<UpgradeManifest<readonly number[]>>[];
2228
+ /**
2229
+ * Unregister upgrade manifests for the specified document types.
2230
+ * @param documentTypes The document types whose upgrade manifests should be unregistered
2231
+ * @returns true if all modules were unregistered, false if any were not found
2232
+ **/
2233
+ unregisterUpgradeManifests(...documentTypes: string[]): boolean;
2234
+ /**
2235
+ * Get the upgrade manifest for a document type.
2236
+ *
2237
+ * @param documentType The document type identifier
2238
+ * @returns The upgrade manifest
2239
+ * @throws ManifestNotFoundError if no manifest is registered for the document type
2240
+ */
2241
+ getUpgradeManifest(documentType: string): UpgradeManifest<readonly number[]>;
2242
+ /**
2243
+ * Compute the upgrade path from one version to another.
2244
+ * Returns the sequence of upgrade transitions needed.
2245
+ *
2246
+ * @param documentType The document type identifier
2247
+ * @param fromVersion The starting version
2248
+ * @param toVersion The target version
2249
+ * @returns Array of upgrade transitions in order
2250
+ * @throws DowngradeNotSupportedError if toVersion is less than fromVersion
2251
+ * @throws ManifestNotFoundError if no upgrade manifest is registered
2252
+ * @throws MissingUpgradeTransitionError if any transition in the path is missing
2253
+ */
2254
+ computeUpgradePath(documentType: string, fromVersion: number, toVersion: number): UpgradeTransition[];
2255
+ /**
2256
+ * Get the upgrade reducer for a single-step version transition.
2257
+ *
2258
+ * @param documentType The document type identifier
2259
+ * @param fromVersion The starting version
2260
+ * @param toVersion The target version (must be fromVersion + 1)
2261
+ * @returns The upgrade reducer function
2262
+ * @throws InvalidUpgradeStepError if toVersion is not fromVersion + 1
2263
+ * @throws ManifestNotFoundError if no upgrade manifest is registered
2264
+ * @throws MissingUpgradeTransitionError if the transition is not found
2265
+ */
2266
+ getUpgradeReducer(documentType: string, fromVersion: number, toVersion: number): UpgradeReducer<any, any>;
2267
+ }
2268
+ //#endregion
2269
+ //#region src/shared/consistency-tracker.d.ts
2270
+ interface IConsistencyTracker {
2271
+ /**
2272
+ * Updates the tracker with new operation indexes.
2273
+ * When multiple coordinates have the same key, keeps the highest operationIndex.
2274
+ * Resolves any pending waiters whose coordinates are now satisfied.
2275
+ */
2276
+ update(coordinates: ConsistencyCoordinate[]): void;
2277
+ /**
2278
+ * Returns the latest operation index for a given key, or undefined if not tracked.
2279
+ */
2280
+ getLatest(key: ConsistencyKey): number | undefined;
2281
+ /**
2282
+ * Returns a promise that resolves when all coordinates are satisfied.
2283
+ * Rejects if the timeout is reached or the signal is aborted.
2284
+ */
2285
+ waitFor(coordinates: ConsistencyCoordinate[], timeoutMs?: number, signal?: AbortSignal): Promise<void>;
2286
+ /**
2287
+ * Returns a serializable snapshot of the current state.
2288
+ */
2289
+ serialize(): Array<[ConsistencyKey, number]>;
2290
+ /**
2291
+ * Restores state from a serialized snapshot.
2292
+ */
2293
+ hydrate(entries: Array<[ConsistencyKey, number]>): void;
2294
+ }
2295
+ /**
2296
+ * Creates a consistency key from documentId, scope, and branch.
2297
+ */
2298
+ declare function makeConsistencyKey(documentId: string, scope: string, branch: string): ConsistencyKey;
2299
+ /**
2300
+ * Tracks operation indexes for documents and provides read-after-write consistency guarantees.
2301
+ * Maintains an in-memory map of the latest operation index for each (documentId, scope, branch) tuple.
2302
+ */
2303
+ declare class ConsistencyTracker implements IConsistencyTracker {
2304
+ private state;
2305
+ private waiters;
2306
+ update(coordinates: ConsistencyCoordinate[]): void;
2307
+ getLatest(key: ConsistencyKey): number | undefined;
2308
+ waitFor(coordinates: ConsistencyCoordinate[], timeoutMs?: number, signal?: AbortSignal): Promise<void>;
2309
+ serialize(): Array<[ConsistencyKey, number]>;
2310
+ hydrate(entries: Array<[ConsistencyKey, number]>): void;
2311
+ private deduplicateCoordinates;
2312
+ private areCoordinatesSatisfied;
2313
+ private checkWaiters;
2314
+ private removeWaiter;
2315
+ }
2316
+ //#endregion
2317
+ //#region src/storage/kysely/types.d.ts
2318
+ interface OperationTable {
2319
+ id: Generated<number>;
2320
+ jobId: string;
2321
+ opId: string;
2322
+ prevOpId: string;
2323
+ writeTimestampUtcMs: Generated<Date>;
2324
+ documentId: string;
2325
+ documentType: string;
2326
+ scope: string;
2327
+ branch: string;
2328
+ timestampUtcMs: Date;
2329
+ index: number;
2330
+ action: unknown;
2331
+ skip: number;
2332
+ error?: string | null;
2333
+ hash: string;
2334
+ }
2335
+ interface KeyframeTable {
2336
+ id: Generated<number>;
2337
+ documentId: string;
2338
+ documentType: string;
2339
+ scope: string;
2340
+ branch: string;
2341
+ revision: number;
2342
+ document: unknown;
2343
+ createdAt: Generated<Date>;
2344
+ }
2345
+ interface DocumentCollectionTable {
2346
+ documentId: string;
2347
+ collectionId: string;
2348
+ joinedOrdinal: bigint;
2349
+ leftOrdinal: bigint | null;
2350
+ }
2351
+ interface OperationIndexOperationTable {
2352
+ ordinal: Generated<number>;
2353
+ opId: string;
2354
+ documentId: string;
2355
+ documentType: string;
2356
+ scope: string;
2357
+ branch: string;
2358
+ timestampUtcMs: string;
2359
+ writeTimestampUtcMs: Generated<Date>;
2360
+ index: number;
2361
+ skip: number;
2362
+ hash: string;
2363
+ action: unknown;
2364
+ sourceRemote: Generated<string>;
2365
+ }
2366
+ interface SyncRemoteTable {
2367
+ name: string;
2368
+ collection_id: string;
2369
+ channel_type: string;
2370
+ channel_id: string;
2371
+ remote_name: string;
2372
+ channel_parameters: unknown;
2373
+ filter_document_ids: unknown;
2374
+ filter_scopes: unknown;
2375
+ filter_branch: string;
2376
+ push_state: string;
2377
+ push_last_success_utc_ms: string | null;
2378
+ push_last_failure_utc_ms: string | null;
2379
+ push_failure_count: number;
2380
+ pull_state: string;
2381
+ pull_last_success_utc_ms: string | null;
2382
+ pull_last_failure_utc_ms: string | null;
2383
+ pull_failure_count: number;
2384
+ created_at: Generated<Date>;
2385
+ updated_at: Generated<Date>;
2386
+ }
2387
+ interface SyncCursorTable {
2388
+ remote_name: string;
2389
+ cursor_type: string;
2390
+ cursor_ordinal: bigint;
2391
+ last_synced_at_utc_ms: string | null;
2392
+ updated_at: Generated<Date>;
2393
+ }
2394
+ /**
2395
+ * Kysely table definition for the `sync_dead_letters` table.
2396
+ */
2397
+ interface SyncDeadLetterTable {
2398
+ ordinal: Generated<number>;
2399
+ id: string;
2400
+ job_id: string;
2401
+ job_dependencies: unknown;
2402
+ remote_name: string;
2403
+ document_id: string;
2404
+ scopes: unknown;
2405
+ branch: string;
2406
+ operations: unknown;
2407
+ error_source: string;
2408
+ error_message: string;
2409
+ created_at: Generated<Date>;
2410
+ }
2411
+ interface Database$1 {
2412
+ Operation: OperationTable;
2413
+ Keyframe: KeyframeTable;
2414
+ document_collections: DocumentCollectionTable;
2415
+ operation_index_operations: OperationIndexOperationTable;
2416
+ sync_remotes: SyncRemoteTable;
2417
+ sync_cursors: SyncCursorTable;
2418
+ sync_dead_letters: SyncDeadLetterTable;
2419
+ }
2420
+ interface DocumentTable {
2421
+ id: string;
2422
+ createdAt: Generated<Date>;
2423
+ updatedAt: Generated<Date>;
2424
+ }
2425
+ interface DocumentRelationshipTable {
2426
+ id: Generated<string>;
2427
+ sourceId: string;
2428
+ targetId: string;
2429
+ relationshipType: string;
2430
+ metadata: unknown;
2431
+ createdAt: Generated<Date>;
2432
+ updatedAt: Generated<Date>;
2433
+ }
2434
+ interface IndexerStateTable {
2435
+ id: Generated<number>;
2436
+ lastOperationId: number;
2437
+ lastOperationTimestamp: Generated<Date>;
2438
+ }
2439
+ interface DocumentIndexerDatabase {
2440
+ Document: DocumentTable;
2441
+ DocumentRelationship: DocumentRelationshipTable;
2442
+ IndexerState: IndexerStateTable;
2443
+ }
2444
+ //#endregion
2445
+ //#region src/sync/errors.d.ts
2446
+ declare class PollingChannelError extends Error {
2447
+ constructor(message: string);
2448
+ }
2449
+ declare class ChannelError extends Error {
2450
+ source: ChannelErrorSource;
2451
+ error: Error;
2452
+ constructor(source: ChannelErrorSource, error: Error);
2453
+ }
2454
+ //#endregion
2455
+ //#region src/sync/sync-operation.d.ts
2456
+ type SyncOperationStatusCallback = (syncOp: SyncOperation, prev: SyncOperationStatus, next: SyncOperationStatus) => void;
2457
+ declare class SyncOperationAggregateError extends Error {
2458
+ errors: Error[];
2459
+ constructor(errors: Error[]);
2460
+ }
2461
+ declare class SyncOperation {
2462
+ readonly id: string;
2463
+ readonly jobId: string;
2464
+ jobDependencies: string[];
2465
+ readonly remoteName: string;
2466
+ readonly documentId: string;
2467
+ readonly scopes: string[];
2468
+ readonly branch: string;
2469
+ readonly operations: OperationWithContext$1[];
2470
+ status: SyncOperationStatus;
2471
+ error?: ChannelError;
2472
+ callbacks: SyncOperationStatusCallback[];
2473
+ constructor(id: string, jobId: string, jobDependencies: string[], remoteName: string, documentId: string, scopes: string[], branch: string, operations: OperationWithContext$1[]);
2474
+ on(callback: SyncOperationStatusCallback): void;
2475
+ started(): void;
2476
+ transported(): void;
2477
+ executed(): void;
2478
+ failed(error: ChannelError): void;
2479
+ transition(next: SyncOperationStatus): void;
2480
+ }
2481
+ //#endregion
2482
+ //#region src/sync/mailbox.d.ts
2483
+ type MailboxCallback = (items: SyncOperation[]) => void;
2484
+ /**
2485
+ * The Mailbox interface is not intended to use any persistence. Instead, the
2486
+ * IChannel implementation is responsible for persisting cursors or other data.
2487
+ *
2488
+ * This means that ackOrdinal and latestOrdinal are in memory only.
2489
+ */
2490
+ interface IMailbox {
2491
+ get items(): ReadonlyArray<SyncOperation>;
2492
+ /**
2493
+ * The latest ordinal that has been acknowledged. Because acknowledged items
2494
+ * are removed from the mailbox, this is the last ordinal that has been removed.
2495
+ */
2496
+ get ackOrdinal(): number;
2497
+ /**
2498
+ * The latest ordinal of the items that are or have been added to the mailbox.
2499
+ * This may be greater than the ack ordinal if items have been added but not
2500
+ * yet acknowledged.
2501
+ */
2502
+ get latestOrdinal(): number;
2503
+ init(ackOrdinal: number): void;
2504
+ advanceOrdinal(ordinal: number): void;
2505
+ get(id: string): SyncOperation | undefined;
2506
+ add(...items: SyncOperation[]): void;
2507
+ remove(...items: SyncOperation[]): void;
2508
+ onAdded(callback: MailboxCallback): void;
2509
+ onRemoved(callback: MailboxCallback): void;
2510
+ pause(): void;
2511
+ resume(): void;
2512
+ flush(): void;
2513
+ isPaused(): boolean;
2514
+ }
2515
+ declare class Mailbox implements IMailbox {
2516
+ private itemsMap;
2517
+ private addedCallbacks;
2518
+ private removedCallbacks;
2519
+ private paused;
2520
+ private addedBuffer;
2521
+ private removedBuffer;
2522
+ private _ack;
2523
+ private _latestOrdinal;
2524
+ init(ackOrdinal: number): void;
2525
+ advanceOrdinal(ordinal: number): void;
2526
+ get items(): ReadonlyArray<SyncOperation>;
2527
+ get ackOrdinal(): number;
2528
+ get latestOrdinal(): number;
2529
+ get(id: string): SyncOperation | undefined;
2530
+ add(...items: SyncOperation[]): void;
2531
+ remove(...items: SyncOperation[]): void;
2532
+ onAdded(callback: MailboxCallback): void;
2533
+ onRemoved(callback: MailboxCallback): void;
2534
+ pause(): void;
2535
+ resume(): void;
2536
+ flush(): void;
2537
+ isPaused(): boolean;
2538
+ }
2539
+ //#endregion
2540
+ //#region src/sync/sync-status-tracker.d.ts
2541
+ declare enum SyncStatus {
2542
+ Synced = "SYNCED",
2543
+ Outgoing = "OUTGOING",
2544
+ Incoming = "INCOMING",
2545
+ OutgoingAndIncoming = "OUTGOING_AND_INCOMING",
2546
+ Error = "ERROR"
2547
+ }
2548
+ type SyncStatusChangeCallback = (documentId: string, status: SyncStatus) => void;
2549
+ interface ISyncStatusTracker {
2550
+ getStatus(documentId: string): SyncStatus | undefined;
2551
+ onChange(callback: SyncStatusChangeCallback): () => void;
2552
+ trackRemote(remoteName: string, channel: IChannel): void;
2553
+ untrackRemote(remoteName: string): void;
2554
+ clear(): void;
2555
+ }
2556
+ declare class SyncStatusTracker implements ISyncStatusTracker {
2557
+ private readonly remotes;
2558
+ private readonly seen;
2559
+ private readonly callbacks;
2560
+ getStatus(documentId: string): SyncStatus | undefined;
2561
+ onChange(callback: SyncStatusChangeCallback): () => void;
2562
+ trackRemote(remoteName: string, channel: IChannel): void;
2563
+ untrackRemote(remoteName: string): void;
2564
+ clear(): void;
2565
+ private handleAdded;
2566
+ private handleRemoved;
2567
+ private getOrCreateCounts;
2568
+ private notifyChange;
2569
+ }
2570
+ //#endregion
2571
+ //#region src/sync/interfaces.d.ts
2572
+ /**
2573
+ * Represents a bidirectional synchronization channel between two reactor instances.
2574
+ *
2575
+ * A channel manages three mailboxes:
2576
+ * - inbox: Sync operations received from the remote that need to be applied locally
2577
+ * - outbox: Sync operations to be sent to the remote
2578
+ * - deadLetter: Sync operations that failed and cannot be retried
2579
+ */
2580
+ type ConnectionStateChangeCallback = (snapshot: ConnectionStateSnapshot) => void;
2581
+ interface IChannel {
2582
+ /**
2583
+ * Mailbox containing sync operations received from the remote that need to be applied locally.
2584
+ * Consumers should register callbacks via onAdded to process incoming sync operations.
2585
+ */
2586
+ inbox: IMailbox;
2587
+ /**
2588
+ * Mailbox containing sync operations that need to be sent to the remote.
2589
+ * The channel is responsible for transporting these sync operations and handling ACKs.
2590
+ */
2591
+ outbox: IMailbox;
2592
+ /**
2593
+ * Mailbox containing sync operations that failed and cannot be retried.
2594
+ * These sync operations require manual intervention or should be logged for debugging.
2595
+ */
2596
+ deadLetter: IMailbox;
2597
+ /**
2598
+ * Initializes the channel asynchronously.
2599
+ * For remote channels, this typically involves registering the channel on the remote server.
2600
+ * Must be called after construction before the channel is used.
2601
+ */
2602
+ init(): Promise<void>;
2603
+ /**
2604
+ * Shuts down the channel and prevents further operations.
2605
+ */
2606
+ shutdown(): Promise<void>;
2607
+ /**
2608
+ * Returns the current connection state snapshot.
2609
+ */
2610
+ getConnectionState(): ConnectionStateSnapshot;
2611
+ /**
2612
+ * Registers a callback that fires when the connection state changes.
2613
+ * Returns an unsubscribe function.
2614
+ */
2615
+ onConnectionStateChange(callback: ConnectionStateChangeCallback): () => void;
2616
+ /**
2617
+ * Fires a single pull cycle on demand. For Manual poll-behavior remotes this is the
2618
+ * mechanism for syncing without enabling background polling. Implementations that do
2619
+ * not poll (e.g. push-only response channels) should treat this as a no-op.
2620
+ */
2621
+ triggerPull(): void;
2622
+ }
2623
+ /**
2624
+ * Factory for creating channel instances.
2625
+ *
2626
+ * Different channel implementations (InternalChannel, GqlChannel, etc.) will have
2627
+ * their own factories that implement this interface.
2628
+ */
2629
+ interface IChannelFactory {
2630
+ /**
2631
+ * Creates a new channel instance with the given configuration.
2632
+ *
2633
+ * @param remoteId - Unique identifier for the remote
2634
+ * @param remoteName - Name of the remote
2635
+ * @param config - Channel configuration including type and parameters
2636
+ * @param cursorStorage - Storage for persisting synchronization cursors
2637
+ * @param collectionId - Collection ID to synchronize
2638
+ * @param filter - Filter to apply to operations
2639
+ * @param operationIndex - Operation index for querying timestamps
2640
+ * @param options - Remote-level options (e.g. pollBehavior). May be omitted; implementations should default sensibly.
2641
+ * @returns A new channel instance
2642
+ */
2643
+ instance(remoteId: string, remoteName: string, config: ChannelConfig, cursorStorage: ISyncCursorStorage, collectionId: string, filter: RemoteFilter, operationIndex: IOperationIndex, options?: RemoteOptions): IChannel;
2644
+ }
2645
+ /**
2646
+ * Represents a configured remote with an active channel.
2647
+ *
2648
+ * A remote defines what to synchronize (collectionId, filter) and how to synchronize it (channel).
2649
+ * The remote name is used as a unique identifier across the system.
2650
+ */
2651
+ type Remote = {
2652
+ /**
2653
+ * Unique identifier for this remote.
2654
+ */
2655
+ id: string;
2656
+ /**
2657
+ * Unique name for this remote.
2658
+ */
2659
+ name: string;
2660
+ /**
2661
+ * Collection ID to synchronize.
2662
+ * Typically created via driveCollectionId(branch, documentId) for drive-level sync.
2663
+ */
2664
+ collectionId: string;
2665
+ /**
2666
+ * Filter to apply to operations.
2667
+ * Can filter by documentId, scope, and branch.
2668
+ */
2669
+ filter: RemoteFilter;
2670
+ /**
2671
+ * Additional configuration options for the remote.
2672
+ */
2673
+ options: RemoteOptions;
2674
+ /**
2675
+ * Active channel for bidirectional communication with the remote.
2676
+ */
2677
+ channel: IChannel;
2678
+ };
2679
+ /**
2680
+ * Orchestrates all synchronization activity for a reactor instance.
2681
+ */
2682
+ interface ISyncManager {
2683
+ /**
2684
+ * Starts the synchronization manager.
2685
+ *
2686
+ * This recreates all remotes from storage and prepares channels for synchronization.
2687
+ * Each remote's channel will begin processing its inbox/outbox mailboxes.
2688
+ *
2689
+ * @returns Promise that resolves when the manager is started
2690
+ */
2691
+ startup(): Promise<void>;
2692
+ /**
2693
+ * Shuts down the synchronization manager.
2694
+ *
2695
+ * This stops all channels, flushes pending operations, and releases resources.
2696
+ * The shutdown status indicates whether the system was cleanly shut down.
2697
+ *
2698
+ * @returns Status object with shutdown information
2699
+ */
2700
+ shutdown(): ShutdownStatus;
2701
+ /**
2702
+ * Gets a remote by name.
2703
+ *
2704
+ * @param name - The name of the remote
2705
+ * @returns The remote
2706
+ * @throws Error if the remote does not exist
2707
+ */
2708
+ getByName(name: string): Remote;
2709
+ /**
2710
+ * Gets a remote by ID.
2711
+ *
2712
+ * @param id - The ID of the remote
2713
+ * @returns The remote
2714
+ * @throws Error if the remote does not exist
2715
+ */
2716
+ getById(id: string): Remote;
2717
+ /**
2718
+ * Adds a new remote and starts its channel.
2719
+ *
2720
+ * The remote configuration is persisted to storage and a channel is created
2721
+ * using the appropriate factory. The channel begins processing immediately.
2722
+ *
2723
+ * @param name - Unique name for the remote
2724
+ * @param collectionId - Collection ID to synchronize
2725
+ * @param channelConfig - Configuration for the channel type and parameters
2726
+ * @param filter - Optional filter for operations (defaults to no filtering)
2727
+ * @param options - Optional remote configuration options
2728
+ * @param id - Optional ID for the remote (generated if not provided)
2729
+ * @returns Promise that resolves with the created remote
2730
+ * @throws Error if a remote with this name already exists
2731
+ */
2732
+ add(name: string, collectionId: string, channelConfig: ChannelConfig, filter?: RemoteFilter, options?: RemoteOptions, id?: string): Promise<Remote>;
2733
+ /**
2734
+ * Triggers a one-shot pull for the named remote. Useful for Manual poll-behavior
2735
+ * remotes, where the channel is registered but does not poll on a schedule.
2736
+ *
2737
+ * @param name - The name of the remote
2738
+ * @throws Error if the remote does not exist
2739
+ */
2740
+ triggerPull(name: string): void;
2741
+ /**
2742
+ * Removes a remote and stops its channel.
2743
+ *
2744
+ * The remote configuration is removed from storage and the channel is shut down.
2745
+ * Any pending sync operations in the channel's mailboxes will be processed before shutdown.
2746
+ *
2747
+ * @param name - The name of the remote to remove
2748
+ * @returns Promise that resolves when the remote is removed
2749
+ * @throws Error if the remote does not exist
2750
+ */
2751
+ remove(name: string): Promise<void>;
2752
+ /**
2753
+ * Lists all configured remotes.
2754
+ *
2755
+ * @returns Array of all remotes
2756
+ */
2757
+ list(): Remote[];
2758
+ /**
2759
+ * Waits for sync operations for a job to complete.
2760
+ * Resolves when SYNC_SUCCEEDED is emitted.
2761
+ * Rejects when SYNC_FAILED is emitted.
2762
+ *
2763
+ * @param jobId - The job id to wait for
2764
+ * @param signal - Optional abort signal
2765
+ * @returns The sync result
2766
+ */
2767
+ waitForSync(jobId: string, signal?: AbortSignal): Promise<SyncResult>;
2768
+ /**
2769
+ * Gets the current sync status for a document.
2770
+ *
2771
+ * @param documentId - The document ID to check
2772
+ * @returns The sync status, or undefined if the document has never been tracked
2773
+ */
2774
+ getSyncStatus(documentId: string): SyncStatus | undefined;
2775
+ /**
2776
+ * Registers a callback that fires when a document's sync status changes.
2777
+ *
2778
+ * @param callback - Called with (documentId, newStatus) on each transition
2779
+ * @returns Unsubscribe function
2780
+ */
2781
+ onSyncStatusChange(callback: SyncStatusChangeCallback): () => void;
2782
+ }
2783
+ //#endregion
2784
+ //#region src/core/types.d.ts
2785
+ /**
2786
+ * A single mutation job within a batch request.
2787
+ */
2788
+ type ExecutionJobPlan = {
2789
+ key: string;
2790
+ documentId: string;
2791
+ scope: string;
2792
+ branch: string;
2793
+ actions: Action[];
2794
+ dependsOn: string[];
2795
+ };
2796
+ /**
2797
+ * Request for batch mutation operation.
2798
+ */
2799
+ type BatchExecutionRequest = {
2800
+ jobs: ExecutionJobPlan[];
2801
+ };
2802
+ /**
2803
+ * Result from batch mutation operation.
2804
+ */
2805
+ type BatchExecutionResult = {
2806
+ jobs: Record<string, JobInfo>;
2807
+ };
2808
+ /**
2809
+ * A single load job within a batch request.
2810
+ */
2811
+ type LoadJobPlan = {
2812
+ key: string;
2813
+ documentId: string;
2814
+ scope: string;
2815
+ branch: string;
2816
+ operations: Operation[];
2817
+ dependsOn: string[];
2818
+ };
2819
+ /**
2820
+ * Request for batch load operation.
2821
+ */
2822
+ type BatchLoadRequest = {
2823
+ jobs: LoadJobPlan[];
2824
+ };
2825
+ /**
2826
+ * Result from batch load operation.
2827
+ */
2828
+ type BatchLoadResult = {
2829
+ jobs: Record<string, JobInfo>;
2830
+ };
2831
+ /**
2832
+ * The main Reactor interface that serves as a facade for document operations.
2833
+ * This interface provides a unified API for document management, including
2834
+ * creation, retrieval, mutation, and deletion operations.
2835
+ */
2836
+ interface IReactor {
2837
+ /**
2838
+ * Signals that the reactor should shutdown.
2839
+ */
2840
+ kill(): ShutdownStatus;
2841
+ /**
2842
+ * Retrieves a list of document model modules.
2843
+ *
2844
+ * @param namespace - Optional namespace like "powerhouse" or "sky", defaults to ""
2845
+ * @param paging - Optional options for paging data in large queries.
2846
+ * @param signal - Optional abort signal to cancel the request
2847
+ * @returns List of document model modules
2848
+ */
2849
+ getDocumentModels(namespace?: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentModelModule>>;
2850
+ /**
2851
+ * Retrieves a specific PHDocument by id
2852
+ *
2853
+ * @param id - Required, this is the document id
2854
+ * @param view - Optional filter containing branch and scopes information
2855
+ * @param consistencyToken - Optional token for read-after-write consistency
2856
+ * @param signal - Optional abort signal to cancel the request
2857
+ * @returns The up-to-date PHDocument
2858
+ */
2859
+ get<TDocument extends PHDocument>(id: string, view?: ViewFilter, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
2860
+ /**
2861
+ * Retrieves a specific PHDocument by slug
2862
+ *
2863
+ * @param slug - Required, this is the document slug
2864
+ * @param view - Optional filter containing branch and scopes information
2865
+ * @param consistencyToken - Optional token for read-after-write consistency
2866
+ * @param signal - Optional abort signal to cancel the request
2867
+ * @returns The up-to-date PHDocument with scopes and list of child document ids
2868
+ */
2869
+ getBySlug<TDocument extends PHDocument>(slug: string, view?: ViewFilter, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
2870
+ /**
2871
+ * Retrieves a specific PHDocument by identifier (either id or slug).
2872
+ * Throws an error if the identifier matches both an id and a slug that refer to different documents.
2873
+ *
2874
+ * @param identifier - Required, this is the document id or slug
2875
+ * @param view - Optional filter containing branch and scopes information
2876
+ * @param consistencyToken - Optional token for read-after-write consistency
2877
+ * @param signal - Optional abort signal to cancel the request
2878
+ * @returns The up-to-date PHDocument with scopes and list of child document ids
2879
+ * @throws {Error} If identifier matches both an ID and slug referring to different documents
2880
+ */
2881
+ getByIdOrSlug<TDocument extends PHDocument>(identifier: string, view?: ViewFilter, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
2882
+ /**
2883
+ * Retrieves outgoing relationships of a given type from a source document.
2884
+ *
2885
+ * @param sourceId - The source document id
2886
+ * @param relationshipType - The relationship type to filter by
2887
+ * @param consistencyToken - Optional token for read-after-write consistency
2888
+ * @param signal - Optional abort signal to cancel the request
2889
+ * @returns The list of target document ids
2890
+ */
2891
+ getOutgoingRelationships(sourceId: string, relationshipType: string, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
2892
+ /**
2893
+ * Retrieves incoming relationships of a given type to a target document.
2894
+ *
2895
+ * @param targetId - The target document id
2896
+ * @param relationshipType - The relationship type to filter by
2897
+ * @param consistencyToken - Optional token for read-after-write consistency
2898
+ * @param signal - Optional abort signal to cancel the request
2899
+ * @returns The list of source document ids
2900
+ */
2901
+ getIncomingRelationships(targetId: string, relationshipType: string, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
2902
+ /**
2903
+ * Retrieves the operations for a document
2904
+ *
2905
+ * @param documentId - The document id
2906
+ * @param view - Optional filter containing branch and scopes information
2907
+ * @param filter - Optional filter for actionTypes, timestamps, and revision
2908
+ * @param paging - Optional pagination options
2909
+ * @param consistencyToken - Optional token for read-after-write consistency
2910
+ * @param signal - Optional abort signal to cancel the request
2911
+ * @returns The list of operations
2912
+ */
2913
+ getOperations(documentId: string, view?: ViewFilter, filter?: OperationFilter, paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<Record<string, PagedResults<Operation>>>;
2914
+ /**
2915
+ * Filters documents by criteria and returns a list of them
2916
+ *
2917
+ * @param search - Search filter options (type, parentId, identifiers)
2918
+ * @param view - Optional filter containing branch and scopes information
2919
+ * @param paging - Optional pagination options
2920
+ * @param consistencyToken - Optional token for read-after-write consistency
2921
+ * @param signal - Optional abort signal to cancel the request
2922
+ * @returns List of documents matching criteria and pagination cursor
2923
+ */
2924
+ find(search: SearchFilter, view?: ViewFilter, paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
2925
+ /**
2926
+ * Creates a document
2927
+ *
2928
+ * @param document - Document with optional id, slug, parent, model type, and initial state
2929
+ * @param signer - Optional signer to sign the actions
2930
+ * @param signal - Optional abort signal to cancel the request
2931
+ * @param meta - Optional metadata that flows through the job lifecycle
2932
+ * @returns The job status
2933
+ */
2934
+ create(document: PHDocument, signer?: ISigner, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
2935
+ /**
2936
+ * Deletes a document
2937
+ *
2938
+ * @param id - Document id
2939
+ * @param signer - Optional signer to sign the actions
2940
+ * @param signal - Optional abort signal to cancel the request
2941
+ * @param meta - Optional metadata that flows through the job lifecycle
2942
+ * @returns The job id and status
2943
+ */
2944
+ deleteDocument(id: string, signer?: ISigner, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
2945
+ /**
2946
+ * Applies a list of actions to a document.
2947
+ *
2948
+ * @param docId - Document id
2949
+ * @param branch - Branch to apply actions to
2950
+ * @param actions - List of actions to apply
2951
+ * @param signal - Optional abort signal to cancel the request
2952
+ * @param meta - Optional metadata that flows through the job lifecycle
2953
+ * @returns The job id and status
2954
+ */
2955
+ execute(docId: string, branch: string, actions: Action[], signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
2956
+ /**
2957
+ * Loads existing operations generated elsewhere into this reactor.
2958
+ *
2959
+ * @param docId - Document id
2960
+ * @param branch - Branch to load operations to
2961
+ * @param operations - List of operations to load
2962
+ * @param signal - Optional abort signal to cancel the request
2963
+ * @param meta - Optional metadata that flows through the job lifecycle
2964
+ * @returns The job id and status
2965
+ */
2966
+ load(docId: string, branch: string, operations: Operation[], signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
2967
+ /**
2968
+ * Applies multiple mutations across documents with dependency management.
2969
+ *
2970
+ * @param request - Batch mutation request containing jobs with dependencies
2971
+ * @param signal - Optional abort signal to cancel the request
2972
+ * @param meta - Optional metadata that flows through the job lifecycle
2973
+ * @returns Map of job keys to job information
2974
+ */
2975
+ executeBatch(request: BatchExecutionRequest, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<BatchExecutionResult>;
2976
+ /**
2977
+ * Loads multiple batches of pre-existing operations across documents with dependency management.
2978
+ *
2979
+ * @param request - Batch load request containing jobs with dependencies
2980
+ * @param signal - Optional abort signal to cancel the request
2981
+ * @param meta - Optional metadata that flows through the job lifecycle
2982
+ * @returns Map of job keys to job information
2983
+ */
2984
+ loadBatch(request: BatchLoadRequest, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<BatchLoadResult>;
2985
+ /**
2986
+ * Adds a relationship between two documents.
2987
+ *
2988
+ * @param sourceId - Source document id
2989
+ * @param targetId - Target document id
2990
+ * @param relationshipType - Relationship type identifier
2991
+ * @param branch - Branch to add the relationship to, defaults to "main"
2992
+ * @param signer - Optional signer to sign the actions
2993
+ * @param signal - Optional abort signal to cancel the request
2994
+ * @returns The job id and status
2995
+ */
2996
+ addRelationship(sourceId: string, targetId: string, relationshipType: string, branch?: string, signer?: ISigner, signal?: AbortSignal): Promise<JobInfo>;
2997
+ /**
2998
+ * Removes a relationship between two documents.
2999
+ *
3000
+ * @param sourceId - Source document id
3001
+ * @param targetId - Target document id
3002
+ * @param relationshipType - Relationship type identifier
3003
+ * @param branch - Branch to remove the relationship from, defaults to "main"
3004
+ * @param signer - Optional signer to sign the actions
3005
+ * @param signal - Optional abort signal to cancel the request
3006
+ * @returns The job id and status
3007
+ */
3008
+ removeRelationship(sourceId: string, targetId: string, relationshipType: string, branch?: string, signer?: ISigner, signal?: AbortSignal): Promise<JobInfo>;
3009
+ /**
3010
+ * Retrieves the status of a job
3011
+ *
3012
+ * @param jobId - The job id
3013
+ * @returns The job status
3014
+ */
3015
+ getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
3016
+ }
3017
+ /**
3018
+ * Feature flags for reactor configuration
3019
+ */
3020
+ type ReactorFeatures = {
3021
+ [key: string]: boolean;
3022
+ };
3023
+ /**
3024
+ * Combined database type that includes all schemas
3025
+ */
3026
+ type Database = Database$1 & DocumentViewDatabase & DocumentIndexerDatabase;
3027
+ /**
3028
+ * Container for all sync manager dependencies created during the build process.
3029
+ */
3030
+ interface SyncModule {
3031
+ remoteStorage: ISyncRemoteStorage;
3032
+ cursorStorage: ISyncCursorStorage;
3033
+ deadLetterStorage: ISyncDeadLetterStorage;
3034
+ channelFactory: IChannelFactory;
3035
+ syncManager: ISyncManager;
3036
+ }
3037
+ /**
3038
+ * Container for all reactor dependencies created during the build process.
3039
+ * Provides direct access to internal components for advanced use cases,
3040
+ * testing, or integration scenarios.
3041
+ */
3042
+ interface ReactorModule {
3043
+ eventBus: IEventBus;
3044
+ documentModelRegistry: IDocumentModelRegistry;
3045
+ queue: IQueue;
3046
+ jobTracker: IJobTracker;
3047
+ executorManager: IJobExecutorManager;
3048
+ database: Kysely<Database>;
3049
+ operationStore: IOperationStore;
3050
+ keyframeStore: IKeyframeStore;
3051
+ writeCache: IWriteCache;
3052
+ operationIndex: IOperationIndex;
3053
+ documentView: IDocumentView;
3054
+ documentViewConsistencyTracker: IConsistencyTracker;
3055
+ documentIndexer: IDocumentIndexer;
3056
+ documentIndexerConsistencyTracker: IConsistencyTracker;
3057
+ readModelCoordinator: IReadModelCoordinator;
3058
+ subscriptionManager: IReactorSubscriptionManager;
3059
+ processorManager: IProcessorManager$1;
3060
+ processorManagerConsistencyTracker: IConsistencyTracker;
3061
+ syncModule: SyncModule | undefined;
3062
+ reactor: IReactor;
3063
+ }
3064
+ /**
3065
+ * Container for all reactor client dependencies created during the build process.
3066
+ * Provides direct access to internal components for advanced use cases,
3067
+ * testing, or integration scenarios.
3068
+ */
3069
+ interface ReactorClientModule {
3070
+ client: ReactorClient;
3071
+ reactor: IReactor;
3072
+ eventBus: IEventBus;
3073
+ documentIndexer: IDocumentIndexer;
3074
+ documentView: IDocumentView;
3075
+ signer: ISigner;
3076
+ subscriptionManager: IReactorSubscriptionManager;
3077
+ jobAwaiter: IJobAwaiter;
3078
+ reactorModule: ReactorModule | undefined;
3079
+ }
3080
+ //#endregion
3081
+ //#region src/client/drive-client.d.ts
3082
+ /**
3083
+ * Implementation of {@link IDriveClient}.
3084
+ *
3085
+ * Holds a back-reference to its parent {@link IReactorClient} for read and
3086
+ * single-document write primitives, plus direct access to {@link IReactor}
3087
+ * for batch execution. The back-reference is captured but never invoked
3088
+ * during construction, so the partial-`this` hazard does not apply.
3089
+ */
3090
+ declare class DriveClient implements IDriveClient {
3091
+ private readonly client;
3092
+ private readonly logger;
3093
+ private readonly reactor;
3094
+ private readonly signer;
3095
+ constructor(client: IReactorClient, logger: ILogger, reactor: IReactor, signer: ISigner);
3096
+ create(input: DriveInput, signal?: AbortSignal): Promise<DocumentDriveDocument>;
3097
+ addFile<TDocument extends PHDocument = PHDocument>(driveIdentifier: string, document: PHDocument, parentFolder?: string, signal?: AbortSignal): Promise<TDocument>;
3098
+ addFolder(driveIdentifier: string, name: string, parentFolder?: string, signal?: AbortSignal): Promise<FolderNode>;
3099
+ removeNode(driveIdentifier: string, nodeId: string, signal?: AbortSignal): Promise<void>;
3100
+ renameNode(driveIdentifier: string, nodeId: string, name: string, signal?: AbortSignal): Promise<Node>;
3101
+ moveNode(driveIdentifier: string, srcNodeId: string, targetParentFolderId: string | undefined, signal?: AbortSignal): Promise<DocumentDriveDocument>;
3102
+ copyNode(driveIdentifier: string, srcNodeId: string, targetParentFolderId: string | undefined, signal?: AbortSignal): Promise<DocumentDriveDocument>;
3103
+ getNode(driveIdentifier: string, nodeId: string, signal?: AbortSignal): Promise<Node>;
3104
+ listNodes(driveIdentifier: string, parentFolder?: string | null, signal?: AbortSignal): Promise<Node[]>;
3105
+ private removeFileNode;
3106
+ }
3107
+ //#endregion
3108
+ //#region src/cache/write-cache-types.d.ts
3109
+ /**
3110
+ * Configuration options for the write cache
3111
+ */
3112
+ type WriteCacheConfig = {
3113
+ /** Maximum number of document streams to cache (LRU eviction). Default: 1000 */maxDocuments: number; /** Number of snapshots to keep in each document's ring buffer. Default: 10 */
3114
+ ringBufferSize: number; /** Persist a keyframe snapshot every N revisions. Default: 10 */
3115
+ keyframeInterval: number;
3116
+ };
3117
+ /**
3118
+ * Unique identifier for a document stream
3119
+ */
3120
+ type DocumentStreamKey = {
3121
+ /** Document identifier */documentId: string; /** Operation scope */
3122
+ scope: string; /** Branch name */
3123
+ branch: string;
3124
+ };
3125
+ /**
3126
+ * A cached document snapshot at a specific revision
3127
+ */
3128
+ type CachedSnapshot = {
3129
+ /** The revision number of this snapshot */revision: number; /** The document state at this revision */
3130
+ document: PHDocument;
3131
+ };
3132
+ /**
3133
+ * Serialized keyframe snapshot for K/V store persistence
3134
+ */
3135
+ type KeyframeSnapshot = {
3136
+ /** The revision number of this keyframe */revision: number; /** Serialized document state */
3137
+ document: string;
3138
+ };
3139
+ //#endregion
3140
+ //#region src/signer/types.d.ts
3141
+ /**
3142
+ * Configuration for signing and verification.
3143
+ */
3144
+ type SignerConfig = {
3145
+ /**
3146
+ * The signer used to sign actions before submission.
3147
+ */
3148
+ signer: ISigner;
3149
+ /**
3150
+ * Optional handler for verifying signatures on incoming operations.
3151
+ * If not provided, signature verification will be skipped.
3152
+ */
3153
+ verifier?: SignatureVerificationHandler;
3154
+ };
3155
+ //#endregion
3156
+ //#region src/storage/migrations/types.d.ts
3157
+ type MigrationStrategy = "auto" | "manual" | "none";
3158
+ interface MigrationResult {
3159
+ success: boolean;
3160
+ migrationsExecuted: string[];
3161
+ error?: Error;
3162
+ }
3163
+ //#endregion
3164
+ //#region src/sync/sync-builder.d.ts
3165
+ declare class SyncBuilder {
3166
+ private channelFactory?;
3167
+ private remoteStorage?;
3168
+ private cursorStorage?;
3169
+ private deadLetterStorage?;
3170
+ private config;
3171
+ withChannelFactory(factory: IChannelFactory): this;
3172
+ withRemoteStorage(storage: ISyncRemoteStorage): this;
3173
+ withCursorStorage(storage: ISyncCursorStorage): this;
3174
+ withDeadLetterStorage(storage: ISyncDeadLetterStorage): this;
3175
+ withMaxDeadLettersPerRemote(limit: number): this;
3176
+ withMaxInboxBatchSize(limit: number): this;
3177
+ build(reactor: IReactor, logger: ILogger, operationIndex: IOperationIndex, eventBus: IEventBus, db: Kysely<Database$1>): ISyncManager;
3178
+ buildModule(reactor: IReactor, logger: ILogger, operationIndex: IOperationIndex, eventBus: IEventBus, db: Kysely<Database$1>): SyncModule;
3179
+ }
3180
+ //#endregion
3181
+ //#region src/core/reactor-builder.d.ts
3182
+ declare class ReactorBuilder {
3183
+ private logger?;
3184
+ private documentModels;
3185
+ private upgradeManifests;
3186
+ private features;
3187
+ private readModels;
3188
+ private executorManager;
3189
+ private executorConfig;
3190
+ private writeCacheConfig?;
3191
+ private migrationStrategy;
3192
+ private syncBuilder?;
3193
+ private eventBus?;
3194
+ private readModelCoordinator?;
3195
+ private signatureVerifier?;
3196
+ private kyselyInstance?;
3197
+ private signalHandlersEnabled;
3198
+ private queueInstance?;
3199
+ private channelScheme?;
3200
+ private jwtHandler?;
3201
+ private documentModelLoader?;
3202
+ private shutdownHooks;
3203
+ withLogger(logger: ILogger): this;
3204
+ withDocumentModels(models: DocumentModelModule<any>[]): this;
3205
+ withUpgradeManifests(manifests: UpgradeManifest<readonly number[]>[]): this;
3206
+ withFeatures(features: ReactorFeatures): this;
3207
+ withReadModel(readModel: IReadModel): this;
3208
+ withReadModelCoordinator(readModelCoordinator: IReadModelCoordinator): this;
3209
+ withExecutor(executor: IJobExecutorManager): this;
3210
+ withExecutorConfig(config: Partial<JobExecutorConfig>): this;
3211
+ withWriteCacheConfig(config: Partial<WriteCacheConfig>): this;
3212
+ withMigrationStrategy(strategy: MigrationStrategy): this;
3213
+ withSync(syncBuilder: SyncBuilder): this;
3214
+ withEventBus(eventBus: IEventBus): this;
3215
+ withSignatureVerifier(verifier: SignatureVerificationHandler): this;
3216
+ withKysely(kysely: Kysely<Database>): this;
3217
+ withQueue(queue: IQueue): this;
3218
+ withChannelScheme(scheme: ChannelScheme): this;
3219
+ withJwtHandler(handler: JwtHandler): this;
3220
+ withDocumentModelLoader(loader: IDocumentModelLoader): this;
3221
+ withSignalHandlers(): this;
3222
+ /**
3223
+ * Register an async cleanup hook to run during graceful shutdown. Hooks fire
3224
+ * after `reactor.kill()` resolves and before `database.destroy()`, so callers
3225
+ * that depend on the reactor (e.g. an HTTP API layered on top) can drain
3226
+ * cleanly before the underlying kysely instance is torn down. Hook errors are
3227
+ * logged and otherwise ignored — one bad hook cannot strand the rest of the
3228
+ * shutdown chain.
3229
+ */
3230
+ withShutdownHook(hook: () => Promise<void>): this;
3231
+ build(): Promise<IReactor>;
3232
+ buildModule(): Promise<ReactorModule>;
3233
+ private attachSignalHandlers;
3234
+ }
3235
+ //#endregion
3236
+ //#region src/core/reactor-client-builder.d.ts
3237
+ /**
3238
+ * Builder class for constructing ReactorClient instances with proper configuration
3239
+ */
3240
+ declare class ReactorClientBuilder {
3241
+ private logger?;
3242
+ private reactorBuilder?;
3243
+ private reactor?;
3244
+ private eventBus?;
3245
+ private documentIndexer?;
3246
+ private documentView?;
3247
+ private signer?;
3248
+ private signatureVerifier?;
3249
+ private subscriptionManager?;
3250
+ private jobAwaiter?;
3251
+ private documentModelLoader?;
3252
+ /**
3253
+ * Sets the logger for the ReactorClient.
3254
+ * @param logger - The logger to use.
3255
+ * @returns The ReactorClientBuilder instance.
3256
+ */
3257
+ withLogger(logger: ILogger): this;
3258
+ /**
3259
+ * Either this or withReactor must be set.
3260
+ */
3261
+ withReactorBuilder(reactorBuilder: ReactorBuilder): this;
3262
+ /**
3263
+ * Either this or withReactorBuilder must be set.
3264
+ */
3265
+ withReactor(reactor: IReactor, eventBus: IEventBus, documentIndexer: IDocumentIndexer, documentView: IDocumentView): this;
3266
+ /**
3267
+ * Sets the signer configuration for signing and verifying actions.
3268
+ *
3269
+ * @param config - Either an ISigner for signing only, or a SignerConfig for both signing and verification
3270
+ */
3271
+ withSigner(config: ISigner | SignerConfig): this;
3272
+ withSubscriptionManager(subscriptionManager: IReactorSubscriptionManager): this;
3273
+ withJobAwaiter(jobAwaiter: IJobAwaiter): this;
3274
+ withDocumentModelLoader(loader: IDocumentModelLoader): this;
3275
+ build(): Promise<ReactorClient>;
3276
+ buildModule(): Promise<ReactorClientModule>;
3277
+ }
3278
+ //#endregion
3279
+ //#region src/core/reactor.d.ts
3280
+ /**
3281
+ * This class implements the IReactor interface and serves as the main entry point
3282
+ * for the new Reactor architecture.
3283
+ */
3284
+ declare class Reactor implements IReactor {
3285
+ private logger;
3286
+ private documentModelRegistry;
3287
+ private shutdownStatus;
3288
+ private setShutdown;
3289
+ private setCompleted;
3290
+ private queue;
3291
+ private jobTracker;
3292
+ private readModelCoordinator;
3293
+ private features;
3294
+ private documentView;
3295
+ private documentIndexer;
3296
+ private operationStore;
3297
+ private eventBus;
3298
+ private executorManager;
3299
+ constructor(logger: ILogger, documentModelRegistry: IDocumentModelRegistry, queue: IQueue, jobTracker: IJobTracker, readModelCoordinator: IReadModelCoordinator, features: ReactorFeatures, documentView: IDocumentView, documentIndexer: IDocumentIndexer, operationStore: IOperationStore, eventBus: IEventBus, executorManager: IJobExecutorManager);
3300
+ kill(): ShutdownStatus;
3301
+ getDocumentModels(namespace?: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentModelModule>>;
3302
+ get<TDocument extends PHDocument>(id: string, view?: ViewFilter, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
3303
+ getBySlug<TDocument extends PHDocument>(slug: string, view?: ViewFilter, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
3304
+ getByIdOrSlug<TDocument extends PHDocument>(identifier: string, view?: ViewFilter, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
3305
+ getOutgoingRelationships(sourceId: string, relationshipType: string, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
3306
+ getIncomingRelationships(targetId: string, relationshipType: string, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
3307
+ getOperations(documentId: string, view?: ViewFilter, filter?: OperationFilter, paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<Record<string, PagedResults<Operation>>>;
3308
+ find(search: SearchFilter, view?: ViewFilter, paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
3309
+ create(document: PHDocument, signer?: ISigner, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
3310
+ deleteDocument(id: string, signer?: ISigner, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
3311
+ execute(docId: string, branch: string, actions: Action[], signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
3312
+ load(docId: string, branch: string, operations: Operation[], signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
3313
+ executeBatch(request: BatchExecutionRequest, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<BatchExecutionResult>;
3314
+ loadBatch(request: BatchLoadRequest, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<BatchLoadResult>;
3315
+ addRelationship(sourceId: string, targetId: string, relationshipType: string, branch?: string, signer?: ISigner, signal?: AbortSignal): Promise<JobInfo>;
3316
+ removeRelationship(sourceId: string, targetId: string, relationshipType: string, branch?: string, signer?: ISigner, signal?: AbortSignal): Promise<JobInfo>;
3317
+ getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
3318
+ private findByIds;
3319
+ private findBySlugs;
3320
+ private findByParentId;
3321
+ private findByType;
3322
+ private emitJobPending;
3323
+ }
3324
+ //#endregion
3325
+ //#region src/shared/drive-url.d.ts
3326
+ interface ParsedDriveUrl {
3327
+ url: string;
3328
+ driveId: string;
3329
+ graphqlEndpoint: string;
3330
+ }
3331
+ /**
3332
+ * Parse a drive URL to extract drive ID and construct GraphQL endpoint.
3333
+ * Preserves any subpath prefix so the result is correct when the reactor is
3334
+ * served behind a proxy at a non-root path.
3335
+ * e.g., "http://localhost:4001/d/abc123" -> { driveId: "abc123", graphqlEndpoint: "http://localhost:4001/graphql/r" }
3336
+ * e.g., "https://example.com/api/reactor/d/abc123" -> { ..., graphqlEndpoint: "https://example.com/api/reactor/graphql/r" }
3337
+ */
3338
+ declare function parseDriveUrl(url: string): ParsedDriveUrl;
3339
+ /**
3340
+ * Extract drive ID from a drive URL.
3341
+ */
3342
+ declare function driveIdFromUrl(url: string): string;
3343
+ //#endregion
3344
+ //#region src/shared/factories.d.ts
3345
+ /**
3346
+ * Factory method to create a ShutdownStatus that can be updated
3347
+ *
3348
+ * @param initialState - Initial shutdown state (default: false)
3349
+ * @returns A tuple of [ShutdownStatus, setShutdown function, setCompleted function]
3350
+ */
3351
+ declare function createMutableShutdownStatus(initialState?: boolean): [ShutdownStatus, (value: boolean) => void, (completed: Promise<void>) => void];
3352
+ //#endregion
3353
+ //#region src/subs/default-error-handler.d.ts
3354
+ /**
3355
+ * Default error handler that re-throws subscription errors.
3356
+ * This ensures that errors are not silently swallowed.
3357
+ */
3358
+ declare class DefaultSubscriptionErrorHandler implements ISubscriptionErrorHandler {
3359
+ handleError(error: unknown, context: SubscriptionErrorContext): void;
3360
+ }
3361
+ //#endregion
3362
+ //#region src/subs/react-subscription-manager.d.ts
3363
+ type DocumentCreatedCallback = (result: PagedResults<string>) => void;
3364
+ type DocumentDeletedCallback = (documentIds: string[]) => void;
3365
+ type DocumentStateUpdatedCallback = (result: PagedResults<PHDocument>) => void;
3366
+ type RelationshipChangedCallback = (parentId: string, childId: string, changeType: RelationshipChangeType) => void;
3367
+ declare class ReactorSubscriptionManager implements IReactorSubscriptionManager {
3368
+ private createdSubscriptions;
3369
+ private deletedSubscriptions;
3370
+ private updatedSubscriptions;
3371
+ private relationshipSubscriptions;
3372
+ private subscriptionCounter;
3373
+ private errorHandler;
3374
+ constructor(errorHandler: ISubscriptionErrorHandler);
3375
+ onDocumentCreated(callback: DocumentCreatedCallback, search?: SearchFilter): () => void;
3376
+ onDocumentDeleted(callback: DocumentDeletedCallback, search?: SearchFilter): () => void;
3377
+ onDocumentStateUpdated(callback: DocumentStateUpdatedCallback, search?: SearchFilter, view?: ViewFilter): () => void;
3378
+ onRelationshipChanged(callback: RelationshipChangedCallback, search?: SearchFilter): () => void;
3379
+ /**
3380
+ * Notify subscribers about created documents
3381
+ */
3382
+ notifyDocumentsCreated(documentIds: string[], documentTypes?: Map<string, string>, parentIds?: Map<string, string | null>): void;
3383
+ /**
3384
+ * Notify subscribers about deleted documents
3385
+ */
3386
+ notifyDocumentsDeleted(documentIds: string[], documentTypes?: Map<string, string>, parentIds?: Map<string, string | null>): void;
3387
+ /**
3388
+ * Notify subscribers about updated documents
3389
+ */
3390
+ notifyDocumentsUpdated(documents: PHDocument[]): void;
3391
+ /**
3392
+ * Notify subscribers about relationship changes
3393
+ */
3394
+ notifyRelationshipChanged(parentId: string, childId: string, changeType: RelationshipChangeType, childType?: string): void;
3395
+ /**
3396
+ * Clear all subscriptions
3397
+ */
3398
+ clearAll(): void;
3399
+ private filterDocumentIds;
3400
+ private filterDocuments;
3401
+ private matchesRelationshipFilter;
3402
+ }
3403
+ //#endregion
3404
+ //#region src/events/event-bus.d.ts
3405
+ declare class EventBus implements IEventBus {
3406
+ readonly eventTypeToSubscribers: Map<number, Subscriber[]>;
3407
+ subscribe<K>(type: number, subscriber: (type: number, event: K) => void | Promise<void>): Unsubscribe;
3408
+ emit(type: number, data: any): Promise<void>;
3409
+ }
3410
+ //#endregion
3411
+ //#region src/registry/document-model-resolver.d.ts
3412
+ interface IDocumentModelResolver {
3413
+ ensureModelLoaded(documentType: string): Promise<void>;
3414
+ }
3415
+ /**
3416
+ * No-op resolver used when no document model loader is configured.
3417
+ * Checks the registry for the model and returns if found; throws if not.
3418
+ * Since there is no loader, missing models cannot be recovered.
3419
+ */
3420
+ declare class NullDocumentModelResolver implements IDocumentModelResolver {
3421
+ private registry?;
3422
+ constructor(registry?: IDocumentModelRegistry | undefined);
3423
+ ensureModelLoaded(documentType: string): Promise<void>;
3424
+ }
3425
+ //#endregion
3426
+ //#region src/queue/queue.d.ts
3427
+ /**
3428
+ * In-memory implementation of the IQueue interface.
3429
+ * Organizes jobs by documentId, scope, and branch to ensure proper ordering.
3430
+ * Ensures serial execution per document by tracking executing jobs.
3431
+ * Implements dependency management through queue hints.
3432
+ */
3433
+ declare class InMemoryQueue implements IQueue {
3434
+ private eventBus;
3435
+ private resolver;
3436
+ private queues;
3437
+ private jobIdToQueueKey;
3438
+ private docIdToJobId;
3439
+ private jobIdToDocId;
3440
+ private completedJobs;
3441
+ private jobIndex;
3442
+ private isBlocked;
3443
+ private onDrainedCallback?;
3444
+ private isPausedFlag;
3445
+ constructor(eventBus: IEventBus, resolver: IDocumentModelResolver);
3446
+ private toErrorInfo;
3447
+ /**
3448
+ * Creates a unique key for a document/scope/branch combination
3449
+ */
3450
+ private createQueueKey;
3451
+ /**
3452
+ * Gets or creates a queue for the given key
3453
+ */
3454
+ private getQueue;
3455
+ /**
3456
+ * Check if a document has any jobs currently executing
3457
+ */
3458
+ private isDocumentExecuting;
3459
+ /**
3460
+ * Mark a job as executing for its document
3461
+ */
3462
+ private markJobExecuting;
3463
+ /**
3464
+ * Mark a job as no longer executing for its document
3465
+ */
3466
+ private markJobComplete;
3467
+ /**
3468
+ * Check if all dependencies for a job have been completed
3469
+ */
3470
+ private areDependenciesMet;
3471
+ /**
3472
+ * Get the next job that has all its dependencies met
3473
+ */
3474
+ private getNextJobWithMetDependencies;
3475
+ private getCreateDocumentType;
3476
+ enqueue(job: Job): Promise<void>;
3477
+ dequeue(documentId: string, scope: string, branch: string, signal?: AbortSignal): Promise<IJobExecutionHandle | null>;
3478
+ dequeueNext(signal?: AbortSignal): Promise<IJobExecutionHandle | null>;
3479
+ size(documentId: string, scope: string, branch: string): Promise<number>;
3480
+ totalSize(): Promise<number>;
3481
+ remove(jobId: string): Promise<boolean>;
3482
+ clear(documentId: string, scope: string, branch: string): Promise<void>;
3483
+ clearAll(): Promise<void>;
3484
+ hasJobs(): Promise<boolean>;
3485
+ completeJob(jobId: string): Promise<void>;
3486
+ failJob(jobId: string, error?: ErrorInfo): Promise<void>;
3487
+ deferJob(jobId: string): void;
3488
+ retryJob(jobId: string, error?: ErrorInfo): Promise<void>;
3489
+ /**
3490
+ * Check if the queue is drained and call the callback if it is
3491
+ */
3492
+ private checkDrained;
3493
+ /**
3494
+ * Returns true if and only if all jobs have been resolved.
3495
+ */
3496
+ get isDrained(): boolean;
3497
+ /**
3498
+ * Blocks the queue from accepting new jobs.
3499
+ * @param onDrained - Optional callback to call when the queue is drained
3500
+ */
3501
+ block(onDrained?: () => void): void;
3502
+ /**
3503
+ * Unblocks the queue from accepting new jobs.
3504
+ */
3505
+ unblock(): void;
3506
+ /**
3507
+ * Pauses job dequeuing. Jobs can still be enqueued but dequeueNext() will return null.
3508
+ */
3509
+ pause(): void;
3510
+ /**
3511
+ * Resumes job dequeuing and emits JOB_AVAILABLE events for pending jobs to wake up executors.
3512
+ */
3513
+ resume(): Promise<void>;
3514
+ /**
3515
+ * Returns whether job dequeuing is paused.
3516
+ */
3517
+ get paused(): boolean;
3518
+ /**
3519
+ * Returns all pending jobs across all queues.
3520
+ */
3521
+ getPendingJobs(): Job[];
3522
+ /**
3523
+ * Returns a map of document IDs to sets of executing job IDs.
3524
+ */
3525
+ getExecutingJobIds(): Map<string, Set<string>>;
3526
+ /**
3527
+ * Returns a job by ID from the job index.
3528
+ */
3529
+ getJob(jobId: string): Job | undefined;
3530
+ }
3531
+ //#endregion
3532
+ //#region src/job-tracker/in-memory-job-tracker.d.ts
3533
+ /**
3534
+ * In-memory implementation of IJobTracker.
3535
+ * Maintains job status in a Map for synchronous access.
3536
+ * Subscribes to operation events to update job states.
3537
+ */
3538
+ declare class InMemoryJobTracker implements IJobTracker {
3539
+ private eventBus;
3540
+ private jobs;
3541
+ private unsubscribers;
3542
+ constructor(eventBus: IEventBus);
3543
+ private subscribeToEvents;
3544
+ private handleWriteReady;
3545
+ private handleReadReady;
3546
+ private handleJobFailed;
3547
+ shutdown(): void;
3548
+ registerJob(jobInfo: JobInfo): void;
3549
+ markRunning(jobId: string): void;
3550
+ markFailed(jobId: string, error: ErrorInfo, job?: Job): void;
3551
+ getJobStatus(jobId: string): JobInfo | null;
3552
+ }
3553
+ //#endregion
3554
+ //#region src/executor/simple-job-executor-manager.d.ts
3555
+ type JobExecutorFactory = () => IJobExecutor;
3556
+ /**
3557
+ * Manages multiple job executors and coordinates job distribution.
3558
+ * Listens for job available events and dispatches jobs to executors.
3559
+ */
3560
+ declare class SimpleJobExecutorManager implements IJobExecutorManager {
3561
+ private executorFactory;
3562
+ private eventBus;
3563
+ private queue;
3564
+ private jobTracker;
3565
+ private logger;
3566
+ private resolver;
3567
+ private executors;
3568
+ private isRunning;
3569
+ private activeJobs;
3570
+ private totalJobsProcessed;
3571
+ private unsubscribe?;
3572
+ private deferredJobs;
3573
+ private jobTimeoutMs;
3574
+ constructor(executorFactory: JobExecutorFactory, eventBus: IEventBus, queue: IQueue, jobTracker: IJobTracker, logger: ILogger, resolver: IDocumentModelResolver, jobTimeoutMs?: number);
3575
+ start(numExecutors: number): Promise<void>;
3576
+ stop(graceful?: boolean): Promise<void>;
3577
+ getExecutors(): IJobExecutor[];
3578
+ getStatus(): ExecutorManagerStatus;
3579
+ private processNextJob;
3580
+ private checkForMoreJobs;
3581
+ private processExistingJobs;
3582
+ private toErrorInfo;
3583
+ private hasCreateDocumentAction;
3584
+ private flushDeferredJobs;
3585
+ private formatErrorHistory;
3586
+ }
3587
+ //#endregion
3588
+ //#region src/cache/collection-membership-cache.d.ts
3589
+ interface ICollectionMembershipCache {
3590
+ getCollectionsForDocuments(documentIds: string[]): Promise<Record<string, string[]>>;
3591
+ invalidate(documentId: string): void;
3592
+ }
3593
+ //#endregion
3594
+ //#region src/cache/document-meta-cache-types.d.ts
3595
+ /**
3596
+ * Cached document metadata from the "document" scope.
3597
+ *
3598
+ * This lightweight structure holds essential document information needed by
3599
+ * the job executor without fetching full scope state. It provides an explicit
3600
+ * cross-scope contract for accessing document scope metadata.
3601
+ */
3602
+ type CachedDocumentMeta = {
3603
+ /**
3604
+ * The full PHDocumentState from document.state.document.
3605
+ * Contains version, hash, isDeleted, deletedAtUtcIso, etc.
3606
+ */
3607
+ state: PHDocumentState;
3608
+ /**
3609
+ * The document type (from header), cached for convenience.
3610
+ */
3611
+ documentType: string;
3612
+ /**
3613
+ * The revision of the document scope when this metadata was captured.
3614
+ * Used for cache invalidation and consistency checks.
3615
+ */
3616
+ documentScopeRevision: number;
3617
+ };
3618
+ /**
3619
+ * Interface for the document metadata cache.
3620
+ *
3621
+ * This cache provides an explicit cross-scope contract for accessing document
3622
+ * scope metadata. It solves the problem where job execution in one scope (e.g.,
3623
+ * "global") needs access to document scope state (version, isDeleted, etc.)
3624
+ * which may be stale in scope-specific caches or keyframes.
3625
+ *
3626
+ * The cache supports:
3627
+ * - Latest metadata retrieval with LRU caching
3628
+ * - Historical metadata reconstruction for reshuffling scenarios
3629
+ * - Eager updates after document scope operations
3630
+ */
3631
+ interface IDocumentMetaCache {
3632
+ /**
3633
+ * Retrieves the LATEST document metadata from cache or rebuilds from operations.
3634
+ *
3635
+ * On cache miss, fetches all document scope operations and reconstructs the
3636
+ * current PHDocumentState by applying UPGRADE_DOCUMENT and DELETE_DOCUMENT
3637
+ * operations.
3638
+ *
3639
+ * @param documentId - The document identifier
3640
+ * @param branch - Branch name
3641
+ * @param signal - Optional abort signal to cancel the operation
3642
+ * @returns The cached or rebuilt document metadata
3643
+ * @throws {Error} "Operation aborted" if signal is aborted
3644
+ * @throws {Error} If document not found (no CREATE_DOCUMENT operation)
3645
+ */
3646
+ getDocumentMeta(documentId: string, branch: string, signal?: AbortSignal): Promise<CachedDocumentMeta>;
3647
+ /**
3648
+ * Rebuilds document metadata at a SPECIFIC revision (always rebuilds, no caching).
3649
+ *
3650
+ * Used during reshuffling when operations need to be inserted at a previous
3651
+ * revision and we need the document scope state as of that point in time.
3652
+ *
3653
+ * @param documentId - The document identifier
3654
+ * @param branch - Branch name
3655
+ * @param targetRevision - The document scope revision to reconstruct up to
3656
+ * @param signal - Optional abort signal to cancel the operation
3657
+ * @returns Document metadata as of the target revision
3658
+ * @throws {Error} "Operation aborted" if signal is aborted
3659
+ * @throws {Error} If document not found
3660
+ */
3661
+ rebuildAtRevision(documentId: string, branch: string, targetRevision: number, signal?: AbortSignal): Promise<CachedDocumentMeta>;
3662
+ /**
3663
+ * Eagerly updates cached metadata after document scope operations.
3664
+ *
3665
+ * Called by the job executor after CREATE_DOCUMENT, UPGRADE_DOCUMENT, or
3666
+ * DELETE_DOCUMENT operations to keep the cache current.
3667
+ *
3668
+ * @param documentId - The document identifier
3669
+ * @param branch - Branch name
3670
+ * @param meta - The new metadata to cache
3671
+ */
3672
+ putDocumentMeta(documentId: string, branch: string, meta: CachedDocumentMeta): void;
3673
+ /**
3674
+ * Invalidates cached document metadata.
3675
+ *
3676
+ * Call before reshuffling operations that modify the document scope, or
3677
+ * when document state may have changed externally.
3678
+ *
3679
+ * @param documentId - The document identifier
3680
+ * @param branch - Optional branch to narrow invalidation (if omitted, all branches)
3681
+ * @returns Number of entries invalidated
3682
+ */
3683
+ invalidate(documentId: string, branch?: string): number;
3684
+ /**
3685
+ * Clears all cached document metadata.
3686
+ */
3687
+ clear(): void;
3688
+ /**
3689
+ * Performs startup initialization.
3690
+ */
3691
+ startup(): Promise<void>;
3692
+ /**
3693
+ * Performs graceful shutdown.
3694
+ */
3695
+ shutdown(): Promise<void>;
3696
+ }
3697
+ //#endregion
3698
+ //#region src/cache/buffer/ring-buffer.d.ts
3699
+ /**
3700
+ * RingBuffer is a generic circular buffer implementation that stores a fixed number
3701
+ * of items. When the buffer is full, new items overwrite the oldest items.
3702
+ *
3703
+ * This implementation maintains O(1) time complexity for push operations and provides
3704
+ * items in chronological order (oldest to newest) via getAll().
3705
+ *
3706
+ * @template T - The type of items stored in the buffer
3707
+ */
3708
+ declare class RingBuffer<T> {
3709
+ private buffer;
3710
+ private head;
3711
+ private size;
3712
+ private capacity;
3713
+ constructor(capacity: number);
3714
+ /**
3715
+ * Adds an item to the buffer. If the buffer is full, overwrites the oldest item.
3716
+ *
3717
+ * @param item - The item to add
3718
+ */
3719
+ push(item: T): void;
3720
+ /**
3721
+ * Returns all items in the buffer in chronological order (oldest to newest).
3722
+ *
3723
+ * @returns Array of items in insertion order
3724
+ */
3725
+ getAll(): T[];
3726
+ /**
3727
+ * Clears all items from the buffer.
3728
+ */
3729
+ clear(): void;
3730
+ /**
3731
+ * Gets the current number of items in the buffer.
3732
+ */
3733
+ get length(): number;
3734
+ }
3735
+ //#endregion
3736
+ //#region src/cache/kysely-write-cache.d.ts
3737
+ type DocumentStream = {
3738
+ key: string;
3739
+ ringBuffer: RingBuffer<CachedSnapshot>;
3740
+ };
3741
+ /**
3742
+ * In-memory write cache with keyframe persistence for PHDocuments.
3743
+ *
3744
+ * Caches document snapshots in ring buffers with LRU eviction. On cache miss,
3745
+ * rebuilds documents from nearest keyframe or full operation history.
3746
+ *
3747
+ * **Performance Characteristics:**
3748
+ * - Cache hit: O(1) lookup in ring buffer
3749
+ * - Cold miss: O(n) where n is total operation count, or O(k) where k is operations since keyframe
3750
+ * - Warm miss: O(m) where m is operations since cached revision
3751
+ * - Eviction: O(1) for LRU tracking and removal
3752
+ *
3753
+ * **Thread Safety:**
3754
+ * Not thread-safe. Designed for single-threaded job executor environment.
3755
+ * External synchronization required for concurrent access across multiple executors.
3756
+ *
3757
+ * **Example:**
3758
+ * ```typescript
3759
+ * const cache = new KyselyWriteCache(
3760
+ * keyframeStore,
3761
+ * operationStore,
3762
+ * registry,
3763
+ * { maxDocuments: 1000, ringBufferSize: 10, keyframeInterval: 10 }
3764
+ * );
3765
+ *
3766
+ * await cache.startup();
3767
+ *
3768
+ * // Retrieve or rebuild document
3769
+ * const doc = await cache.getState(docId, docType, scope, branch, revision);
3770
+ *
3771
+ * // Cache result after job execution
3772
+ * cache.putState(docId, docType, scope, branch, newRevision, updatedDoc);
3773
+ *
3774
+ * await cache.shutdown();
3775
+ * ```
3776
+ */
3777
+ declare class KyselyWriteCache implements IWriteCache {
3778
+ private streams;
3779
+ private lruTracker;
3780
+ private keyframeStore;
3781
+ private operationStore;
3782
+ private registry;
3783
+ private config;
3784
+ constructor(keyframeStore: IKeyframeStore, operationStore: IOperationStore, registry: IDocumentModelRegistry, config: WriteCacheConfig);
3785
+ withScopedStores(operationStore: IOperationStore, keyframeStore: IKeyframeStore): KyselyWriteCache;
3786
+ /**
3787
+ * Initializes the write cache.
3788
+ * Currently a no-op as keyframe store lifecycle is managed externally.
3789
+ */
3790
+ startup(): Promise<void>;
3791
+ /**
3792
+ * Shuts down the write cache.
3793
+ * Currently a no-op as keyframe store lifecycle is managed externally.
3794
+ */
3795
+ shutdown(): Promise<void>;
3796
+ /**
3797
+ * Retrieves document state at a specific revision from cache or rebuilds it.
3798
+ *
3799
+ * Cache hit path: Returns cached snapshot if available (O(1))
3800
+ * Warm miss path: Rebuilds from cached base revision + incremental ops
3801
+ * Cold miss path: Rebuilds from keyframe or from scratch using all operations
3802
+ *
3803
+ * @param documentId - The document identifier
3804
+ * @param scope - The operation scope
3805
+ * @param branch - The operation branch
3806
+ * @param targetRevision - The target revision, or undefined for newest
3807
+ * @param signal - Optional abort signal to cancel the operation
3808
+ * @returns The document at the target revision
3809
+ * @throws {Error} "Operation aborted" if signal is aborted
3810
+ * @throws {ModuleNotFoundError} If document type not registered in registry
3811
+ * @throws {Error} "Failed to rebuild document" if operation store fails
3812
+ * @throws {Error} If reducer throws during operation application
3813
+ * @throws {Error} If document serialization fails
3814
+ */
3815
+ getState(documentId: string, scope: string, branch: string, targetRevision?: number, signal?: AbortSignal): Promise<PHDocument>;
3816
+ /**
3817
+ * Stores a document snapshot in the cache at a specific revision.
3818
+ *
3819
+ * The cached document is a shallow copy of the input with its operation history
3820
+ * truncated to the last operation per scope and its clipboard cleared. This keeps
3821
+ * memory use and copy costs constant regardless of operation count. Consumers of
3822
+ * getState() must not rely on the full operation history being present; the only
3823
+ * guaranteed invariant is that operations[scope].at(-1) reflects the latest
3824
+ * operation index for each scope.
3825
+ *
3826
+ * Updates LRU tracker and may evict least recently used stream if at capacity.
3827
+ * Asynchronously persists keyframes at configured intervals (fire-and-forget).
3828
+ *
3829
+ * @param documentId - The document identifier
3830
+ * @param scope - The operation scope
3831
+ * @param branch - The operation branch
3832
+ * @param revision - The revision number
3833
+ * @param document - The document to cache
3834
+ * @throws {Error} If document serialization fails
3835
+ */
3836
+ putState(documentId: string, scope: string, branch: string, revision: number, document: PHDocument): void;
3837
+ /**
3838
+ * Invalidates cached document streams.
3839
+ *
3840
+ * Supports three invalidation scopes:
3841
+ * - Document-level: invalidate(documentId) - removes all streams for document
3842
+ * - Scope-level: invalidate(documentId, scope) - removes all branches for scope
3843
+ * - Stream-level: invalidate(documentId, scope, branch) - removes specific stream
3844
+ *
3845
+ * @param documentId - The document identifier
3846
+ * @param scope - Optional scope to narrow invalidation
3847
+ * @param branch - Optional branch to narrow invalidation (requires scope)
3848
+ * @returns The number of streams evicted
3849
+ */
3850
+ invalidate(documentId: string, scope?: string, branch?: string): number;
3851
+ /**
3852
+ * Clears the entire cache, removing all cached document streams.
3853
+ * Resets LRU tracking state. This operation always succeeds.
3854
+ */
3855
+ clear(): void;
3856
+ /**
3857
+ * Retrieves a specific stream for a document. Exposed on the implementation
3858
+ * for testing, but not on the interface.
3859
+ *
3860
+ * @internal
3861
+ */
3862
+ getStream(documentId: string, scope: string, branch: string): DocumentStream | undefined;
3863
+ private findNearestKeyframe;
3864
+ private coldMissRebuild;
3865
+ private warmMissRebuild;
3866
+ private findNearestOlderSnapshot;
3867
+ private makeStreamKey;
3868
+ private getOrCreateStream;
3869
+ private isKeyframeRevision;
3870
+ }
3871
+ //#endregion
3872
+ //#region src/storage/kysely/store.d.ts
3873
+ declare class KyselyOperationStore implements IOperationStore {
3874
+ private db;
3875
+ private trx?;
3876
+ constructor(db: Kysely<Database$1>);
3877
+ private get queryExecutor();
3878
+ withTransaction(trx: Transaction<Database$1>): KyselyOperationStore;
3879
+ apply(documentId: string, documentType: string, scope: string, branch: string, revision: number, fn: (txn: AtomicTxn) => void | Promise<void>, signal?: AbortSignal): Promise<void>;
3880
+ private executeApply;
3881
+ getSince(documentId: string, scope: string, branch: string, revision: number, filter?: OperationFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
3882
+ getSinceId(id: number, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<OperationWithContext$1>>;
3883
+ getConflicting(documentId: string, scope: string, branch: string, minTimestamp: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
3884
+ getRevisions(documentId: string, branch: string, signal?: AbortSignal): Promise<DocumentRevisions>;
3885
+ private rowToOperation;
3886
+ private rowToOperationWithContext;
3887
+ }
3888
+ //#endregion
3889
+ //#region src/storage/kysely/keyframe-store.d.ts
3890
+ declare class KyselyKeyframeStore implements IKeyframeStore {
3891
+ private db;
3892
+ private trx?;
3893
+ constructor(db: Kysely<Database$1>);
3894
+ private get queryExecutor();
3895
+ withTransaction(trx: Transaction<Database$1>): KyselyKeyframeStore;
3896
+ putKeyframe(documentId: string, scope: string, branch: string, revision: number, document: PHDocument, signal?: AbortSignal): Promise<void>;
3897
+ findNearestKeyframe(documentId: string, scope: string, branch: string, targetRevision: number, signal?: AbortSignal): Promise<{
3898
+ revision: number;
3899
+ document: PHDocument;
3900
+ } | undefined>;
3901
+ listKeyframes(documentId: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<Array<{
3902
+ scope: string;
3903
+ branch: string;
3904
+ revision: number;
3905
+ document: PHDocument;
3906
+ }>>;
3907
+ deleteKeyframes(documentId: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<number>;
3908
+ }
3909
+ //#endregion
3910
+ //#region src/executor/execution-scope.d.ts
3911
+ interface ExecutionStores {
3912
+ operationStore: IOperationStore;
3913
+ operationIndex: IOperationIndex;
3914
+ writeCache: IWriteCache;
3915
+ documentMetaCache: IDocumentMetaCache;
3916
+ collectionMembershipCache: ICollectionMembershipCache;
3917
+ }
3918
+ interface IExecutionScope {
3919
+ run<T>(fn: (stores: ExecutionStores) => Promise<T>, signal?: AbortSignal): Promise<T>;
3920
+ }
3921
+ //#endregion
3922
+ //#region src/executor/simple-job-executor.d.ts
3923
+ /**
3924
+ * Simple job executor that processes a job by applying actions through document model reducers.
3925
+ */
3926
+ declare class SimpleJobExecutor implements IJobExecutor {
3927
+ private logger;
3928
+ private registry;
3929
+ private operationStore;
3930
+ private eventBus;
3931
+ private writeCache;
3932
+ private operationIndex;
3933
+ private documentMetaCache;
3934
+ private collectionMembershipCache;
3935
+ private config;
3936
+ private signatureVerifierModule;
3937
+ private documentActionHandler;
3938
+ private executionScope;
3939
+ constructor(logger: ILogger, registry: IDocumentModelRegistry, operationStore: IOperationStore, eventBus: IEventBus, writeCache: IWriteCache, operationIndex: IOperationIndex, documentMetaCache: IDocumentMetaCache, collectionMembershipCache: ICollectionMembershipCache, config: JobExecutorConfig, signatureVerifier?: SignatureVerificationHandler, executionScope?: IExecutionScope);
3940
+ /**
3941
+ * Execute a single job by applying all its actions through the appropriate reducers.
3942
+ * Actions are processed sequentially in order.
3943
+ */
3944
+ executeJob(job: Job, signal?: AbortSignal): Promise<JobResult>;
3945
+ private getCollectionMembershipsForOperations;
3946
+ private processActions;
3947
+ private executeRegularAction;
3948
+ private executeLoadJob;
3949
+ private accumulateResultOrReturnError;
3950
+ }
3951
+ //#endregion
3952
+ //#region src/registry/implementation.d.ts
3953
+ /**
3954
+ * Error thrown when a document model module is not found in the registry.
3955
+ */
3956
+ declare class ModuleNotFoundError extends Error {
3957
+ readonly documentType: string;
3958
+ readonly requestedVersion: number | undefined;
3959
+ constructor(documentType: string, version?: number);
3960
+ static isError(error: unknown): error is ModuleNotFoundError;
3961
+ }
3962
+ /**
3963
+ * Error thrown when attempting to register a module that already exists.
3964
+ */
3965
+ declare class DuplicateModuleError extends Error {
3966
+ constructor(documentType: string, version?: number);
3967
+ static isError(error: unknown): error is DuplicateModuleError;
3968
+ }
3969
+ /**
3970
+ * Error thrown when a module is invalid or malformed.
3971
+ */
3972
+ declare class InvalidModuleError extends Error {
3973
+ constructor(message: string);
3974
+ }
3975
+ /**
3976
+ * Error thrown when attempting to register an upgrade manifest that already exists.
3977
+ */
3978
+ declare class DuplicateManifestError extends Error {
3979
+ constructor(documentType: string);
3980
+ static isError(error: unknown): error is DuplicateManifestError;
3981
+ }
3982
+ /**
3983
+ * In-memory implementation of the IDocumentModelRegistry interface.
3984
+ * Manages document model modules with version-aware storage and upgrade manifest support.
3985
+ */
3986
+ declare class DocumentModelRegistry implements IDocumentModelRegistry {
3987
+ private modules;
3988
+ private manifests;
3989
+ registerModules(...modules: DocumentModelModule<any>[]): RegistrationResult<DocumentModelModule<any>>[];
3990
+ unregisterModules(...documentTypes: string[]): boolean;
3991
+ getModule(documentType: string, version?: number): DocumentModelModule<any>;
3992
+ getAllModules(): DocumentModelModule<any>[];
3993
+ clear(): void;
3994
+ getSupportedVersions(documentType: string): number[];
3995
+ getLatestVersion(documentType: string): number;
3996
+ registerUpgradeManifests(...manifestsToRegister: UpgradeManifest<readonly number[]>[]): RegistrationResult<UpgradeManifest<readonly number[]>>[];
3997
+ unregisterUpgradeManifests(...documentTypes: string[]): boolean;
3998
+ getUpgradeManifest(documentType: string): UpgradeManifest<readonly number[]>;
3999
+ computeUpgradePath(documentType: string, fromVersion: number, toVersion: number): UpgradeTransition[];
4000
+ getUpgradeReducer(documentType: string, fromVersion: number, toVersion: number): UpgradeReducer<any, any>;
4001
+ }
4002
+ //#endregion
4003
+ //#region src/read-models/base-read-model.d.ts
4004
+ type BaseReadModelConfig = {
4005
+ readModelId: string;
4006
+ rebuildStateOnInit: boolean;
4007
+ };
4008
+ /**
4009
+ * Base class for read models that provides catch-up/rewind functionality.
4010
+ * Handles initialization, state tracking via ViewState table, and consistency tracking.
4011
+ * Subclasses override commitOperations() with their specific domain logic.
4012
+ */
4013
+ declare class BaseReadModel implements IReadModel {
4014
+ protected db: Kysely<DocumentViewDatabase>;
4015
+ protected operationIndex: IOperationIndex;
4016
+ protected writeCache: IWriteCache;
4017
+ protected consistencyTracker: IConsistencyTracker;
4018
+ protected config: BaseReadModelConfig;
4019
+ protected lastOrdinal: number;
4020
+ readonly name: string;
4021
+ constructor(db: Kysely<DocumentViewDatabase>, operationIndex: IOperationIndex, writeCache: IWriteCache, consistencyTracker: IConsistencyTracker, config: BaseReadModelConfig);
4022
+ /**
4023
+ * Initializes the read model by loading state and catching up on missed operations.
4024
+ */
4025
+ init(): Promise<void>;
4026
+ /**
4027
+ * Template method: runs domain-specific commitOperations, then persists
4028
+ * state and updates consistency tracking.
4029
+ */
4030
+ indexOperations(items: OperationWithContext$1[]): Promise<void>;
4031
+ /**
4032
+ * Waits for the read model to reach the specified consistency level.
4033
+ */
4034
+ waitForConsistency(token: ConsistencyToken, timeoutMs?: number, signal?: AbortSignal): Promise<void>;
4035
+ protected commitOperations(items: OperationWithContext$1[]): Promise<void>;
4036
+ /**
4037
+ * Rebuilds document state for each operation using the write cache.
4038
+ */
4039
+ protected rebuildStateForOperations(operations: OperationWithContext$1[]): Promise<OperationWithContext$1[]>;
4040
+ /**
4041
+ * Loads the last processed ordinal from the ViewState table.
4042
+ * Returns undefined if no state exists for this read model.
4043
+ */
4044
+ protected loadState(): Promise<number | undefined>;
4045
+ /**
4046
+ * Initializes the ViewState row for this read model.
4047
+ */
4048
+ protected initializeState(): Promise<void>;
4049
+ /**
4050
+ * Saves the last processed ordinal to the ViewState table.
4051
+ */
4052
+ protected saveState(trx: Transaction<DocumentViewDatabase>, items: OperationWithContext$1[]): Promise<void>;
4053
+ /**
4054
+ * Updates the consistency tracker with the processed operations.
4055
+ */
4056
+ protected updateConsistencyTracker(items: OperationWithContext$1[]): void;
4057
+ }
4058
+ //#endregion
4059
+ //#region src/storage/kysely/document-indexer.d.ts
4060
+ type IndexerDatabase = Database$1 & DocumentIndexerDatabase & DocumentViewDatabase;
4061
+ declare class KyselyDocumentIndexer extends BaseReadModel implements IDocumentIndexer {
4062
+ private _db;
4063
+ constructor(db: Kysely<IndexerDatabase>, operationIndex: IOperationIndex, writeCache: IWriteCache, consistencyTracker: IConsistencyTracker);
4064
+ protected commitOperations(items: OperationWithContext$1[]): Promise<void>;
4065
+ getOutgoing(documentId: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
4066
+ getIncoming(documentId: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
4067
+ getOrphanedChildren(parentIds: string[], types?: string[], signal?: AbortSignal): Promise<string[]>;
4068
+ hasRelationship(sourceId: string, targetId: string, types?: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<boolean>;
4069
+ getUndirectedRelationships(a: string, b: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
4070
+ getDirectedRelationships(sourceId: string, targetId: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
4071
+ findPath(sourceId: string, targetId: string, types?: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[] | null>;
4072
+ findAncestors(documentId: string, types?: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<IDocumentGraph>;
4073
+ getRelationshipTypes(consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
4074
+ private handleAddRelationship;
4075
+ private handleRemoveRelationship;
4076
+ }
4077
+ //#endregion
4078
+ //#region src/read-models/coordinator.d.ts
4079
+ /**
4080
+ * Coordinates read model synchronization by listening to operation write events
4081
+ * and updating all registered read models in parallel.
4082
+ *
4083
+ * This coordinator is responsible for:
4084
+ * - Subscribing to OPERATION_WRITTEN events from the event bus
4085
+ * - Distributing operation updates to all registered read models
4086
+ * - Managing the lifecycle of read model subscriptions
4087
+ *
4088
+ * Read models are updated asynchronously and in parallel to avoid blocking
4089
+ * the write path. Errors in read model updates are propagated through the
4090
+ * event bus but do not affect the write operation success.
4091
+ */
4092
+ declare class ReadModelCoordinator implements IReadModelCoordinator {
4093
+ private eventBus;
4094
+ readonly preReady: IReadModel[];
4095
+ readonly postReady: IReadModel[];
4096
+ private unsubscribe?;
4097
+ private isRunning;
4098
+ readonly readModels: IReadModel[];
4099
+ constructor(eventBus: IEventBus, preReady: IReadModel[], postReady: IReadModel[]);
4100
+ /**
4101
+ * Start listening for operation events and updating read models.
4102
+ * Can be called multiple times safely (subsequent calls are no-ops).
4103
+ */
4104
+ start(): void;
4105
+ /**
4106
+ * Stop listening and clean up subscriptions.
4107
+ * Can be called multiple times safely (subsequent calls are no-ops).
4108
+ */
4109
+ stop(): void;
4110
+ /**
4111
+ * Handle write ready events by updating all read models in parallel.
4112
+ * Errors from individual read models are collected and re-thrown as an aggregate.
4113
+ */
4114
+ private handleWriteReady;
4115
+ }
4116
+ //#endregion
4117
+ //#region src/read-models/document-view.d.ts
4118
+ type Database$2 = Database$1 & DocumentViewDatabase;
4119
+ declare class KyselyDocumentView extends BaseReadModel implements IDocumentView {
4120
+ private operationStore;
4121
+ private _db;
4122
+ constructor(db: Kysely<Database$2>, operationStore: IOperationStore, operationIndex: IOperationIndex, writeCache: IWriteCache, consistencyTracker: IConsistencyTracker);
4123
+ protected commitOperations(items: OperationWithContext$1[]): Promise<void>;
4124
+ exists(documentIds: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<boolean[]>;
4125
+ get<TDocument extends PHDocument>(documentId: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
4126
+ getMany<TDocument extends PHDocument>(documentIds: string[], view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument[]>;
4127
+ getByIdOrSlug<TDocument extends PHDocument>(identifier: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
4128
+ findByType(type: string, view?: ViewFilter$1, paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
4129
+ resolveSlug(slug: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string | undefined>;
4130
+ resolveSlugs(slugs: string[], view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
4131
+ resolveIdOrSlug(identifier: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string>;
4132
+ }
4133
+ //#endregion
4134
+ //#region src/storage/migrations/migrator.d.ts
4135
+ declare const REACTOR_SCHEMA = "reactor";
4136
+ declare function runMigrations(db: Kysely<any>, schema?: string): Promise<MigrationResult>;
4137
+ declare function getMigrationStatus(db: Kysely<any>, schema?: string): Promise<readonly kysely.MigrationInfo[]>;
4138
+ //#endregion
4139
+ //#region src/storage/kysely/sync-cursor-storage.d.ts
4140
+ declare class KyselySyncCursorStorage implements ISyncCursorStorage {
4141
+ private readonly db;
4142
+ constructor(db: Kysely<Database$1>);
4143
+ list(remoteName: string, signal?: AbortSignal): Promise<RemoteCursor[]>;
4144
+ get(remoteName: string, cursorType: "inbox" | "outbox", signal?: AbortSignal): Promise<RemoteCursor>;
4145
+ upsert(cursor: RemoteCursor, signal?: AbortSignal): Promise<void>;
4146
+ remove(remoteName: string, signal?: AbortSignal): Promise<void>;
4147
+ }
4148
+ //#endregion
4149
+ //#region src/storage/kysely/sync-remote-storage.d.ts
4150
+ declare class KyselySyncRemoteStorage implements ISyncRemoteStorage {
4151
+ private readonly db;
4152
+ constructor(db: Kysely<Database$1>);
4153
+ list(signal?: AbortSignal): Promise<RemoteRecord[]>;
4154
+ get(name: string, signal?: AbortSignal): Promise<RemoteRecord>;
4155
+ upsert(remote: RemoteRecord, signal?: AbortSignal): Promise<void>;
4156
+ remove(name: string, signal?: AbortSignal): Promise<void>;
4157
+ }
4158
+ //#endregion
4159
+ //#region src/sync/channels/gql-request-channel-factory.d.ts
4160
+ /**
4161
+ * Factory for creating GqlRequestChannel instances.
4162
+ *
4163
+ * Extracts GraphQL-specific configuration from ChannelConfig.parameters and
4164
+ * instantiates GqlRequestChannel instances for network-based synchronization.
4165
+ *
4166
+ * The optional jwtHandler enables dynamic JWT token generation per-request,
4167
+ * which is useful for short-lived tokens with audience-specific claims.
4168
+ */
4169
+ declare class GqlRequestChannelFactory implements IChannelFactory {
4170
+ private readonly logger;
4171
+ private readonly jwtHandler?;
4172
+ private readonly queue;
4173
+ constructor(logger: ILogger, jwtHandler: JwtHandler | undefined, queue: IQueue);
4174
+ /**
4175
+ * Creates a new GqlRequestChannel instance with the given configuration.
4176
+ * See GqlChannelConfig for the expected parameters.
4177
+ *
4178
+ * @param config - Channel configuration including type and parameters
4179
+ * @param cursorStorage - Storage for persisting synchronization cursors
4180
+ * @param operationIndex - Operation index for querying timestamps
4181
+ * @returns A new GqlRequestChannel instance
4182
+ */
4183
+ instance(remoteId: string, remoteName: string, config: ChannelConfig, cursorStorage: ISyncCursorStorage, collectionId: string, filter: RemoteFilter, operationIndex: IOperationIndex, options?: RemoteOptions): IChannel;
4184
+ }
4185
+ //#endregion
4186
+ //#region src/sync/channels/gql-response-channel-factory.d.ts
4187
+ /**
4188
+ * Factory for creating GqlResponseChannel instances.
4189
+ */
4190
+ declare class GqlResponseChannelFactory implements IChannelFactory {
4191
+ private readonly logger;
4192
+ constructor(logger: ILogger);
4193
+ instance(remoteId: string, remoteName: string, config: ChannelConfig, cursorStorage: ISyncCursorStorage): IChannel;
4194
+ }
4195
+ //#endregion
4196
+ //#region src/sync/channels/poll-timer.d.ts
4197
+ /**
4198
+ * Timer that controls when polling occurs.
4199
+ * GqlChannel registers a delegate; the timer invokes it when appropriate.
4200
+ * The delegate returns a Promise; timer waits for completion before scheduling next tick.
4201
+ */
4202
+ type IPollTimer = {
4203
+ /** Register the delegate to be called on each tick. Returns Promise that timer awaits. */setDelegate: (delegate: () => Promise<void>) => void; /** Start the timer (begins calling delegate periodically) */
4204
+ start: () => void; /** Stop the timer */
4205
+ stop: () => void;
4206
+ /**
4207
+ * Fires the delegate exactly once without changing the running/paused state.
4208
+ * Used by Manual polling mode to pull on demand without resuming the schedule.
4209
+ */
4210
+ triggerNow: () => void;
4211
+ };
4212
+ //#endregion
4213
+ //#region src/sync/channels/gql-req-channel.d.ts
4214
+ /**
4215
+ * Configuration parameters for GqlChannel
4216
+ */
4217
+ type GqlChannelConfig = {
4218
+ /** The GraphQL endpoint URL */url: string; /** Dynamic JWT token handler for generating fresh tokens per-request */
4219
+ jwtHandler?: JwtHandler; /** Custom fetch function for testing (default: global fetch) */
4220
+ fetchFn?: typeof fetch; /** Collection ID to synchronize */
4221
+ collectionId: string; /** Filter to apply to operations */
4222
+ filter: RemoteFilter; /** Base delay in ms for exponential backoff on push retries */
4223
+ retryBaseDelayMs: number; /** Maximum delay in ms for exponential backoff on push retries */
4224
+ retryMaxDelayMs: number;
4225
+ };
4226
+ /**
4227
+ * GraphQL-based synchronization channel for network communication between reactors.
4228
+ */
4229
+ declare class GqlRequestChannel implements IChannel {
4230
+ private readonly logger;
4231
+ readonly inbox: IMailbox;
4232
+ readonly outbox: IMailbox;
4233
+ readonly deadLetter: IMailbox;
4234
+ readonly config: GqlChannelConfig;
4235
+ private readonly bufferedOutbox;
4236
+ private readonly channelId;
4237
+ private readonly remoteName;
4238
+ private readonly cursorStorage;
4239
+ private readonly operationIndex;
4240
+ private readonly pollTimer;
4241
+ private readonly abortController;
4242
+ private isShutdown;
4243
+ private failureCount;
4244
+ private lastSuccessUtcMs?;
4245
+ private lastFailureUtcMs?;
4246
+ private lastPersistedInboxOrdinal;
4247
+ private lastPersistedOutboxOrdinal;
4248
+ private pushFailureCount;
4249
+ private pushRetryTimer;
4250
+ private pushBlocked;
4251
+ private isPushing;
4252
+ private pendingDrain;
4253
+ private receivingPages;
4254
+ private connectionState;
4255
+ private readonly connectionStateCallbacks;
4256
+ constructor(logger: ILogger, channelId: string, remoteName: string, cursorStorage: ISyncCursorStorage, config: GqlChannelConfig, operationIndex: IOperationIndex, pollTimer: IPollTimer);
4257
+ /**
4258
+ * Shuts down the channel and prevents further operations.
4259
+ */
4260
+ shutdown(): Promise<void>;
4261
+ getConnectionState(): ConnectionStateSnapshot;
4262
+ onConnectionStateChange(callback: ConnectionStateChangeCallback): () => void;
4263
+ triggerPull(): void;
4264
+ /**
4265
+ * Initializes the channel by registering it on the remote server and starting polling.
4266
+ */
4267
+ init(): Promise<void>;
4268
+ private transitionConnectionState;
4269
+ /**
4270
+ * Polls the remote for new sync envelopes.
4271
+ */
4272
+ private poll;
4273
+ /**
4274
+ * Handles dead letters reported by the remote server.
4275
+ * Creates local dead letter SyncOperations so the channel quiesces.
4276
+ */
4277
+ private handleRemoteDeadLetters;
4278
+ /**
4279
+ * Handles polling errors with error classification.
4280
+ * Returns true if the error was handled (caller should not rethrow).
4281
+ */
4282
+ private handlePollError;
4283
+ /**
4284
+ * Recovers from a "Channel not found" error by re-registering and restarting polling.
4285
+ * Self-retries with backoff instead of restarting the poll timer on failure.
4286
+ */
4287
+ private recoverFromChannelNotFound;
4288
+ /**
4289
+ * Queries the remote GraphQL endpoint for sync envelopes.
4290
+ */
4291
+ private pollSyncEnvelopes;
4292
+ /**
4293
+ * Registers or updates this channel on the remote server via GraphQL mutation.
4294
+ * Returns the remote's ack ordinal so the client can trim its outbox.
4295
+ */
4296
+ private touchRemoteChannel;
4297
+ /**
4298
+ * Fire-and-forget push with retry on recoverable errors.
4299
+ * On success, clears push blocked state. On recoverable error, blocks
4300
+ * further pushes and schedules a retry. On unrecoverable error, moves
4301
+ * ops to deadLetter.
4302
+ */
4303
+ private attemptPush;
4304
+ /**
4305
+ * Schedules a retry of all current outbox items using exponential backoff.
4306
+ */
4307
+ private schedulePushRetry;
4308
+ /**
4309
+ * Drains pending outbox items that arrived while a push was in-flight.
4310
+ * Server-side action.id dedup handles any overlap with the previous push.
4311
+ */
4312
+ private drainOutbox;
4313
+ /**
4314
+ * Classifies an error as recoverable or unrecoverable based on its type.
4315
+ * Recoverable errors are transient and worth retrying (network, 5xx, parse).
4316
+ * Unrecoverable errors will not self-heal (auth, client errors, GraphQL rejections).
4317
+ */
4318
+ private classifyError;
4319
+ /**
4320
+ * Pushes multiple sync operations to the remote via a single GraphQL mutation.
4321
+ * Creates one SyncEnvelope per SyncOperation with key/dependsOn for batch ordering.
4322
+ */
4323
+ private pushSyncOperations;
4324
+ /**
4325
+ * Gets the authorization header value using jwtHandler.
4326
+ */
4327
+ private getAuthorizationHeader;
4328
+ /**
4329
+ * Executes a GraphQL query or mutation against the remote endpoint.
4330
+ */
4331
+ private executeGraphQL;
4332
+ get poller(): IPollTimer;
4333
+ }
4334
+ //#endregion
4335
+ //#region src/sync/channels/gql-res-channel.d.ts
4336
+ /**
4337
+ * This class is used server-side to accumulate inbox + outbox operations.
4338
+ *
4339
+ * In general, the resolvers are responsible for updating mailboxes.
4340
+ */
4341
+ declare class GqlResponseChannel implements IChannel {
4342
+ private readonly logger;
4343
+ readonly inbox: Mailbox;
4344
+ readonly outbox: Mailbox;
4345
+ readonly deadLetter: Mailbox;
4346
+ private readonly channelId;
4347
+ private readonly remoteName;
4348
+ private readonly cursorStorage;
4349
+ private isShutdown;
4350
+ private lastPersistedInboxOrdinal;
4351
+ private lastPersistedOutboxOrdinal;
4352
+ private connectionState;
4353
+ private readonly connectionStateCallbacks;
4354
+ constructor(logger: ILogger, channelId: string, remoteName: string, cursorStorage: ISyncCursorStorage);
4355
+ shutdown(): Promise<void>;
4356
+ getConnectionState(): ConnectionStateSnapshot;
4357
+ onConnectionStateChange(callback: ConnectionStateChangeCallback): () => void;
4358
+ /** Response channels are push-driven; resolvers populate mailboxes directly. */
4359
+ triggerPull(): void;
4360
+ private transitionConnectionState;
4361
+ init(): Promise<void>;
4362
+ }
4363
+ //#endregion
4364
+ //#region src/sync/channels/interval-poll-timer.d.ts
4365
+ type PollTimerConfig = {
4366
+ intervalMs: number;
4367
+ maxQueueDepth: number;
4368
+ backpressureCheckIntervalMs: number;
4369
+ retryBaseDelayMs: number;
4370
+ retryMaxDelayMs: number;
4371
+ /**
4372
+ * If true, start() puts the timer into a paused state — running but not ticking.
4373
+ * Use resume() to begin scheduling ticks, or triggerNow() to fire a single tick
4374
+ * without leaving the paused state. Defaults to false (auto-tick on start).
4375
+ */
4376
+ startPaused: boolean;
4377
+ };
4378
+ /**
4379
+ * Default poll timer using setTimeout.
4380
+ * Waits for delegate completion before scheduling next tick.
4381
+ * Checks queue depth and defers polling when backpressure is detected.
4382
+ */
4383
+ declare class IntervalPollTimer implements IPollTimer {
4384
+ private delegate;
4385
+ private timer;
4386
+ private running;
4387
+ private paused;
4388
+ private consecutiveFailures;
4389
+ private readonly queue;
4390
+ private readonly config;
4391
+ constructor(queue: IQueue, config?: Partial<PollTimerConfig>);
4392
+ setDelegate(delegate: () => Promise<void>): void;
4393
+ start(): void;
4394
+ stop(): void;
4395
+ private tick;
4396
+ private scheduleNext;
4397
+ private scheduleRetry;
4398
+ private scheduleBackpressureRecheck;
4399
+ pause(): void;
4400
+ resume(): void;
4401
+ triggerNow(): void;
4402
+ isPaused(): boolean;
4403
+ isRunning(): boolean;
4404
+ getIntervalMs(): number;
4405
+ setIntervalMs(ms: number): void;
4406
+ }
4407
+ //#endregion
4408
+ //#region src/sync/channels/utils.d.ts
4409
+ /**
4410
+ * Converts a SyncEnvelope containing operations into multiple SyncOperations.
4411
+ *
4412
+ * This function batches operations by documentId, preserving cross-document ordering.
4413
+ * For operations [a1, a2, a3, b1, b2, a4], it returns:
4414
+ * - SyncOperation 1: [a1, a2, a3] for doc-a
4415
+ * - SyncOperation 2: [b1, b2] for doc-b
4416
+ * - SyncOperation 3: [a4] for doc-a
4417
+ *
4418
+ * This ensures operations are grouped for efficient processing while maintaining
4419
+ * causality across documents.
4420
+ */
4421
+ declare function envelopesToSyncOperations(envelope: SyncEnvelope, remoteName: string): SyncOperation[];
4422
+ //#endregion
4423
+ //#region src/sync/utils.d.ts
4424
+ type OperationBatch = {
4425
+ documentId: string;
4426
+ branch: string;
4427
+ scope: string;
4428
+ operations: OperationWithContext$1[];
4429
+ };
4430
+ /**
4431
+ * Trims a mailbox using the ack ordinal.
4432
+ */
4433
+ declare function trimMailboxFromAckOrdinal(mailbox: IMailbox, ackOrdinal: number): void;
4434
+ /**
4435
+ * Batches consecutive operations by documentId and scope, preserving ordering.
4436
+ *
4437
+ * For operations [a1_doc, a1_global, a2_doc, b1_global], this returns:
4438
+ * - Batch 1: [a1_doc] for doc-a, document scope
4439
+ * - Batch 2: [a1_global] for doc-a, global scope
4440
+ * - Batch 3: [a2_doc] for doc-a, document scope
4441
+ * - Batch 4: [b1_global] for doc-b, global scope
4442
+ *
4443
+ * This ensures operations are grouped for efficient processing while maintaining
4444
+ * causality across documents and scopes.
4445
+ */
4446
+ declare function batchOperationsByDocument(operations: OperationWithContext$1[]): OperationBatch[];
4447
+ /**
4448
+ * Merges SyncOperations that share the same (documentId, scope, branch) into
4449
+ * a single SyncOperation per group. Within each group, operations are sorted
4450
+ * by context.ordinal. The merged SyncOperation keeps the first group member's
4451
+ * jobId; all other jobIds are remapped so external dependencies still resolve.
4452
+ */
4453
+ declare function consolidateSyncOperations(syncOps: SyncOperation[]): SyncOperation[];
4454
+ //#endregion
4455
+ //#region src/admin/types.d.ts
4456
+ type KeyframeValidationIssue = {
4457
+ scope: string;
4458
+ branch: string;
4459
+ revision: number;
4460
+ keyframeHash: string;
4461
+ replayedHash: string;
4462
+ };
4463
+ type SnapshotValidationIssue = {
4464
+ scope: string;
4465
+ branch: string;
4466
+ snapshotHash: string;
4467
+ replayedHash: string;
4468
+ };
4469
+ type ValidationResult = {
4470
+ documentId: string;
4471
+ isConsistent: boolean;
4472
+ keyframeIssues: KeyframeValidationIssue[];
4473
+ snapshotIssues: SnapshotValidationIssue[];
4474
+ };
4475
+ type RebuildResult = {
4476
+ documentId: string;
4477
+ keyframesDeleted: number;
4478
+ scopesInvalidated: number;
4479
+ };
4480
+ interface IDocumentIntegrityService {
4481
+ validateDocument(documentId: string, branch?: string, signal?: AbortSignal): Promise<ValidationResult>;
4482
+ rebuildKeyframes(documentId: string, branch?: string, signal?: AbortSignal): Promise<RebuildResult>;
4483
+ rebuildSnapshots(documentId: string, branch?: string, signal?: AbortSignal): Promise<RebuildResult>;
4484
+ }
4485
+ //#endregion
4486
+ //#region src/admin/document-integrity-service.d.ts
4487
+ declare class DocumentIntegrityService implements IDocumentIntegrityService {
4488
+ private readonly keyframeStore;
4489
+ private readonly operationStore;
4490
+ private readonly writeCache;
4491
+ private readonly documentView;
4492
+ private readonly documentModelRegistry;
4493
+ constructor(keyframeStore: IKeyframeStore, operationStore: IOperationStore, writeCache: IWriteCache, documentView: IDocumentView, documentModelRegistry: IDocumentModelRegistry);
4494
+ validateDocument(documentId: string, branch?: string, signal?: AbortSignal): Promise<ValidationResult>;
4495
+ rebuildKeyframes(documentId: string, branch?: string, signal?: AbortSignal): Promise<RebuildResult>;
4496
+ rebuildSnapshots(documentId: string, branch?: string, signal?: AbortSignal): Promise<RebuildResult>;
4497
+ private discoverScopes;
4498
+ }
4499
+ //#endregion
4500
+ //#region src/processors/processor-manager.d.ts
4501
+ /**
4502
+ * Manages processor lifecycle based on operations.
4503
+ * Extends BaseReadModel to receive operations from ReadModelCoordinator.
4504
+ *
4505
+ * Responsibilities:
4506
+ * 1. Detect drive creation from CREATE_DOCUMENT operations
4507
+ * 2. Create processors for each drive using registered factories
4508
+ * 3. Route operations to matching processors based on filters
4509
+ * 4. Clean up processors when drives are deleted or factories are unregistered
4510
+ * 5. Track per-processor cursors for failure recovery and backfill
4511
+ */
4512
+ declare class ProcessorManager extends BaseReadModel implements IProcessorManager$1 {
4513
+ private factoryRegistry;
4514
+ private processorsByDrive;
4515
+ private factoryToProcessors;
4516
+ private knownDriveIds;
4517
+ private cursorCache;
4518
+ private logger;
4519
+ constructor(db: Kysely<DocumentViewDatabase>, operationIndex: IOperationIndex, writeCache: IWriteCache, consistencyTracker: IConsistencyTracker, logger: ILogger);
4520
+ init(): Promise<void>;
4521
+ protected commitOperations(items: OperationWithContext$1[]): Promise<void>;
4522
+ registerFactory(identifier: string, factory: ProcessorFactory$1): Promise<void>;
4523
+ unregisterFactory(identifier: string): Promise<void>;
4524
+ get(processorId: string): TrackedProcessor$1 | undefined;
4525
+ getAll(): TrackedProcessor$1[];
4526
+ private allTrackedProcessors;
4527
+ private detectAndRegisterNewDrives;
4528
+ private detectAndCleanupDeletedDrives;
4529
+ private discoverExistingDrives;
4530
+ private isDeletedDocumentADrive;
4531
+ private createProcessorsForDrive;
4532
+ private backfillProcessor;
4533
+ private retryProcessor;
4534
+ private cleanupDriveProcessors;
4535
+ private safeDisconnect;
4536
+ private routeOperationsToProcessors;
4537
+ private loadAllCursors;
4538
+ private safeSaveProcessorCursor;
4539
+ private saveProcessorCursor;
4540
+ private deleteProcessorCursors;
4541
+ }
4542
+ //#endregion
4543
+ export { type AtomicTxn, type AttachmentHash, type AttachmentRef, BaseReadModel, type BatchLoadRequest, type BatchLoadResult, type CachedSnapshot, type ChannelConfig, ChannelError, ChannelErrorSource, type ChannelHealth, type ChannelMeta, ChannelScheme, type ConnectionState, type ConnectionStateChangeCallback, type ConnectionStateChangedEvent, type ConnectionStateSnapshot, type ConsistencyCoordinate, type ConsistencyKey, type ConsistencyToken, ConsistencyTracker, type Database, type DeadLetterAddedEvent, DefaultSubscriptionErrorHandler, type DocumentChangeEvent, DocumentChangeType, type DocumentGraphEdge, type DocumentIndexerDatabase, DocumentIntegrityService, DocumentModelRegistry, type DocumentRelationship, type DocumentRevisions, type DocumentStreamKey, type DocumentViewDatabase, DriveClient, DuplicateManifestError, DuplicateModuleError, DuplicateOperationError, EventBus, EventBusAggregateError, type ExecutorStartedEvent, type ExecutorStoppedEvent, type GqlChannelConfig, GqlRequestChannel, GqlRequestChannelFactory, GqlResponseChannel, GqlResponseChannelFactory, type IChannel, type IChannelFactory, type IConsistencyTracker, type IDocumentGraph, type IDocumentIndexer, type IDocumentIntegrityService, type IDocumentModelLoader, type IDocumentModelRegistry, type IDocumentView, type IDriveClient, type IEventBus, type IJobAwaiter, type IJobExecutor, type IJobExecutorManager, type IJobTracker, type IKeyframeStore, type IOperationIndex, type IOperationStore, type IPollTimer, type IProcessor, type IProcessorHostModule, type IProcessorManager, type IQueue, type IReactor, type IReactorClient, type IReactorSubscriptionManager, type IReadModel, type IReadModelCoordinator, type IRelationalDb, type ISubscriptionErrorHandler, type ISyncCursorStorage, type ISyncManager, type ISyncRemoteStorage, type ISyncStatusTracker, type IWriteCache, SimpleJobExecutor as InMemoryJobExecutor, SimpleJobExecutor, InMemoryJobTracker, InMemoryQueue, type InsertableDocumentSnapshot, IntervalPollTimer, InvalidModuleError, type Job, type JobAvailableEvent, JobAwaiter, type JobCompletedEvent, type JobExecutorConfig, JobExecutorEventTypes, type JobExecutorFactory, type JobFailedEvent, type JobInfo, type JobPendingEvent, type JobReadReadyEvent, type JobResult, type JobRunningEvent, type JobStartedEvent, JobStatus, type JobWriteReadyEvent, type JwtHandler, type KeyframeSnapshot, type KeyframeValidationIssue, KyselyDocumentIndexer, KyselyDocumentView, KyselyKeyframeStore, KyselyOperationStore, KyselySyncCursorStorage, KyselySyncRemoteStorage, KyselyWriteCache, type LoadJobPlan, Mailbox, ModuleNotFoundError, NullDocumentModelResolver, type OperationBatch, type OperationContext, type OperationFilter, type OperationIndexEntry, type OperationTable, type OperationWithContext, OptimisticLockError, type PagedResults, type PagingOptions, type ParsedDriveUrl, PollBehavior, PollingChannelError, type ProcessorApp, type ProcessorFactory, type ProcessorFactoryBuilder, type ProcessorFilter, ProcessorManager, type ProcessorRecord, type ProcessorStatus, PropagationMode, QueueEventTypes, REACTOR_SCHEMA, Reactor, ReactorBuilder, ReactorClient, ReactorClientBuilder, type ReactorClientModule, ReactorEventTypes, type ReactorFeatures, type JobFailedEvent$1 as ReactorJobFailedEvent, type ReactorModule, ReactorSubscriptionManager, ReadModelCoordinator, type RebuildResult, RelationalDbProcessor, RelationshipChangeType, type Remote, type RemoteCursor, type RemoteFilter, type RemoteOptions, type RemoteRecord, type RemoteStatus, RevisionMismatchError, type SearchFilter, type ShutdownStatus, type SignatureVerificationHandler, type SignerConfig, SimpleJobExecutorManager, type SnapshotValidationIssue, type Database$1 as StorageDatabase, type SubscriptionErrorContext, SyncBuilder, type SyncEnvelope, type SyncEnvelopeType, SyncEventTypes, type SyncFailedEvent, type SyncModule, SyncOperation, SyncOperationAggregateError, type SyncOperationErrorType, SyncOperationStatus, type SyncPendingEvent, SyncStatus, type SyncStatusChangeCallback, SyncStatusTracker, type SyncSucceededEvent, type TrackedProcessor, type Unsubscribe, type ValidationResult, type ViewFilter, type WriteCacheConfig, addRelationshipAction, batchOperationsByDocument, consolidateSyncOperations, createDocumentAction, createMutableShutdownStatus, createRelationalDb, deleteDocumentAction, documentActions, driveCollectionId, driveIdFromUrl, envelopesToSyncOperations, getMigrationStatus, makeConsistencyKey, parseDriveUrl, removeRelationshipAction, runMigrations, trimMailboxFromAckOrdinal, upgradeDocumentAction };
4544
+ //# sourceMappingURL=index.d.ts.map