@agentshouse/mdruntime 0.1.0-cbb8d8acc9d19 → 0.1.0-cbbae1fff01c6

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