@agentshouse/mdruntime 0.1.0-c6bf34fa9e444 → 0.1.0-c6d3d5d8beeb0

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 (321) hide show
  1. package/README.md +21 -19
  2. package/dist/acceptance.d.ts +0 -3
  3. package/dist/acceptance.d.ts.map +1 -1
  4. package/dist/acceptance.js +105 -166
  5. package/dist/act-lanes.d.ts +30 -0
  6. package/dist/act-lanes.d.ts.map +1 -0
  7. package/dist/act-lanes.js +225 -0
  8. package/dist/actions.d.ts +8 -2
  9. package/dist/actions.d.ts.map +1 -1
  10. package/dist/actions.js +180 -85
  11. package/dist/adapter.d.ts +222 -73
  12. package/dist/adapter.d.ts.map +1 -1
  13. package/dist/attached-model.d.ts +0 -1
  14. package/dist/attached-model.d.ts.map +1 -1
  15. package/dist/attached-model.js +2 -7
  16. package/dist/{binary.d.ts → attachment.d.ts} +8 -4
  17. package/dist/attachment.d.ts.map +1 -0
  18. package/dist/attachment.js +15 -0
  19. package/dist/authored.d.ts +88 -0
  20. package/dist/authored.d.ts.map +1 -0
  21. package/dist/authored.js +345 -0
  22. package/dist/bootstrap.d.ts +1 -1
  23. package/dist/bootstrap.d.ts.map +1 -1
  24. package/dist/bootstrap.js +6 -18
  25. package/dist/chain.d.ts +1 -1
  26. package/dist/chain.d.ts.map +1 -1
  27. package/dist/chain.js +5 -2
  28. package/dist/change-set.d.ts +4 -0
  29. package/dist/change-set.d.ts.map +1 -1
  30. package/dist/change-set.js +6 -0
  31. package/dist/change.d.ts +6 -2
  32. package/dist/change.d.ts.map +1 -1
  33. package/dist/change.js +7 -2
  34. package/dist/chat-types.d.ts +0 -2
  35. package/dist/chat-types.d.ts.map +1 -1
  36. package/dist/chat-types.js +2 -4
  37. package/dist/client.d.ts +30 -23
  38. package/dist/client.d.ts.map +1 -1
  39. package/dist/client.js +55 -68
  40. package/dist/collection.d.ts +27 -4
  41. package/dist/collection.d.ts.map +1 -1
  42. package/dist/collection.js +34 -10
  43. package/dist/column.d.ts +5 -0
  44. package/dist/column.d.ts.map +1 -0
  45. package/dist/column.js +9 -0
  46. package/dist/compile.d.ts +4 -1
  47. package/dist/compile.d.ts.map +1 -1
  48. package/dist/compile.js +101 -63
  49. package/dist/connection.d.ts +1 -1
  50. package/dist/connection.d.ts.map +1 -1
  51. package/dist/connection.js +45 -28
  52. package/dist/context.d.ts.map +1 -1
  53. package/dist/context.js +1 -1
  54. package/dist/conversation-live.d.ts +150 -0
  55. package/dist/conversation-live.d.ts.map +1 -0
  56. package/dist/conversation-live.js +260 -0
  57. package/dist/conversation-row.d.ts +23 -1
  58. package/dist/conversation-row.d.ts.map +1 -1
  59. package/dist/conversation-row.js +39 -4
  60. package/dist/conversation.d.ts +67 -49
  61. package/dist/conversation.d.ts.map +1 -1
  62. package/dist/conversation.js +993 -1032
  63. package/dist/declaration.d.ts +10 -0
  64. package/dist/declaration.d.ts.map +1 -0
  65. package/dist/declaration.js +24 -0
  66. package/dist/discovery.d.ts +3 -1
  67. package/dist/discovery.d.ts.map +1 -1
  68. package/dist/discovery.js +47 -47
  69. package/dist/download.d.ts +6 -0
  70. package/dist/download.d.ts.map +1 -0
  71. package/dist/download.js +42 -0
  72. package/dist/durability.d.ts +5 -0
  73. package/dist/durability.d.ts.map +1 -1
  74. package/dist/durability.js +7 -0
  75. package/dist/entry.d.ts +26 -1
  76. package/dist/entry.d.ts.map +1 -1
  77. package/dist/entry.js +126 -36
  78. package/dist/expectation.d.ts +26 -13
  79. package/dist/expectation.d.ts.map +1 -1
  80. package/dist/expectation.js +72 -19
  81. package/dist/failure.d.ts +3 -0
  82. package/dist/failure.d.ts.map +1 -1
  83. package/dist/failure.js +8 -0
  84. package/dist/figures.d.ts +2 -1
  85. package/dist/figures.d.ts.map +1 -1
  86. package/dist/figures.js +8 -6
  87. package/dist/file.d.ts +1 -1
  88. package/dist/file.d.ts.map +1 -1
  89. package/dist/file.js +3 -2
  90. package/dist/host.d.ts +24 -4
  91. package/dist/host.d.ts.map +1 -1
  92. package/dist/host.js +108 -32
  93. package/dist/house-query.d.ts +24 -0
  94. package/dist/house-query.d.ts.map +1 -0
  95. package/dist/house-query.js +102 -0
  96. package/dist/identity.d.ts +1 -1
  97. package/dist/identity.d.ts.map +1 -1
  98. package/dist/identity.js +1 -1
  99. package/dist/index.d.ts +30 -15
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +20 -8
  102. package/dist/install.d.ts +10 -6
  103. package/dist/install.d.ts.map +1 -1
  104. package/dist/install.js +93 -116
  105. package/dist/lifecycle.d.ts +2 -2
  106. package/dist/lifecycle.d.ts.map +1 -1
  107. package/dist/lifecycle.js +81 -56
  108. package/dist/linked-file.d.ts +7 -0
  109. package/dist/linked-file.d.ts.map +1 -0
  110. package/dist/linked-file.js +16 -0
  111. package/dist/listing.d.ts +29 -22
  112. package/dist/listing.d.ts.map +1 -1
  113. package/dist/listing.js +71 -78
  114. package/dist/live.d.ts +19 -3
  115. package/dist/live.d.ts.map +1 -1
  116. package/dist/live.js +97 -39
  117. package/dist/loaded.d.ts +7 -0
  118. package/dist/loaded.d.ts.map +1 -0
  119. package/dist/loaded.js +46 -0
  120. package/dist/locks.d.ts +2 -4
  121. package/dist/locks.d.ts.map +1 -1
  122. package/dist/locks.js +12 -39
  123. package/dist/lost.d.ts.map +1 -1
  124. package/dist/lost.js +11 -23
  125. package/dist/media.d.ts +20 -4
  126. package/dist/media.d.ts.map +1 -1
  127. package/dist/media.js +184 -37
  128. package/dist/memory.d.ts +10 -4
  129. package/dist/memory.d.ts.map +1 -1
  130. package/dist/memory.js +103 -40
  131. package/dist/messages.d.ts +21 -6
  132. package/dist/messages.d.ts.map +1 -1
  133. package/dist/messages.js +54 -42
  134. package/dist/modal.d.ts +2 -0
  135. package/dist/modal.d.ts.map +1 -0
  136. package/dist/modal.js +11 -0
  137. package/dist/model.d.ts +10 -8
  138. package/dist/model.d.ts.map +1 -1
  139. package/dist/model.js +6 -5
  140. package/dist/models.d.ts +4 -8
  141. package/dist/models.d.ts.map +1 -1
  142. package/dist/models.js +97 -137
  143. package/dist/name.d.ts +0 -1
  144. package/dist/name.d.ts.map +1 -1
  145. package/dist/name.js +3 -7
  146. package/dist/observation.d.ts +29 -12
  147. package/dist/observation.d.ts.map +1 -1
  148. package/dist/observation.js +217 -85
  149. package/dist/online.d.ts +7 -0
  150. package/dist/online.d.ts.map +1 -0
  151. package/dist/online.js +29 -0
  152. package/dist/opened.d.ts +6 -6
  153. package/dist/opened.d.ts.map +1 -1
  154. package/dist/opened.js +7 -7
  155. package/dist/opening.d.ts.map +1 -1
  156. package/dist/opening.js +26 -11
  157. package/dist/outcome.d.ts +33 -13
  158. package/dist/outcome.d.ts.map +1 -1
  159. package/dist/outcome.js +36 -6
  160. package/dist/overlay.d.ts +23 -8
  161. package/dist/overlay.d.ts.map +1 -1
  162. package/dist/overlay.js +132 -48
  163. package/dist/page-metadata.d.ts +8 -0
  164. package/dist/page-metadata.d.ts.map +1 -0
  165. package/dist/page-metadata.js +19 -0
  166. package/dist/parts.d.ts +6 -58
  167. package/dist/parts.d.ts.map +1 -1
  168. package/dist/parts.js +28 -110
  169. package/dist/paths.d.ts +1 -0
  170. package/dist/paths.d.ts.map +1 -1
  171. package/dist/paths.js +22 -0
  172. package/dist/preparation.d.ts +33 -7
  173. package/dist/preparation.d.ts.map +1 -1
  174. package/dist/preparation.js +210 -92
  175. package/dist/presence.d.ts +58 -0
  176. package/dist/presence.d.ts.map +1 -0
  177. package/dist/presence.js +231 -0
  178. package/dist/queries.d.ts +2 -2
  179. package/dist/queries.d.ts.map +1 -1
  180. package/dist/queries.js +138 -80
  181. package/dist/query.d.ts +2 -3
  182. package/dist/query.d.ts.map +1 -1
  183. package/dist/questions.d.ts +3 -5
  184. package/dist/questions.d.ts.map +1 -1
  185. package/dist/questions.js +6 -7
  186. package/dist/queue.d.ts +40 -0
  187. package/dist/queue.d.ts.map +1 -0
  188. package/dist/queue.js +482 -0
  189. package/dist/reach.d.ts +15 -6
  190. package/dist/reach.d.ts.map +1 -1
  191. package/dist/reach.js +200 -40
  192. package/dist/react.d.ts +21 -1
  193. package/dist/react.d.ts.map +1 -1
  194. package/dist/react.js +33 -1
  195. package/dist/readiness.d.ts +23 -5
  196. package/dist/readiness.d.ts.map +1 -1
  197. package/dist/readiness.js +18 -10
  198. package/dist/reads.d.ts +5 -2
  199. package/dist/reads.d.ts.map +1 -1
  200. package/dist/reads.js +64 -11
  201. package/dist/recovery.d.ts +4 -1
  202. package/dist/recovery.d.ts.map +1 -1
  203. package/dist/recovery.js +31 -8
  204. package/dist/refresh.d.ts +1 -1
  205. package/dist/refresh.js +6 -6
  206. package/dist/refusal.d.ts.map +1 -1
  207. package/dist/refusal.js +5 -6
  208. package/dist/replica.d.ts +6 -16
  209. package/dist/replica.d.ts.map +1 -1
  210. package/dist/replica.js +20 -21
  211. package/dist/retried.d.ts +30 -0
  212. package/dist/retried.d.ts.map +1 -0
  213. package/dist/retried.js +72 -0
  214. package/dist/room-draft.d.ts +32 -9
  215. package/dist/room-draft.d.ts.map +1 -1
  216. package/dist/room-draft.js +282 -72
  217. package/dist/room-drafts.d.ts.map +1 -1
  218. package/dist/room-drafts.js +29 -23
  219. package/dist/room-list.d.ts +10 -0
  220. package/dist/room-list.d.ts.map +1 -0
  221. package/dist/room-list.js +47 -0
  222. package/dist/rows.d.ts +11 -3
  223. package/dist/rows.d.ts.map +1 -1
  224. package/dist/rows.js +28 -15
  225. package/dist/run-tables.d.ts +25 -0
  226. package/dist/run-tables.d.ts.map +1 -0
  227. package/dist/run-tables.js +98 -0
  228. package/dist/running.d.ts +5 -0
  229. package/dist/running.d.ts.map +1 -0
  230. package/dist/running.js +10 -0
  231. package/dist/runs.d.ts +27 -0
  232. package/dist/runs.d.ts.map +1 -0
  233. package/dist/runs.js +92 -0
  234. package/dist/runtime.d.ts +16 -21
  235. package/dist/runtime.d.ts.map +1 -1
  236. package/dist/save.d.ts +43 -86
  237. package/dist/save.d.ts.map +1 -1
  238. package/dist/save.js +337 -232
  239. package/dist/saves.d.ts +9 -45
  240. package/dist/saves.d.ts.map +1 -1
  241. package/dist/saves.js +208 -748
  242. package/dist/seed.d.ts.map +1 -1
  243. package/dist/seed.js +4 -5
  244. package/dist/selector.d.ts +3 -0
  245. package/dist/selector.d.ts.map +1 -0
  246. package/dist/selector.js +22 -0
  247. package/dist/shared.d.ts +1 -6
  248. package/dist/shared.d.ts.map +1 -1
  249. package/dist/shared.js +13 -95
  250. package/dist/shown.d.ts +10 -6
  251. package/dist/shown.d.ts.map +1 -1
  252. package/dist/shown.js +108 -75
  253. package/dist/socket/lanes.d.ts +12 -4
  254. package/dist/socket/lanes.d.ts.map +1 -1
  255. package/dist/socket/lanes.js +34 -8
  256. package/dist/socket/session.d.ts +4 -2
  257. package/dist/socket/session.d.ts.map +1 -1
  258. package/dist/socket/session.js +3 -0
  259. package/dist/socket.d.ts +7 -7
  260. package/dist/socket.d.ts.map +1 -1
  261. package/dist/socket.js +13 -16
  262. package/dist/source.d.ts +42 -7
  263. package/dist/source.d.ts.map +1 -1
  264. package/dist/source.js +81 -13
  265. package/dist/store/installs.d.ts +2 -2
  266. package/dist/store/installs.d.ts.map +1 -1
  267. package/dist/store/installs.js +10 -4
  268. package/dist/store/readiness.d.ts +5 -4
  269. package/dist/store/readiness.d.ts.map +1 -1
  270. package/dist/store/readiness.js +28 -12
  271. package/dist/store/records.d.ts +33 -11
  272. package/dist/store/records.d.ts.map +1 -1
  273. package/dist/store/records.js +94 -28
  274. package/dist/store/rooms-shown.d.ts +8 -0
  275. package/dist/store/rooms-shown.d.ts.map +1 -0
  276. package/dist/store/rooms-shown.js +13 -0
  277. package/dist/store/space.d.ts +1 -1
  278. package/dist/store/space.d.ts.map +1 -1
  279. package/dist/store/space.js +0 -2
  280. package/dist/store/watchers.js +1 -2
  281. package/dist/store.d.ts +26 -16
  282. package/dist/store.d.ts.map +1 -1
  283. package/dist/store.js +50 -18
  284. package/dist/stored.d.ts +42 -17
  285. package/dist/stored.d.ts.map +1 -1
  286. package/dist/stored.js +236 -66
  287. package/dist/surface.d.ts +21 -9
  288. package/dist/surface.d.ts.map +1 -1
  289. package/dist/surface.js +74 -38
  290. package/dist/sync.d.ts +4 -3
  291. package/dist/sync.d.ts.map +1 -1
  292. package/dist/sync.js +136 -110
  293. package/dist/tables.d.ts +43 -58
  294. package/dist/tables.d.ts.map +1 -1
  295. package/dist/tables.js +114 -334
  296. package/dist/tallies.d.ts.map +1 -1
  297. package/dist/tallies.js +8 -9
  298. package/dist/validation.d.ts +2 -0
  299. package/dist/validation.d.ts.map +1 -1
  300. package/dist/validation.js +51 -11
  301. package/dist/wire.d.ts +72 -12
  302. package/dist/wire.d.ts.map +1 -1
  303. package/dist/wire.js +31 -14
  304. package/package.json +4 -3
  305. package/dist/attempt.d.ts +0 -16
  306. package/dist/attempt.d.ts.map +0 -1
  307. package/dist/attempt.js +0 -70
  308. package/dist/binary.d.ts.map +0 -1
  309. package/dist/binary.js +0 -8
  310. package/dist/job.d.ts +0 -33
  311. package/dist/job.d.ts.map +0 -1
  312. package/dist/job.js +0 -54
  313. package/dist/log.d.ts +0 -6
  314. package/dist/log.d.ts.map +0 -1
  315. package/dist/log.js +0 -14
  316. package/dist/socket/rooms.d.ts +0 -43
  317. package/dist/socket/rooms.d.ts.map +0 -1
  318. package/dist/socket/rooms.js +0 -90
  319. package/dist/store/fences.d.ts +0 -16
  320. package/dist/store/fences.d.ts.map +0 -1
  321. package/dist/store/fences.js +0 -26
package/dist/saves.js CHANGED
@@ -1,440 +1,166 @@
1
- import { parseFrontmatter } from '@agentshouse/mdmodel';
2
- import { binaryRecord } from './binary.js';
3
- import { changeSet, mergeChangeSets } from './change-set.js';
4
- import { leaving as leavingIn, partnerOf, queuedFile, } from './change.js';
5
- import { available, composedOf } from './collection.js';
1
+ import { isImageType, parse } from '@agentshouse/mdmodel';
2
+ import { attachmentRecord } from './attachment.js';
3
+ import { changeSet } from './change-set.js';
4
+ import { queuedFile } from './change.js';
5
+ import { available, definitionsAt, typeAt } from './collection.js';
6
6
  import { runtimeError } from './failure.js';
7
7
  import { attachedFile } from './file.js';
8
8
  import { roomDraftRevision } from './identity.js';
9
- import { confirmedAgain } from './install.js';
10
9
  import { compositionFor } from './listing.js';
11
- import { absentBinary, attachAnswer, binaryAnswer, binaryLinkAnswer, failure, OFFLINE, UNCERTAIN, } from './outcome.js';
12
- import { sameBinary } from './overlay.js';
10
+ import { scoped } from './models.js';
11
+ import { absentAttachment, attachAnswer, attachmentAnswer, attachmentLinkAnswer, failure, linkedAnswer, OFFLINE, UNCERTAIN, } from './outcome.js';
12
+ import { sameAttachment } from './overlay.js';
13
13
  import { ancestors } from './paths.js';
14
- import { connectionNow, prepare } from './preparation.js';
15
- import { entryAt, landed, movedBy, overlayOf, replaying, slicing, slicingWith, standing, storedRecord, touchedBy, } from './replica.js';
16
- import { binaryBase, changedParts, changesOf, held, heldFile, joinedDraft, moveTarget, readSavedParts, returnedBy, returnedInto, withdrawnDrafts, } from './room-draft.js';
14
+ import { connectionNow } from './preparation.js';
15
+ import { append, sliceAt, withdrawable } from './queue.js';
16
+ import { entryAt, replaying, slicing, } from './replica.js';
17
+ import { attachmentBase, changesOf, held, heldFile, joinedOver, moveTarget, readSavedParts, } from './room-draft.js';
17
18
  import { refuse } from './refusal.js';
18
19
  import { visibleOf } from './room-drafts.js';
19
- import { documentKey } from './rows.js';
20
- import { buildBatch, buildMove, joined, limiting, queuedDocuments, requeuing, } from './save.js';
20
+ import { destination, planSave, } from './save.js';
21
21
  import { pendingShown } from './shown.js';
22
22
  import { paced, ROW_WEIGHT, stepped } from './turn.js';
23
23
  import { validatedNeighbourhood } from './validation.js';
24
- export function withdrawable(states) {
25
- return (batch) => {
26
- const state = states.get(batch.id);
27
- return state !== undefined && state.submission.state !== 'submitted' && !state.lost;
28
- };
29
- }
30
- export async function sliceAt(store, record, view, queue, extra = [], moved = []) {
31
- const local = await store.open();
32
- const needed = new Set([...touchedBy(queue), ...extra]);
33
- const movedPaths = [...new Set([...movedBy(queue, record.locator), ...moved])];
34
- if (movedPaths.length > 0) {
35
- for (const { path } of await local.referrers(record.key, view, movedPaths)) {
36
- needed.add(path);
37
- }
38
- }
39
- const paths = [...needed];
40
- return stepped(slicing(await local.entries(record.key, view, paths), paths));
41
- }
42
- export async function landedWhole(store, locator, batch, confirmedLayer, current) {
43
- if (!landed(batch, confirmedLayer, current))
44
- return false;
45
- const partner = partnerOf(batch, locator);
46
- if (partner === null)
47
- return true;
48
- const other = await store.replica(partner);
49
- const half = other?.queue.find((one) => one.id === batch.id);
50
- if (other === undefined || half === undefined)
51
- return false;
52
- return landed(half, await sliceAt(store, other.record, 'confirmed', [half]));
53
- }
54
- async function carriedBack(store, locator, unlanded, written) {
55
- const back = new Map();
56
- const taken = [];
57
- for (const batch of unlanded) {
58
- const between = batch.between;
59
- if (between === undefined)
60
- continue;
61
- const source = between.source.room;
62
- const destination = between.destination.room;
63
- const local = await store.open();
64
- const arrived = (await local.pending(destination, batch.id)).state?.drafts ?? [];
65
- for (const { path: to } of arrived) {
66
- const record = await store.draft(destination, to);
67
- const path = between.moves.find((move) => move.to === to)?.path;
68
- if (record === undefined || path === undefined)
69
- continue;
70
- const [into, key] = source === locator ? [written, path] : [back, documentKey(source, path)];
71
- const existing = into.get(key) ?? (await store.draft(source, path));
72
- taken.push({ locator: destination, path: to });
73
- into.set(key, {
74
- locator: source,
75
- path,
76
- revision: roomDraftRevision(),
77
- parts: returnedInto(existing?.parts, record.parts),
78
- returned: existing?.returned ?? null,
79
- });
80
- }
24
+ const FULL = { outcome: 'refused', code: 'durable-write', retryable: true };
25
+ async function savedRoom({ store, presence }, locator) {
26
+ const replica = await store.replica(locator);
27
+ if (replica === undefined || presence.lost(locator)) {
28
+ throw runtimeError('unknown-room', `Unknown Room ${locator}`);
81
29
  }
82
- const records = [...back.values()];
83
- const elsewhere = taken.filter((one) => one.locator !== locator);
84
- const rooms = new Set([...records, ...elsewhere].map((one) => one.locator));
85
- return {
86
- taken: taken.filter((one) => one.locator === locator).map(({ path }) => path),
87
- writes: [...rooms].map((room) => ({
88
- locator: room,
89
- roomDrafts: records.filter((record) => record.locator === room),
90
- consumedRoomDrafts: elsewhere.filter((one) => one.locator === room).map(({ path }) => path),
91
- })),
92
- changes: [...rooms].map((room) => changeSet(room, {
93
- drafts: [...records, ...elsewhere]
94
- .filter((one) => one.locator === room)
95
- .map(({ path }) => path),
96
- })),
97
- };
98
- }
99
- export function preparedAfter(runtime, locator, answer) {
100
- if (answer.indexed[locator] === false)
101
- prepare(runtime, [locator]);
30
+ return replica;
102
31
  }
103
- export function replayed(store, record, confirmedLayer, queue) {
104
- return stepped(replaying(confirmedLayer, queue, record.locator, store.composed(record)));
105
- }
106
- export async function overlayDiff(record, before, visible, touched) {
107
- const kept = before !== undefined && before.record.key === record.key ? before.overlaid : new Set();
108
- return {
109
- overlay: {
110
- set: await stepped(overlayOf(visible, touched)),
111
- cleared: [...kept].filter((path) => !touched.has(path)),
112
- },
113
- touched,
114
- };
115
- }
116
- export async function settle(runtime, local, locator, work, record, queue, settling = {}) {
117
- return together(runtime, local, [
118
- await settlement(runtime, local, locator, work, record, queue, settling),
119
- ]);
120
- }
121
- async function unpairedIn(store, locator, batch) {
122
- const { state } = await (await store.open()).pending(locator, batch.id);
123
- if (state === undefined)
124
- return false;
125
- return !leavingIn(batch, locator) || withdrawable(new Map([[batch.id, state]]))(batch);
126
- }
127
- export async function together(runtime, local, settlements) {
128
- const settled = new Set(settlements.map(({ locator }) => locator));
129
- const all = [...settlements];
130
- for (let wave = settlements; wave.length > 0;) {
131
- const partnered = new Map();
132
- for (const { locator, left } of wave) {
133
- for (const batch of left) {
134
- const partner = partnerOf(batch, locator);
135
- if (partner === null ||
136
- settled.has(partner) ||
137
- !(await unpairedIn(runtime.store, partner, batch))) {
138
- continue;
139
- }
140
- partnered.set(partner, [...(partnered.get(partner) ?? []), batch]);
32
+ export function saveRoomDrafts(runtime, locator, named, writtenBy) {
33
+ const { store } = runtime;
34
+ return store.exclusive(async () => {
35
+ if (store.space.full())
36
+ return FULL;
37
+ const replica = await savedRoom(runtime, locator);
38
+ const drafts = new Map((await store.drafts(locator, named.map(({ path }) => path))).map((record) => [record.path, record]));
39
+ const saved = [];
40
+ for (const { path, revision } of named) {
41
+ const record = drafts.get(path);
42
+ if (record === undefined || record.revision !== revision) {
43
+ return { outcome: 'refused', code: 'stale', retryable: false, file: path };
141
44
  }
45
+ if (!saved.some((draft) => draft.path === path))
46
+ saved.push({ path, parts: record.parts });
142
47
  }
143
- const partners = [];
144
- for (const [partner, batches] of partnered) {
145
- settled.add(partner);
146
- partners.push(await unpairing(runtime, local, partner, batches));
147
- }
148
- all.push(...partners);
149
- wave = partners;
150
- }
151
- const answer = await local.commit({
152
- rooms: all.flatMap(({ commit }) => commit.rooms),
153
- writes: all.flatMap(({ commit }) => commit.writes),
48
+ const result = await loaded(runtime, locator, replica, saved, new Set(saved.map(({ path }) => path)), [], writtenBy);
49
+ if (result.outcome !== 'refused' || result.code !== 'changed-underneath')
50
+ return result;
51
+ return joinedUnderneath(runtime, locator, saved.map(({ path }) => drafts.get(path)), result);
154
52
  });
155
- return mergeChangeSets(all.map((one) => one.apply(answer)));
156
- }
157
- export async function settlement(runtime, local, locator, work, record, queue, settling = {}) {
158
- const { store, journal, localSaves } = runtime;
159
- const before = work.replica;
160
- const view = settling.view ?? 'confirmed';
161
- const previousQueue = work.queue;
162
- const overrides = settling.changes;
163
- const read = await sliceAt(store, record, view, queue, [
164
- ...(before !== undefined && before.record.key === record.key ? before.overlaid : []),
165
- ...(overrides?.set.map(({ path }) => path) ?? []),
166
- ...(overrides?.removed ?? []),
167
- ]);
168
- const confirmedLayer = overrides === undefined
169
- ? read
170
- : await stepped(slicingWith(read, overrides.set, overrides.removed));
171
- const composition = store.composed(record);
172
- const shown = queue.filter((batch) => {
173
- const held = store.landed.of(locator, batch.id);
174
- return (held !== undefined &&
175
- Object.entries(held).some(([path, revision]) => confirmedLayer.revisions[path] !== revision));
176
- });
177
- const unshown = queue.filter((batch) => !shown.includes(batch));
178
- const { withdrawn, kept } = await stepped(standing(confirmedLayer, unshown, withdrawable(work.states), localSaves, locator, composition));
179
- const founded = kept.filter((batch) => !unshown.includes(batch));
180
- const queueChanged = kept.length !== previousQueue.length || founded.length > 0;
181
- const unqueued = shown.map((batch) => ({ batch, landed: true }));
182
- for (const batch of withdrawn) {
183
- unqueued.push({ batch, landed: await landedWhole(store, locator, batch, confirmedLayer) });
184
- }
185
- const returning = [
186
- ...[...unqueued].reverse().map(({ batch, landed: held }) => ({
187
- batch,
188
- returned: localSaves || held ? null : returnedBy('withdrawn'),
189
- })),
190
- ...(settling.leaving ?? []),
191
- ];
192
- const written = new Map();
193
- for (const { batch, returned: reason } of returning) {
194
- if (reason === null || batch.between?.destination.room === locator)
195
- continue;
196
- for (const saved of work.states.get(batch.id)?.drafts ?? []) {
197
- const existing = written.get(saved.path) ?? (await store.draft(locator, saved.path));
198
- written.set(saved.path, {
199
- locator,
200
- path: saved.path,
201
- revision: roomDraftRevision(),
202
- parts: returnedInto(existing?.parts, saved.parts),
203
- returned: reason,
204
- });
205
- }
206
- }
207
- const carried = await carriedBack(store, locator, [
208
- ...[...unqueued].reverse().flatMap(({ batch, landed: held }) => (held ? [] : [batch])),
209
- ...(settling.leaving ?? []).flatMap(({ batch, returned }) => returned === null ? [] : [batch]),
210
- ], written);
211
- const replayedLayer = await replayed(store, record, confirmedLayer, kept);
212
- const { overlay } = await overlayDiff(record, before, replayedLayer.visible, replayedLayer.touched);
213
- const commit = {
214
- rooms: [
215
- {
216
- locator,
217
- key: record.key,
218
- record: storedRecord(record),
219
- roots: record.typedSelection?.roots ?? [],
220
- composed: composedOf(composition),
221
- ...settling.commit,
222
- ...(overrides === undefined
223
- ? {}
224
- : { confirmed: { set: overrides.set, removed: overrides.removed } }),
225
- overlay,
226
- },
227
- ],
228
- writes: [
229
- {
230
- locator,
231
- queue: kept,
232
- stored: previousQueue,
233
- founded,
234
- roomDrafts: [...written.values()],
235
- consumedRoomDrafts: carried.taken,
236
- },
237
- ...carried.writes,
238
- ],
239
- };
240
- const staying = new Set(kept.map((batch) => batch.id));
241
- return {
242
- locator,
243
- left: previousQueue.filter((batch) => !staying.has(batch.id)),
244
- commit,
245
- apply: (answer) => {
246
- for (const batch of previousQueue) {
247
- if (!staying.has(batch.id))
248
- store.landed.drop(locator, batch.id);
249
- }
250
- const drafts = [...written.keys(), ...carried.taken];
251
- for (const { batch, landed: held } of unqueued) {
252
- const outcome = localSaves ? 'dropped' : held ? 'landed' : 'withdrawn';
253
- journal.record(`outcome ${locator} ${batch.id} ${outcome}`);
254
- }
255
- const changed = answer.changed[locator];
256
- if (settling.commit?.published !== undefined ||
257
- settling.commit?.refreshed === true ||
258
- overrides !== undefined) {
259
- confirmedAgain(store, locator);
260
- }
261
- preparedAfter(runtime, locator, answer);
262
- return mergeChangeSets([
263
- changeSet(locator, {
264
- documents: changed === undefined ? [] : changed,
265
- room: settling.room,
266
- queue: queueChanged,
267
- drafts,
268
- }),
269
- ...carried.changes,
270
- ]);
271
- },
272
- };
273
- }
274
- export async function unpairing(runtime, local, locator, batches) {
275
- const { store, journal, localSaves, submitLater } = runtime;
276
- const ids = new Set(batches.map(({ id }) => id));
277
- const leaving = batches.map((batch) => ({
278
- batch,
279
- returned: !localSaves && leavingIn(batch, locator) ? returnedBy('withdrawn') : null,
280
- }));
281
- const outcome = localSaves ? 'dropped' : 'unpaired';
282
- const work = await store.work(locator);
283
- const current = work.replica;
284
- if (current !== undefined) {
285
- const settled = await settlement(runtime, local, locator, work, current.record, current.queue.filter((one) => !ids.has(one.id)), { leaving });
286
- return {
287
- ...settled,
288
- apply(answer) {
289
- for (const batch of batches)
290
- journal.record(`outcome ${locator} ${batch.id} ${outcome}`);
291
- const set = settled.apply(answer);
292
- submitLater(locator);
293
- return set;
294
- },
295
- };
296
- }
297
- const queue = work.queue.filter((one) => !ids.has(one.id));
298
- const written = new Map();
299
- for (const { batch, returned } of leaving) {
300
- if (returned === null)
301
- continue;
302
- for (const saved of work.states.get(batch.id)?.drafts ?? []) {
303
- written.set(saved.path, {
304
- locator,
305
- path: saved.path,
306
- revision: roomDraftRevision(),
307
- parts: returnedInto((written.get(saved.path) ?? (await store.draft(locator, saved.path)))?.parts, saved.parts),
308
- returned,
309
- });
310
- }
311
- }
312
- const carried = await carriedBack(store, locator, leaving.flatMap(({ batch, returned }) => (returned === null ? [] : [batch])), written);
313
- return {
314
- locator,
315
- left: batches,
316
- commit: {
317
- rooms: [],
318
- writes: [
319
- {
320
- locator,
321
- queue,
322
- stored: work.queue,
323
- roomDrafts: [...written.values()],
324
- consumedRoomDrafts: carried.taken,
325
- },
326
- ...carried.writes,
327
- ],
328
- },
329
- apply() {
330
- for (const batch of batches)
331
- journal.record(`outcome ${locator} ${batch.id} ${outcome}`);
332
- submitLater(locator);
333
- return mergeChangeSets([
334
- changeSet(locator, {
335
- queue: true,
336
- drafts: [...written.keys(), ...carried.taken],
337
- }),
338
- ...carried.changes,
339
- ]);
340
- },
341
- };
342
53
  }
343
- async function savedRoom(store, locator) {
344
- const local = await store.open();
345
- const replica = await store.replica(locator);
346
- if (replica === undefined || store.fences.has(locator)) {
347
- throw runtimeError('unknown-room', `Unknown Room ${locator}`);
348
- }
349
- return { local, replica };
54
+ async function joinedUnderneath({ store }, locator, records, refused) {
55
+ const visible = (await visibleOf(store, locator, records.map(({ path }) => path)));
56
+ const joined = records.flatMap((record) => {
57
+ const join = joinedOver(record.parts, record.marks, record.path, visible);
58
+ return join === null ? [] : [{ ...record, ...join, revision: roomDraftRevision() }];
59
+ });
60
+ if (joined.length === 0)
61
+ return refused;
62
+ await (await store.open()).commit({ rooms: [], writes: [{ locator, roomDrafts: joined }] });
63
+ await store.changed(changeSet(locator, { drafts: joined.map(({ path }) => path) }));
64
+ return refused;
350
65
  }
351
- export async function saveRoomDrafts(runtime, locator, named, writtenBy) {
66
+ export function saveParts(runtime, locator, named, writtenBy) {
352
67
  const { store } = runtime;
353
- const target = await savedRoom(store, locator);
354
- const drafts = new Map((await store.drafts(locator, named.map(({ path }) => path))).map((record) => [record.path, record]));
355
- const saved = [];
356
- for (const { path, revision } of named) {
357
- const record = drafts.get(path);
358
- if (record === undefined || record.revision !== revision) {
359
- return { outcome: 'refused', code: 'stale', retryable: false, file: path };
68
+ return store.exclusive(async () => {
69
+ const read = readSavedParts(named);
70
+ if (store.space.full())
71
+ return FULL;
72
+ const replica = await savedRoom(runtime, locator);
73
+ const saved = [];
74
+ const files = [];
75
+ const filed = read.filter(({ parts }) => parts.file !== undefined).map(({ path }) => path);
76
+ const visible = filed.length === 0 ? undefined : await visibleOf(store, locator, filed);
77
+ for (const { path, parts } of read) {
78
+ const file = parts.file === undefined
79
+ ? undefined
80
+ : await heldFile(parts.file.blob, parts.file.base === undefined ? attachmentBase(visible, path) : parts.file.base);
81
+ if (parts.file !== undefined && file !== undefined) {
82
+ files.push({ key: file.localId, blob: parts.file.blob });
83
+ }
84
+ saved.push({ path, parts: held(undefined, parts, file) });
360
85
  }
361
- if (!saved.some((draft) => draft.path === path))
362
- saved.push({ path, parts: record.parts });
363
- }
364
- return committed(runtime, locator, target, saved, new Set(saved.map(({ path }) => path)), writtenBy);
86
+ return loaded(runtime, locator, replica, saved, new Set(), files, writtenBy);
87
+ });
365
88
  }
366
- export async function saveParts(runtime, locator, named, writtenBy) {
89
+ async function unmodeledIn(runtime, record) {
90
+ const composition = compositionFor(runtime, record);
91
+ if (available(composition))
92
+ return false;
93
+ const local = await runtime.store.open();
94
+ const roots = record.declaration.typedSelection?.roots ?? [];
95
+ return local.typedWithin(record.key, 'visible', roots, false);
96
+ }
97
+ async function savingRoom(runtime, replica, changes, extra, drafted) {
367
98
  const { store } = runtime;
368
- const read = readSavedParts(named);
369
- const target = await savedRoom(store, locator);
370
- const saved = [];
371
- const files = [];
372
- const filed = read.filter(({ parts }) => parts.file !== undefined).map(({ path }) => path);
373
- const visible = filed.length === 0 ? undefined : await visibleOf(store, locator, filed);
374
- for (const { path, parts } of read) {
375
- const file = parts.file === undefined
376
- ? undefined
377
- : await heldFile(parts.file.blob, parts.file.base === undefined ? binaryBase(visible, path) : parts.file.base);
378
- if (parts.file !== undefined && file !== undefined) {
379
- files.push({ key: file.localId, blob: parts.file.blob });
380
- }
381
- saved.push({ path, parts: held(undefined, parts, file) });
382
- }
383
- return committed(runtime, locator, target, saved, new Set(), writtenBy, files);
384
- }
385
- async function carriedDrafts(store, locator, saved, consumed) {
386
- if (!saved.some(({ parts }) => parts.move !== undefined))
387
- return new Map();
388
- const holding = new Map((await store.drafts(locator)).map((record) => [record.path, record]));
389
- return new Map(saved.flatMap(({ path, parts }) => {
390
- const record = holding.get(path);
391
- if (parts.move === undefined || record === undefined || consumed.has(path))
392
- return [];
393
- const to = moveTarget(parts.move);
394
- if (to === path || holding.has(to))
395
- return [];
396
- return [[path, { ...record, path: to, revision: roomDraftRevision() }]];
397
- }));
398
- }
399
- async function savingIn(store, replica, changes, extra, leaving = []) {
400
- const record = replica.record;
99
+ const { record, queue, states } = replica;
401
100
  const local = await store.open();
402
101
  const paths = [
403
102
  ...extra,
404
103
  ...changes.flatMap((change) => change.kind === 'move' ? [change.path, change.to] : [change.path]),
405
104
  ];
406
- const moved = [
407
- ...leaving,
408
- ...changes.flatMap((change) => (change.kind === 'move' ? [change.path] : [])),
409
- ];
105
+ const moved = changes.flatMap((change) => (change.kind === 'move' ? [change.path] : []));
410
106
  const removed = changes.flatMap((change) => (change.kind === 'remove' ? [change.path] : []));
411
107
  const referring = removed.length === 0
412
108
  ? []
413
109
  : (await local.referrers(record.key, 'confirmed', removed)).map(({ path }) => path);
414
- const confirmedLayer = await sliceAt(store, record, 'confirmed', replica.queue, [...paths, ...paths.flatMap(ancestors), ...referring], moved);
415
- const { visible } = await replayed(store, record, confirmedLayer, replica.queue);
110
+ const confirmed = await sliceAt(store, record, 'confirmed', queue, [...paths, ...paths.flatMap(ancestors), ...referring], moved);
416
111
  const composition = store.composed(record);
112
+ const changeable = withdrawable(states);
417
113
  return {
418
- record,
419
- confirmed: confirmedLayer,
420
- visible,
421
- folders: new Set(await local.folders(record.key, 'visible', paths)),
422
- *visibleOver(queue) {
423
- return (yield* replaying(confirmedLayer, queue, record.locator, composition)).visible;
114
+ held: { replica, confirmed },
115
+ room: {
116
+ record,
117
+ rule: runtime.writeRule(record.declaration),
118
+ composition: compositionFor(runtime, record),
119
+ queue,
120
+ changeable: new Set(queue.filter(changeable).map(({ id }) => id)),
121
+ saved: new Map([...states].map(([id, state]) => [id, state.drafts])),
122
+ *replay(over) {
123
+ return (yield* replaying(confirmed, over, record.locator, composition)).visible;
124
+ },
125
+ folders: new Set(await local.folders(record.key, paths)),
126
+ modelled: !(await unmodeledIn(runtime, record)),
127
+ drafts: new Map(drafted.length === 0
128
+ ? []
129
+ : (await store.drafts(record.locator, drafted)).map((held) => [held.path, held])),
130
+ validate: validatorOf(runtime, record, confirmed),
424
131
  },
425
132
  };
426
133
  }
427
- async function unmodeledIn(runtime, record) {
428
- const composition = compositionFor(runtime, record);
429
- if (available(composition))
430
- return false;
431
- const local = await runtime.store.open();
432
- const roots = record.typedSelection?.roots ?? [];
433
- return local.typedWithin(record.key, 'visible', roots, false);
134
+ function targetsOf(saved) {
135
+ return saved.flatMap(({ parts }) => (parts.move === undefined ? [] : [moveTarget(parts.move)]));
136
+ }
137
+ async function loaded(runtime, locator, replica, saved, consumed, files, writtenBy) {
138
+ const { store } = runtime;
139
+ const localSaves = runtime.savesLocally(locator);
140
+ const into = destination(locator, saved);
141
+ const target = into === null ? undefined : await savedRoom(runtime, into);
142
+ const paths = saved.map(({ path }) => path);
143
+ const targets = targetsOf(saved);
144
+ const parts = saved.map(({ path, parts: held }) => changesOf(path, held));
145
+ const source = target === undefined
146
+ ? await savingRoom(runtime, replica, parts.flatMap(({ changes }) => changes), [...paths, ...parts.flatMap(({ bases }) => bases.map(({ path }) => path))], targets.length === 0 ? [] : [...paths, ...targets])
147
+ : await savingRoom(runtime, replica, paths.map((path) => ({ kind: 'remove', path })), paths, paths);
148
+ const arriving = target === undefined ? undefined : await savingRoom(runtime, target, [], targets, targets);
149
+ const { providerLimits } = await (await store.open()).facts();
150
+ const plan = await planSave({ saved, consumed, writtenBy, local: localSaves, providerLimits }, source.room, arriving?.room);
151
+ return append(runtime, {
152
+ plan,
153
+ files,
154
+ held: new Map([source, ...(arriving === undefined ? [] : [arriving])].map(({ room, held }) => [
155
+ room.record.locator,
156
+ held,
157
+ ])),
158
+ after: () => pendingShown(runtime, locator),
159
+ });
434
160
  }
435
161
  function textDiffers(left, right) {
436
162
  return ((left?.content ?? undefined) !== (right?.content ?? undefined) ||
437
- !sameBinary(left?.binary ?? undefined, right?.binary ?? undefined));
163
+ !sameAttachment(left?.binary ?? undefined, right?.binary ?? undefined));
438
164
  }
439
165
  function textOf(entry) {
440
166
  if (entry === null)
@@ -451,13 +177,16 @@ function lookupOf(local, key, view) {
451
177
  ]));
452
178
  };
453
179
  }
454
- function declaredOf(entry) {
180
+ function declaredOf(composition, path, entry) {
455
181
  if (entry.binary !== null)
456
182
  return { type: undefined, binary: true };
457
- const read = parseFrontmatter(entry.content ?? '');
458
- return { type: read.ok ? (read.frontmatter.type ?? 'any') : undefined, binary: false };
183
+ const content = entry.content ?? '';
184
+ return {
185
+ type: typeAt(composition, path, parse(content, path, definitionsAt(composition, path))),
186
+ binary: false,
187
+ };
459
188
  }
460
- function overriddenLookup(lookup, overrides) {
189
+ function overriddenLookup(composition, lookup, overrides) {
461
190
  return async (paths) => {
462
191
  const known = new Map(await lookup(paths.filter((path) => !overrides.has(path))));
463
192
  for (const path of paths) {
@@ -467,7 +196,7 @@ function overriddenLookup(lookup, overrides) {
467
196
  if (entry === null)
468
197
  known.delete(path);
469
198
  else
470
- known.set(path, declaredOf(entry));
199
+ known.set(path, declaredOf(composition, path, entry));
471
200
  }
472
201
  return known;
473
202
  };
@@ -488,10 +217,12 @@ function validatorOf(runtime, record, confirmedLayer) {
488
217
  if (textOf(was) !== textOf(now))
489
218
  changes.push({ path, was: textOf(was), now: textOf(now) });
490
219
  }
491
- return validatedNeighbourhood(changes, compositionFor(runtime, record), {
492
- lookup: overriddenLookup(lookupOf(local, record.key, 'confirmed'), overrides),
220
+ const composition = compositionFor(runtime, record);
221
+ return validatedNeighbourhood(changes, composition, {
222
+ lookup: overriddenLookup(composition, lookupOf(local, record.key, 'confirmed'), overrides),
493
223
  texts: textsOf(local, record.key, 'confirmed'),
494
224
  referrers: referrersOf(local, record.key, 'confirmed'),
225
+ holders: (sought) => local.holders(record.key, 'confirmed', sought),
495
226
  });
496
227
  };
497
228
  }
@@ -506,305 +237,6 @@ function referrersOf(local, key, view) {
506
237
  ...new Set((await local.referrers(key, view, targets)).map(({ path }) => path)),
507
238
  ];
508
239
  }
509
- async function sideOf(runtime, locator, replica, saving) {
510
- const record = replica.record;
511
- return {
512
- room: locator,
513
- handle: record.handle,
514
- baseRoomVersion: record.roomVersion,
515
- composition: compositionFor(runtime, record),
516
- operations: record.operations,
517
- providerOwnedPaths: record.providerOwnedPaths,
518
- visible: saving.visible,
519
- folders: saving.folders,
520
- queued: queuedDocuments(replica.queue),
521
- unmodeled: await unmodeledIn(runtime, record),
522
- validate: validatorOf(runtime, record, saving.confirmed),
523
- };
524
- }
525
- function movedInto(locator, saved) {
526
- const into = saved.find(({ parts }) => parts.move?.room !== undefined && parts.move.room !== locator);
527
- return into?.parts.move?.room ?? null;
528
- }
529
- async function saveCommit(store, local, files, rooms) {
530
- const commits = [];
531
- for (const { locator, saving, before, queue } of rooms) {
532
- const replayedLayer = await replayed(store, saving.record, saving.confirmed, queue);
533
- const diff = await overlayDiff(saving.record, before, replayedLayer.visible, replayedLayer.touched);
534
- commits.push({
535
- locator,
536
- key: saving.record.key,
537
- roots: saving.record.typedSelection?.roots ?? [],
538
- composed: composedOf(store.composed(saving.record)),
539
- overlay: diff.overlay,
540
- });
541
- }
542
- try {
543
- return await local.commit({
544
- rooms: commits,
545
- writes: rooms.map(({ write }) => write),
546
- files,
547
- whole: true,
548
- });
549
- }
550
- catch {
551
- return null;
552
- }
553
- }
554
- async function committedMove(runtime, locator, destination, { local, replica }, saved, consumed, writtenBy, files) {
555
- const { store, localSaves } = runtime;
556
- const mixed = saved.find(({ parts }) => Object.keys(parts).length !== 1 || parts.move?.room !== destination);
557
- if (mixed !== undefined) {
558
- return { outcome: 'refused', code: 'mixed-room-move', retryable: false, file: mixed.path };
559
- }
560
- const moves = saved.map(({ path, parts }) => ({ path, to: moveTarget(parts.move) }));
561
- const sourceSaving = await savingIn(store, replica, moves.map(({ path }) => ({ kind: 'remove', path })), saved.map(({ path }) => path), moves.map(({ path }) => path));
562
- const changed = saved.flatMap(({ path, parts }) => changedParts(path, parts, sourceSaving.visible));
563
- if (changed.length > 0)
564
- return { outcome: 'refused', code: 'changed-underneath', retryable: false, parts: changed };
565
- const target = await store.replica(destination);
566
- if (target === undefined || store.fences.has(destination)) {
567
- throw runtimeError('unknown-room', `Unknown Room ${destination}`);
568
- }
569
- const arriving = await savingIn(store, target, [], moves.map(({ to }) => to));
570
- const built = await buildMove({
571
- source: await sideOf(runtime, locator, replica, sourceSaving),
572
- destination: await sideOf(runtime, destination, target, arriving),
573
- moves,
574
- providerLimits: (await local.facts()).providerLimits,
575
- local: localSaves,
576
- ...(writtenBy === undefined ? {} : { writtenBy }),
577
- });
578
- if (built.kind === 'refused')
579
- return { outcome: 'refused', ...built.refusal };
580
- const id = built.leaving.id;
581
- const leavingDrafts = new Map((await store.drafts(locator, saved.map(({ path }) => path))).map((record) => [record.path, record]));
582
- const arrivingDrafts = new Set((await store.drafts(destination, moves.map(({ to }) => to))).map(({ path }) => path));
583
- const carrying = saved.flatMap(({ path, parts }) => {
584
- const record = leavingDrafts.get(path);
585
- const to = moveTarget(parts.move);
586
- if (record === undefined || consumed.has(path) || arrivingDrafts.has(to)) {
587
- return [];
588
- }
589
- const moved = {
590
- ...record,
591
- locator: destination,
592
- path: to,
593
- revision: roomDraftRevision(),
594
- };
595
- return [{ from: path, record: moved }];
596
- });
597
- const carried = carrying.map(({ record }) => record);
598
- const marked = carried.map(({ path }) => ({ path, parts: {} }));
599
- const left = [...consumed, ...carrying.map(({ from }) => from)];
600
- const leavingQueue = [...replica.queue, built.leaving];
601
- const arrivingQueue = [...target.queue, built.arriving];
602
- const answer = await saveCommit(store, local, files, [
603
- {
604
- locator,
605
- saving: sourceSaving,
606
- before: replica,
607
- queue: leavingQueue,
608
- write: {
609
- locator,
610
- queue: leavingQueue,
611
- stored: replica.queue,
612
- saved: new Map([[id, saved]]),
613
- consumedRoomDrafts: left,
614
- },
615
- },
616
- {
617
- locator: destination,
618
- saving: arriving,
619
- before: target,
620
- queue: arrivingQueue,
621
- write: {
622
- locator: destination,
623
- queue: arrivingQueue,
624
- stored: target.queue,
625
- saved: new Map([[id, marked]]),
626
- roomDrafts: carried,
627
- },
628
- },
629
- ]);
630
- if (answer === null)
631
- return { outcome: 'refused', code: 'durable-write', retryable: true };
632
- if (answer.fenced !== null) {
633
- throw runtimeError('unknown-room', `Unknown Room ${answer.fenced}`);
634
- }
635
- if (store.fences.has(locator) || store.fences.has(destination)) {
636
- throw runtimeError('unknown-room', `Unknown Room ${locator}`);
637
- }
638
- preparedAfter(runtime, locator, answer);
639
- preparedAfter(runtime, destination, answer);
640
- const shownNow = store.changed(mergeChangeSets([
641
- changeSet(locator, {
642
- documents: answer.changed[locator] ?? [],
643
- queue: true,
644
- drafts: left,
645
- }),
646
- changeSet(destination, {
647
- documents: answer.changed[destination] ?? [],
648
- queue: true,
649
- drafts: carried.map(({ path }) => path),
650
- }),
651
- ]));
652
- await Promise.all([shownNow, queuedSave(runtime, locator)]);
653
- return { outcome: 'saved', identifier: id };
654
- }
655
- function queuedSave(runtime, locator) {
656
- const shownNow = pendingShown(runtime);
657
- runtime.submitLater(locator);
658
- return shownNow;
659
- }
660
- async function committed(runtime, locator, target, saved, consumed, writtenBy, files = []) {
661
- const { store, localSaves } = runtime;
662
- if (store.space.full())
663
- return { outcome: 'refused', code: 'durable-write', retryable: true };
664
- const into = movedInto(locator, saved);
665
- if (into !== null) {
666
- return committedMove(runtime, locator, into, target, saved, consumed, writtenBy, files);
667
- }
668
- const { local, replica } = target;
669
- const { providerLimits } = await local.facts();
670
- const parts = saved.map(({ path, parts: held }) => changesOf(path, held));
671
- const changes = parts.flatMap(({ changes: made }) => made);
672
- const saving = await savingIn(store, replica, changes, [
673
- ...saved.map(({ path }) => path),
674
- ...parts.flatMap(({ bases }) => bases.map(({ path }) => path)),
675
- ]);
676
- const changed = saved.flatMap(({ path, parts: held }) => changedParts(path, held, saving.visible));
677
- if (changed.length > 0)
678
- return { outcome: 'refused', code: 'changed-underneath', retryable: false, parts: changed };
679
- const requeue = await stepped(requeuing(replica.queue, changes, saving.visible, withdrawable(replica.states), saving.visibleOver));
680
- if (requeue.kind === 'refused')
681
- return { outcome: 'refused', ...requeue.refusal };
682
- const foreign = [...requeue.withdrawn.keys()].some((origin) => {
683
- const writer = replica.queue.find((batch) => batch.id === origin)?.writtenBy;
684
- return writer?.app !== writtenBy?.app || writer?.release !== writtenBy?.release;
685
- });
686
- if (foreign) {
687
- return {
688
- outcome: 'refused',
689
- code: 'unknown-revision',
690
- retryable: false,
691
- file: [...requeue.queued].at(-1),
692
- };
693
- }
694
- const withdrawing = requeue.withdrawn.size > 0;
695
- const input = {
696
- local: localSaves,
697
- baseRoomVersion: replica.record.roomVersion,
698
- composition: compositionFor(runtime, replica.record),
699
- operations: replica.record.operations,
700
- providerOwnedPaths: replica.record.providerOwnedPaths,
701
- providerLimits,
702
- handle: replica.record.handle,
703
- visible: saving.visible,
704
- folders: saving.folders,
705
- changes,
706
- bases: parts.flatMap(({ bases }) => bases),
707
- queued: queuedDocuments(replica.queue),
708
- writtenBy,
709
- unmodeled: await unmodeledIn(runtime, replica.record),
710
- validate: validatorOf(runtime, replica.record, saving.confirmed),
711
- };
712
- const checked = withdrawing
713
- ? await buildBatch({ ...input, queued: new Set([...input.queued, ...requeue.queued]) })
714
- : null;
715
- if (checked?.kind === 'refused')
716
- return { outcome: 'refused', ...checked.refusal };
717
- const owners = [...requeue.owners].flatMap((origin) => {
718
- const batch = requeue.withdrawn.get(origin);
719
- return batch === undefined || batch === null ? [] : [{ origin, batch }];
720
- });
721
- if (owners.length > 1) {
722
- return {
723
- outcome: 'refused',
724
- code: 'unknown-revision',
725
- retryable: false,
726
- file: [...requeue.queued].at(-1),
727
- };
728
- }
729
- const built = !withdrawing
730
- ? await buildBatch(input)
731
- : requeue.changes.length === 0
732
- ? null
733
- : await buildBatch({
734
- ...input,
735
- visible: await stepped(saving.visibleOver(requeue.queue)),
736
- changes: requeue.changes,
737
- queued: queuedDocuments(requeue.queue),
738
- });
739
- if (built?.kind === 'refused')
740
- return { outcome: 'refused', ...built.refusal };
741
- const [owner] = owners;
742
- const join = built === null || owner === undefined ? null : joined(requeue.queue, owner.batch, built.batch);
743
- if (join?.kind === 'refused')
744
- return { outcome: 'refused', ...join.refusal };
745
- const withdrawn = new Map(requeue.withdrawn);
746
- if (join !== null && owner !== undefined)
747
- withdrawn.set(owner.origin, join.batch);
748
- const drafted = new Map();
749
- for (const [origin, replaced] of withdrawn) {
750
- if (replaced === null)
751
- continue;
752
- const carried = withdrawnDrafts(replica.states.get(origin)?.drafts ?? [], changes);
753
- drafted.set(replaced.id, replaced === join?.batch
754
- ? [
755
- ...carried.map((held) => joinedDraft(held, saved)),
756
- ...saved.filter((draft) => !carried.some((held) => held.path === draft.path)),
757
- ]
758
- : carried);
759
- }
760
- if (built !== null && join === null)
761
- drafted.set(built.batch.id, saved);
762
- const batches = join !== null ? join.queue : built === null ? requeue.queue : [...requeue.queue, built.batch];
763
- for (const replaced of withdrawn.values()) {
764
- if (replaced === null || !batches.includes(replaced))
765
- continue;
766
- const limited = await stepped(limiting(batches, replaced, providerLimits, saving.visibleOver));
767
- if (limited !== null)
768
- return { outcome: 'refused', ...limited };
769
- }
770
- const carried = await carriedDrafts(store, locator, saved, consumed);
771
- const left = [...consumed, ...carried.keys()];
772
- const arrived = [...carried.values()];
773
- const answer = await saveCommit(store, local, files, [
774
- {
775
- locator,
776
- saving,
777
- before: replica,
778
- queue: batches,
779
- write: {
780
- locator,
781
- queue: batches,
782
- stored: replica.queue,
783
- saved: drafted,
784
- consumedRoomDrafts: left,
785
- roomDrafts: arrived,
786
- },
787
- },
788
- ]);
789
- if (answer === null)
790
- return { outcome: 'refused', code: 'durable-write', retryable: true };
791
- if (answer.fenced !== null) {
792
- throw runtimeError('unknown-room', `Unknown Room ${answer.fenced}`);
793
- }
794
- if (store.fences.has(locator))
795
- throw runtimeError('unknown-room', `Unknown Room ${locator}`);
796
- preparedAfter(runtime, locator, answer);
797
- const shownNow = store.changed(changeSet(locator, {
798
- documents: answer.changed[locator] ?? [],
799
- queue: true,
800
- drafts: [...left, ...arrived.map(({ path }) => path)],
801
- }));
802
- await Promise.all([shownNow, queuedSave(runtime, locator)]);
803
- const identifier = join?.batch.id ??
804
- built?.batch.id ??
805
- [...requeue.withdrawn].map(([origin, replaced]) => replaced?.id ?? origin).at(-1);
806
- return { outcome: 'saved', identifier };
807
- }
808
240
  async function queuedFacts(store, locator, path, localId) {
809
241
  for (const batch of (await store.replica(locator))?.queue ?? []) {
810
242
  const change = batch.changes[queuedFile(batch, path, localId)];
@@ -820,8 +252,8 @@ export function batchFile(store, batch) {
820
252
  return (await store.open()).file(localId, change?.kind === 'binary' ? change.mediaType : '');
821
253
  };
822
254
  }
823
- async function transferBinary(runtime, request, transfer, answer) {
824
- const { store, socket, journal } = runtime;
255
+ async function transferAttachment(runtime, request, transfer, answer) {
256
+ const { store, socket, presence } = runtime;
825
257
  const { session } = socket;
826
258
  if (socket.closed() || session.now().refusal !== null)
827
259
  return UNCERTAIN;
@@ -837,41 +269,38 @@ async function transferBinary(runtime, request, transfer, answer) {
837
269
  const { closed, authorization, refusal } = session.now();
838
270
  if (closed || authorization === undefined || refusal !== null)
839
271
  return UNCERTAIN;
840
- const since = store.fences.count();
841
- journal.record(`transfer binary ${request.locator} ${request.path}`);
272
+ const since = presence.losses();
842
273
  try {
843
274
  const result = await transfer(authorization);
844
275
  const settled = result;
845
- journal.record(`outcome binary ${settled.kind}`);
846
- if (store.fences.since(request.locator, since))
276
+ if (request.locator !== null && presence.lostSince(request.locator, since))
847
277
  return failure({ kind: 'room-not-readable', locator: request.locator });
848
278
  if (settled.kind === 'scoped-refusal') {
849
279
  const room = await store.record(settled.locator);
850
280
  if (room !== undefined)
851
- await runtime.scoped(settled, room, await store.open());
281
+ await scoped(runtime, settled, room.locator, room.declaration);
852
282
  }
853
283
  if (settled.kind === 'revoked-authorization')
854
284
  await refuse(runtime, 'revoked-authorization');
855
285
  return answer(result);
856
286
  }
857
287
  catch {
858
- journal.record('outcome binary transport-uncertainty');
859
288
  return UNCERTAIN;
860
289
  }
861
290
  }
862
- function fetchBinary(runtime, request, name) {
291
+ function fetchAttachment(runtime, request, name) {
863
292
  const { store, socket } = runtime;
864
- return transferBinary(runtime, request, (authorization) => store.opened.fetch(name, () => socket.binary(authorization, request)), binaryAnswer);
293
+ return transferAttachment(runtime, request, (authorization) => store.opened.fetch(name, () => socket.binary(authorization, request)), attachmentAnswer);
865
294
  }
866
- async function readBinary(runtime, request, name) {
295
+ async function readAttachment(runtime, request, name) {
867
296
  if (runtime.socket.closed())
868
297
  return UNCERTAIN;
869
298
  const held = await runtime.store.opened.find(name);
870
299
  if (held !== null)
871
300
  return held;
872
- return fetchBinary(runtime, request, name);
301
+ return fetchAttachment(runtime, request, name);
873
302
  }
874
- async function binaryPath(store, locator, path, revision) {
303
+ async function attachmentPath(store, locator, path, revision) {
875
304
  if (revision !== undefined)
876
305
  return { kind: 'path', locator, path, revision };
877
306
  const replica = await store.replica(locator);
@@ -884,7 +313,7 @@ async function binaryPath(store, locator, path, revision) {
884
313
  return null;
885
314
  if (held.binary.state === 'pending')
886
315
  return { kind: 'pending', localId: held.binary.localId };
887
- const record = binaryRecord(path, held.binary, held.revision ?? undefined);
316
+ const record = attachmentRecord(path, held.binary, held.revision ?? undefined);
888
317
  if (record.state !== 'accepted')
889
318
  return null;
890
319
  const queued = replica.queue.flatMap((batch) => batch.changes);
@@ -912,17 +341,17 @@ async function binaryPath(store, locator, path, revision) {
912
341
  revision: record.revision,
913
342
  };
914
343
  }
915
- async function askedBinary({ store, socket }, locator, path, revision) {
344
+ async function askedAttachment({ store, socket }, locator, path, revision) {
916
345
  await socket.ready;
917
346
  const drafted = (await store.draft(locator, path))?.parts.file;
918
347
  return drafted !== undefined && drafted.localId === revision
919
348
  ? { kind: 'pending', localId: revision }
920
- : binaryPath(store, locator, path, revision);
349
+ : attachmentPath(store, locator, path, revision);
921
350
  }
922
- async function pendingBinary(store, locator, path, localId) {
351
+ async function pendingAttachment(store, locator, path, localId) {
923
352
  const facts = await queuedFacts(store, locator, path, localId);
924
353
  return facts === null
925
- ? absentBinary(path)
354
+ ? absentAttachment(path)
926
355
  : {
927
356
  kind: 'binary',
928
357
  file: localId,
@@ -930,13 +359,13 @@ async function pendingBinary(store, locator, path, localId) {
930
359
  mediaType: facts.mediaType,
931
360
  };
932
361
  }
933
- async function readBinaryPath(runtime, locator, path, revision) {
934
- const asked = await askedBinary(runtime, locator, path, revision);
362
+ async function readAttachmentPath(runtime, locator, path, revision) {
363
+ const asked = await askedAttachment(runtime, locator, path, revision);
935
364
  if (asked === null)
936
- return absentBinary(path);
365
+ return absentAttachment(path);
937
366
  if (asked.kind === 'pending')
938
- return pendingBinary(runtime.store, locator, path, asked.localId);
939
- return readBinary(runtime, asked, { locator, path: asked.path, revision: asked.revision });
367
+ return pendingAttachment(runtime.store, locator, path, asked.localId);
368
+ return readAttachment(runtime, asked, { locator, path: asked.path, revision: asked.revision });
940
369
  }
941
370
  async function heldMediaType(store, locator, path) {
942
371
  const replica = await store.record(locator);
@@ -944,23 +373,42 @@ async function heldMediaType(store, locator, path) {
944
373
  return held === undefined ? store.attached.of(locator, path)?.mediaType : held.binary?.mediaType;
945
374
  }
946
375
  function linkOf(runtime, asked, held) {
947
- return transferBinary(runtime, asked, (authorization) => runtime.socket.link(authorization, asked), (result) => binaryLinkAnswer(result, held));
376
+ return transferAttachment(runtime, asked, (authorization) => runtime.socket.link(authorization, asked), (result) => attachmentLinkAnswer(result, held));
948
377
  }
949
- async function linkBinaryPath(runtime, locator, path, revision) {
378
+ async function linkAttachmentPath(runtime, locator, path, revision) {
950
379
  const { store, socket } = runtime;
951
380
  await socket.ready;
952
- const asked = await binaryPath(store, locator, path, revision);
381
+ const asked = await attachmentPath(store, locator, path, revision);
953
382
  if (asked === null || asked.kind === 'pending')
954
- return absentBinary(path);
383
+ return absentAttachment(path);
955
384
  return linkOf(runtime, asked, revision === undefined ? await heldMediaType(store, locator, path) : undefined);
956
385
  }
957
- async function showBinaryPath(runtime, locator, path, revision) {
386
+ function shownImage(runtime, asked, name) {
387
+ const { store, socket } = runtime;
388
+ return new Promise((answer) => {
389
+ void transferAttachment(runtime, asked, (authorization) => store.opened.fetch(name, async () => {
390
+ const read = await socket.binary(authorization, asked);
391
+ const copies = read.kind === 'binary' ? (read.copies ?? []) : [];
392
+ if (read.kind === 'binary' && read.url !== undefined && copies.length > 0) {
393
+ answer({
394
+ kind: 'link',
395
+ url: read.url,
396
+ name: asked.path.slice(asked.path.lastIndexOf('/') + 1),
397
+ mediaType: read.mediaType,
398
+ copies,
399
+ });
400
+ }
401
+ return read;
402
+ }), attachmentAnswer).then(answer);
403
+ });
404
+ }
405
+ async function showAttachmentPath(runtime, locator, path, revision) {
958
406
  const { store } = runtime;
959
- const asked = await askedBinary(runtime, locator, path, revision);
407
+ const asked = await askedAttachment(runtime, locator, path, revision);
960
408
  if (asked === null)
961
- return absentBinary(path);
409
+ return absentAttachment(path);
962
410
  if (asked.kind === 'pending')
963
- return pendingBinary(store, locator, path, asked.localId);
411
+ return pendingAttachment(store, locator, path, asked.localId);
964
412
  if (runtime.socket.closed())
965
413
  return UNCERTAIN;
966
414
  const name = { locator, path: asked.path, revision: asked.revision };
@@ -968,11 +416,12 @@ async function showBinaryPath(runtime, locator, path, revision) {
968
416
  if (kept !== null)
969
417
  return kept;
970
418
  const mediaType = await heldMediaType(store, locator, path);
971
- if (mediaType?.startsWith('image/') === true)
972
- return fetchBinary(runtime, asked, name);
973
- return linkOf(runtime, asked, revision === undefined ? mediaType : undefined);
419
+ if (mediaType !== undefined && isImageType(mediaType))
420
+ return shownImage(runtime, asked, name);
421
+ const linked = await linkOf(runtime, asked, revision === undefined ? mediaType : undefined);
422
+ return linked.kind === 'link' ? { ...linked, copies: [] } : linked;
974
423
  }
975
- async function attachBinary(runtime, locator, file) {
424
+ async function attachFile(runtime, locator, file, answer) {
976
425
  const { store, socket } = runtime;
977
426
  await socket.ready;
978
427
  await socket.firstDiscovery;
@@ -982,23 +431,34 @@ async function attachBinary(runtime, locator, file) {
982
431
  socket.session.now().refusal !== null)
983
432
  return OFFLINE;
984
433
  const request = await attachedFile(locator, file);
985
- return transferBinary(runtime, { locator, path: file.name }, async (held) => {
434
+ return transferAttachment(runtime, { locator }, async (held) => {
986
435
  const result = await socket.attach(held, request);
987
- if (result.kind === 'attached') {
436
+ if (result.kind === 'attached' && locator !== null) {
988
437
  store.attached.hold(locator, result.path, {
989
438
  revision: result.revision,
990
439
  mediaType: request.mediaType,
991
440
  });
992
441
  }
993
442
  return result;
994
- }, attachAnswer);
443
+ }, answer);
444
+ }
445
+ async function keyedAttachment(runtime, link) {
446
+ await runtime.socket.ready;
447
+ const asked = { kind: 'key', link };
448
+ return transferAttachment(runtime, { locator: null }, (authorization) => runtime.socket.link(authorization, asked), (result) => attachmentLinkAnswer(result));
449
+ }
450
+ export function conversationFiles(runtime) {
451
+ return {
452
+ attach: (file) => attachFile(runtime, null, file, linkedAnswer),
453
+ attachment: (link) => keyedAttachment(runtime, link),
454
+ };
995
455
  }
996
- export function binaryFileSurface(runtime) {
456
+ export function attachmentSurface(runtime) {
997
457
  return {
998
458
  part: runtime.store.part,
999
- read: (room, path, revision) => readBinaryPath(runtime, room, path, revision),
1000
- link: (room, path, revision) => linkBinaryPath(runtime, room, path, revision),
1001
- show: (room, path, revision) => showBinaryPath(runtime, room, path, revision),
1002
- attach: (room, file) => attachBinary(runtime, room, file),
459
+ read: (room, path, revision) => readAttachmentPath(runtime, room, path, revision),
460
+ link: (room, path, revision) => linkAttachmentPath(runtime, room, path, revision),
461
+ show: (room, path, revision) => showAttachmentPath(runtime, room, path, revision),
462
+ attach: (room, file) => attachFile(runtime, room, file, attachAnswer),
1003
463
  };
1004
464
  }