@agentshouse/mdruntime 0.1.0-c8f3163f32f93 → 0.1.0-c90a12b59fe09

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 (382) hide show
  1. package/README.md +19 -16
  2. package/dist/acceptance.d.ts +3 -0
  3. package/dist/acceptance.d.ts.map +1 -0
  4. package/dist/acceptance.js +318 -0
  5. package/dist/act-lanes.d.ts +29 -0
  6. package/dist/act-lanes.d.ts.map +1 -0
  7. package/dist/act-lanes.js +177 -0
  8. package/dist/actions.d.ts +25 -0
  9. package/dist/actions.d.ts.map +1 -0
  10. package/dist/actions.js +261 -0
  11. package/dist/adapter.d.ts +175 -115
  12. package/dist/adapter.d.ts.map +1 -1
  13. package/dist/attached-model.d.ts +7 -10
  14. package/dist/attached-model.d.ts.map +1 -1
  15. package/dist/attached-model.js +40 -41
  16. package/dist/binary.d.ts +0 -5
  17. package/dist/binary.d.ts.map +1 -1
  18. package/dist/binary.js +1 -1
  19. package/dist/bootstrap.d.ts +31 -11
  20. package/dist/bootstrap.d.ts.map +1 -1
  21. package/dist/bootstrap.js +309 -109
  22. package/dist/cell.d.ts +6 -0
  23. package/dist/cell.d.ts.map +1 -0
  24. package/dist/cell.js +9 -0
  25. package/dist/chain.d.ts +12 -0
  26. package/dist/chain.d.ts.map +1 -0
  27. package/dist/chain.js +64 -0
  28. package/dist/change-set.d.ts +13 -14
  29. package/dist/change-set.d.ts.map +1 -1
  30. package/dist/change-set.js +17 -63
  31. package/dist/change.d.ts +32 -1
  32. package/dist/change.d.ts.map +1 -1
  33. package/dist/change.js +14 -3
  34. package/dist/chat-types.d.ts +5 -0
  35. package/dist/chat-types.d.ts.map +1 -0
  36. package/dist/chat-types.js +13 -0
  37. package/dist/client.d.ts +45 -23
  38. package/dist/client.d.ts.map +1 -1
  39. package/dist/client.js +129 -25
  40. package/dist/collection.d.ts +31 -9
  41. package/dist/collection.d.ts.map +1 -1
  42. package/dist/collection.js +49 -80
  43. package/dist/compile.d.ts +18 -0
  44. package/dist/compile.d.ts.map +1 -0
  45. package/dist/compile.js +724 -0
  46. package/dist/connection.d.ts +8 -117
  47. package/dist/connection.d.ts.map +1 -1
  48. package/dist/connection.js +113 -2596
  49. package/dist/context.d.ts +2 -0
  50. package/dist/context.d.ts.map +1 -0
  51. package/dist/{chat/context.js → context.js} +1 -4
  52. package/dist/conversation-live.d.ts +138 -0
  53. package/dist/conversation-live.d.ts.map +1 -0
  54. package/dist/conversation-live.js +249 -0
  55. package/dist/conversation-row.d.ts +33 -0
  56. package/dist/conversation-row.d.ts.map +1 -0
  57. package/dist/conversation-row.js +53 -0
  58. package/dist/conversation.d.ts +73 -45
  59. package/dist/conversation.d.ts.map +1 -1
  60. package/dist/conversation.js +1040 -651
  61. package/dist/declaration.d.ts +10 -0
  62. package/dist/declaration.d.ts.map +1 -0
  63. package/dist/declaration.js +24 -0
  64. package/dist/digest.d.ts +7 -0
  65. package/dist/digest.d.ts.map +1 -0
  66. package/dist/digest.js +113 -0
  67. package/dist/discovery.d.ts +10 -0
  68. package/dist/discovery.d.ts.map +1 -0
  69. package/dist/discovery.js +153 -0
  70. package/dist/durability.d.ts +22 -1
  71. package/dist/durability.d.ts.map +1 -1
  72. package/dist/durability.js +5 -0
  73. package/dist/entry.d.ts +7 -4
  74. package/dist/entry.d.ts.map +1 -1
  75. package/dist/entry.js +33 -28
  76. package/dist/expectation.d.ts +26 -13
  77. package/dist/expectation.d.ts.map +1 -1
  78. package/dist/expectation.js +72 -19
  79. package/dist/failure.d.ts +3 -0
  80. package/dist/failure.d.ts.map +1 -1
  81. package/dist/failure.js +6 -0
  82. package/dist/figures.d.ts +49 -0
  83. package/dist/figures.d.ts.map +1 -0
  84. package/dist/figures.js +197 -0
  85. package/dist/file.d.ts +2 -19
  86. package/dist/file.d.ts.map +1 -1
  87. package/dist/file.js +7 -122
  88. package/dist/holdings.d.ts +29 -0
  89. package/dist/holdings.d.ts.map +1 -0
  90. package/dist/holdings.js +95 -0
  91. package/dist/host.d.ts +27 -4
  92. package/dist/host.d.ts.map +1 -1
  93. package/dist/host.js +162 -25
  94. package/dist/index.d.ts +40 -13
  95. package/dist/index.d.ts.map +1 -1
  96. package/dist/index.js +18 -2
  97. package/dist/install.d.ts +54 -0
  98. package/dist/install.d.ts.map +1 -0
  99. package/dist/install.js +539 -0
  100. package/dist/lifecycle.d.ts +7 -0
  101. package/dist/lifecycle.d.ts.map +1 -0
  102. package/dist/lifecycle.js +279 -0
  103. package/dist/listing.d.ts +48 -0
  104. package/dist/listing.d.ts.map +1 -0
  105. package/dist/listing.js +139 -0
  106. package/dist/live.d.ts +23 -0
  107. package/dist/live.d.ts.map +1 -0
  108. package/dist/live.js +165 -0
  109. package/dist/locks.d.ts +7 -0
  110. package/dist/locks.d.ts.map +1 -0
  111. package/dist/locks.js +33 -0
  112. package/dist/log.d.ts +1 -0
  113. package/dist/log.d.ts.map +1 -1
  114. package/dist/lost.d.ts +5 -0
  115. package/dist/lost.d.ts.map +1 -0
  116. package/dist/lost.js +50 -0
  117. package/dist/media.d.ts +8 -0
  118. package/dist/media.d.ts.map +1 -0
  119. package/dist/media.js +218 -0
  120. package/dist/memory.d.ts +22 -7
  121. package/dist/memory.d.ts.map +1 -1
  122. package/dist/memory.js +282 -110
  123. package/dist/messages.d.ts +49 -0
  124. package/dist/messages.d.ts.map +1 -0
  125. package/dist/messages.js +150 -0
  126. package/dist/model.d.ts +11 -12
  127. package/dist/model.d.ts.map +1 -1
  128. package/dist/model.js +7 -15
  129. package/dist/models.d.ts +10 -0
  130. package/dist/models.d.ts.map +1 -0
  131. package/dist/models.js +156 -0
  132. package/dist/name.d.ts +4 -0
  133. package/dist/name.d.ts.map +1 -0
  134. package/dist/name.js +122 -0
  135. package/dist/observation.d.ts +22 -4
  136. package/dist/observation.d.ts.map +1 -1
  137. package/dist/observation.js +127 -26
  138. package/dist/opened.d.ts +22 -0
  139. package/dist/opened.d.ts.map +1 -0
  140. package/dist/opened.js +107 -0
  141. package/dist/opening.d.ts +4 -0
  142. package/dist/opening.d.ts.map +1 -0
  143. package/dist/opening.js +59 -0
  144. package/dist/outcome.d.ts +52 -8
  145. package/dist/outcome.d.ts.map +1 -1
  146. package/dist/outcome.js +57 -0
  147. package/dist/overlay.d.ts +8 -4
  148. package/dist/overlay.d.ts.map +1 -1
  149. package/dist/overlay.js +135 -199
  150. package/dist/page-metadata.d.ts +8 -0
  151. package/dist/page-metadata.d.ts.map +1 -0
  152. package/dist/page-metadata.js +19 -0
  153. package/dist/parts.d.ts +3 -0
  154. package/dist/parts.d.ts.map +1 -0
  155. package/dist/parts.js +10 -0
  156. package/dist/paths.d.ts +2 -0
  157. package/dist/paths.d.ts.map +1 -1
  158. package/dist/paths.js +26 -0
  159. package/dist/preparation.d.ts +20 -0
  160. package/dist/preparation.d.ts.map +1 -0
  161. package/dist/preparation.js +233 -0
  162. package/dist/presence.d.ts +52 -0
  163. package/dist/presence.d.ts.map +1 -0
  164. package/dist/presence.js +220 -0
  165. package/dist/queries.d.ts +16 -0
  166. package/dist/queries.d.ts.map +1 -0
  167. package/dist/queries.js +285 -0
  168. package/dist/query.d.ts +49 -183
  169. package/dist/query.d.ts.map +1 -1
  170. package/dist/query.js +3 -464
  171. package/dist/{chat/questions.d.ts → questions.d.ts} +5 -7
  172. package/dist/questions.d.ts.map +1 -0
  173. package/dist/{chat/questions.js → questions.js} +11 -7
  174. package/dist/queue.d.ts +40 -0
  175. package/dist/queue.d.ts.map +1 -0
  176. package/dist/queue.js +465 -0
  177. package/dist/reach.d.ts +21 -7
  178. package/dist/reach.d.ts.map +1 -1
  179. package/dist/reach.js +316 -96
  180. package/dist/react.d.ts +21 -6
  181. package/dist/react.d.ts.map +1 -1
  182. package/dist/react.js +40 -18
  183. package/dist/{chat/read.d.ts → read.d.ts} +2 -0
  184. package/dist/read.d.ts.map +1 -0
  185. package/dist/{chat/read.js → read.js} +4 -0
  186. package/dist/readiness.d.ts +49 -0
  187. package/dist/readiness.d.ts.map +1 -0
  188. package/dist/readiness.js +27 -0
  189. package/dist/reads.d.ts +39 -0
  190. package/dist/reads.d.ts.map +1 -0
  191. package/dist/reads.js +178 -0
  192. package/dist/recovery.d.ts +28 -0
  193. package/dist/recovery.d.ts.map +1 -0
  194. package/dist/recovery.js +254 -0
  195. package/dist/refresh.d.ts +17 -14
  196. package/dist/refresh.d.ts.map +1 -1
  197. package/dist/refresh.js +145 -53
  198. package/dist/refusal.d.ts +5 -0
  199. package/dist/refusal.d.ts.map +1 -0
  200. package/dist/refusal.js +57 -0
  201. package/dist/replica.d.ts +50 -33
  202. package/dist/replica.d.ts.map +1 -1
  203. package/dist/replica.js +339 -162
  204. package/dist/retried.d.ts +30 -0
  205. package/dist/retried.d.ts.map +1 -0
  206. package/dist/retried.js +72 -0
  207. package/dist/room-draft.d.ts +39 -10
  208. package/dist/room-draft.d.ts.map +1 -1
  209. package/dist/room-draft.js +194 -118
  210. package/dist/room-drafts.d.ts +24 -0
  211. package/dist/room-drafts.d.ts.map +1 -0
  212. package/dist/room-drafts.js +217 -0
  213. package/dist/rows.d.ts +30 -37
  214. package/dist/rows.d.ts.map +1 -1
  215. package/dist/rows.js +60 -128
  216. package/dist/runtime.d.ts +36 -0
  217. package/dist/runtime.d.ts.map +1 -0
  218. package/dist/runtime.js +1 -0
  219. package/dist/save.d.ts +43 -43
  220. package/dist/save.d.ts.map +1 -1
  221. package/dist/save.js +799 -259
  222. package/dist/saves.d.ts +32 -0
  223. package/dist/saves.d.ts.map +1 -0
  224. package/dist/saves.js +413 -0
  225. package/dist/search.d.ts +15 -55
  226. package/dist/search.d.ts.map +1 -1
  227. package/dist/search.js +10 -121
  228. package/dist/seed.d.ts +25 -0
  229. package/dist/seed.d.ts.map +1 -0
  230. package/dist/seed.js +145 -0
  231. package/dist/shared.d.ts +10 -0
  232. package/dist/shared.d.ts.map +1 -0
  233. package/dist/shared.js +339 -0
  234. package/dist/shown.d.ts +32 -0
  235. package/dist/shown.d.ts.map +1 -0
  236. package/dist/shown.js +290 -0
  237. package/dist/socket/admission.d.ts +7 -0
  238. package/dist/socket/admission.d.ts.map +1 -0
  239. package/dist/socket/admission.js +39 -0
  240. package/dist/socket/answers.d.ts +6 -0
  241. package/dist/socket/answers.d.ts.map +1 -0
  242. package/dist/socket/answers.js +20 -0
  243. package/dist/socket/lanes.d.ts +21 -0
  244. package/dist/socket/lanes.d.ts.map +1 -0
  245. package/dist/socket/lanes.js +80 -0
  246. package/dist/socket/reads.d.ts +10 -0
  247. package/dist/socket/reads.d.ts.map +1 -0
  248. package/dist/socket/reads.js +31 -0
  249. package/dist/socket/session.d.ts +38 -0
  250. package/dist/socket/session.d.ts.map +1 -0
  251. package/dist/socket/session.js +23 -0
  252. package/dist/socket.d.ts +68 -0
  253. package/dist/socket.d.ts.map +1 -0
  254. package/dist/socket.js +171 -0
  255. package/dist/source.d.ts +54 -0
  256. package/dist/source.d.ts.map +1 -0
  257. package/dist/source.js +82 -0
  258. package/dist/status.d.ts +5 -2
  259. package/dist/status.d.ts.map +1 -1
  260. package/dist/status.js +3 -7
  261. package/dist/store/installs.d.ts +30 -0
  262. package/dist/store/installs.d.ts.map +1 -0
  263. package/dist/store/installs.js +34 -0
  264. package/dist/store/readiness.d.ts +10 -0
  265. package/dist/store/readiness.d.ts.map +1 -0
  266. package/dist/store/readiness.js +52 -0
  267. package/dist/store/records.d.ts +212 -0
  268. package/dist/store/records.d.ts.map +1 -0
  269. package/dist/store/records.js +430 -0
  270. package/dist/store/room-held.d.ts +8 -0
  271. package/dist/store/room-held.d.ts.map +1 -0
  272. package/dist/store/room-held.js +17 -0
  273. package/dist/store/space.d.ts +11 -0
  274. package/dist/store/space.d.ts.map +1 -0
  275. package/dist/store/space.js +41 -0
  276. package/dist/store/watchers.d.ts +17 -0
  277. package/dist/store/watchers.d.ts.map +1 -0
  278. package/dist/store/watchers.js +56 -0
  279. package/dist/store/writes.d.ts +24 -0
  280. package/dist/store/writes.d.ts.map +1 -0
  281. package/dist/store/writes.js +125 -0
  282. package/dist/store.d.ts +111 -134
  283. package/dist/store.d.ts.map +1 -1
  284. package/dist/store.js +158 -611
  285. package/dist/stored.d.ts +156 -0
  286. package/dist/stored.d.ts.map +1 -0
  287. package/dist/stored.js +649 -0
  288. package/dist/surface.d.ts +88 -0
  289. package/dist/surface.d.ts.map +1 -0
  290. package/dist/surface.js +223 -0
  291. package/dist/sync.d.ts +19 -0
  292. package/dist/sync.d.ts.map +1 -0
  293. package/dist/sync.js +540 -0
  294. package/dist/tables.d.ts +412 -0
  295. package/dist/tables.d.ts.map +1 -0
  296. package/dist/tables.js +737 -0
  297. package/dist/tallies.d.ts +18 -0
  298. package/dist/tallies.d.ts.map +1 -0
  299. package/dist/tallies.js +129 -0
  300. package/dist/transfer.d.ts +0 -5
  301. package/dist/transfer.d.ts.map +1 -1
  302. package/dist/turn.d.ts +9 -0
  303. package/dist/turn.d.ts.map +1 -0
  304. package/dist/turn.js +75 -0
  305. package/dist/validation.d.ts +29 -0
  306. package/dist/validation.d.ts.map +1 -0
  307. package/dist/validation.js +104 -0
  308. package/dist/windows.d.ts +11 -0
  309. package/dist/windows.d.ts.map +1 -0
  310. package/dist/windows.js +16 -0
  311. package/dist/wire.d.ts +220 -36
  312. package/dist/wire.d.ts.map +1 -1
  313. package/dist/wire.js +73 -33
  314. package/package.json +19 -19
  315. package/AGENTS.md +0 -299
  316. package/dist/attempt.d.ts +0 -16
  317. package/dist/attempt.d.ts.map +0 -1
  318. package/dist/attempt.js +0 -70
  319. package/dist/chat/acts.d.ts +0 -33
  320. package/dist/chat/acts.d.ts.map +0 -1
  321. package/dist/chat/acts.js +0 -36
  322. package/dist/chat/context.d.ts +0 -3
  323. package/dist/chat/context.d.ts.map +0 -1
  324. package/dist/chat/input.d.ts +0 -9
  325. package/dist/chat/input.d.ts.map +0 -1
  326. package/dist/chat/input.js +0 -99
  327. package/dist/chat/kit.d.ts +0 -60
  328. package/dist/chat/kit.d.ts.map +0 -1
  329. package/dist/chat/kit.js +0 -123
  330. package/dist/chat/lasting.d.ts +0 -6
  331. package/dist/chat/lasting.d.ts.map +0 -1
  332. package/dist/chat/lasting.js +0 -19
  333. package/dist/chat/list.d.ts +0 -26
  334. package/dist/chat/list.d.ts.map +0 -1
  335. package/dist/chat/list.js +0 -62
  336. package/dist/chat/markdown.d.ts +0 -20
  337. package/dist/chat/markdown.d.ts.map +0 -1
  338. package/dist/chat/markdown.js +0 -188
  339. package/dist/chat/message.d.ts +0 -6
  340. package/dist/chat/message.d.ts.map +0 -1
  341. package/dist/chat/message.js +0 -192
  342. package/dist/chat/messages.d.ts +0 -21
  343. package/dist/chat/messages.d.ts.map +0 -1
  344. package/dist/chat/messages.js +0 -151
  345. package/dist/chat/name.d.ts +0 -6
  346. package/dist/chat/name.d.ts.map +0 -1
  347. package/dist/chat/name.js +0 -37
  348. package/dist/chat/opened.d.ts +0 -11
  349. package/dist/chat/opened.d.ts.map +0 -1
  350. package/dist/chat/opened.js +0 -17
  351. package/dist/chat/overlay.d.ts +0 -31
  352. package/dist/chat/overlay.d.ts.map +0 -1
  353. package/dist/chat/overlay.js +0 -97
  354. package/dist/chat/parts.d.ts +0 -57
  355. package/dist/chat/parts.d.ts.map +0 -1
  356. package/dist/chat/parts.js +0 -119
  357. package/dist/chat/process.d.ts +0 -20
  358. package/dist/chat/process.d.ts.map +0 -1
  359. package/dist/chat/process.js +0 -32
  360. package/dist/chat/provider.d.ts +0 -63
  361. package/dist/chat/provider.d.ts.map +0 -1
  362. package/dist/chat/provider.js +0 -620
  363. package/dist/chat/question.d.ts +0 -9
  364. package/dist/chat/question.d.ts.map +0 -1
  365. package/dist/chat/question.js +0 -80
  366. package/dist/chat/questions.d.ts.map +0 -1
  367. package/dist/chat/read.d.ts.map +0 -1
  368. package/dist/chat/ready.d.ts +0 -33
  369. package/dist/chat/ready.d.ts.map +0 -1
  370. package/dist/chat/ready.js +0 -91
  371. package/dist/chat/style.d.ts +0 -4
  372. package/dist/chat/style.d.ts.map +0 -1
  373. package/dist/chat/style.js +0 -302
  374. package/dist/chat.d.ts +0 -14
  375. package/dist/chat.d.ts.map +0 -1
  376. package/dist/chat.js +0 -8
  377. package/dist/fence.d.ts +0 -6
  378. package/dist/fence.d.ts.map +0 -1
  379. package/dist/fence.js +0 -10
  380. package/dist/read-side.d.ts +0 -18
  381. package/dist/read-side.d.ts.map +0 -1
  382. package/dist/read-side.js +0 -440
@@ -1,2609 +1,126 @@
1
- import { attachedModel } from './attached-model.js';
2
- import { cached, modelTypes, NO_MODEL, sameModel, } from './model.js';
3
- import { observing } from './observation.js';
4
- import { filterOf, identityOf, planOf, } from './query.js';
5
- import { createReadSide } from './read-side.js';
6
- import { markdownPath, roomOfKey } from './rows.js';
7
- import { createSearchIndex, searchPlanOf, } from './search.js';
8
- import { bootstrapRoom } from './bootstrap.js';
9
- import { changeSet, mergeChangeSets } from './change-set.js';
10
- import { createConversationStore, } from './conversation.js';
11
- import { queuedFile } from './change.js';
12
- import { validRoot } from './collection.js';
13
- import { runtimeError } from './failure.js';
1
+ import { submitLater } from './acceptance.js';
2
+ import { invokeAction, called, readConversationHistory, resendLater } from './actions.js';
3
+ import { builtInModel, roomTypesOf } from './attached-model.js';
4
+ import { createLiveConversations } from './conversation-live.js';
5
+ import { writeRule } from './declaration.js';
6
+ import { refusedForSpace } from './durability.js';
7
+ import { uncaught } from './failure.js';
8
+ import { createFigures } from './figures.js';
9
+ import { scheduleCurrency, spaceFreed, start } from './lifecycle.js';
10
+ import { createLiveQueries } from './live.js';
14
11
  import { createLog } from './log.js';
15
- import { binaryRecord } from './binary.js';
16
- import { absentBinary, binaryAnswer, calledResult, failure, historyAnswer, undeclared, UNCERTAIN, } from './outcome.js';
17
- import { refreshRoom } from './refresh.js';
18
- import { buildBatch, joined, limitedIn, requeued } from './save.js';
19
- import { applyReturned, compositionOf, confirmedOf, landed, readReclassified, replicaOf, sameMembership, withdrawals, } from './replica.js';
20
- import { binaryBase, changedParts, changesOf, held, heldFile, joinedDraft, readParts, returnedBy, returnedInto, staleWrite, underneath, withdrawnDrafts, } from './room-draft.js';
21
- import { same, saving, STARTING, transferring, } from './status.js';
22
- import { detectStorageLoss, nextGeneration } from './durability.js';
23
- import { FencedMap } from './fence.js';
24
- import { roomDraftRevision } from './identity.js';
25
- import { beneath, normalize } from './paths.js';
26
- import { openRuntimeStore, } from './store.js';
27
- import { unconfirmed } from './transfer.js';
28
- import { governs, holds, narrowed, planReach, } from './reach.js';
29
- function within(root, path) {
30
- return root === '' || beneath(root, path);
31
- }
32
- function declaredSelection(room) {
33
- const selection = room.typedSelection;
34
- if (selection === undefined)
35
- return true;
36
- if (!Array.isArray(selection.roots) || selection.roots.length === 0)
37
- return false;
38
- return selection.roots.every((root, index) => validRoot(root) &&
39
- root !== '' &&
40
- selection.roots.every((other, at) => at === index || !within(other, root)));
41
- }
42
- const OPENING_LANE = 'opening';
43
- const CONVERSATION_LANE = 'conversations';
44
- const ROOM_READS = 256;
45
- function roomLane(locator) {
46
- return `room ${locator}`;
47
- }
12
+ import { open } from './opening.js';
13
+ import { deliverOwedReadiness, filled, prepare } from './preparation.js';
14
+ import { createPresence } from './presence.js';
15
+ import { answeredPlan, figuresCover, roomTallies } from './queries.js';
16
+ import { readAnswers } from './reads.js';
17
+ import { createRecovery } from './recovery.js';
18
+ import { createRetries } from './retried.js';
19
+ import { publishChangeSet, show } from './shown.js';
20
+ import { createSocket } from './socket.js';
21
+ import { createStore } from './store.js';
22
+ import { composedRuntime } from './surface.js';
23
+ const ROOM_ATTEMPTS = 16;
48
24
  export function composeRuntime(options) {
49
- const localSaves = options.adapter.localSaves === true;
50
- let authorization = options.authorization;
51
- let opening;
52
- let store;
53
- const fences = new Map();
54
- const isFenced = (locator) => fences.has(locator);
55
- let fencings = 0;
56
- const lastFenced = new Map();
57
- const fencedSince = (locator, since) => fences.has(locator) || (lastFenced.get(locator) ?? 0) > since;
58
- let discoveries = 0;
59
- const replicas = new FencedMap(isFenced);
60
- const queuesWithoutReplica = new FencedMap(isFenced);
61
- const pendings = new Map();
62
- const roomDrafts = new FencedMap(isFenced);
63
- const presentations = new Map();
64
- let limits = [];
65
- let capabilities = [];
66
- const rooms = new FencedMap(isFenced);
67
- const counted = new Map();
68
- const unreadable = new Set();
69
- const isModelFenced = (key) => isFenced(key.slice(key.indexOf(' ') + 1));
70
- const models = new FencedMap(isModelFenced);
71
- const liveModels = new FencedMap(isModelFenced);
72
- const invalidModels = new Set();
73
- const discovered = new Map();
74
- let roomsListed = false;
75
- const scopedRefusals = new Map();
76
- const sourceRefusals = new Map();
77
- const declarationRefusals = new Set();
78
- function modelKey(locator, attached) {
79
- return `${attached} ${locator}`;
80
- }
81
- function modelOf(locator, attached = 'collection') {
82
- return models.get(modelKey(locator, attached)) ?? NO_MODEL;
83
- }
84
- function savedModel(locator, attached) {
85
- return invalidModels.has(modelKey(locator, attached))
86
- ? { status: 'unavailable', reason: 'revoked' }
87
- : modelOf(locator, attached);
88
- }
89
- function compositionFor(record) {
90
- return compositionOf({
91
- ...record,
92
- model: savedModel(record.locator, 'collection'),
93
- selectionModel: savedModel(record.locator, 'typed-selection'),
94
- });
95
- }
96
- let refusal = null;
97
- let storageLoss = null;
98
- let status = STARTING;
99
- let shown = STARTING;
100
- let discoveryPaused = false;
101
- let resetTimer;
102
- let closed = false;
103
- let stopping = false;
104
- let withdrawStream;
105
- const announced = new Map();
106
- let underway = null;
107
- let streamed = null;
108
- let handed = false;
109
- const submitting = new Map();
110
- const answering = new Map();
111
- let complete = false;
112
- let recorded = false;
113
- const stale = new Set();
114
- let generation = 0;
115
- let discovering = null;
116
- let opened = null;
117
- const owed = new Set();
118
- const lanes = new Map();
119
- let roomReads = { generation, free: ROOM_READS, waiting: [] };
120
- const working = new Set();
121
- let mutations = Promise.resolve();
122
- const roomListeners = new Set();
123
- const refusalListeners = new Set();
124
- const storageLossListeners = new Set();
125
- const statusListeners = new Set();
126
- const queueSubscriptions = new Set();
127
- const roomDraftListeners = new Set();
128
- const presentationListeners = new Set();
129
- const readSide = createReadSide();
130
- let withdrawConversations;
131
- let currencyQueued = null;
132
- let socketOpen = false;
133
- let serviceMode = 'open';
134
- let haltedRefusal = false;
135
- let openSignals = 0;
136
- const serviceModeListeners = new Set();
137
- let member = null;
138
- const memberListeners = new Set();
139
- const materialized = new Set();
140
- let everyRoom = false;
141
- const transfers = new FencedMap(isFenced);
142
- const conversations = createConversationStore({
143
- agents: declaredAgents,
144
- documents: (locator) => rowsQuery(planOf({ rooms: [locator], select: 'all' }, roomFacts())),
145
- call: (name, input) => invokeAction(name, input),
146
- durably,
147
- stream: () => options.adapter.conversations,
148
- publish: publishChangeSet,
149
- online: () => !status.providerUnreachable && refusal === null,
150
- closed: () => closed,
151
- });
152
- const searchIndex = createSearchIndex({
153
- documents: () => readSide.documents(),
154
- document: (room, path) => readSide.document(room, path),
155
- messages: () => conversations.messages(),
156
- message: (conversation, identity) => conversations.message(conversation, identity),
157
- });
25
+ const { adapter, shell } = options;
26
+ const roomTypes = roomTypesOf(adapter.roomTypes, adapter.nameableRoomTypes);
27
+ const builtIn = builtInModel(roomTypes);
28
+ const typedPaths = adapter.typedPaths ?? [];
158
29
  const journal = createLog();
159
- let notifyReady = () => { };
160
- const ready = new Promise((resolve) => {
161
- notifyReady = resolve;
162
- });
163
- function rememberRoomDraft(record) {
164
- const room = roomDrafts.get(record.locator) ?? new Map();
165
- room.set(record.path, record);
166
- roomDrafts.set(record.locator, room);
167
- }
168
- function forgetRoomDraft(locator, path) {
169
- const room = roomDrafts.get(locator);
170
- if (room === undefined)
171
- return;
172
- room.delete(path);
173
- if (room.size === 0)
174
- roomDrafts.delete(locator);
175
- }
176
- function roomDraftOf(record) {
177
- return structuredClone({
178
- room: record.locator,
179
- path: record.path,
180
- revision: record.revision,
181
- parts: record.parts,
182
- changedUnderneath: underneath(record.parts, record.path, replicas.get(record.locator)?.visible),
183
- returned: record.returned,
184
- });
185
- }
186
- function snapshotRoomDrafts() {
187
- const records = [...roomDrafts.values()].flatMap((room) => [...room.values()]);
188
- records.sort((left, right) => {
189
- if (left.locator !== right.locator)
190
- return left.locator < right.locator ? -1 : 1;
191
- if (left.path !== right.path)
192
- return left.path < right.path ? -1 : 1;
193
- return 0;
194
- });
195
- return records.map(roomDraftOf);
196
- }
197
- function publishRoomDrafts(waitingOnly) {
198
- if (closed)
199
- return;
200
- const value = snapshotRoomDrafts();
201
- for (const listener of roomDraftListeners) {
202
- if (waitingOnly && listener.ready)
203
- continue;
204
- listener.ready = true;
205
- listener.notify(value);
206
- }
207
- }
208
- function presentationOf(app) {
209
- const value = presentations.get(app);
210
- return value === undefined ? null : structuredClone(value);
211
- }
212
- function emitPresentation(app) {
213
- if (closed)
214
- return;
215
- for (const listener of presentationListeners) {
216
- if (listener.app === app && listener.ready)
217
- listener.notify(presentationOf(app));
218
- }
219
- }
220
- function pending() {
221
- return (!localSaves &&
222
- (queuesWithoutReplica.size > 0 ||
223
- [...replicas.values()].some((replica) => replica.queue.length > 0)));
224
- }
225
- function attention() {
226
- const attentionRequired = [];
227
- for (const record of [...roomDrafts.values()].flatMap((room) => [...room.values()])) {
228
- if (record.returned === null)
229
- continue;
230
- attentionRequired.push({
231
- room: record.locator,
232
- path: record.path,
233
- returned: structuredClone(record.returned),
234
- });
235
- }
236
- attentionRequired.sort((left, right) => {
237
- if (left.room !== right.room)
238
- return left.room < right.room ? -1 : 1;
239
- if (left.path !== right.path)
240
- return left.path < right.path ? -1 : 1;
241
- return 0;
242
- });
243
- let reset = null;
244
- for (const { submission } of pendings.values()) {
245
- if (submission.state !== 'reset')
246
- continue;
247
- if (reset === null || submission.reset < reset)
248
- reset = submission.reset;
249
- }
250
- return { attentionRequired, reset };
251
- }
252
- function documentsIn(locator) {
253
- const replica = replicas.get(locator);
254
- if (replica === undefined)
255
- return 0;
256
- const roots = replica.confirmed.record.typedSelection?.roots ?? [];
257
- const paths = [
258
- ...Object.keys(replica.visible.documents).filter(markdownPath),
259
- ...Object.keys(replica.visible.binaries),
260
- ];
261
- return paths.filter((path) => !roots.some((root) => beneath(root, path))).length;
262
- }
263
- function listed() {
264
- return structuredClone([...rooms.values()].map((room) => {
265
- const documents = documentsIn(room.locator);
266
- counted.set(room.locator, documents);
267
- return { ...room, documents };
268
- }));
269
- }
270
- function roomFacts(reach = null) {
271
- const held = [...rooms.values()]
272
- .filter((room) => holds(reach, room.locator))
273
- .map((room) => {
274
- const governed = governs(reach, room);
275
- const attached = [
276
- ...(governed.collection ? [modelOf(room.locator)] : []),
277
- ...(governed.selection ? [modelOf(room.locator, 'typed-selection')] : []),
278
- ];
279
- return {
280
- locator: room.locator,
281
- available: attached.every((model) => model.status !== 'unavailable'),
282
- types: attached.flatMap((model) => model.status === 'unavailable' ? [] : Object.values(model.types)),
283
- };
284
- });
285
- return { listed: roomsListed, rooms: held };
286
- }
287
- function emitRooms() {
288
- const value = listed();
289
- for (const listener of roomListeners)
290
- listener(value);
291
- }
292
- function emitRefusal() {
293
- for (const listener of refusalListeners)
294
- listener(refusal);
295
- }
296
- function emitStorageLoss() {
297
- for (const listener of storageLossListeners)
298
- listener(storageLoss);
299
- }
300
- function emitMember() {
301
- for (const listener of memberListeners)
302
- listener(member);
303
- }
304
- function moveTo(next) {
305
- if (closed)
306
- return;
307
- status = next;
308
- show();
309
- }
310
- function show() {
311
- if (closed)
312
- return;
313
- const next = status.state === 'synced' && !conversations.current()
314
- ? { ...status, state: 'syncing' }
315
- : status;
316
- if (same(shown, next))
317
- return;
318
- shown = next;
319
- for (const listener of statusListeners)
320
- listener(shown);
321
- }
322
- function entryOf(batch) {
323
- if (localSaves)
324
- return Object.freeze({ batch, state: 'local' });
325
- const state = pendings.get(batch.id);
326
- if (state?.accepted !== undefined) {
327
- return Object.freeze({ batch, state: 'accepted', roomVersion: state.accepted });
328
- }
329
- return Object.freeze({ batch, ...(state?.submission ?? { state: 'waiting' }) });
330
- }
331
- function entriesOf(locator) {
332
- return (replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? []).map(entryOf);
333
- }
334
- function emitQueue(locator) {
335
- const entries = entriesOf(locator);
336
- for (const subscription of queueSubscriptions) {
337
- if (subscription.locator === locator)
338
- subscription.notify(entries);
339
- }
340
- }
341
- function applyChangeSet(set) {
342
- const held = everyRoom
343
- ? set
344
- : { ...set, documents: set.documents.filter(({ locator }) => materialized.has(locator)) };
345
- readSide.apply(held);
346
- searchIndex.changed(held);
347
- }
348
- function materialize(locators) {
349
- if (everyRoom)
350
- return;
351
- if (locators === null)
352
- everyRoom = true;
353
- const sets = [];
354
- for (const locator of locators ?? [...replicas.keys()]) {
355
- if (materialized.has(locator))
356
- continue;
357
- materialized.add(locator);
358
- const replica = replicas.get(locator);
359
- if (replica !== undefined)
360
- sets.push(changeSet(locator, null, replica));
361
- }
362
- if (sets.length === 0)
363
- return;
364
- const set = mergeChangeSets(sets);
365
- readSide.apply(set);
366
- searchIndex.changed(set);
367
- }
368
- function reachedRooms(plan) {
369
- if (plan.rooms !== null)
370
- return plan.rooms;
371
- if (plan.reach === null)
372
- return null;
373
- return [...plan.reach.rooms, ...plan.reach.documents.map(roomOfKey)];
374
- }
375
- function rowsQuery(plan) {
376
- materialize(reachedRooms(plan));
377
- return readSide.query(plan);
378
- }
379
- function publishChangeSet(set) {
380
- applyChangeSet(set);
381
- if (set.rooms.length > 0 ||
382
- [...new Set(set.documents.map(({ locator }) => locator))].some((locator) => rooms.has(locator) && counted.get(locator) !== documentsIn(locator)))
383
- emitRooms();
384
- for (const locator of set.queues)
385
- emitQueue(locator);
386
- if (set.drafts.length > 0 ||
387
- set.documents.some((change) => roomDrafts.get(change.locator)?.has(change.path) === true)) {
388
- publishRoomDrafts(false);
389
- }
390
- for (const app of set.presentations)
391
- emitPresentation(app);
392
- conversations.changed(set);
393
- }
394
- function stopTimer() {
395
- if (resetTimer === undefined)
396
- return;
397
- clearTimeout(resetTimer);
398
- resetTimer = undefined;
399
- }
400
- function armTimer() {
401
- stopTimer();
402
- if (closed || stopping)
403
- return;
404
- let earliest = null;
405
- for (const { submission } of pendings.values()) {
406
- if (submission.state !== 'reset')
407
- continue;
408
- const at = Date.parse(submission.reset);
409
- if (earliest === null || at < earliest)
410
- earliest = at;
411
- }
412
- if (earliest === null)
413
- return;
414
- // A Save House held back goes again only once the reset its answer named has passed.
415
- resetTimer = setTimeout(() => {
416
- resetTimer = undefined;
417
- submitAll();
418
- }, Math.max(0, earliest - Date.now()));
419
- }
420
- async function refuse(reason, provider = null) {
421
- stopTimer();
422
- discoveryPaused = true;
423
- try {
424
- if (reason === 'revoked-authorization') {
425
- await exclusive(async () => {
426
- const revoked = { status: 'unavailable', reason: 'revoked' };
427
- try {
428
- const local = await openLocal();
429
- await local.revokeModels([...replicas.values()].map((replica) => replica.confirmed.record));
430
- }
431
- catch {
432
- journal.record('model revocation persistence failed');
433
- }
434
- const keys = new Set(models.keys());
435
- for (const locator of rooms.keys()) {
436
- keys.add(modelKey(locator, 'collection'));
437
- keys.add(modelKey(locator, 'typed-selection'));
438
- }
439
- for (const key of keys) {
440
- invalidModels.add(key);
441
- models.set(key, revoked);
442
- liveModels.delete(key);
443
- }
444
- const changed = [];
445
- for (const [locator, room] of rooms) {
446
- const before = replicas.get(locator) ?? null;
447
- if (before !== null) {
448
- const record = {
449
- ...before.confirmed.record,
450
- model: revoked,
451
- selectionModel: revoked,
452
- };
453
- replicas.set(locator, replicaOf(confirmedOf(record, before.confirmed), before.queue, before));
454
- }
455
- rooms.set(locator, {
456
- ...room,
457
- model: modelTypes(revoked),
458
- typedSelection: room.typedSelection === null
459
- ? null
460
- : { ...room.typedSelection, model: modelTypes(revoked) },
461
- });
462
- changed.push(changeSet(locator, before, replicas.get(locator) ?? null, { room: true }));
463
- }
464
- publishChangeSet(mergeChangeSets(changed));
465
- });
466
- }
467
- }
468
- finally {
469
- refusal = {
470
- code: reason,
471
- retryable: false,
472
- reauthorizationOffered: reason === 'revoked-authorization',
473
- refusal: provider,
474
- };
475
- journal.record(`connection refused ${reason}`);
476
- emitRefusal();
477
- }
478
- }
479
- function list(room, synchronizationAvailable) {
480
- const selection = room.typedSelection ?? null;
481
- rooms.set(room.locator, {
482
- name: room.name,
483
- locator: room.locator,
484
- handle: room.handle,
485
- operations: room.operations,
486
- replica: room.replica,
487
- model: modelTypes(modelOf(room.locator)),
488
- typedSelection: selection === null
489
- ? null
490
- : {
491
- roots: selection.roots,
492
- model: modelTypes(modelOf(room.locator, 'typed-selection')),
493
- },
494
- providerOwnedPaths: room.providerOwnedPaths,
495
- roomVersion: replicas.get(room.locator)?.confirmed.record.roomVersion ?? null,
496
- synchronizationAvailable,
497
- refusal: scopedRefusals.get(room.locator) ?? sourceRefusals.get(room.locator) ?? null,
498
- });
499
- }
500
- async function applyDiscovery(found, started) {
501
- for (const room of found) {
502
- const fence = fences.get(room.locator);
503
- if (fence !== undefined && fence.erased && fence.at < started)
504
- fences.delete(room.locator);
505
- }
506
- const listed = found.filter((room) => !fences.has(room.locator));
507
- const listedLocators = new Set(listed.map((room) => room.locator));
508
- for (const locator of listedLocators)
509
- scopedRefusals.delete(locator);
510
- discovered.clear();
511
- for (const room of listed)
512
- discovered.set(room.locator, room);
513
- const unlisted = unlistedHeld(new Set(found.map((room) => room.locator)));
514
- if (options.adapter.exhaustiveDiscovery === true)
515
- await loseRooms(unlisted);
516
- else
517
- unlistedKept(unlisted);
518
- for (const room of listed) {
519
- const held = replicas.get(room.locator)?.confirmed.record;
520
- if (held !== undefined && held.replica.selection !== room.replica.selection) {
521
- list(held, false);
522
- continue;
523
- }
524
- list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));
525
- }
526
- roomsListed = true;
527
- emitRooms();
528
- return listed;
529
- }
530
- function unlistedHeld(listed) {
531
- return [
532
- ...new Set([
533
- ...rooms.keys(),
534
- ...roomDrafts.keys(),
535
- ...transfers.keys(),
536
- ...queuesWithoutReplica.keys(),
537
- ]),
538
- ].filter((locator) => !listed.has(locator));
539
- }
540
- function unlistedKept(unlisted) {
541
- for (const locator of unlisted) {
542
- const held = replicas.get(locator)?.confirmed.record;
543
- if (held !== undefined)
544
- list(held, false);
545
- else
546
- rooms.delete(locator);
547
- }
548
- }
549
- function fence(locators) {
550
- const fresh = [...new Set(locators)].filter((locator) => !fences.has(locator));
551
- const removed = fresh.map((locator) => changeSet(locator, replicas.get(locator) ?? null, null, {
552
- room: true,
553
- queue: true,
554
- drafts: [...(roomDrafts.get(locator)?.keys() ?? [])],
555
- }));
556
- for (const locator of fresh) {
557
- fences.set(locator, { at: discoveries, erased: false });
558
- lastFenced.set(locator, ++fencings);
559
- for (const batch of replicas.get(locator)?.queue ?? queuesWithoutReplica.get(locator) ?? [])
560
- pendings.delete(batch.id);
561
- replicas.delete(locator);
562
- queuesWithoutReplica.delete(locator);
563
- rooms.delete(locator);
564
- roomDrafts.delete(locator);
565
- transfers.delete(locator);
566
- discovered.delete(locator);
567
- announced.delete(locator);
568
- unreadable.delete(locator);
569
- stale.delete(locator);
570
- scopedRefusals.delete(locator);
571
- sourceRefusals.delete(locator);
572
- declarationRefusals.delete(locator);
573
- for (const attached of ['collection', 'typed-selection']) {
574
- const key = modelKey(locator, attached);
575
- models.delete(key);
576
- liveModels.delete(key);
577
- invalidModels.delete(key);
578
- }
579
- journal.record(`room lost ${locator}`);
580
- }
581
- if (fresh.length === 0)
582
- return fresh;
583
- publishChangeSet(mergeChangeSets(removed));
584
- for (const locator of fresh)
585
- materialized.delete(locator);
586
- moveTo({ ...status, ...attention() });
587
- return fresh;
588
- }
589
- async function erased(local, locators) {
590
- await local.erase(locators);
591
- for (const locator of locators) {
592
- const held = fences.get(locator);
593
- if (held !== undefined)
594
- held.erased = true;
595
- }
596
- }
597
- async function loseRooms(locators) {
598
- const fresh = fence(locators);
599
- if (fresh.length > 0)
600
- await durably((local) => erased(local, fresh));
601
- }
602
- function restored(key, persisted) {
603
- const prior = models.get(key);
604
- if (prior !== undefined &&
605
- prior.status !== 'unavailable' &&
606
- (persisted.status === 'unavailable' || !sameModel(prior.snapshot, persisted.snapshot))) {
607
- invalidModels.add(key);
608
- }
609
- const model = persisted.status === 'unavailable' ||
610
- liveModels.get(key) === JSON.stringify(persisted.snapshot)
611
- ? persisted
612
- : cached(persisted);
613
- models.set(key, model);
614
- if (model.status === 'unavailable') {
615
- liveModels.delete(key);
616
- invalidModels.delete(key);
617
- }
618
- return model;
619
- }
620
- async function hydrate(opened) {
621
- const [records, queues, kept, presented, held, chatDrafts, lastCompleted, declared, named, known, staged,] = await Promise.all([
622
- opened.all(),
623
- opened.queues(),
624
- opened.roomDrafts(),
625
- opened.presentation(),
626
- opened.conversations(),
627
- opened.chatDrafts(),
628
- opened.lastCompleted(),
629
- opened.providerLimits(),
630
- opened.capabilities(),
631
- opened.member(),
632
- opened.transfers(),
633
- ]);
634
- transfers.clear();
635
- for (const record of staged)
636
- transfers.set(record.locator, record);
637
- limits = declared;
638
- capabilities = named;
639
- member = known;
640
- roomDrafts.clear();
641
- for (const record of kept)
642
- rememberRoomDraft(record);
643
- presentations.clear();
644
- for (const record of presented)
645
- presentations.set(record.app, record.value);
646
- conversations.hydrate(held, chatDrafts);
647
- const queuedBatches = new Map(queues.map((queue) => [queue.locator, queue.pending.map(({ batch }) => batch)]));
648
- pendings.clear();
649
- for (const queue of queues) {
650
- for (const { batch, state } of queue.pending)
651
- pendings.set(batch.id, state);
652
- }
653
- const previousReplicas = new Map(replicas);
654
- replicas.clear();
655
- queuesWithoutReplica.clear();
656
- const replicated = new Set(records.map((record) => record.locator));
657
- for (const [locator, queue] of queuedBatches) {
658
- if (!replicated.has(locator))
659
- queuesWithoutReplica.set(locator, queue);
660
- }
661
- for (const record of records) {
662
- const model = restored(modelKey(record.locator, 'collection'), record.model);
663
- const selectionModel = restored(modelKey(record.locator, 'typed-selection'), record.selectionModel);
664
- const prior = previousReplicas.get(record.locator);
665
- const confirmed = confirmedOf({ ...record, model, selectionModel }, prior?.confirmed);
666
- replicas.set(record.locator, replicaOf(confirmed, queuedBatches.get(record.locator) ?? [], prior));
667
- const existing = rooms.get(record.locator);
668
- if (existing === undefined)
669
- list(record, false);
670
- else {
671
- rooms.set(record.locator, {
672
- ...existing,
673
- roomVersion: record.roomVersion,
674
- operations: record.operations,
675
- replica: record.replica,
676
- model: modelTypes(model),
677
- typedSelection: record.typedSelection === null
678
- ? null
679
- : {
680
- roots: record.typedSelection.roots,
681
- model: modelTypes(selectionModel),
682
- },
683
- });
684
- }
685
- }
686
- return {
687
- lastCompleted,
688
- locators: new Set([...queuedBatches.keys(), ...replicas.keys()]),
689
- read: mergeChangeSets([...new Set([...previousReplicas.keys(), ...replicas.keys()])].map((locator) => changeSet(locator, previousReplicas.get(locator) ?? null, replicas.get(locator) ?? null))),
690
- };
691
- }
692
- async function readState(opened) {
693
- const { lastCompleted, locators, read } = await hydrate(opened);
694
- applyChangeSet(read);
695
- if (replicas.size > 0)
696
- emitRooms();
697
- if (member !== null)
698
- emitMember();
699
- for (const locator of locators)
700
- emitQueue(locator);
701
- publishRoomDrafts(false);
702
- return lastCompleted;
703
- }
704
- async function open() {
705
- if (closed)
706
- throw new Error('runtime closed');
707
- const opened = await openRuntimeStore(isFenced);
708
- store = opened;
709
- const interrupted = await opened.fences();
710
- for (const locator of interrupted) {
711
- fences.set(locator, { at: discoveries, erased: false });
712
- lastFenced.set(locator, ++fencings);
713
- }
714
- const kept = options.shell.generation;
715
- const storedGeneration = await opened.generation();
716
- const loss = detectStorageLoss(storedGeneration, kept);
717
- const generation = nextGeneration(storedGeneration, kept);
718
- if (generation !== storedGeneration)
719
- await opened.rememberGeneration(generation);
720
- if (generation !== kept)
721
- await options.shell.keepGeneration(generation);
722
- if (loss !== null) {
723
- storageLoss = loss;
724
- emitStorageLoss();
725
- }
726
- const lastCompleted = await readState(opened);
727
- if (interrupted.length > 0)
728
- await erased(opened, interrupted);
729
- moveTo({ ...status, lastCompleted, ...attention() });
730
- return opened;
731
- }
732
- function durably(work) {
733
- return exclusive(async () => {
734
- const local = await openLocal();
735
- return work(local);
736
- });
737
- }
738
- function openLocal() {
739
- opening ??= open().catch((error) => {
740
- opening = undefined;
741
- throw error;
742
- });
743
- return opening;
744
- }
745
- function exclusive(work) {
746
- const next = mutations.then(work, work);
747
- mutations = next.then(() => undefined, () => undefined);
748
- return next;
749
- }
750
- function withdrawable(batch) {
751
- const state = pendings.get(batch.id);
752
- return state !== undefined && state.submission.state !== 'submitted' && !state.lost;
753
- }
754
- async function settle(local, locator, before, confirmed, queue, settling = {}) {
755
- const previousQueue = before?.queue ?? queuesWithoutReplica.get(locator) ?? [];
756
- const withdrawn = withdrawals(confirmed, queue, withdrawable, localSaves);
757
- const kept = queue.filter((batch) => !withdrawn.includes(batch));
758
- const unqueued = withdrawn.map((batch) => ({
759
- batch,
760
- returned: localSaves || landed(batch, confirmed) ? null : returnedBy('withdrawn'),
761
- }));
762
- const returning = [
763
- ...[...unqueued].reverse(),
764
- ...(settling.leaving === undefined ? [] : [settling.leaving]),
765
- ];
766
- const written = new Map();
767
- for (const { batch, returned } of returning) {
768
- if (returned === null)
769
- continue;
770
- for (const saved of pendings.get(batch.id)?.drafts ?? []) {
771
- const existing = written.get(saved.path) ?? roomDrafts.get(locator)?.get(saved.path);
772
- written.set(saved.path, {
773
- locator,
774
- path: saved.path,
775
- revision: roomDraftRevision(),
776
- parts: returnedInto(existing?.parts, saved.parts),
777
- returned,
778
- });
779
- }
780
- }
781
- await local.keepAuthored({ locator, queue: kept, roomDrafts: [...written.values()] });
782
- for (const batch of previousQueue) {
783
- if (!kept.includes(batch))
784
- pendings.delete(batch.id);
785
- }
786
- for (const record of written.values())
787
- rememberRoomDraft(record);
788
- try {
789
- await local.write({
790
- next: confirmed.record,
791
- previous: before?.confirmed.record ?? null,
792
- ...(settling.stored === undefined ? {} : { stored: settling.stored }),
793
- });
794
- }
795
- catch (error) {
796
- const held = before === undefined ? null : replicaOf(before.confirmed, kept, before);
797
- if (held !== null)
798
- replicas.set(locator, held);
799
- else if (kept.length > 0)
800
- queuesWithoutReplica.set(locator, kept);
801
- else
802
- queuesWithoutReplica.delete(locator);
803
- publishChangeSet(changeSet(locator, before ?? null, held, {
804
- queue: kept.length !== previousQueue.length,
805
- drafts: [...written.keys()],
806
- }));
807
- moveTo({ ...status, ...attention() });
808
- throw error;
809
- }
810
- queuesWithoutReplica.delete(locator);
811
- for (const { batch, returned } of unqueued) {
812
- const outcome = localSaves ? 'dropped' : returned === null ? 'landed' : 'withdrawn';
813
- journal.record(`outcome ${locator} ${batch.id} ${outcome}`);
814
- }
815
- replicas.set(locator, replicaOf(confirmed, kept, before));
816
- return changeSet(locator, before ?? null, replicas.get(locator) ?? null, {
817
- room: settling.room,
818
- queue: kept.length !== previousQueue.length,
819
- drafts: [...written.keys()],
820
- });
821
- }
822
- function adoptModels(locator, record) {
823
- for (const [attached, model] of [
824
- ['collection', record.model],
825
- ['typed-selection', record.selectionModel],
826
- ]) {
827
- const key = modelKey(locator, attached);
828
- models.set(key, model);
829
- invalidModels.delete(key);
830
- if (model.status === 'current')
831
- liveModels.set(key, JSON.stringify(model.snapshot));
832
- else if (model.status === 'unavailable')
833
- liveModels.delete(key);
834
- }
835
- }
836
- function remodel(locator, answers, held) {
837
- const taken = (answer, previous, attached) => {
838
- if (answer === undefined)
839
- return previous;
840
- const { state, refused } = attachedModel(answer, previous);
841
- if (refused !== null) {
842
- const where = refused.location === undefined ? '' : ` ${refused.location}`;
843
- journal.record(`model invalid ${locator} ${attached} ${refused.identity} ${refused.rule}${where}`);
844
- }
845
- models.set(modelKey(locator, attached), state);
846
- return state;
847
- };
848
- return {
849
- collection: taken(answers?.collection, held.collection, 'collection'),
850
- selection: taken(answers?.selection, held.selection, 'typed-selection'),
851
- };
852
- }
853
- function publish(local, room, confirmed, landing, live) {
854
- const { base, stored } = landing;
855
- return exclusive(async () => {
856
- if (!live())
857
- return true;
858
- const prior = replicas.get(room.locator);
859
- if (base !== undefined &&
860
- (prior?.confirmed.record.roomVersion !== base.record.roomVersion ||
861
- prior.confirmed.record.revisions !== base.record.revisions)) {
862
- return false;
863
- }
864
- adoptModels(room.locator, confirmed.record);
865
- const queue = prior?.queue ?? queuesWithoutReplica.get(room.locator) ?? [];
866
- const roomVersion = confirmed.record.roomVersion;
867
- const accepted = queue.filter((batch) => {
868
- const accepted = pendings.get(batch.id)?.accepted;
869
- return (accepted !== undefined && options.adapter.reached(room.locator, roomVersion, accepted));
870
- });
871
- const set = await settle(local, room.locator, prior, confirmed, queue.filter((batch) => !accepted.includes(batch)), { room: true, ...(stored === undefined ? {} : { stored }) });
872
- if (stored !== undefined)
873
- transfers.delete(room.locator);
874
- for (const batch of accepted)
875
- pendings.delete(batch.id);
876
- stale.delete(room.locator);
877
- if (unreadable.delete(room.locator))
878
- scopedRefusals.delete(room.locator);
879
- sourceRefusals.delete(room.locator);
880
- declarationRefusals.delete(room.locator);
881
- list(room, true);
882
- publishChangeSet(set);
883
- moveTo({ ...status, ...attention() });
884
- options.adapter.roomStream?.published(room.locator, roomVersion);
885
- return true;
886
- });
887
- }
888
- async function saveRoomDrafts(locator, named, writtenBy) {
889
- const local = await openLocal();
890
- const replica = replicas.get(locator);
891
- const room = rooms.get(locator);
892
- if (replica === undefined || room === undefined) {
893
- throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
894
- }
895
- const saved = [];
896
- for (const { path, revision } of named) {
897
- const record = roomDrafts.get(locator)?.get(path);
898
- if (record === undefined || record.revision !== revision) {
899
- return { outcome: 'refused', code: 'stale', retryable: false, file: path };
900
- }
901
- if (!saved.some((draft) => draft.path === path))
902
- saved.push({ path, parts: record.parts });
903
- }
904
- const changed = saved.flatMap(({ path, parts }) => changedParts(path, underneath(parts, path, replica.visible)));
905
- if (changed.length > 0)
906
- return { outcome: 'refused', code: 'changed-underneath', retryable: false, parts: changed };
907
- const parts = saved.map(({ path, parts }) => changesOf(path, parts));
908
- const changes = parts.flatMap(({ changes }) => changes);
909
- const requeue = requeued(replica.queue, changes, replica.visible, withdrawable, (queue) => replicaOf(replica.confirmed, queue, replica).visible);
910
- if (requeue.kind === 'refused')
911
- return { outcome: 'refused', ...requeue.refusal };
912
- const foreign = [...requeue.withdrawn.keys()].some((origin) => {
913
- const writer = replica.queue.find((batch) => batch.id === origin)?.writtenBy;
914
- return writer?.app !== writtenBy?.app || writer?.release !== writtenBy?.release;
915
- });
916
- if (foreign) {
917
- return {
918
- outcome: 'refused',
919
- code: 'unknown-revision',
920
- retryable: false,
921
- file: [...requeue.queued].at(-1),
922
- };
923
- }
924
- const withdrawing = requeue.withdrawn.size > 0;
925
- const input = {
926
- local: localSaves,
927
- baseRoomVersion: replica.confirmed.record.roomVersion,
928
- composition: compositionFor(replica.confirmed.record),
929
- operations: room.operations,
930
- providerOwnedPaths: room.providerOwnedPaths,
931
- providerLimits: limits,
932
- handle: room.handle,
933
- visible: replica.visible,
934
- changes,
935
- bases: parts.flatMap(({ bases }) => bases),
936
- writtenBy,
937
- };
938
- const checked = withdrawing ? buildBatch({ ...input, queued: requeue.queued }) : null;
939
- if (checked?.kind === 'refused')
940
- return { outcome: 'refused', ...checked.refusal };
941
- const owners = [...requeue.owners].flatMap((origin) => {
942
- const batch = requeue.withdrawn.get(origin);
943
- return batch === undefined || batch === null ? [] : [{ origin, batch }];
944
- });
945
- if (owners.length > 1) {
946
- return {
947
- outcome: 'refused',
948
- code: 'unknown-revision',
949
- retryable: false,
950
- file: [...requeue.queued].at(-1),
951
- };
952
- }
953
- const built = !withdrawing
954
- ? buildBatch(input)
955
- : requeue.changes.length === 0
956
- ? null
957
- : buildBatch({
958
- ...input,
959
- visible: replicaOf(replica.confirmed, requeue.queue, replica).visible,
960
- changes: requeue.changes,
961
- });
962
- if (built?.kind === 'refused')
963
- return { outcome: 'refused', ...built.refusal };
964
- const [owner] = owners;
965
- const join = built === null || owner === undefined
966
- ? null
967
- : joined(requeue.queue, owner.batch, built.batch);
968
- if (join?.kind === 'refused')
969
- return { outcome: 'refused', ...join.refusal };
970
- const withdrawn = new Map(requeue.withdrawn);
971
- if (join !== null && owner !== undefined)
972
- withdrawn.set(owner.origin, join.batch);
973
- const drafted = new Map();
974
- for (const [origin, replaced] of withdrawn) {
975
- if (replaced === null)
976
- continue;
977
- const carried = withdrawnDrafts(pendings.get(origin)?.drafts ?? [], changes);
978
- drafted.set(replaced.id, replaced === join?.batch
979
- ? [
980
- ...carried.map((held) => joinedDraft(held, saved)),
981
- ...saved.filter((draft) => !carried.some((held) => held.path === draft.path)),
982
- ]
983
- : carried);
984
- }
985
- if (built !== null && join === null)
986
- drafted.set(built.batch.id, saved);
987
- const batches = join !== null ? join.queue : built === null ? requeue.queue : [...requeue.queue, built.batch];
988
- for (const replaced of withdrawn.values()) {
989
- if (replaced === null || !batches.includes(replaced))
990
- continue;
991
- const limited = limitedIn(batches, replaced, limits, (queue) => replicaOf(replica.confirmed, queue, replica).visible);
992
- if (limited !== null)
993
- return { outcome: 'refused', ...limited };
994
- }
995
- const consumed = saved.map(({ path }) => path);
996
- try {
997
- await local.keepAuthored({
998
- locator,
999
- queue: batches,
1000
- saved: drafted,
1001
- consumedRoomDrafts: consumed,
1002
- });
1003
- }
1004
- catch {
1005
- return { outcome: 'refused', code: 'durable-write', retryable: true };
1006
- }
1007
- if (fences.has(locator))
1008
- throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
1009
- for (const origin of withdrawn.keys())
1010
- pendings.delete(origin);
1011
- for (const [id, drafts] of drafted) {
1012
- pendings.set(id, { drafts, submission: { state: 'waiting' }, lost: false });
1013
- }
1014
- if (!localSaves)
1015
- recorded = false;
1016
- for (const path of consumed)
1017
- forgetRoomDraft(locator, path);
1018
- replicas.set(locator, replicaOf(replica.confirmed, batches, replica));
1019
- publishChangeSet(changeSet(locator, replica, replicas.get(locator) ?? null, {
1020
- queue: true,
1021
- drafts: consumed,
1022
- }));
1023
- moveTo({ ...(localSaves ? status : saving(status)), ...attention() });
1024
- submitLater(locator);
1025
- const identifier = join?.batch.id ??
1026
- built?.batch.id ??
1027
- [...requeue.withdrawn].map(([origin, replaced]) => replaced?.id ?? origin).at(-1);
1028
- return { outcome: 'saved', identifier };
1029
- }
1030
- async function mark(local, locator, identifier, submission, lost) {
1031
- const state = pendings.get(identifier);
1032
- if (!continuing() ||
1033
- state === undefined ||
1034
- (JSON.stringify(state.submission) === JSON.stringify(submission) && state.lost === lost)) {
1035
- return;
1036
- }
1037
- await local.submit(locator, identifier, submission, lost);
1038
- if (fences.has(locator))
1039
- return;
1040
- pendings.set(identifier, { ...state, submission, lost });
1041
- const replica = replicas.get(locator);
1042
- if (replica !== undefined)
1043
- publishChangeSet(changeSet(locator, replica, replica, { queue: true }));
1044
- moveTo({ ...status, ...attention() });
1045
- }
1046
- async function keepUpload(local, locator, identifier, upload) {
1047
- if (!continuing())
1048
- throw new Error('connection refused');
1049
- await local.keepUpload(locator, identifier, upload);
1050
- if (fences.has(locator))
1051
- throw runtimeError('room-not-held', `No Local Replica for ${locator}`);
1052
- pendings.set(identifier, { ...pendings.get(identifier), upload });
1053
- if (!continuing())
1054
- throw new Error('connection refused');
1055
- }
1056
- async function readHistory(locator, path, query = {}) {
1057
- if (closed || refusal !== null)
1058
- return UNCERTAIN;
1059
- try {
1060
- await ensureAuthorization();
1061
- }
1062
- catch {
1063
- return UNCERTAIN;
1064
- }
1065
- if (closed || authorization === undefined || refusal !== null)
1066
- return UNCERTAIN;
1067
- const since = fencings;
1068
- const transfer = ['transfer', 'history', locator, path];
1069
- if (query.revision !== undefined)
1070
- transfer.push(query.revision);
1071
- if (query.pageToken !== undefined)
1072
- transfer.push(query.pageToken);
1073
- journal.record(transfer.join(' '));
1074
- try {
1075
- const result = await options.adapter.history(authorization, {
1076
- locator,
1077
- path,
1078
- ...(query.revision === undefined ? {} : { revision: query.revision }),
1079
- ...(query.pageToken === undefined ? {} : { pageToken: query.pageToken }),
1080
- });
1081
- journal.record(`outcome history ${result.kind}`);
1082
- if (fencedSince(locator, since))
1083
- return failure({ kind: 'room-not-readable', locator });
1084
- if (result.kind === 'scoped-refusal') {
1085
- const room = replicas.get(result.locator)?.confirmed.record;
1086
- if (room !== undefined)
1087
- await scoped(result, room, await openLocal());
1088
- }
1089
- if (result.kind === 'revoked-authorization')
1090
- await refuse('revoked-authorization');
1091
- return historyAnswer(result);
1092
- }
1093
- catch {
1094
- journal.record('outcome history transport-uncertainty');
1095
- return UNCERTAIN;
1096
- }
1097
- }
1098
- function queuedBlob(locator, path, localId) {
1099
- for (const batch of replicas.get(locator)?.queue ?? []) {
1100
- const change = batch.changes[queuedFile(batch, path, localId)];
1101
- if (change?.kind === 'binary')
1102
- return change.blob;
1103
- }
1104
- return null;
1105
- }
1106
- function binaryRoom(request) {
1107
- if (request.kind === 'path')
1108
- return request.locator;
1109
- const scope = options.adapter.referrerScope(request.referrer);
1110
- return scope?.kind === 'room' ? scope.locator : null;
1111
- }
1112
- async function readBinary(request) {
1113
- if (closed || refusal !== null)
1114
- return UNCERTAIN;
1115
- try {
1116
- await ensureAuthorization();
1117
- }
1118
- catch {
1119
- return UNCERTAIN;
1120
- }
1121
- if (closed || authorization === undefined || refusal !== null)
1122
- return UNCERTAIN;
1123
- const since = fencings;
1124
- journal.record(request.kind === 'path'
1125
- ? `transfer binary ${request.locator} ${request.path}`
1126
- : `transfer binary ${request.fileRef}`);
1127
- try {
1128
- const result = await options.adapter.binary(authorization, request);
1129
- journal.record(`outcome binary ${result.kind}`);
1130
- const locator = binaryRoom(request);
1131
- if (locator !== null && fencedSince(locator, since))
1132
- return failure({ kind: 'room-not-readable', locator });
1133
- if (result.kind === 'scoped-refusal') {
1134
- const room = replicas.get(result.locator)?.confirmed.record;
1135
- if (room !== undefined)
1136
- await scoped(result, room, await openLocal());
1137
- }
1138
- if (result.kind === 'revoked-authorization')
1139
- await refuse('revoked-authorization');
1140
- return binaryAnswer(result);
1141
- }
1142
- catch {
1143
- journal.record('outcome binary transport-uncertainty');
1144
- return UNCERTAIN;
1145
- }
1146
- }
1147
- async function readBinaryPath(locator, path, revision) {
1148
- await ready;
1149
- if (revision !== undefined)
1150
- return readBinary({ kind: 'path', locator, path, revision });
1151
- const visible = replicas.get(locator)?.visible;
1152
- const held = visible?.binaries[path];
1153
- if (visible === undefined || held === undefined)
1154
- return absentBinary(path);
1155
- if (held.state === 'pending') {
1156
- const blob = queuedBlob(locator, path, held.localId);
1157
- return blob === null ? absentBinary(path) : { kind: 'binary', blob };
1158
- }
1159
- const record = binaryRecord(path, held, visible.revisions[path]);
1160
- if (record.state !== 'accepted')
1161
- return absentBinary(path);
1162
- const replica = replicas.get(locator);
1163
- const queued = (replica?.queue ?? []).flatMap((batch) => batch.changes);
1164
- const holds = (at) => {
1165
- const kept = replica?.confirmed.record.binaries[at];
1166
- return (kept?.state === 'accepted' &&
1167
- kept.fileRef === record.fileRef &&
1168
- replica?.confirmed.record.revisions[at] === record.revision);
1169
- };
1170
- let confirmed = path;
1171
- for (let index = queued.length - 1; index >= 0 && !holds(confirmed); index -= 1) {
1172
- const change = queued[index];
1173
- if (change.kind === 'move' && change.to === confirmed)
1174
- confirmed = change.path;
1175
- }
1176
- return readBinary({
1177
- kind: 'path',
1178
- locator,
1179
- path: confirmed,
1180
- revision: record.revision,
1181
- fileRef: record.fileRef,
1182
- });
1183
- }
1184
- async function readBinaryReference(reference) {
1185
- await ready;
1186
- return readBinary({
1187
- kind: 'reference',
1188
- fileRef: reference.fileRef,
1189
- referrer: reference.referrer,
1190
- });
1191
- }
1192
- function declaredAgents() {
1193
- for (const capability of capabilities) {
1194
- if (capability.conversationAgents !== undefined)
1195
- return capability.conversationAgents;
1196
- }
1197
- return undefined;
1198
- }
1199
- function declaredAction(name) {
1200
- for (const capability of capabilities) {
1201
- for (const action of capability.actions ?? []) {
1202
- if (action.name === name)
1203
- return action;
1204
- }
1205
- }
1206
- return undefined;
1207
- }
1208
- async function invokeAction(name, input) {
1209
- await ready;
1210
- if (closed || refusal !== null)
1211
- return UNCERTAIN;
1212
- if (declaredAction(name) === undefined)
1213
- return undeclared(name);
1214
- try {
1215
- await ensureAuthorization();
1216
- }
1217
- catch {
1218
- return UNCERTAIN;
1219
- }
1220
- if (closed || authorization === undefined || refusal !== null)
1221
- return UNCERTAIN;
1222
- journal.record(`transfer action ${name}`);
1223
- try {
1224
- const result = await options.adapter.action(authorization, { name, input });
1225
- if (result.kind === 'scoped-refusal') {
1226
- const room = replicas.get(result.locator)?.confirmed.record;
1227
- if (room !== undefined)
1228
- await scoped(result, room, await openLocal());
1229
- }
1230
- if (result.kind === 'revoked-authorization')
1231
- await refuse('revoked-authorization');
1232
- journal.record(`outcome action ${result.kind}`);
1233
- if (result.kind === 'rejected')
1234
- journal.record(`refusal rejected ${result.code}`);
1235
- return calledResult(result);
1236
- }
1237
- catch {
1238
- journal.record('outcome action transport-uncertainty');
1239
- return UNCERTAIN;
1240
- }
1241
- }
1242
- function continuing() {
1243
- return !closed && !discoveryPaused;
1244
- }
1245
- function reachedBy(locator, roomVersion) {
1246
- const held = replicas.get(locator);
1247
- return (held !== undefined &&
1248
- options.adapter.reached(locator, held.confirmed.record.roomVersion, roomVersion));
1249
- }
1250
- function writtenAfter(locator, roomVersion, path) {
1251
- const written = replicas.get(locator)?.confirmed.record.written[path];
1252
- return (written !== undefined &&
1253
- options.adapter.reached(locator, written, roomVersion) &&
1254
- !options.adapter.reached(locator, roomVersion, written));
1255
- }
1256
- async function pullRefresh(authorized, confirmed, live) {
1257
- if (!live())
1258
- return unconfirmed;
1259
- try {
1260
- const result = await refreshRoom(options.adapter, authorized, confirmed, (models, held) => (live() ? remodel(confirmed.record.locator, models, held) : held), live);
1261
- const detail = result.kind === 'advanced' ? result.confirmed.record.roomVersion : result.kind;
1262
- journal.record(`transfer refresh ${confirmed.record.locator} ${detail}`);
1263
- return result;
1264
- }
1265
- catch (error) {
1266
- journal.record(`transfer refresh ${confirmed.record.locator} transport-uncertainty`);
1267
- throw error;
1268
- }
1269
- }
1270
- function staging(local, live) {
1271
- return {
1272
- held: (locator) => transfers.get(locator) ?? null,
1273
- staged: (record) => local.staged(record),
1274
- stage: (record, page) => exclusive(async () => {
1275
- if (!live())
1276
- return false;
1277
- await local.stage(record, page);
1278
- transfers.set(record.locator, record);
1279
- return true;
1280
- }),
1281
- abandon: (locator) => exclusive(async () => {
1282
- if (!live())
1283
- return;
1284
- await local.abandon(locator);
1285
- transfers.delete(locator);
1286
- }),
1287
- };
1288
- }
1289
- function reusable(room) {
1290
- const record = replicas.get(room.locator)?.confirmed.record;
1291
- if (record === undefined || record.replica.selection !== room.replica.selection)
1292
- return null;
1293
- return { documents: record.documents, revisions: record.revisions };
1294
- }
1295
- async function pullBootstrap(authorized, room, local, live) {
1296
- if (!live())
1297
- return unconfirmed;
1298
- try {
1299
- const result = await bootstrapRoom(options.adapter, authorized, room, {
1300
- collection: modelOf(room.locator),
1301
- selection: modelOf(room.locator, 'typed-selection'),
1302
- }, (models, held) => (live() ? remodel(room.locator, models, held) : held), live, staging(local, live), reusable(room));
1303
- const detail = result.kind === 'staged' ? result.confirmed.record.roomVersion : result.kind;
1304
- journal.record(`transfer bootstrap ${room.locator} ${detail}`);
1305
- return result;
1306
- }
1307
- catch (error) {
1308
- journal.record(`transfer bootstrap ${room.locator} transport-uncertainty`);
1309
- throw error;
1310
- }
1311
- }
1312
- async function advance(room, local, authorized, live) {
1313
- const held = replicas.get(room.locator);
1314
- if (held !== undefined) {
1315
- const refreshed = await pullRefresh(authorized, held.confirmed, live);
1316
- if (!live())
1317
- return unconfirmed;
1318
- if (refreshed.kind === 'still-current') {
1319
- stale.delete(room.locator);
1320
- if (sourceRefusals.has(room.locator))
1321
- return null;
1322
- if (unreadable.delete(room.locator)) {
1323
- scopedRefusals.delete(room.locator);
1324
- list(room, true);
1325
- emitRooms();
30
+ const retries = createRetries(shell);
31
+ const socket = createSocket(adapter, journal, retries, options.authorization);
32
+ const presence = createPresence();
33
+ const store = createStore({
34
+ retries,
35
+ database: {
36
+ async ask(request) {
37
+ try {
38
+ return await options.database.ask(request);
1326
39
  }
1327
- return null;
1328
- }
1329
- if (refreshed.kind === 'advanced') {
1330
- if (!(await publish(local, room, refreshed.confirmed, { base: held.confirmed }, live))) {
1331
- const now = replicas.get(room.locator)?.confirmed.record.roomVersion;
1332
- const reached = now !== undefined &&
1333
- options.adapter.reached(room.locator, now, refreshed.confirmed.record.roomVersion);
1334
- return reached ? null : advance(room, local, authorized, live);
40
+ catch (error) {
41
+ if (refusedForSpace(error))
42
+ filled(runtime);
43
+ throw error;
1335
44
  }
1336
- await retainModel(local, room, 'collection', modelOf(room.locator));
1337
- return null;
1338
- }
1339
- if (refreshed.kind !== 'beyond-horizon')
1340
- return refreshed;
1341
- if (opened !== null) {
1342
- owed.add(room.locator);
1343
- return unconfirmed;
1344
- }
1345
- }
1346
- const bootstrapped = await pullBootstrap(authorized, room, local, live);
1347
- if (!live())
1348
- return unconfirmed;
1349
- if (bootstrapped.kind !== 'staged')
1350
- return bootstrapped;
1351
- await publish(local, room, bootstrapped.confirmed, { stored: bootstrapped.stored }, live);
1352
- return null;
1353
- }
1354
- async function withhold(withheld, room, local, progress) {
1355
- if (withheld.kind === 'refused')
1356
- stale.delete(room.locator);
1357
- else
1358
- stale.add(room.locator);
1359
- if (withheld.kind === 'scoped-refusal') {
1360
- await scoped(withheld, room, local);
1361
- }
1362
- else if (withheld.kind === 'transport-uncertainty') {
1363
- progress.reachable = false;
1364
- }
1365
- else if (withheld.kind === 'retryable-refusal') {
1366
- journal.record(`refusal ${withheld.kind} ${withheld.code}`);
1367
- }
1368
- else if (withheld.kind === 'room-not-readable') {
1369
- unreadable.add(room.locator);
1370
- list(room, false);
1371
- emitRooms();
1372
- }
1373
- else if (withheld.kind === 'refused') {
1374
- refusedSource(room, withheld);
1375
- }
1376
- else if (withheld.kind === 'revoked-authorization') {
1377
- await refuse('revoked-authorization');
1378
- }
1379
- }
1380
- function refusedSource(room, { refusal }) {
1381
- sourceRefusals.set(room.locator, {
1382
- code: refusal.rule,
1383
- retryable: false,
1384
- fields: {
1385
- file: refusal.file,
1386
- ...(refusal.location === undefined ? {} : { location: refusal.location }),
1387
- ...(refusal.referrers === undefined ? {} : { referrers: refusal.referrers }),
1388
45
  },
1389
- });
1390
- declarationRefusals.delete(room.locator);
1391
- unreadable.add(room.locator);
1392
- list(room, false);
1393
- emitRooms();
1394
- journal.record(`source refused ${room.locator} ${refusal.rule} ${refusal.file}`);
1395
- }
1396
- function leaving(batch, result) {
1397
- if (result.kind === 'expired')
1398
- return { batch, returned: returnedBy('expired') };
1399
- return {
1400
- batch,
1401
- returned: {
1402
- kind: result.kind,
1403
- code: result.code,
1404
- fields: result.fields,
1405
- retryable: result.retryable,
1406
- },
1407
- };
1408
- }
1409
- function logAccepted(locator, submitted, accepted) {
1410
- journal.record(`outcome ${locator} ${submitted.id} accepted ${accepted.roomVersion}` +
1411
- (accepted.author === undefined ? '' : ` author ${accepted.author}`) +
1412
- (accepted.time === undefined ? '' : ` time ${accepted.time}`));
1413
- }
1414
- async function adoptAccepted(room, local, submitted, accepted) {
1415
- if (!continuing())
1416
- return unconfirmed;
1417
- const current = replicas.get(room.locator);
1418
- if (current === undefined || !current.queue.some((batch) => batch.id === submitted.id)) {
1419
- return null;
1420
- }
1421
- const held = current.confirmed.record.roomVersion;
1422
- logAccepted(room.locator, submitted, accepted);
1423
- const applied = options.adapter.reached(room.locator, held, accepted.roomVersion)
1424
- ? { kind: 'staged', confirmed: current.confirmed }
1425
- : applyReturned(current.confirmed, submitted, accepted, options.adapter.follows(room.locator, held, accepted.roomVersion)
1426
- ? accepted.roomVersion
1427
- : held, accepted.roomVersion);
1428
- if (applied.kind !== 'staged') {
1429
- const state = pendings.get(submitted.id);
1430
- await local.accept(room.locator, submitted.id, accepted.roomVersion);
1431
- if (state !== undefined && !fences.has(room.locator))
1432
- pendings.set(submitted.id, { ...state, accepted: accepted.roomVersion });
1433
- emitQueue(room.locator);
1434
- return applied;
1435
- }
1436
- const set = await settle(local, room.locator, current, applied.confirmed, current.queue.filter((batch) => batch.id !== submitted.id), { room: true });
1437
- pendings.delete(submitted.id);
1438
- unreadable.delete(room.locator);
1439
- sourceRefusals.delete(room.locator);
1440
- declarationRefusals.delete(room.locator);
1441
- list(room, true);
1442
- publishChangeSet(set);
1443
- moveTo({ ...status, ...attention() });
1444
- return null;
1445
- }
1446
- async function adopted(room, local, submitted, accepted) {
1447
- const failed = await exclusive(() => adoptAccepted(room, local, submitted, accepted));
1448
- if (failed === null)
1449
- return true;
1450
- if (failed.kind === 'refused' && continuing())
1451
- refusedSource(room, failed);
1452
- return false;
1453
- }
1454
- async function submitRoom(room, local, authorized, progress) {
1455
- while (continuing() && authorization !== undefined) {
1456
- const replica = replicas.get(room.locator);
1457
- const head = replica?.queue[0];
1458
- if (replica === undefined || head === undefined)
1459
- return;
1460
- if (pendings.get(head.id)?.accepted !== undefined)
1461
- return;
1462
- const state = pendings.get(head.id);
1463
- const { submission, lost: earlier } = state ?? {
1464
- submission: { state: 'waiting' },
1465
- lost: false,
1466
- };
1467
- if (submission.state === 'reset' && Date.now() < Date.parse(submission.reset)) {
1468
- progress.complete = false;
1469
- return;
1470
- }
1471
- if (writesHeld()) {
1472
- progress.complete = false;
1473
- journal.record(`submission ${room.locator} ${head.id} held`);
1474
- return;
1475
- }
1476
- const lost = earlier || submission.state === 'submitted';
1477
- let result;
1478
- journal.record(`submission ${room.locator} ${head.id}`);
1479
- await exclusive(() => mark(local, room.locator, head.id, { state: 'submitted' }, lost));
1480
- if (discoveryPaused || fences.has(room.locator))
1481
- return;
1482
- if (writesHeld()) {
1483
- await exclusive(() => mark(local, room.locator, head.id, submission, earlier));
1484
- progress.complete = false;
1485
- journal.record(`submission ${room.locator} ${head.id} held`);
1486
- return;
1487
- }
1488
- const opensBefore = openSignals;
1489
- const answered = awaitingAnswer(room.locator);
1490
- try {
1491
- result = await options.adapter.mutate(authorized, {
1492
- locator: room.locator,
1493
- changeBatch: head,
1494
- ...(state?.upload === undefined ? {} : { upload: state.upload }),
1495
- }, (upload) => exclusive(() => keepUpload(local, room.locator, head.id, upload)));
1496
- }
1497
- catch {
1498
- answered();
1499
- progress.complete = false;
1500
- if (continuing())
1501
- progress.reachable = false;
1502
- return;
1503
- }
1504
- if (result.kind !== 'accepted' || !continuing())
1505
- answered();
1506
- if (!continuing())
1507
- return;
1508
- if (result.kind === 'transport-uncertainty') {
1509
- progress.complete = false;
1510
- progress.reachable = false;
1511
- return;
1512
- }
1513
- if (result.kind === 'room-not-readable') {
1514
- progress.complete = false;
1515
- unreadable.add(room.locator);
1516
- list(room, false);
1517
- emitRooms();
1518
- return;
1519
- }
1520
- if (result.kind === 'revoked-authorization') {
1521
- await refuse('revoked-authorization');
1522
- return;
1523
- }
1524
- if (result.kind === 'scoped-refusal') {
1525
- await scoped(result, room, local);
1526
- progress.complete = false;
1527
- return;
1528
- }
1529
- if (result.kind === 'write-halted') {
1530
- journal.record(`outcome ${room.locator} ${head.id} write-halted`);
1531
- await exclusive(() => mark(local, room.locator, head.id, { state: 'waiting' }, lost));
1532
- if (serviceMode === 'open' && openSignals !== opensBefore)
1533
- continue;
1534
- haltedRefusal = true;
1535
- progress.complete = false;
1536
- return;
1537
- }
1538
- if (result.kind === 'conflicted' ||
1539
- result.kind === 'rejected' ||
1540
- result.kind === 'expired' ||
1541
- result.kind === 'retryable-refusal') {
1542
- if (result.kind === 'expired') {
1543
- const withheld = await advance(room, local, authorized, continuing);
1544
- if (withheld !== null)
1545
- return withhold(withheld, room, local, progress);
1546
- }
1547
- journal.record(`outcome ${room.locator} ${head.id} ${result.kind}` +
1548
- (result.kind === 'conflicted' && result.roomVersion !== undefined
1549
- ? ` ${result.roomVersion}`
1550
- : ''));
1551
- if (result.kind !== 'expired')
1552
- journal.record(`refusal ${result.kind} ${result.code}`);
1553
- }
1554
- if (result.kind === 'retryable-refusal') {
1555
- const reset = result.reset;
1556
- progress.complete = false;
1557
- await exclusive(() => mark(local, room.locator, head.id, reset === undefined ? { state: 'waiting' } : { state: 'reset', reset }, lost));
1558
- armTimer();
1559
- return;
1560
- }
1561
- if (result.kind === 'conflicted' || result.kind === 'rejected' || result.kind === 'expired') {
1562
- const left = leaving(head, result);
1563
- await exclusive(async () => {
1564
- if (!continuing())
1565
- return;
1566
- const current = replicas.get(room.locator);
1567
- if (current === undefined || !current.queue.some((batch) => batch.id === head.id)) {
1568
- return;
1569
- }
1570
- const set = await settle(local, room.locator, current, current.confirmed, current.queue.filter((batch) => batch.id !== head.id), {
1571
- leaving: (result.kind === 'expired' && landed(head, current.confirmed)) ||
1572
- (result.kind === 'conflicted' && landed(head, current.confirmed, result.affected))
1573
- ? { ...left, returned: null }
1574
- : left,
1575
- });
1576
- publishChangeSet(set);
1577
- moveTo({ ...status, ...attention() });
1578
- });
1579
- if (result.kind === 'expired')
1580
- continue;
1581
- const withheld = await advance(room, local, authorized, continuing);
1582
- if (withheld !== null)
1583
- return withhold(withheld, room, local, progress);
1584
- continue;
1585
- }
1586
- const kept = await adopted(room, local, head, result).finally(answered);
1587
- if (!kept) {
1588
- progress.complete = false;
1589
- return;
1590
- }
1591
- }
1592
- }
1593
- function awaitingAnswer(locator) {
1594
- let release = () => { };
1595
- const awaited = new Promise((resolve) => {
1596
- release = resolve;
1597
- });
1598
- answering.set(locator, { generation, answered: awaited });
1599
- return () => {
1600
- if (answering.get(locator)?.answered === awaited)
1601
- answering.delete(locator);
1602
- release();
1603
- };
1604
- }
1605
- async function retainModel(local, room, attached, next) {
1606
- const key = modelKey(room.locator, attached);
1607
- const previous = modelOf(room.locator, attached);
1608
- const heldBefore = replicas.get(room.locator)?.confirmed.record;
1609
- if (JSON.stringify(previous) === JSON.stringify(next) &&
1610
- (heldBefore === undefined ||
1611
- (JSON.stringify(heldBefore.operations) === JSON.stringify(room.operations) &&
1612
- JSON.stringify(heldBefore.replica) === JSON.stringify(room.replica) &&
1613
- JSON.stringify(heldBefore.typedSelection) ===
1614
- JSON.stringify(room.typedSelection ?? null))))
1615
- return;
1616
- if (next.status === 'unavailable') {
1617
- invalidModels.add(key);
1618
- liveModels.delete(key);
1619
- }
1620
- await exclusive(async () => {
1621
- if (!continuing())
1622
- return;
1623
- const held = replicas.get(room.locator);
1624
- if (held !== undefined) {
1625
- const declared = {
1626
- ...held.confirmed.record,
1627
- operations: room.operations,
1628
- replica: room.replica,
1629
- typedSelection: room.typedSelection ?? null,
1630
- ...(attached === 'collection' ? { model: next } : { selectionModel: next }),
1631
- };
1632
- const reclassified = sameMembership(declared, held.confirmed.record)
1633
- ? { kind: 'staged', confirmed: confirmedOf(declared, held.confirmed) }
1634
- : readReclassified(declared, held.confirmed);
1635
- const record = reclassified.kind === 'staged'
1636
- ? declared
1637
- : {
1638
- ...declared,
1639
- typedSelection: held.confirmed.record.typedSelection,
1640
- };
1641
- const read = reclassified.kind === 'deferred'
1642
- ? { kind: 'staged', confirmed: confirmedOf(record, held.confirmed) }
1643
- : reclassified;
1644
- await local.write({ next: record, previous: held.confirmed.record });
1645
- if (read.kind === 'staged') {
1646
- replicas.set(room.locator, replicaOf(read.confirmed, held.queue, held));
1647
- if (declarationRefusals.delete(room.locator)) {
1648
- sourceRefusals.delete(room.locator);
1649
- unreadable.delete(room.locator);
1650
- }
1651
- }
1652
- else if (read.kind === 'refused') {
1653
- replicas.set(room.locator, { ...held, confirmed: { ...held.confirmed, record } });
1654
- refusedSource(room, read);
1655
- declarationRefusals.add(room.locator);
1656
- }
1657
- }
1658
- models.set(key, next);
1659
- if (next.status === 'current') {
1660
- liveModels.set(key, JSON.stringify(next.snapshot));
1661
- invalidModels.delete(key);
1662
- }
1663
- list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));
1664
- if (held === undefined)
1665
- emitRooms();
1666
- else
1667
- publishChangeSet(changeSet(room.locator, held, replicas.get(room.locator) ?? null, { room: true }));
1668
- });
1669
- }
1670
- async function scoped(result, room, local) {
1671
- scopedRefusals.set(room.locator, {
1672
- code: result.code,
1673
- fields: result.fields,
1674
- retryable: result.retryable,
1675
- });
1676
- let scopedAway = room;
1677
- if (result.scope === 'model')
1678
- await retainModel(local, room, 'collection', {
1679
- status: 'unavailable',
1680
- reason: 'not-readable',
1681
- });
1682
- else if (result.scope !== 'operation') {
1683
- unreadable.add(room.locator);
1684
- scopedAway = {
1685
- ...room,
1686
- replica: { ...room.replica, admission: 'unavailable' },
1687
- operations: {
1688
- ...room.operations,
1689
- ...(result.scope === 'content' ? { read: [] } : {}),
1690
- ...(result.scope === 'sync' ? { sync: [] } : {}),
1691
- },
1692
- };
1693
- await retainModel(local, scopedAway, 'collection', modelOf(room.locator));
1694
- }
1695
- if (!continuing())
1696
- return;
1697
- list(scopedAway, scopedAway.replica.admission === 'admitted' && !unreadable.has(room.locator));
1698
- emitRooms();
1699
- journal.record(`scoped refusal ${room.locator} ${result.scope} ${result.code}`);
1700
- }
1701
- function heldRooms(listed) {
1702
- return listed.flatMap((room) => {
1703
- const record = replicas.get(room.locator)?.confirmed.record;
1704
- if (record === undefined || record.replica.selection !== room.replica.selection)
1705
- return [];
1706
- return [
1707
- {
1708
- locator: room.locator,
1709
- roomVersion: record.roomVersion,
1710
- documents: record.documents,
1711
- revisions: record.revisions,
1712
- },
1713
- ];
1714
- });
1715
- }
1716
- async function synchronize(listed, local, progress, attempt, live) {
1717
- const prepared = await Promise.allSettled(listed.map((room) => prepareRoom(room, local, progress)));
1718
- if (!live())
1719
- return;
1720
- const ready = listed.filter((_, index) => {
1721
- const outcome = prepared[index];
1722
- return outcome?.status === 'fulfilled' && outcome.value;
1723
- });
1724
- if (attempt === 'opened') {
1725
- options.adapter.roomStream?.hold(heldRooms(ready));
1726
- handed = true;
1727
- }
1728
- discovering?.release();
1729
- const loaded = await Promise.allSettled(ready
1730
- .filter((room) => attempt === 'unstreamed' || !replicas.has(room.locator))
1731
- .map((room) => roomTask(room.locator, (held) => loadRoom(room, local, progress, held))));
1732
- const failed = [...prepared, ...loaded].find((room) => room.status === 'rejected');
1733
- if (failed !== undefined)
1734
- throw failed.reason;
1735
- }
1736
- async function prepareRoom(room, local, progress) {
1737
- if (closed || authorization === undefined) {
1738
- progress.complete = false;
1739
- return false;
1740
- }
1741
- const prior = replicas.get(room.locator)?.confirmed.record;
1742
- if (prior !== undefined && prior.replica.selection !== room.replica.selection) {
1743
- list(prior, false);
1744
- emitRooms();
1745
- journal.record(`selection changed ${room.locator}`);
1746
- progress.complete = false;
1747
- return false;
1748
- }
1749
- if (prior !== undefined)
1750
- await retainModel(local, room, 'collection', modelOf(room.locator));
1751
- if (discoveryPaused || authorization === undefined)
1752
- return false;
1753
- if (room.replica.admission !== 'admitted') {
1754
- if (replicas.has(room.locator))
1755
- progress.complete = false;
1756
- return false;
1757
- }
1758
- return true;
1759
- }
1760
- async function caughtUp(room, local, progress, live) {
1761
- const held = replicas.get(room.locator)?.confirmed.record.roomVersion;
1762
- if (held === undefined || authorization === undefined || !live())
1763
- return;
1764
- const behind = [announced.get(room.locator), room.roomVersion].some((later) => later !== undefined && !options.adapter.reached(room.locator, held, later));
1765
- if (!behind)
1766
- return;
1767
- const withheld = await advance(room, local, authorization, live);
1768
- if (withheld !== null)
1769
- await withhold(withheld, room, local, progress);
1770
- }
1771
- function revoked(locator) {
1772
- return ['collection', 'typed-selection'].some((attached) => {
1773
- const model = modelOf(locator, attached);
1774
- return model.status === 'unavailable' && model.reason === 'revoked';
1775
- });
1776
- }
1777
- async function loadRoom(room, local, progress, live) {
1778
- if (!live() || authorization === undefined)
1779
- return;
1780
- if (replicas.has(room.locator) && revoked(room.locator)) {
1781
- await reload(room, local, progress, live);
1782
- return;
1783
- }
1784
- const withheld = await advance(room, local, authorization, live);
1785
- if (withheld !== null) {
1786
- await withhold(withheld, room, local, progress);
1787
- return;
1788
- }
1789
- await caughtUp(room, local, progress, live);
1790
- }
1791
- async function reload(room, local, progress, live) {
1792
- if (!live() || authorization === undefined)
1793
- return;
1794
- const bootstrapped = await pullBootstrap(authorization, room, local, live);
1795
- if (!live())
1796
- return;
1797
- if (bootstrapped.kind !== 'staged') {
1798
- await withhold(bootstrapped, room, local, progress);
1799
- return;
1800
- }
1801
- await publish(local, room, bootstrapped.confirmed, { stored: bootstrapped.stored }, live);
1802
- await caughtUp(room, local, progress, live);
1803
- }
1804
- async function discoverRooms(local, progress, attempt, live) {
1805
- if (closed || authorization === undefined) {
1806
- notifyReady();
1807
- return;
1808
- }
1809
- moveTo(transferring(status));
1810
- discoveries += 1;
1811
- const started = discoveries;
1812
- let result;
1813
- try {
1814
- result = await options.adapter.discover(authorization);
1815
- }
1816
- catch {
1817
- result = { kind: 'transport-uncertainty' };
1818
- }
1819
- if (!live()) {
1820
- progress.complete = false;
1821
- notifyReady();
1822
- return;
1823
- }
1824
- journal.record(`connection discover ${result.kind}`);
1825
- if (result.kind === 'transport-uncertainty') {
1826
- for (const room of rooms.values()) {
1827
- await retainModel(local, room, 'collection', cached(modelOf(room.locator)));
1828
- if (room.typedSelection !== null) {
1829
- await retainModel(local, room, 'typed-selection', cached(modelOf(room.locator, 'typed-selection')));
1830
- }
1831
- }
1832
- progress.reachable = false;
1833
- progress.complete = false;
1834
- notifyReady();
1835
- return;
1836
- }
1837
- if (result.kind === 'contract-unavailable') {
1838
- journal.record(`connection contract unavailable ${result.code}`);
1839
- await refuse('missing-required-guarantee', {
1840
- code: result.code,
1841
- fields: result.fields,
1842
- retryable: result.retryable,
1843
- });
1844
- notifyReady();
1845
- return;
1846
- }
1847
- if (result.kind === 'revoked-authorization') {
1848
- await refuse('revoked-authorization');
1849
- notifyReady();
1850
- return;
1851
- }
1852
- for (const room of result.rooms) {
1853
- if (room.operations === undefined ||
1854
- !['read', 'sync', 'write', 'delete'].every((operation) => Array.isArray(room.operations[operation]) &&
1855
- room.operations[operation].every((scope) => typeof scope === 'string')) ||
1856
- room.replica === undefined ||
1857
- typeof room.replica.selection !== 'string' ||
1858
- room.replica.selection.length === 0 ||
1859
- !['admitted', 'unavailable'].includes(room.replica.admission)) {
1860
- journal.record(`invalid model or replica declaration ${room.locator}`);
1861
- await refuse('missing-required-guarantee');
1862
- notifyReady();
1863
- return;
1864
- }
1865
- if (!declaredSelection(room)) {
1866
- journal.record(`invalid typed selection declaration ${room.locator}`);
1867
- await refuse('missing-required-guarantee');
1868
- notifyReady();
1869
- return;
1870
- }
1871
- }
1872
- if (refusal !== null) {
1873
- refusal = null;
1874
- emitRefusal();
1875
- }
1876
- const previousCapabilities = capabilities;
1877
- capabilities = result.capabilities;
1878
- notifyReady();
1879
- if (JSON.stringify(result.providerLimits) !== JSON.stringify(limits) ||
1880
- JSON.stringify(result.capabilities) !== JSON.stringify(previousCapabilities)) {
1881
- limits = result.providerLimits;
1882
- await local.declare(limits, capabilities);
1883
- }
1884
- const signedIn = result.member ?? null;
1885
- if (JSON.stringify(signedIn) !== JSON.stringify(member)) {
1886
- await local.keepMember(signedIn);
1887
- member = signedIn;
1888
- emitMember();
1889
- }
1890
- await synchronize(await applyDiscovery(result.rooms, started), local, progress, attempt, live);
1891
- }
1892
- async function ensureAuthorization() {
1893
- if (authorization !== undefined)
1894
- return;
1895
- try {
1896
- authorization = await options.adapter.authorize();
1897
- journal.record('connection authorize');
1898
- }
1899
- catch (error) {
1900
- journal.record('connection authorize transport-uncertainty');
1901
- throw error;
1902
- }
1903
- }
1904
- async function admittedRead(work) {
1905
- if (roomReads.generation !== generation) {
1906
- roomReads = { generation, free: ROOM_READS, waiting: [] };
1907
- }
1908
- const reads = roomReads;
1909
- while (reads.free === 0)
1910
- await new Promise((admit) => reads.waiting.push(admit));
1911
- reads.free -= 1;
1912
- try {
1913
- await work();
1914
- }
1915
- finally {
1916
- reads.free += 1;
1917
- reads.waiting.shift()?.();
1918
- }
1919
- }
1920
- function roomTask(locator, work) {
1921
- return task(roomLane(locator), (live) => admittedRead(() => work(live)));
1922
- }
1923
- function task(lane, work) {
1924
- if (stopping)
1925
- return Promise.resolve();
1926
- const held = lanes.get(lane);
1927
- const current = held?.generation === generation ? held : { generation, chain: Promise.resolve() };
1928
- const turn = current.generation;
1929
- const live = () => turn === generation && continuing();
1930
- const run = current.chain.then(() => work(live)).catch(() => undefined);
1931
- current.chain = run;
1932
- lanes.set(lane, current);
1933
- working.add(run);
1934
- void run.finally(() => working.delete(run));
1935
- return run;
1936
- }
1937
- function sync(attempt) {
1938
- return task(OPENING_LANE, async (live) => {
1939
- if (!live()) {
1940
- notifyReady();
1941
- return;
1942
- }
1943
- const progress = { complete: true, reachable: true };
1944
- const gate = discover();
1945
- if (attempt === 'opened')
1946
- opened = generation;
1947
- underway = attempt === 'opened' ? { generation, progress } : null;
1948
- if (attempt === 'opened')
1949
- streamed = progress;
1950
- complete = false;
1951
- recorded = false;
1952
- moveTo(transferring(status));
1953
- handed = false;
1954
- try {
1955
- const local = await openLocal();
1956
- if (!live())
1957
- return;
1958
- await ensureAuthorization();
1959
- if (!live())
1960
- return;
1961
- await discoverRooms(local, progress, attempt, live);
1962
- }
1963
- catch {
1964
- progress.complete = false;
1965
- if (attempt === 'opened' && !handed)
1966
- progress.reachable = false;
1967
- }
1968
- finally {
1969
- gate.release();
1970
- notifyReady();
1971
- }
1972
- if (!live())
1973
- return;
1974
- if (attempt !== 'opened') {
1975
- await finishOpening(progress, live);
1976
- return;
1977
- }
1978
- if (handed || closed || progress.reachable)
1979
- return;
1980
- underway = null;
1981
- opened = null;
1982
- journal.record('connection reopen');
1983
- await rest(progress, live);
1984
- options.adapter.roomStream?.reopen();
1985
- });
1986
- }
1987
- function closedSocket(revoked) {
1988
- const opened = socketOpen;
1989
- socketOpen = false;
1990
- if (revoked) {
1991
- void refuse('revoked-authorization');
1992
- return;
1993
- }
1994
- complete = false;
1995
- if (streamed !== null)
1996
- streamed.complete = false;
1997
- moveTo({
1998
- ...status,
1999
- state: status.state === 'synced' ? 'syncing' : status.state,
2000
- providerUnreachable: status.providerUnreachable || !opened,
2001
- });
2002
- }
2003
- function applyOpening(expired) {
2004
- const progress = underway?.generation === generation ? underway.progress : null;
2005
- const cycle = progress ?? { complete: true, reachable: true };
2006
- const replacing = reloadNow((room) => expired.includes(room.locator), cycle);
2007
- return task(OPENING_LANE, async (live) => {
2008
- underway = null;
2009
- if (!live())
2010
- return;
2011
- if (progress === null) {
2012
- await replacing;
2013
- await rest(cycle, live);
2014
- return;
2015
- }
2016
- await roomsCarried(expired);
2017
- if (!live())
2018
- return;
2019
- if (opened === generation)
2020
- opened = null;
2021
- const replaced = new Set(owed);
2022
- owed.clear();
2023
- try {
2024
- const local = await openLocal();
2025
- const held = [...discovered.values()].filter((room) => replicas.has(room.locator));
2026
- const reloading = held.filter((room) => !expired.includes(room.locator) &&
2027
- (replaced.has(room.locator) || revoked(room.locator)));
2028
- const reloads = Promise.allSettled(reloading.map((room) => roomTask(room.locator, (current) => reload(room, local, progress, current))));
2029
- const reloaded = [...(await reloads), ...(await replacing)];
2030
- if (progress.reachable) {
2031
- for (const room of held) {
2032
- if (!expired.includes(room.locator) && !reloading.includes(room)) {
2033
- await confirmModels(room, local);
2034
- }
2035
- }
2036
- }
2037
- const failed = reloaded.find((outcome) => outcome.status === 'rejected');
2038
- if (failed !== undefined)
2039
- throw failed.reason;
2040
- }
2041
- catch {
2042
- progress.complete = false;
2043
- progress.reachable = false;
2044
- }
2045
- if (live())
2046
- await finishOpening(progress, live);
2047
- });
2048
- }
2049
- async function reloadNow(replaced, progress) {
2050
- try {
2051
- const local = await openLocal();
2052
- return await Promise.allSettled([...discovered.values()]
2053
- .filter((room) => replicas.has(room.locator) && replaced(room))
2054
- .map((room) => roomTask(room.locator, (live) => reload(room, local, progress, live))));
2055
- }
2056
- catch {
2057
- progress.reachable = false;
2058
- return [];
2059
- }
2060
- }
2061
- async function confirmModels(room, local) {
2062
- for (const attached of ['collection', 'typed-selection']) {
2063
- const model = modelOf(room.locator, attached);
2064
- if (model.status === 'cached') {
2065
- await retainModel(local, room, attached, { ...model, status: 'current' });
2066
- }
2067
- }
2068
- }
2069
- function submitLater(locator) {
2070
- if (localSaves)
2071
- return;
2072
- const running = submitting.get(locator);
2073
- if (running !== undefined) {
2074
- running.again = true;
2075
- return;
2076
- }
2077
- const run = { again: false, done: Promise.resolve() };
2078
- submitting.set(locator, run);
2079
- run.done = (async () => {
2080
- try {
2081
- do {
2082
- run.again = false;
2083
- const room = discovered.get(locator);
2084
- if (closed || stopping || discoveryPaused || room === undefined)
2085
- return;
2086
- const progress = { complete: true, reachable: true };
2087
- try {
2088
- await ensureAuthorization();
2089
- if (authorization === undefined)
2090
- return;
2091
- await submitRoom(room, await openLocal(), authorization, progress);
2092
- }
2093
- catch {
2094
- progress.reachable = false;
2095
- }
2096
- armTimer();
2097
- await rest(progress);
2098
- } while (run.again);
2099
- }
2100
- finally {
2101
- submitting.delete(locator);
2102
- }
2103
- })();
2104
- }
2105
- function submitAll() {
2106
- for (const [locator, replica] of replicas) {
2107
- if (replica.queue.length > 0)
2108
- submitLater(locator);
2109
- }
2110
- }
2111
- async function finishOpening(progress, live) {
2112
- try {
2113
- if (!live()) {
2114
- progress.complete = false;
2115
- return;
2116
- }
2117
- submitAll();
2118
- await conversations.reconcile();
2119
- if (status.providerUnreachable)
2120
- conversations.reconnected();
2121
- const reading = { complete: true, reachable: true };
2122
- await conversations.catchUp(reading);
2123
- if (progress.reachable && reading.reachable)
2124
- await conversations.resend(reading);
2125
- if (!reading.reachable)
2126
- progress.reachable = false;
2127
- }
2128
- catch {
2129
- progress.complete = false;
2130
- }
2131
- finally {
2132
- if (live()) {
2133
- complete = progress.complete;
2134
- await rest(progress, live);
2135
- }
2136
- }
2137
- }
2138
- async function rest(progress, live = () => !closed) {
2139
- if (!live())
2140
- return;
2141
- let lastCompleted = status.lastCompleted;
2142
- let synced = complete && stale.size === 0 && !pending();
2143
- if (synced && !recorded) {
2144
- const completedAt = new Date().toISOString();
2145
- try {
2146
- await (await openLocal()).complete(completedAt);
2147
- if (!live())
2148
- return;
2149
- recorded = true;
2150
- lastCompleted = completedAt;
2151
- }
2152
- catch {
2153
- synced = false;
2154
- }
2155
- }
2156
- moveTo({
2157
- state: pending() ? 'pending' : synced && complete ? 'synced' : 'syncing',
2158
- lastCompleted,
2159
- providerUnreachable: !progress.reachable,
2160
- ...attention(),
2161
- });
2162
- }
2163
- function discover() {
2164
- let release = () => { };
2165
- const done = new Promise((resolve) => {
2166
- release = resolve;
2167
- });
2168
- discovering = { generation, done, release };
2169
- return discovering;
2170
- }
2171
- function applyRoom(locator, roomVersion) {
2172
- announced.set(locator, roomVersion);
2173
- return task(roomLane(locator), async (live) => {
2174
- if (discovering?.generation === generation)
2175
- await discovering.done;
2176
- const saving = answering.get(locator);
2177
- if (saving?.generation === generation)
2178
- await saving.answered;
2179
- if (!live() || authorization === undefined)
2180
- return;
2181
- const room = discovered.get(locator);
2182
- const held = replicas.get(locator);
2183
- if (room === undefined || room.replica.admission !== 'admitted')
2184
- return;
2185
- if (held !== undefined &&
2186
- (held.confirmed.record.replica.selection !== room.replica.selection ||
2187
- options.adapter.reached(locator, held.confirmed.record.roomVersion, roomVersion))) {
2188
- return;
2189
- }
2190
- const during = underway?.generation === generation ? underway.progress : null;
2191
- const progress = during ?? { complete: true, reachable: true };
2192
- if (during === null)
2193
- moveTo(transferring(status));
2194
- try {
2195
- const local = await openLocal();
2196
- await admittedRead(async () => {
2197
- if (!live() || authorization === undefined)
2198
- return;
2199
- const withheld = await advance(room, local, authorization, live);
2200
- if (withheld !== null)
2201
- await withhold(withheld, room, local, progress);
2202
- });
2203
- }
2204
- catch {
2205
- stale.add(locator);
2206
- }
2207
- finally {
2208
- if (during === null)
2209
- await rest(progress, live);
2210
- }
2211
- });
2212
- }
2213
- function roomsCarried(replacing) {
2214
- const replaced = new Set(replacing.map(roomLane));
2215
- return Promise.all([...lanes]
2216
- .filter(([lane, held]) => lane !== OPENING_LANE && !replaced.has(lane) && held.generation === generation)
2217
- .map(([, held]) => held.chain));
2218
- }
2219
- const receipts = {
2220
- heads: async () => (await openLocal()).receivedHeads(),
2221
- parts: async (key, count) => (await openLocal()).receivedParts(key, count),
2222
- keep: async (key, head, part) => (await openLocal()).keepReceived(key, head, part),
2223
- drop: async (keys) => (await openLocal()).dropReceived(keys),
2224
- };
2225
- function observeStream() {
2226
- const stream = options.adapter.roomStream;
2227
- if (stream === undefined || withdrawStream !== undefined)
2228
- return;
2229
- withdrawStream = stream.observe((event) => {
2230
- if (closed || stopping)
2231
- return;
2232
- if (event.kind === 'opened') {
2233
- socketOpen = true;
2234
- generation += 1;
2235
- void sync('opened');
2236
- }
2237
- else if (event.kind === 'closed')
2238
- closedSocket(event.revoked);
2239
- else if (event.kind === 'opening')
2240
- void applyOpening(event.expired);
2241
- else
2242
- void applyRoom(event.locator, event.roomVersion);
2243
- }, receipts);
2244
- }
2245
- function writesHeld() {
2246
- return serviceMode === 'write-halted' || haltedRefusal;
2247
- }
2248
- function signalled(mode) {
2249
- if (closed)
2250
- return;
2251
- if (mode === 'open')
2252
- openSignals += 1;
2253
- const releasing = mode === 'open' && (haltedRefusal || serviceMode === 'write-halted');
2254
- if (mode === 'open')
2255
- haltedRefusal = false;
2256
- if (mode !== serviceMode) {
2257
- serviceMode = mode;
2258
- journal.record(`service mode ${mode}`);
2259
- for (const listener of serviceModeListeners)
2260
- listener(mode);
2261
- }
2262
- if (releasing)
2263
- submitAll();
2264
- }
2265
- function observeConversations() {
2266
- const stream = options.adapter.conversations;
2267
- if (stream === undefined || withdrawConversations !== undefined)
2268
- return;
2269
- withdrawConversations = stream.observe((event) => {
2270
- if (conversations.receive(event)) {
2271
- void ready.then(scheduleCurrency);
2272
- return;
2273
- }
2274
- if (event.kind !== 'gap' || conversations.current())
2275
- return;
2276
- show();
2277
- scheduleCurrency();
2278
- });
2279
- }
2280
- function scheduleCurrency() {
2281
- if (currencyQueued === generation || closed || stopping)
2282
- return;
2283
- currencyQueued = generation;
2284
- void task(CONVERSATION_LANE, runCurrency);
2285
- }
2286
- async function runCurrency(live) {
2287
- if (currencyQueued === generation)
2288
- currencyQueued = null;
2289
- if (!live())
2290
- return;
2291
- await conversations.reconcile();
2292
- if (conversations.current()) {
2293
- show();
2294
- return;
2295
- }
2296
- const progress = { complete: false, reachable: !status.providerUnreachable };
2297
- moveTo(transferring(status));
2298
- try {
2299
- await conversations.catchUp(progress);
2300
- }
2301
- catch {
2302
- progress.reachable = false;
2303
- }
2304
- await rest(progress, live);
2305
- }
2306
- function close() {
2307
- if (closed)
2308
- return;
2309
- closed = true;
2310
- withdrawStream?.();
2311
- withdrawStream = undefined;
2312
- withdrawConversations?.();
2313
- withdrawConversations = undefined;
2314
- withdrawServiceMode?.();
2315
- conversations.close();
2316
- stopTimer();
2317
- store?.close();
2318
- void opening?.then((opened) => {
2319
- opened.close();
2320
- }, () => { });
2321
- roomListeners.clear();
2322
- refusalListeners.clear();
2323
- storageLossListeners.clear();
2324
- statusListeners.clear();
2325
- serviceModeListeners.clear();
2326
- memberListeners.clear();
2327
- readSide.close();
2328
- queueSubscriptions.clear();
2329
- roomDraftListeners.clear();
2330
- presentationListeners.clear();
2331
- }
2332
- async function stop() {
2333
- stopping = true;
2334
- stopTimer();
2335
- await Promise.all(working);
2336
- await Promise.all([...submitting.values()].map((run) => run.done));
2337
- await mutations;
2338
- close();
2339
- }
2340
- const withdrawServiceMode = options.adapter.serviceMode?.observe(signalled);
2341
- observeConversations();
2342
- options.signal?.addEventListener('abort', close, { once: true });
2343
- if (options.signal?.aborted)
2344
- close();
2345
- observeStream();
2346
- void openLocal().then(() => {
2347
- if (capabilities.length > 0)
2348
- notifyReady();
2349
- }, () => {
2350
- notifyReady();
2351
- });
2352
- if (options.adapter.roomStream === undefined)
2353
- void sync('unstreamed');
2354
- function planned(input, reach) {
2355
- return planOf(input, roomFacts(reach), planReach(reach));
2356
- }
2357
- function watchPlan(plan, deliver) {
2358
- materialize(reachedRooms(plan));
2359
- return readSide.watch(plan, identityOf(plan), deliver);
2360
- }
2361
- async function searched(input, reach) {
2362
- const plan = searchPlanOf(input);
2363
- const selected = plan.documents === undefined && reach === null
2364
- ? null
2365
- : (await rowsQuery(filterOf(plan.documents ?? {}, roomFacts(reach), planReach(reach)))).documents;
2366
- if (selected === null)
2367
- materialize(null);
2368
- return searchIndex.search(reach === null || reach.conversations ? plan : { ...plan, conversations: [] }, selected);
2369
- }
2370
- const watch = (topic, input, deliver) => {
2371
- if (topic === 'room-drafts') {
2372
- const listener = { notify: deliver, ready: false };
2373
- roomDraftListeners.add(listener);
2374
- void exclusive(async () => {
2375
- await openLocal();
2376
- if (closed || !roomDraftListeners.has(listener))
2377
- return;
2378
- listener.ready = true;
2379
- }).then(() => {
2380
- if (closed || !listener.ready || !roomDraftListeners.has(listener))
2381
- return;
2382
- listener.notify(snapshotRoomDrafts());
2383
- }, () => { });
2384
- return () => {
2385
- roomDraftListeners.delete(listener);
2386
- };
2387
- }
2388
- if (topic === 'conversation') {
2389
- return conversations.watch(input[0], input[1], deliver);
2390
- }
2391
- if (topic === 'conversations')
2392
- return conversations.watchList(deliver);
2393
- if (topic === 'agents')
2394
- return conversations.watchAgents(deliver);
2395
- if (topic === 'presentation') {
2396
- const listener = {
2397
- app: input[0],
2398
- notify: deliver,
2399
- ready: false,
2400
- };
2401
- presentationListeners.add(listener);
2402
- void exclusive(async () => {
2403
- await openLocal();
2404
- }).then(() => {
2405
- if (closed || !presentationListeners.has(listener))
2406
- return;
2407
- listener.ready = true;
2408
- listener.notify(presentationOf(listener.app));
2409
- }, () => { });
2410
- return () => {
2411
- presentationListeners.delete(listener);
2412
- };
2413
- }
2414
- if (topic === 'rooms') {
2415
- roomListeners.add(deliver);
2416
- deliver(listed());
2417
- return () => {
2418
- roomListeners.delete(deliver);
2419
- };
2420
- }
2421
- if (topic === 'connection-refusal') {
2422
- refusalListeners.add(deliver);
2423
- deliver(refusal);
2424
- return () => {
2425
- refusalListeners.delete(deliver);
2426
- };
2427
- }
2428
- if (topic === 'storage-loss') {
2429
- storageLossListeners.add(deliver);
2430
- deliver(storageLoss);
2431
- return () => {
2432
- storageLossListeners.delete(deliver);
2433
- };
2434
- }
2435
- if (topic === 'sync-status') {
2436
- statusListeners.add(deliver);
2437
- deliver(shown);
2438
- return () => {
2439
- statusListeners.delete(deliver);
2440
- };
2441
- }
2442
- if (topic === 'service-mode') {
2443
- serviceModeListeners.add(deliver);
2444
- deliver(serviceMode);
2445
- return () => {
2446
- serviceModeListeners.delete(deliver);
2447
- };
2448
- }
2449
- if (topic === 'member') {
2450
- memberListeners.add(deliver);
2451
- deliver(member);
2452
- return () => {
2453
- memberListeners.delete(deliver);
2454
- };
2455
- }
2456
- if (topic === 'queue') {
2457
- const queue = { locator: input[0], notify: deliver };
2458
- queueSubscriptions.add(queue);
2459
- queue.notify(entriesOf(queue.locator));
2460
- return () => {
2461
- queueSubscriptions.delete(queue);
2462
- };
2463
- }
2464
- return watchPlan(planned(input[0], null), deliver);
2465
- };
2466
- const md = {
2467
- loaded() {
2468
- return openLocal().then(() => undefined);
2469
46
  },
2470
- rooms() {
2471
- return listed();
47
+ roomTypes,
48
+ builtIn,
49
+ typedPaths,
50
+ persistence: shell.persistence,
51
+ lost: presence.lost,
52
+ opening: (local) => open(runtime, local),
53
+ unpublished(error) {
54
+ journal.record(`publication failed ${error instanceof Error ? error.name : 'unknown'}`);
55
+ uncaught(error);
2472
56
  },
2473
- query: ((input) => rowsQuery(planned(input, null))),
2474
- search: (input) => searched(input, null),
2475
- types(locator) {
2476
- return {
2477
- collection: modelTypes(modelOf(locator)),
2478
- typedSelection: rooms.get(locator)?.typedSelection === undefined ||
2479
- rooms.get(locator)?.typedSelection === null
2480
- ? null
2481
- : modelTypes(modelOf(locator, 'typed-selection')),
2482
- };
57
+ changed(set) {
58
+ if (set.unindexed.length > 0)
59
+ prepare(runtime, set.unindexed);
60
+ for (const locator of set.due)
61
+ submitLater(runtime, locator);
62
+ return publishChangeSet(runtime, set);
2483
63
  },
2484
- roomDraft: {
2485
- list() {
2486
- return exclusive(async () => {
2487
- await openLocal();
2488
- return snapshotRoomDrafts();
2489
- }).then((listed) => {
2490
- publishRoomDrafts(true);
2491
- return listed;
2492
- });
2493
- },
2494
- read(room, path) {
2495
- const record = roomDrafts.get(room)?.get(path);
2496
- return record === undefined ? null : roomDraftOf(record);
2497
- },
2498
- write(room, path, revision, input) {
2499
- return exclusive(async () => {
2500
- const parts = readParts(input);
2501
- if (path === '' || normalize(path) !== path)
2502
- throw runtimeError('room-draft-malformed');
2503
- const local = await openLocal();
2504
- const current = roomDrafts.get(room)?.get(path);
2505
- if ((current?.revision ?? null) !== revision) {
2506
- return staleWrite(current === undefined ? null : roomDraftOf(current));
2507
- }
2508
- const file = parts.file === undefined
2509
- ? undefined
2510
- : await heldFile(parts.file.blob, binaryBase(replicas.get(room)?.visible, path));
2511
- const record = {
2512
- locator: room,
2513
- path,
2514
- revision: roomDraftRevision(),
2515
- parts: held(current?.parts, parts, file),
2516
- returned: current?.returned ?? null,
2517
- };
2518
- await local.keepRoomDraft(record);
2519
- rememberRoomDraft(record);
2520
- publishChangeSet(changeSet(room, null, null, { drafts: [path] }));
2521
- return { outcome: 'written', roomDraft: roomDraftOf(record) };
2522
- });
2523
- },
2524
- discard(room, path, revision) {
2525
- return exclusive(async () => {
2526
- const local = await openLocal();
2527
- const current = roomDrafts.get(room)?.get(path);
2528
- if (current === undefined || current.revision !== revision) {
2529
- return staleWrite(current === undefined ? null : roomDraftOf(current));
2530
- }
2531
- await local.discardRoomDraft(room, path);
2532
- forgetRoomDraft(room, path);
2533
- publishChangeSet(changeSet(room, null, null, { drafts: [path] }));
2534
- moveTo({ ...status, ...attention() });
2535
- return { outcome: 'written', roomDraft: null };
2536
- });
2537
- },
2538
- },
2539
- conversation: conversations.surface,
2540
- chatDraft: conversations.chatDraft,
2541
- presentation: {
2542
- read(app) {
2543
- return exclusive(async () => {
2544
- await openLocal();
2545
- return presentationOf(app);
2546
- });
64
+ deliverReadiness: (owed) => deliverOwedReadiness(runtime, owed),
65
+ spaceFreed: () => spaceFreed(runtime),
66
+ });
67
+ const recovery = (options.recovery ?? createRecovery()).scope(ROOM_ATTEMPTS);
68
+ const runtime = {
69
+ store,
70
+ socket,
71
+ presence,
72
+ journal,
73
+ recovery,
74
+ retries,
75
+ shell,
76
+ localSaves: adapter.localSaves === true,
77
+ roomTypes,
78
+ builtIn,
79
+ typedPaths,
80
+ writeRule: (declaration) => writeRule(declaration, adapter.pathRule ?? (() => true), adapter.localSaves === true),
81
+ usableWhenHeld: options.usableWhenHeld ?? [],
82
+ build: options.build ?? '',
83
+ conversations: createLiveConversations({
84
+ call: (name, input, attempt) => invokeAction(runtime, name, input, { attempt }),
85
+ history: (request) => readConversationHistory(runtime, request),
86
+ durably: store.durably,
87
+ local: store.open,
88
+ again: () => {
89
+ void socket.ready.then(() => scheduleCurrency(runtime));
2547
90
  },
2548
- write(app, value) {
2549
- return exclusive(async () => {
2550
- const local = await openLocal();
2551
- const stored = structuredClone(value);
2552
- await local.present({ app, value: stored });
2553
- presentations.set(app, stored);
2554
- publishChangeSet(changeSet('', null, null, { presentation: app }));
2555
- });
91
+ settled: () => {
92
+ show(runtime);
2556
93
  },
2557
- },
2558
- save(room, named, writtenBy) {
2559
- return exclusive(() => saveRoomDrafts(room, named, writtenBy));
2560
- },
2561
- history(locator, path, query) {
2562
- return readHistory(locator, path, query);
2563
- },
2564
- binaryFile: {
2565
- read: readBinaryPath,
2566
- readReference: readBinaryReference,
2567
- },
2568
- call(name, input) {
2569
- return invokeAction(name, input);
2570
- },
2571
- reached(locator, roomVersion, path) {
2572
- return path === undefined
2573
- ? reachedBy(locator, roomVersion)
2574
- : writtenAfter(locator, roomVersion, path);
2575
- },
2576
- log() {
2577
- return journal.export();
2578
- },
2579
- persistence() {
2580
- return options.shell.persistentStorage;
2581
- },
2582
- observe: observing(watch),
2583
- async reauthorize() {
2584
- if (refusal === null || !refusal.reauthorizationOffered)
2585
- return;
2586
- journal.record('connection reauthorize');
2587
- await Promise.all([...lanes.values()]
2588
- .filter((held) => held.generation === generation)
2589
- .map((held) => held.chain));
2590
- await mutations;
2591
- authorization = undefined;
2592
- discoveryPaused = false;
2593
- if (options.adapter.roomStream === undefined)
2594
- await sync('unstreamed');
2595
- else
2596
- await task(OPENING_LANE, ensureAuthorization);
2597
- },
2598
- };
2599
- const reachable = {
2600
- md,
2601
- watch,
2602
- referrerScope: (referrer) => options.adapter.referrerScope(referrer),
2603
- plan: planned,
2604
- query: (plan) => rowsQuery(plan),
2605
- watchPlan,
2606
- search: searched,
94
+ stream: socket.conversations,
95
+ publish: store.changed,
96
+ online: socket.reached,
97
+ full: store.space.full,
98
+ closed: socket.closed,
99
+ unanswered: () => resendLater(runtime),
100
+ recovery: recovery.scope(),
101
+ retries,
102
+ }),
103
+ liveQueries: createLiveQueries((plan, cover) => answeredPlan(runtime, plan, cover), store.covering),
104
+ figures: createFigures({
105
+ cover: () => figuresCover(runtime),
106
+ rooms: (rooms, since) => roomTallies(runtime, rooms, since),
107
+ conversations: (conversations, since) => store.ask({ kind: 'conversation.tallies', conversations, since }),
108
+ }),
109
+ lastAnswers: readAnswers({
110
+ database: store,
111
+ build: options.build ?? '',
112
+ unkept: adapter.unkeptReads ?? [],
113
+ leading: adapter.leadingReads ?? [],
114
+ recovery: recovery.scope(),
115
+ retries,
116
+ call: (name, input, attempt) => called(runtime, name, input, attempt),
117
+ online: socket.reached,
118
+ streaming: socket.isOpen,
119
+ closed: socket.closed,
120
+ full: store.space.full,
121
+ filled: () => filled(runtime),
122
+ }),
2607
123
  };
2608
- return { md, stop, lose: loseRooms, watch, within: (reach) => narrowed(reachable, reach) };
124
+ start(runtime, options.signal);
125
+ return composedRuntime(runtime);
2609
126
  }