@agentshouse/mdruntime 0.1.0-cc5745cd9af96 → 0.1.0-ccbe92df1c4f6

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 (188) hide show
  1. package/AGENTS.md +96 -78
  2. package/README.md +9 -8
  3. package/dist/adapter.d.ts +40 -32
  4. package/dist/adapter.d.ts.map +1 -1
  5. package/dist/attached-model.d.ts +4 -1
  6. package/dist/attached-model.d.ts.map +1 -1
  7. package/dist/attached-model.js +13 -3
  8. package/dist/binary.d.ts +0 -5
  9. package/dist/binary.d.ts.map +1 -1
  10. package/dist/binary.js +1 -1
  11. package/dist/bootstrap.d.ts +24 -6
  12. package/dist/bootstrap.d.ts.map +1 -1
  13. package/dist/bootstrap.js +148 -82
  14. package/dist/chain.d.ts +11 -0
  15. package/dist/chain.d.ts.map +1 -0
  16. package/dist/chain.js +64 -0
  17. package/dist/change-set.d.ts +6 -16
  18. package/dist/change-set.d.ts.map +1 -1
  19. package/dist/change-set.js +11 -94
  20. package/dist/change.d.ts +31 -1
  21. package/dist/change.d.ts.map +1 -1
  22. package/dist/change.js +10 -1
  23. package/dist/chat/house.d.ts +25 -0
  24. package/dist/chat/house.d.ts.map +1 -0
  25. package/dist/chat/house.js +38 -0
  26. package/dist/chat/input.d.ts +3 -1
  27. package/dist/chat/input.d.ts.map +1 -1
  28. package/dist/chat/input.js +11 -18
  29. package/dist/chat/list.d.ts.map +1 -1
  30. package/dist/chat/list.js +1 -1
  31. package/dist/chat/markdown.d.ts +1 -2
  32. package/dist/chat/markdown.d.ts.map +1 -1
  33. package/dist/chat/markdown.js +2 -19
  34. package/dist/chat/message.d.ts.map +1 -1
  35. package/dist/chat/message.js +63 -11
  36. package/dist/chat/messages.d.ts +12 -1
  37. package/dist/chat/messages.d.ts.map +1 -1
  38. package/dist/chat/messages.js +36 -13
  39. package/dist/chat/name.d.ts +1 -0
  40. package/dist/chat/name.d.ts.map +1 -1
  41. package/dist/chat/name.js +1 -1
  42. package/dist/chat/opened.d.ts +1 -0
  43. package/dist/chat/opened.d.ts.map +1 -1
  44. package/dist/chat/opened.js +2 -0
  45. package/dist/chat/overlay.d.ts.map +1 -1
  46. package/dist/chat/overlay.js +1 -5
  47. package/dist/chat/parts.d.ts +1 -0
  48. package/dist/chat/parts.d.ts.map +1 -1
  49. package/dist/chat/parts.js +3 -2
  50. package/dist/chat/provider.d.ts +7 -1
  51. package/dist/chat/provider.d.ts.map +1 -1
  52. package/dist/chat/provider.js +75 -78
  53. package/dist/chat/ready.d.ts +4 -1
  54. package/dist/chat/ready.d.ts.map +1 -1
  55. package/dist/chat/ready.js +7 -5
  56. package/dist/chat/room-file.d.ts +8 -0
  57. package/dist/chat/room-file.d.ts.map +1 -0
  58. package/dist/chat/room-file.js +72 -0
  59. package/dist/chat/style.d.ts.map +1 -1
  60. package/dist/chat/style.js +5 -0
  61. package/dist/chat.d.ts +1 -0
  62. package/dist/chat.d.ts.map +1 -1
  63. package/dist/client.d.ts +6 -3
  64. package/dist/client.d.ts.map +1 -1
  65. package/dist/client.js +28 -2
  66. package/dist/collection.d.ts +6 -20
  67. package/dist/collection.d.ts.map +1 -1
  68. package/dist/collection.js +30 -352
  69. package/dist/compile.d.ts +16 -0
  70. package/dist/compile.d.ts.map +1 -0
  71. package/dist/compile.js +721 -0
  72. package/dist/connection.d.ts +13 -8
  73. package/dist/connection.d.ts.map +1 -1
  74. package/dist/connection.js +2179 -817
  75. package/dist/conversation.d.ts +5 -3
  76. package/dist/conversation.d.ts.map +1 -1
  77. package/dist/conversation.js +84 -65
  78. package/dist/digest.d.ts +7 -0
  79. package/dist/digest.d.ts.map +1 -0
  80. package/dist/digest.js +113 -0
  81. package/dist/durability.d.ts +3 -5
  82. package/dist/durability.d.ts.map +1 -1
  83. package/dist/durability.js +5 -0
  84. package/dist/entry.d.ts +3 -1
  85. package/dist/entry.d.ts.map +1 -1
  86. package/dist/entry.js +18 -24
  87. package/dist/file.d.ts +2 -10
  88. package/dist/file.d.ts.map +1 -1
  89. package/dist/file.js +3 -120
  90. package/dist/fulltext.d.ts +27 -0
  91. package/dist/fulltext.d.ts.map +1 -0
  92. package/dist/fulltext.js +368 -0
  93. package/dist/host.d.ts +4 -4
  94. package/dist/host.d.ts.map +1 -1
  95. package/dist/host.js +16 -8
  96. package/dist/identity.d.ts +0 -1
  97. package/dist/identity.d.ts.map +1 -1
  98. package/dist/identity.js +0 -3
  99. package/dist/index.d.ts +12 -9
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +4 -1
  102. package/dist/live.d.ts +22 -0
  103. package/dist/live.d.ts.map +1 -0
  104. package/dist/live.js +123 -0
  105. package/dist/memory.d.ts +1 -0
  106. package/dist/memory.d.ts.map +1 -1
  107. package/dist/memory.js +20 -15
  108. package/dist/messages.d.ts +28 -0
  109. package/dist/messages.d.ts.map +1 -0
  110. package/dist/messages.js +90 -0
  111. package/dist/name.d.ts +4 -0
  112. package/dist/name.d.ts.map +1 -0
  113. package/dist/name.js +122 -0
  114. package/dist/observation.d.ts +12 -0
  115. package/dist/observation.d.ts.map +1 -1
  116. package/dist/observation.js +84 -0
  117. package/dist/opened.d.ts +22 -0
  118. package/dist/opened.d.ts.map +1 -0
  119. package/dist/opened.js +107 -0
  120. package/dist/outcome.d.ts +28 -4
  121. package/dist/outcome.d.ts.map +1 -1
  122. package/dist/outcome.js +22 -0
  123. package/dist/overlay.d.ts +1 -4
  124. package/dist/overlay.d.ts.map +1 -1
  125. package/dist/overlay.js +22 -148
  126. package/dist/query.d.ts +5 -1
  127. package/dist/query.d.ts.map +1 -1
  128. package/dist/query.js +13 -1
  129. package/dist/reach.d.ts +5 -3
  130. package/dist/reach.d.ts.map +1 -1
  131. package/dist/reach.js +149 -61
  132. package/dist/readiness.d.ts +19 -9
  133. package/dist/readiness.d.ts.map +1 -1
  134. package/dist/readiness.js +2 -2
  135. package/dist/reads.d.ts.map +1 -1
  136. package/dist/reads.js +4 -2
  137. package/dist/recovery.d.ts +2 -2
  138. package/dist/recovery.d.ts.map +1 -1
  139. package/dist/recovery.js +8 -7
  140. package/dist/refresh.d.ts +15 -14
  141. package/dist/refresh.d.ts.map +1 -1
  142. package/dist/refresh.js +112 -70
  143. package/dist/replica.d.ts +57 -39
  144. package/dist/replica.d.ts.map +1 -1
  145. package/dist/replica.js +275 -195
  146. package/dist/room-draft.d.ts +3 -1
  147. package/dist/room-draft.d.ts.map +1 -1
  148. package/dist/room-draft.js +21 -13
  149. package/dist/rows.d.ts +29 -31
  150. package/dist/rows.d.ts.map +1 -1
  151. package/dist/rows.js +113 -69
  152. package/dist/save.d.ts +49 -14
  153. package/dist/save.d.ts.map +1 -1
  154. package/dist/save.js +352 -98
  155. package/dist/search.d.ts +11 -43
  156. package/dist/search.d.ts.map +1 -1
  157. package/dist/search.js +0 -213
  158. package/dist/shared.d.ts +4 -3
  159. package/dist/shared.d.ts.map +1 -1
  160. package/dist/shared.js +67 -34
  161. package/dist/store.d.ts +87 -94
  162. package/dist/store.d.ts.map +1 -1
  163. package/dist/store.js +314 -720
  164. package/dist/stored.d.ts +145 -0
  165. package/dist/stored.d.ts.map +1 -0
  166. package/dist/stored.js +567 -0
  167. package/dist/tables.d.ts +344 -0
  168. package/dist/tables.d.ts.map +1 -0
  169. package/dist/tables.js +580 -0
  170. package/dist/turn.d.ts +1 -1
  171. package/dist/turn.d.ts.map +1 -1
  172. package/dist/turn.js +31 -20
  173. package/dist/validation.d.ts +30 -0
  174. package/dist/validation.d.ts.map +1 -0
  175. package/dist/validation.js +162 -0
  176. package/dist/windows.d.ts +2 -6
  177. package/dist/windows.d.ts.map +1 -1
  178. package/dist/windows.js +30 -34
  179. package/dist/wire.d.ts +13 -1
  180. package/dist/wire.d.ts.map +1 -1
  181. package/dist/wire.js +4 -1
  182. package/dist/words.d.ts +19 -0
  183. package/dist/words.d.ts.map +1 -0
  184. package/dist/words.js +150 -0
  185. package/package.json +11 -5
  186. package/dist/read-side.d.ts +0 -27
  187. package/dist/read-side.d.ts.map +0 -1
  188. package/dist/read-side.js +0 -826
package/dist/store.js CHANGED
@@ -1,816 +1,410 @@
1
- import { sameBinary, sameChange } from './overlay.js';
2
- import { differences } from './shared.js';
3
- import { inUnits, ROW_WEIGHT, stepped } from './turn.js';
4
- import { precedes } from './windows.js';
5
- const DATABASE = 'mdruntime';
6
- const AUTHORED = 'mdruntime-authored';
7
- const FENCES = 'fences';
8
- const ROOMS = 'rooms';
9
- const DOCUMENTS = 'documents';
10
- const BINARY_FILES = 'binaryFiles';
11
- const TRANSFERS = 'transfers';
12
- const RECEIVED = 'received';
13
- const RECEIVED_PARTS = 'receivedParts';
14
- const PENDING_CHANGES = 'pendingChanges';
15
- const DECLARATIONS = 'declarations';
16
- const ROOM_DRAFTS = 'roomDrafts';
17
- const PRESENTATION = 'presentation';
18
- const CONVERSATIONS = 'conversations';
19
- const MESSAGES = 'messages';
20
- const CHAT_DRAFTS = 'chatDrafts';
21
- const CALLS = 'calls';
22
- const QUEUES = 'queues';
23
- const FACTS = 'facts';
24
- const CURRENT = 'current';
25
- const MEMBER = 'member';
26
- const TARGETS = 'targets';
27
- const GENERATION = 'generation';
28
- const HOLDER = 'holder';
29
- const BINDING = 'binding';
30
- export const STORE_SCHEMA = 25;
31
- const REPLICA_SHAPE = 23;
32
- export const AUTHORED_SCHEMA = 3;
33
- const AUTHORED_STORES = [
34
- [QUEUES, { keyPath: 'locator' }],
35
- [PENDING_CHANGES, { keyPath: ['locator', 'id'] }],
36
- [ROOM_DRAFTS, { keyPath: ['locator', 'path'] }],
37
- [CHAT_DRAFTS, { keyPath: 'conversation' }],
38
- [CALLS, { keyPath: 'operation' }],
39
- [FACTS, undefined],
40
- [FENCES, { keyPath: 'locator' }],
41
- ];
42
- const REPLICA_STORES = [
43
- [ROOMS, { keyPath: 'locator' }],
44
- [DOCUMENTS, { keyPath: ['locator', 'transfer', 'path'] }],
45
- [BINARY_FILES, { keyPath: ['locator', 'transfer', 'path'] }],
46
- [TRANSFERS, { keyPath: 'locator' }],
47
- [RECEIVED, { keyPath: 'key' }],
48
- [RECEIVED_PARTS, { keyPath: ['key', 'index'] }],
49
- [DECLARATIONS, undefined],
50
- [PRESENTATION, { keyPath: 'app' }],
51
- [CONVERSATIONS, { keyPath: 'conversation' }],
52
- [MESSAGES, { keyPath: ['conversation', 'identity'] }],
53
- ];
54
- const READ_BATCH = 256;
55
- const MESSAGE_INDEXES = [
56
- ['conversation', 'conversation'],
57
- ['position', ['conversation', 'position']],
58
- ['turn', ['conversation', 'turn']],
59
- ];
60
- function settled(request) {
61
- return new Promise((resolve, reject) => {
62
- request.onsuccess = () => resolve(request.result);
63
- request.onerror = () => reject(request.error);
64
- });
65
- }
66
- const turns = new Map();
67
- function idle(database) {
68
- return turns.get(database.name) ?? Promise.resolve();
69
- }
70
- export function transacted(database, stores, mode, work) {
71
- let release = () => { };
72
- const turn = new Promise((resolve) => {
73
- release = resolve;
74
- });
75
- const before = idle(database);
76
- const queued = before.then(() => turn);
77
- turns.set(database.name, queued);
78
- void queued.then(() => {
79
- if (turns.get(database.name) === queued)
80
- turns.delete(database.name);
81
- });
82
- return before.then(() => {
83
- let transaction;
84
- try {
85
- transaction = database.transaction(stores, mode);
86
- }
87
- catch (error) {
88
- release();
89
- throw error;
90
- }
91
- const committed = new Promise((resolve, reject) => {
92
- transaction.oncomplete = () => {
93
- release();
94
- resolve();
95
- };
96
- transaction.onabort = () => {
97
- release();
98
- reject(transaction.error);
99
- };
100
- transaction.onerror = () => reject(transaction.error);
101
- });
102
- let value;
103
- try {
104
- value = work(transaction);
105
- }
106
- catch (error) {
107
- void committed.catch(() => { });
108
- transaction.abort();
109
- throw error;
110
- }
111
- return Promise.all([value, committed]).then(([held]) => held);
112
- });
113
- }
114
- const EMPTY_DECLARATIONS = {
115
- lastCompleted: null,
116
- providerLimits: [],
117
- capabilities: [],
118
- };
119
- function declaration(database) {
120
- return transacted(database, DECLARATIONS, 'readonly', (transaction) => settled(transaction.objectStore(DECLARATIONS).get(CURRENT))).then((record) => record ?? EMPTY_DECLARATIONS);
121
- }
122
- function updateDeclaration(database, update) {
123
- return transacted(database, DECLARATIONS, 'readwrite', (transaction) => {
124
- const store = transaction.objectStore(DECLARATIONS);
125
- const prior = store.get(CURRENT);
126
- prior.onsuccess = () => {
127
- store.put(update(prior.result ?? EMPTY_DECLARATIONS), CURRENT);
128
- };
129
- });
1
+ import { binaryLocalId } from './identity.js';
2
+ const FILE = '\u0000file';
3
+ function batchFiles(batch) {
4
+ return batch.changes.flatMap((change) => (change.kind === 'binary' ? [change.localId] : []));
130
5
  }
131
- function amendPending(database, locator, id, amendment) {
132
- return transacted(database, PENDING_CHANGES, 'readwrite', (transaction) => {
133
- const pending = transaction.objectStore(PENDING_CHANGES);
134
- const request = pending.get([locator, id]);
135
- request.onsuccess = () => {
136
- const record = request.result;
137
- if (record !== undefined)
138
- pending.put({ ...record, ...amendment });
139
- };
140
- });
141
- }
142
- function accepted({ conversation: _held, ...message }) {
143
- return message;
144
- }
145
- function roomRecord(record) {
146
- const { documents, binaries, revisions, fileIds, changes, written, ...room } = record;
147
- return room;
148
- }
149
- function chatDraftRecord(record) {
150
- return { ...record, revision: record.revision ?? '' };
151
- }
152
- function underTransfer(locator, transfer, after) {
153
- return after === undefined
154
- ? IDBKeyRange.bound([locator, transfer], [locator, transfer, []])
155
- : IDBKeyRange.bound([locator, transfer, after], [locator, transfer, []], true);
156
- }
157
- function underRoom(locator) {
158
- return IDBKeyRange.bound([locator], [locator, []]);
159
- }
160
- async function readTransfer(store, locator, transfer, receive) {
161
- let range = underTransfer(locator, transfer);
162
- for (;;) {
163
- const batch = await settled(store.getAll(range, READ_BATCH));
164
- for (const record of batch)
165
- receive(record);
166
- if (batch.length < READ_BATCH)
167
- return;
168
- range = underTransfer(locator, transfer, batch[batch.length - 1].path);
169
- }
6
+ function draftFiles(drafts) {
7
+ return drafts.flatMap(({ parts }) => (parts.file === undefined ? [] : [parts.file.localId]));
170
8
  }
171
- function emptyLayer() {
172
- return { documents: {}, binaries: {}, revisions: {}, fileIds: {}, changes: {}, written: {} };
173
- }
174
- async function readLayer(transaction, locator, transfer) {
175
- const layer = emptyLayer();
176
- const head = (held) => {
177
- if (held.revision !== null)
178
- layer.revisions[held.path] = held.revision;
179
- if (held.fileId !== null)
180
- layer.fileIds[held.path] = held.fileId;
181
- if (held.change !== null)
182
- layer.changes[held.path] = held.change;
183
- };
184
- await readTransfer(transaction.objectStore(DOCUMENTS), locator, transfer, (document) => {
185
- layer.documents[document.path] = document.content;
186
- if (document.written !== null)
187
- layer.written[document.path] = document.written;
188
- head(document);
189
- });
190
- await readTransfer(transaction.objectStore(BINARY_FILES), locator, transfer, (file) => {
191
- layer.binaries[file.path] = file.binary;
192
- head(file);
193
- });
194
- return layer;
195
- }
196
- function documentRecord(locator, transfer, layer, path) {
197
- return {
198
- locator,
199
- transfer,
200
- path,
201
- content: layer.documents[path],
202
- revision: layer.revisions[path] ?? null,
203
- fileId: layer.fileIds[path] ?? null,
204
- change: layer.changes[path] ?? null,
205
- written: layer.written[path] ?? null,
206
- };
9
+ function roomDraftRow(record) {
10
+ return { path: record.path, record: JSON.stringify(record), files: draftFiles([record]) };
207
11
  }
208
- function binaryFileRecord(locator, transfer, layer, path) {
12
+ function authoredRows({ locator, queue, founded, saved, roomDrafts, consumedRoomDrafts, accepted }, held) {
209
13
  return {
210
14
  locator,
211
- transfer,
212
- path,
213
- revision: layer.revisions[path] ?? null,
214
- fileId: layer.fileIds[path] ?? null,
215
- change: layer.changes[path] ?? null,
216
- binary: layer.binaries[path],
15
+ ...(queue === undefined
16
+ ? {}
17
+ : {
18
+ order: queue.map(({ id }) => id),
19
+ added: queue
20
+ .filter(({ id }) => held?.has(id) !== true)
21
+ .map((batch) => {
22
+ const drafts = saved?.get(batch.id) ?? [];
23
+ return {
24
+ id: batch.id,
25
+ batch: JSON.stringify(batch),
26
+ state: JSON.stringify({
27
+ drafts,
28
+ submission: { state: 'waiting' },
29
+ lost: false,
30
+ }),
31
+ files: [...batchFiles(batch), ...draftFiles(drafts)],
32
+ };
33
+ }),
34
+ }),
35
+ ...(founded === undefined
36
+ ? {}
37
+ : {
38
+ founded: founded.map((batch) => ({
39
+ id: batch.id,
40
+ batch: JSON.stringify(batch),
41
+ files: batchFiles(batch),
42
+ })),
43
+ }),
44
+ ...(roomDrafts === undefined ? {} : { roomDrafts: roomDrafts.map(roomDraftRow) }),
45
+ ...(consumedRoomDrafts === undefined ? {} : { consumedRoomDrafts }),
46
+ ...(accepted === undefined
47
+ ? {}
48
+ : {
49
+ amendments: accepted.map(({ id, roomVersion }) => ({
50
+ id,
51
+ amendment: JSON.stringify({ accepted: roomVersion }),
52
+ })),
53
+ }),
217
54
  };
218
55
  }
219
- function* changedIn(next, base) {
220
- if (base === null)
221
- return new Set([...Object.keys(next.documents), ...Object.keys(next.binaries)]);
222
- return new Set([
223
- ...(yield* differences(base.documents, next.documents)),
224
- ...(yield* differences(base.revisions, next.revisions)),
225
- ...(yield* differences(base.fileIds, next.fileIds)),
226
- ...(yield* differences(base.written, next.written)),
227
- ...(yield* differences(base.changes, next.changes, sameChange)),
228
- ...(yield* differences(base.binaries, next.binaries, sameBinary)),
229
- ]);
230
- }
231
- function writeLayer(transaction, locator, transfer, layer) {
232
- const { next, base, paths } = layer;
233
- const documents = transaction.objectStore(DOCUMENTS);
234
- const files = transaction.objectStore(BINARY_FILES);
235
- let last = null;
236
- return inUnits(paths, (path) => {
237
- if (next.documents[path] !== undefined) {
238
- last = documents.put(documentRecord(locator, transfer, next, path));
239
- }
240
- else if (base?.documents[path] !== undefined) {
241
- last = documents.delete([locator, transfer, path]);
242
- }
243
- if (next.binaries[path] !== undefined) {
244
- last = files.put(binaryFileRecord(locator, transfer, next, path));
245
- }
246
- else if (base?.binaries[path] !== undefined) {
247
- last = files.delete([locator, transfer, path]);
248
- }
249
- return ROW_WEIGHT + (next.documents[path]?.length ?? 0);
250
- }, () => { }, () => {
251
- const request = last;
252
- last = null;
253
- return request === null
254
- ? Promise.resolve()
255
- : new Promise((resolve) => request.addEventListener('success', () => resolve()));
256
- });
56
+ function marked(value) {
57
+ return typeof value === 'object' && value !== null && FILE in value;
257
58
  }
258
- function removeRoomEntries(store, locator) {
259
- const keys = store.getAllKeys();
260
- keys.onsuccess = () => {
261
- for (const key of keys.result) {
262
- if (Array.isArray(key) && key[0] === locator)
263
- store.delete(key);
59
+ function keyed(keys, value) {
60
+ const stored = [];
61
+ const files = [];
62
+ const record = JSON.stringify(value, (_name, held) => {
63
+ if (!(held instanceof Blob))
64
+ return held;
65
+ let key = keys.get(held);
66
+ if (key === undefined) {
67
+ key = binaryLocalId();
68
+ keys.set(held, key);
264
69
  }
265
- };
266
- }
267
- function removeDatabase(name) {
268
- return new Promise((resolve, reject) => {
269
- const removal = indexedDB.deleteDatabase(name);
270
- removal.onsuccess = () => resolve();
271
- removal.onerror = () => reject(removal.error);
70
+ stored.push({ key, blob: held });
71
+ files.push(key);
72
+ return { [FILE]: key, type: held.type };
272
73
  });
74
+ return { record, files, stored };
273
75
  }
274
- export async function authoredHolder() {
275
- const authored = await openAuthored();
276
- try {
277
- const held = await transacted(authored, FACTS, 'readonly', (transaction) => settled(transaction.objectStore(FACTS).get(HOLDER)));
278
- return typeof held === 'string' ? held : null;
279
- }
280
- finally {
281
- authored.close();
282
- }
283
- }
284
- export async function authoredBy(holder) {
285
- const authored = await openAuthored();
286
- try {
287
- let owned = true;
288
- await transacted(authored, FACTS, 'readwrite', (transaction) => {
289
- const facts = transaction.objectStore(FACTS);
290
- const held = facts.get(HOLDER);
291
- held.onsuccess = () => {
292
- if (held.result === undefined)
293
- facts.put(holder, HOLDER);
294
- else
295
- owned = held.result === holder;
296
- };
297
- });
298
- return owned;
299
- }
300
- finally {
301
- authored.close();
302
- }
76
+ async function filed(value, read) {
77
+ if (Array.isArray(value))
78
+ return Promise.all(value.map((item) => filed(item, read)));
79
+ if (marked(value))
80
+ return read(value[FILE], value.type);
81
+ if (typeof value !== 'object' || value === null)
82
+ return value;
83
+ const restored = {};
84
+ for (const [name, item] of Object.entries(value))
85
+ restored[name] = await filed(item, read);
86
+ return restored;
303
87
  }
304
- export async function authoredBinding() {
305
- const authored = await openAuthored();
306
- try {
307
- const held = await transacted(authored, FACTS, 'readonly', (transaction) => settled(transaction.objectStore(FACTS).get(BINDING)));
308
- return typeof held === 'string' ? held : null;
309
- }
310
- finally {
311
- authored.close();
312
- }
88
+ function json(value, fallback) {
89
+ return value === undefined ? fallback : JSON.parse(value);
313
90
  }
314
- export async function bindAuthored(binding) {
315
- const authored = await openAuthored();
316
- try {
317
- await transacted(authored, FACTS, 'readwrite', (transaction) => {
318
- transaction.objectStore(FACTS).put(binding, BINDING);
91
+ export function openRuntimeStore(fenced, authored) {
92
+ const keys = new WeakMap();
93
+ const read = async (key, type) => {
94
+ const blob = await authored.ask({ kind: 'authored.file', key, type });
95
+ keys.set(blob, key);
96
+ return blob;
97
+ };
98
+ const restored = async (records) => Promise.all(records.map(async (record) => (await filed(JSON.parse(record), read))));
99
+ const amend = async (locator, id, amendment) => {
100
+ if (fenced(locator))
101
+ return;
102
+ await authored.ask({
103
+ kind: 'authored.amend',
104
+ locator,
105
+ id,
106
+ amendment: JSON.stringify(amendment),
319
107
  });
320
- }
321
- finally {
322
- authored.close();
323
- }
324
- }
325
- export async function removeRuntimeStore(holder) {
326
- await removeDatabase(DATABASE);
327
- if (holder !== undefined && (await authoredBy(holder)))
328
- return true;
329
- await removeDatabase(AUTHORED);
330
- return false;
331
- }
332
- export function openDatabase(name, version, upgrade) {
333
- return new Promise((resolve, reject) => {
334
- const opening = indexedDB.open(name, version);
335
- opening.onupgradeneeded = (event) => upgrade(opening, event.oldVersion);
336
- opening.onsuccess = () => resolve(opening.result);
337
- opening.onerror = () => {
338
- if (opening.error?.name !== 'VersionError') {
339
- reject(opening.error);
340
- return;
341
- }
342
- removeDatabase(name)
343
- .then(() => openDatabase(name, version, upgrade))
344
- .then(resolve, reject);
345
- };
346
- });
347
- }
348
- function openReplica() {
349
- return openDatabase(DATABASE, STORE_SCHEMA, (opening, oldVersion) => {
350
- const database = opening.result;
351
- if (oldVersion < REPLICA_SHAPE) {
352
- for (const name of [...database.objectStoreNames])
353
- database.deleteObjectStore(name);
354
- }
355
- for (const [name, parameters] of REPLICA_STORES) {
356
- if (database.objectStoreNames.contains(name))
357
- continue;
358
- database.createObjectStore(name, parameters);
359
- }
360
- const messages = opening.transaction.objectStore(MESSAGES);
361
- for (const [name, keyPath] of MESSAGE_INDEXES) {
362
- if (!messages.indexNames.contains(name))
363
- messages.createIndex(name, keyPath);
364
- }
365
- });
366
- }
367
- function openAuthored() {
368
- return openDatabase(AUTHORED, AUTHORED_SCHEMA, (opening) => {
369
- const database = opening.result;
370
- for (const [name, parameters] of AUTHORED_STORES) {
371
- if (!database.objectStoreNames.contains(name))
372
- database.createObjectStore(name, parameters);
108
+ };
109
+ const fact = (name) => authored.ask({ kind: 'authored.fact', name });
110
+ const queued = new Map();
111
+ const changed = new Map();
112
+ const change = (key) => changed.set(key, (changed.get(key) ?? 0) + 1);
113
+ const rows = (writes) => writes.map((write) => authoredRows(write, queued.get(write.locator)));
114
+ const noted = (writes) => {
115
+ for (const { locator, queue } of writes) {
116
+ if (queue !== undefined)
117
+ queued.set(locator, new Set(queue.map(({ id }) => id)));
373
118
  }
374
- });
375
- }
376
- export async function openRuntimeStore(fenced) {
377
- const authored = await openAuthored();
378
- const database = await openReplica().catch((error) => {
379
- authored.close();
380
- throw error;
381
- });
119
+ };
382
120
  return {
383
- all() {
384
- return transacted(database, [ROOMS, DOCUMENTS, BINARY_FILES], 'readonly', async (transaction) => {
385
- const rooms = await settled(transaction.objectStore(ROOMS).getAll());
386
- const records = [];
387
- for (const room of rooms.filter((held) => !fenced(held.locator))) {
388
- records.push({
389
- ...room,
390
- ...(await readLayer(transaction, room.locator, room.transfer)),
391
- });
392
- }
393
- return records;
394
- });
121
+ async opened() {
122
+ const held = await authored.ask({ kind: 'replica.open' });
123
+ const unindexed = new Set(held.keys.flatMap(({ key, rederiving }) => (rederiving === null ? [] : [key])));
124
+ const overlaid = new Map();
125
+ for (const { key, path } of held.overlaid) {
126
+ const paths = overlaid.get(key) ?? new Set();
127
+ paths.add(path);
128
+ overlaid.set(key, paths);
129
+ }
130
+ return {
131
+ rooms: new Map(held.rooms
132
+ .filter(({ locator }) => !fenced(locator))
133
+ .map(({ locator, key, record }) => [
134
+ locator,
135
+ { ...JSON.parse(record), key },
136
+ ])),
137
+ transfers: new Map(held.transfers
138
+ .filter(({ locator }) => !fenced(locator))
139
+ .map(({ locator, key, record }) => [
140
+ locator,
141
+ { ...JSON.parse(record), key },
142
+ ])),
143
+ unindexed,
144
+ overlaid,
145
+ erasing: held.erasing.length > 0,
146
+ orphans: held.orphans,
147
+ lastCompleted: json(held.facts.lastCompleted, null),
148
+ providerLimits: json(held.facts.providerLimits, []),
149
+ capabilities: json(held.facts.capabilities, []),
150
+ member: json(held.facts.member, null),
151
+ targets: json(held.facts.targets, {}),
152
+ presentation: held.presentation.map(({ app, value }) => ({
153
+ app,
154
+ value: JSON.parse(value),
155
+ })),
156
+ };
395
157
  },
396
- async keepAuthored({ locator, queue, founded, saved, roomDrafts, consumedRoomDrafts }) {
397
- if (fenced(locator))
398
- return;
399
- await transacted(authored, [QUEUES, PENDING_CHANGES, ROOM_DRAFTS], 'readwrite', (transaction) => {
400
- const order = transaction.objectStore(QUEUES);
401
- const pending = transaction.objectStore(PENDING_CHANGES);
402
- const held = order.get(locator);
403
- held.onsuccess = () => {
404
- const before = new Set(held.result?.order ?? []);
405
- const after = new Set(queue.map((batch) => batch.id));
406
- if (queue.length === 0)
407
- order.delete(locator);
408
- else
409
- order.put({ locator, order: [...after] });
410
- for (const id of before) {
411
- if (!after.has(id))
412
- pending.delete([locator, id]);
413
- }
414
- for (const batch of queue) {
415
- if (!before.has(batch.id)) {
416
- pending.put({
417
- locator,
418
- id: batch.id,
419
- batch,
420
- drafts: saved?.get(batch.id) ?? [],
421
- submission: { state: 'waiting' },
422
- lost: false,
423
- });
424
- }
425
- }
426
- for (const batch of founded ?? []) {
427
- if (!before.has(batch.id))
428
- continue;
429
- const stored = pending.get([locator, batch.id]);
430
- stored.onsuccess = () => {
431
- const record = stored.result;
432
- if (record !== undefined)
433
- pending.put({ ...record, batch });
434
- };
435
- }
436
- };
437
- const draftStore = transaction.objectStore(ROOM_DRAFTS);
438
- for (const path of consumedRoomDrafts ?? [])
439
- draftStore.delete([locator, path]);
440
- for (const record of roomDrafts ?? [])
441
- draftStore.put(record);
442
- });
158
+ counts(rooms) {
159
+ return authored.ask({ kind: 'replica.counts', rooms });
443
160
  },
444
- async write({ next, previous, stored }) {
445
- if (next === previous || fenced(next.locator))
446
- return;
447
- const moved = previous?.transfer !== next.transfer;
448
- const base = moved ? (stored ?? null) : previous;
449
- const paths = await stepped(changedIn(next, base));
450
- if (fenced(next.locator))
451
- return;
452
- await transacted(database, [ROOMS, DOCUMENTS, BINARY_FILES, TRANSFERS], 'readwrite', (transaction) => {
453
- transaction.objectStore(ROOMS).put(roomRecord(next));
454
- if (moved && previous !== null) {
455
- const range = underTransfer(previous.locator, previous.transfer);
456
- transaction.objectStore(DOCUMENTS).delete(range);
457
- transaction.objectStore(BINARY_FILES).delete(range);
458
- }
459
- if (moved)
460
- transaction.objectStore(TRANSFERS).delete(next.locator);
461
- return writeLayer(transaction, next.locator, next.transfer, { next, base, paths });
462
- });
161
+ query(plan, rooms, budget) {
162
+ return authored.ask({ kind: 'replica.query', plan, rooms, budget });
463
163
  },
464
- async revokeModels(records) {
465
- await transacted(database, ROOMS, 'readwrite', (transaction) => {
466
- const rooms = transaction.objectStore(ROOMS);
467
- const revoked = { status: 'unavailable', reason: 'revoked' };
468
- for (const record of records) {
469
- if (fenced(record.locator))
470
- continue;
471
- rooms.put(roomRecord({ ...record, model: revoked, selectionModel: revoked }));
472
- }
473
- });
164
+ changes(keys) {
165
+ return keys.reduce((total, key) => total + (changed.get(key) ?? 0), 0);
474
166
  },
475
- async lastCompleted() {
476
- return (await declaration(database)).lastCompleted;
167
+ entries(key, view, paths) {
168
+ return authored.ask({ kind: 'replica.entries', key, view, paths });
477
169
  },
478
- complete(at) {
479
- return updateDeclaration(database, (record) => ({ ...record, lastCompleted: at }));
170
+ typed(key, view, paths) {
171
+ return authored.ask({ kind: 'replica.typed', key, view, paths });
480
172
  },
481
- async providerLimits() {
482
- return (await declaration(database)).providerLimits;
173
+ referrers(key, view, targets, kinds) {
174
+ return authored.ask({ kind: 'replica.referrers', key, view, targets, kinds });
483
175
  },
484
- async capabilities() {
485
- return (await declaration(database)).capabilities;
176
+ walk(key, view, after, bytes) {
177
+ return authored.ask({ kind: 'replica.walk', key, view, after, bytes });
486
178
  },
487
- declare(limits, capabilities) {
488
- return updateDeclaration(database, (record) => ({
489
- ...record,
490
- providerLimits: limits,
491
- capabilities,
492
- }));
179
+ files(key, view, after, limit) {
180
+ return authored.ask({ kind: 'replica.files', key, view, after, limit });
181
+ },
182
+ typedWithin(key, view, roots, within) {
183
+ return authored.ask({ kind: 'replica.typedWithin', key, view, roots, within });
184
+ },
185
+ search(ask) {
186
+ return authored.ask({ kind: 'replica.search', ...ask });
187
+ },
188
+ async stage(record, composition, page, written) {
189
+ if (fenced(record.locator))
190
+ return null;
191
+ const { key, ...kept } = record;
192
+ return authored.ask({
193
+ kind: 'replica.stage',
194
+ locator: record.locator,
195
+ transfer: record.transfer,
196
+ record: JSON.stringify(kept),
197
+ key,
198
+ composition,
199
+ entries: page.entries,
200
+ folders: page.folders,
201
+ ...(written === undefined ? {} : { written }),
202
+ });
493
203
  },
494
- async member() {
495
- const held = await transacted(database, DECLARATIONS, 'readonly', (transaction) => settled(transaction.objectStore(DECLARATIONS).get(MEMBER)));
496
- return held ?? null;
204
+ async transferPart(locator, token) {
205
+ if (fenced(locator))
206
+ return null;
207
+ return authored.ask({ kind: 'replica.transferPart', locator, token });
497
208
  },
498
- async keepMember(member) {
499
- await transacted(database, DECLARATIONS, 'readwrite', (transaction) => {
500
- transaction.objectStore(DECLARATIONS).put(member, MEMBER);
209
+ async keepPart(locator, token, part) {
210
+ if (fenced(locator))
211
+ return;
212
+ await authored.ask({ kind: 'replica.keepPart', locator, token, part });
213
+ },
214
+ async refresh(key, page) {
215
+ await authored.ask({
216
+ kind: 'replica.refresh',
217
+ key,
218
+ entries: page.entries,
219
+ removals: page.removals,
220
+ folders: page.folders,
221
+ folderRemovals: page.folderRemovals,
501
222
  });
502
223
  },
503
- async targets() {
504
- const held = await transacted(database, DECLARATIONS, 'readonly', (transaction) => settled(transaction.objectStore(DECLARATIONS).get(TARGETS)));
505
- return held ?? {};
224
+ async unrefresh(key) {
225
+ await authored.ask({ kind: 'replica.unrefresh', key });
506
226
  },
507
- async keepTargets(targets) {
508
- await transacted(database, DECLARATIONS, 'readwrite', (transaction) => {
509
- transaction.objectStore(DECLARATIONS).put(targets, TARGETS);
227
+ async commit({ rooms, writes = [], files = [], whole = false, discards = [] }) {
228
+ const kept = whole ? writes : writes.filter(({ locator }) => !fenced(locator));
229
+ const refused = whole ? kept.find(({ locator }) => fenced(locator)) : undefined;
230
+ if (refused !== undefined) {
231
+ return { fenced: refused.locator, counts: {}, changed: {}, indexed: {} };
232
+ }
233
+ for (const room of rooms)
234
+ change(room.key);
235
+ const committed = await authored.ask({
236
+ kind: 'replica.commit',
237
+ ...(kept.length === 0 && files.length === 0 && discards.length === 0
238
+ ? {}
239
+ : { authored: { writes: rows(kept), files, whole, discards } }),
240
+ rooms: rooms.filter(({ locator }) => !fenced(locator)),
510
241
  });
242
+ if (committed.fenced === null || !whole)
243
+ noted(kept);
244
+ for (const locator of discards)
245
+ queued.delete(locator);
246
+ return committed;
247
+ },
248
+ async fence(locators) {
249
+ await authored.ask({ kind: 'replica.fence', locators });
250
+ for (const locator of locators)
251
+ queued.delete(locator);
252
+ },
253
+ async erase(locator, limit) {
254
+ return (await authored.ask({ kind: 'replica.erase', locator, limit })).remaining;
255
+ },
256
+ async abandon(locator, kept = false) {
257
+ if (fenced(locator))
258
+ return null;
259
+ return authored.ask({ kind: 'replica.abandon', locator, kept });
260
+ },
261
+ async release(key) {
262
+ await authored.ask({ kind: 'replica.release', key });
263
+ },
264
+ async rederive(key, limit) {
265
+ change(key);
266
+ return (await authored.ask({ kind: 'replica.rederive', key, limit })).done;
267
+ },
268
+ async fact(name, value) {
269
+ await authored.ask({ kind: 'replica.fact', name, value: JSON.stringify(value) });
511
270
  },
512
271
  async queues() {
513
- const [queues, pending] = await transacted(authored, [QUEUES, PENDING_CHANGES], 'readonly', (transaction) => Promise.all([
514
- settled(transaction.objectStore(QUEUES).getAll()),
515
- settled(transaction.objectStore(PENDING_CHANGES).getAll()),
516
- ]));
272
+ const { queues, pending } = await authored.ask({ kind: 'authored.queues' });
273
+ queued.clear();
274
+ for (const queue of queues)
275
+ queued.set(queue.locator, new Set(queue.ids));
517
276
  const byId = new Map(pending.map((record) => [`${record.locator}\0${record.id}`, record]));
518
277
  return queues
519
278
  .filter((queue) => !fenced(queue.locator))
520
279
  .map((queue) => ({
521
280
  locator: queue.locator,
522
- pending: queue.order.map((id) => {
281
+ pending: queue.ids.map((id) => {
523
282
  const record = byId.get(`${queue.locator}\0${id}`);
524
283
  if (record === undefined)
525
284
  throw new Error(`Missing Pending Change ${queue.locator}/${id}`);
526
- const { batch, drafts, submission, lost, upload, accepted } = record;
527
- return { batch, state: { drafts, submission, lost, upload, accepted } };
285
+ return {
286
+ batch: JSON.parse(record.batch),
287
+ state: JSON.parse(record.state),
288
+ };
528
289
  }),
529
290
  }));
530
291
  },
531
- async submit(locator, id, submission, lost) {
532
- if (!fenced(locator))
533
- await amendPending(authored, locator, id, { submission, lost });
292
+ submit(locator, id, submission, lost) {
293
+ return amend(locator, id, { submission, lost });
534
294
  },
535
- async accept(locator, id, roomVersion) {
536
- if (!fenced(locator))
537
- await amendPending(authored, locator, id, { accepted: roomVersion });
538
- },
539
- async keepUpload(locator, id, upload) {
540
- if (!fenced(locator))
541
- await amendPending(authored, locator, id, { upload });
295
+ keepUpload(locator, id, upload) {
296
+ return amend(locator, id, { upload });
542
297
  },
543
298
  async roomDrafts() {
544
- const held = await transacted(authored, ROOM_DRAFTS, 'readonly', (transaction) => settled(transaction.objectStore(ROOM_DRAFTS).getAll()));
545
- return held.filter((record) => !fenced(record.locator));
546
- },
547
- presentation() {
548
- return transacted(database, PRESENTATION, 'readonly', (transaction) => settled(transaction.objectStore(PRESENTATION).getAll()));
299
+ const held = await authored.ask({ kind: 'authored.roomDrafts' });
300
+ return held
301
+ .map((record) => JSON.parse(record))
302
+ .filter((record) => !fenced(record.locator));
549
303
  },
550
304
  async present(record) {
551
- await transacted(database, PRESENTATION, 'readwrite', (transaction) => {
552
- transaction.objectStore(PRESENTATION).put(record);
305
+ await authored.ask({
306
+ kind: 'replica.present',
307
+ app: record.app,
308
+ value: JSON.stringify(record.value ?? null),
553
309
  });
554
310
  },
555
311
  conversations() {
556
- return transacted(database, [CONVERSATIONS, MESSAGES], 'readonly', async (transaction) => {
557
- const records = await settled(transaction.objectStore(CONVERSATIONS).getAll());
558
- const held = new Map(records.map(({ conversation, read, partial }) => [
559
- conversation,
560
- { conversation, read, partial: partial === true },
561
- ]));
562
- const keys = transaction.objectStore(MESSAGES).index('conversation');
563
- await new Promise((resolve, reject) => {
564
- const cursor = keys.openKeyCursor(null, 'nextunique');
565
- cursor.onerror = () => reject(cursor.error);
566
- cursor.onsuccess = () => {
567
- const at = cursor.result;
568
- if (at === null) {
569
- resolve();
570
- return;
571
- }
572
- const conversation = at.key;
573
- if (!held.has(conversation)) {
574
- held.set(conversation, { conversation, read: undefined, partial: true });
575
- }
576
- at.continue();
577
- };
578
- });
579
- return [...held.values()];
580
- });
312
+ return authored.ask({ kind: 'conversation.held' });
581
313
  },
582
- async keepMessages({ conversation, messages, read }) {
583
- await transacted(database, [CONVERSATIONS, MESSAGES], 'readwrite', (transaction) => {
584
- const stored = transaction.objectStore(MESSAGES);
585
- for (const message of messages) {
586
- stored.put({ ...message, conversation });
587
- }
588
- if (read !== undefined) {
589
- transaction.objectStore(CONVERSATIONS).put({
590
- conversation,
591
- read: read.at,
592
- ...(read.partial ? { partial: true } : {}),
593
- });
594
- }
595
- });
314
+ async keepMessages(write) {
315
+ await authored.ask({ kind: 'conversation.keep', ...write });
596
316
  },
597
317
  messageWindow(conversation, limit, before) {
598
- return transacted(database, MESSAGES, 'readonly', async (transaction) => {
599
- const index = transaction.objectStore(MESSAGES).index('position');
600
- const range = IDBKeyRange.bound([conversation], [conversation, before?.[0] ?? []]);
601
- const latest = [];
602
- let more = false;
603
- await new Promise((resolve, reject) => {
604
- const cursor = index.openCursor(range, 'prev');
605
- cursor.onerror = () => reject(cursor.error);
606
- cursor.onsuccess = () => {
607
- const at = cursor.result;
608
- if (at === null) {
609
- resolve();
610
- return;
611
- }
612
- const record = at.value;
613
- if (!precedes(record, before)) {
614
- at.continue();
615
- return;
616
- }
617
- if (latest.length === limit) {
618
- more = true;
619
- resolve();
620
- return;
621
- }
622
- latest.push(accepted(record));
623
- at.continue();
624
- };
625
- });
626
- return { messages: latest.reverse(), more };
627
- });
318
+ return authored.ask({ kind: 'conversation.window', conversation, limit, before });
628
319
  },
629
320
  messageCount(conversation) {
630
- return transacted(database, MESSAGES, 'readonly', (transaction) => settled(transaction.objectStore(MESSAGES).index('conversation').count(conversation)));
631
- },
632
- async messagesAfter(conversation, identity) {
633
- const range = identity === null
634
- ? IDBKeyRange.bound([conversation], [conversation, []])
635
- : IDBKeyRange.bound([conversation, identity], [conversation, []], true);
636
- const held = await transacted(database, MESSAGES, 'readonly', (transaction) => settled(transaction.objectStore(MESSAGES).getAll(range, READ_BATCH)));
637
- return held.map(accepted);
321
+ return authored.ask({ kind: 'conversation.count', conversation });
638
322
  },
639
- async messageIdentities(conversation) {
640
- const keys = await transacted(database, MESSAGES, 'readonly', (transaction) => settled(transaction.objectStore(MESSAGES).index('conversation').getAllKeys(conversation)));
641
- return keys.map((key) => key[1]);
642
- },
643
- async turnArrived(conversation, turn) {
644
- const held = await transacted(database, MESSAGES, 'readonly', (transaction) => settled(transaction.objectStore(MESSAGES).index('turn').count([conversation, turn])));
645
- return held > 0;
323
+ turnArrived(conversation, turn) {
324
+ return authored.ask({ kind: 'conversation.turn', conversation, turn });
646
325
  },
647
326
  async dropConversations(conversations) {
648
- await transacted(authored, CHAT_DRAFTS, 'readwrite', (drafts) => {
649
- for (const conversation of conversations)
650
- drafts.objectStore(CHAT_DRAFTS).delete(conversation);
651
- });
652
- await transacted(database, [CONVERSATIONS, MESSAGES], 'readwrite', (transaction) => {
653
- const messages = transaction.objectStore(MESSAGES);
654
- for (const conversation of conversations) {
655
- transaction.objectStore(CONVERSATIONS).delete(conversation);
656
- const keys = messages.index('conversation').getAllKeys(conversation);
657
- keys.onsuccess = () => {
658
- for (const key of keys.result)
659
- messages.delete(key);
660
- };
661
- }
662
- });
327
+ await authored.ask({ kind: 'conversation.drop', conversations });
663
328
  },
664
329
  async chatDrafts() {
665
- const held = await transacted(authored, CHAT_DRAFTS, 'readonly', (transaction) => settled(transaction.objectStore(CHAT_DRAFTS).getAll()));
666
- return held.map(chatDraftRecord);
330
+ const records = await authored.ask({ kind: 'authored.chatDrafts' });
331
+ return records.map((record) => JSON.parse(record));
667
332
  },
668
333
  async keepChatDrafts(records) {
669
- await transacted(authored, CHAT_DRAFTS, 'readwrite', (transaction) => {
670
- for (const record of records)
671
- transaction.objectStore(CHAT_DRAFTS).put(record);
334
+ await authored.ask({
335
+ kind: 'authored.chatDraft',
336
+ kept: records.map((record) => ({
337
+ conversation: record.conversation,
338
+ record: JSON.stringify(record),
339
+ })),
340
+ dropped: [],
672
341
  });
673
342
  },
674
343
  async dropChatDraft(conversation) {
675
- await transacted(authored, CHAT_DRAFTS, 'readwrite', (transaction) => {
676
- transaction.objectStore(CHAT_DRAFTS).delete(conversation);
677
- });
344
+ await authored.ask({ kind: 'authored.chatDraft', kept: [], dropped: [conversation] });
678
345
  },
679
- calls() {
680
- return transacted(authored, CALLS, 'readonly', (transaction) => settled(transaction.objectStore(CALLS).getAll()));
346
+ async calls() {
347
+ return restored(await authored.ask({ kind: 'authored.calls' }));
681
348
  },
682
349
  async keepCall(record) {
683
- await transacted(authored, CALLS, 'readwrite', (transaction) => {
684
- transaction.objectStore(CALLS).put(record);
350
+ const { stored, ...kept } = keyed(keys, record);
351
+ await authored.ask({
352
+ kind: 'authored.call',
353
+ operation: record.operation,
354
+ kept,
355
+ files: stored,
685
356
  });
686
357
  },
687
358
  async dropCall(operation) {
688
- await transacted(authored, CALLS, 'readwrite', (transaction) => {
689
- transaction.objectStore(CALLS).delete(operation);
690
- });
359
+ await authored.ask({ kind: 'authored.call', operation, kept: null, files: [] });
691
360
  },
692
- async keepRoomDraft(record) {
361
+ async keepRoomDraft(record, files) {
693
362
  if (fenced(record.locator))
694
363
  return;
695
- await transacted(authored, ROOM_DRAFTS, 'readwrite', (transaction) => {
696
- transaction.objectStore(ROOM_DRAFTS).put(record);
364
+ const { path, ...kept } = roomDraftRow(record);
365
+ await authored.ask({
366
+ kind: 'authored.roomDraft',
367
+ locator: record.locator,
368
+ path,
369
+ kept,
370
+ files,
697
371
  });
698
372
  },
699
373
  async discardRoomDraft(locator, path) {
700
374
  if (fenced(locator))
701
375
  return;
702
- await transacted(authored, ROOM_DRAFTS, 'readwrite', (transaction) => {
703
- transaction.objectStore(ROOM_DRAFTS).delete([locator, path]);
704
- });
705
- },
706
- async fences() {
707
- const held = await transacted(authored, FENCES, 'readonly', (transaction) => settled(transaction.objectStore(FENCES).getAll()));
708
- return held.map((fence) => fence.locator);
709
- },
710
- async erase(locators) {
711
- await transacted(authored, [FENCES, QUEUES, PENDING_CHANGES, ROOM_DRAFTS], 'readwrite', (work) => {
712
- for (const locator of locators) {
713
- work.objectStore(FENCES).put({ locator });
714
- work.objectStore(QUEUES).delete(locator);
715
- for (const name of [PENDING_CHANGES, ROOM_DRAFTS]) {
716
- removeRoomEntries(work.objectStore(name), locator);
717
- }
718
- }
719
- });
720
- await transacted(database, [ROOMS, DOCUMENTS, BINARY_FILES, TRANSFERS], 'readwrite', (transaction) => {
721
- for (const locator of locators) {
722
- transaction.objectStore(ROOMS).delete(locator);
723
- transaction.objectStore(TRANSFERS).delete(locator);
724
- transaction.objectStore(DOCUMENTS).delete(underRoom(locator));
725
- transaction.objectStore(BINARY_FILES).delete(underRoom(locator));
726
- }
727
- });
728
- await transacted(authored, FENCES, 'readwrite', (fences) => {
729
- for (const locator of locators)
730
- fences.objectStore(FENCES).delete(locator);
731
- });
376
+ await authored.ask({ kind: 'authored.roomDraft', locator, path, kept: null, files: [] });
732
377
  },
733
- async discard(locator) {
734
- await transacted(authored, [QUEUES, PENDING_CHANGES], 'readwrite', (transaction) => {
735
- transaction.objectStore(QUEUES).delete(locator);
736
- removeRoomEntries(transaction.objectStore(PENDING_CHANGES), locator);
737
- });
738
- },
739
- async transfers() {
740
- const held = await transacted(database, TRANSFERS, 'readonly', (transaction) => settled(transaction.objectStore(TRANSFERS).getAll()));
741
- return held.filter((record) => !fenced(record.locator));
742
- },
743
- staged(record) {
744
- return transacted(database, [DOCUMENTS, BINARY_FILES], 'readonly', (transaction) => readLayer(transaction, record.locator, record.transfer));
745
- },
746
- async stage(record, page) {
747
- if (fenced(record.locator))
748
- return;
749
- const paths = await stepped(changedIn(page, null));
750
- if (fenced(record.locator))
751
- return;
752
- await transacted(database, [TRANSFERS, DOCUMENTS, BINARY_FILES], 'readwrite', (transaction) => {
753
- transaction.objectStore(TRANSFERS).put(record);
754
- return writeLayer(transaction, record.locator, record.transfer, {
755
- next: page,
756
- base: null,
757
- paths,
758
- });
759
- });
760
- },
761
- async abandon(locator) {
762
- if (fenced(locator))
763
- return;
764
- await transacted(database, [TRANSFERS, DOCUMENTS, BINARY_FILES], 'readwrite', (transaction) => {
765
- const transfers = transaction.objectStore(TRANSFERS);
766
- const held = transfers.get(locator);
767
- held.onsuccess = () => {
768
- const record = held.result;
769
- if (record === undefined)
770
- return;
771
- transfers.delete(locator);
772
- const range = underTransfer(locator, record.transfer);
773
- transaction.objectStore(DOCUMENTS).delete(range);
774
- transaction.objectStore(BINARY_FILES).delete(range);
775
- };
776
- });
378
+ fences() {
379
+ return authored.ask({ kind: 'authored.fences' });
777
380
  },
778
381
  receivedHeads() {
779
- return transacted(database, RECEIVED, 'readonly', (transaction) => settled(transaction.objectStore(RECEIVED).getAll()));
382
+ return authored.ask({ kind: 'replica.received' });
780
383
  },
781
- async receivedParts(key, count) {
782
- const kept = await transacted(database, RECEIVED_PARTS, 'readonly', (transaction) => settled(transaction
783
- .objectStore(RECEIVED_PARTS)
784
- .getAll(IDBKeyRange.bound([key, 0], [key, count], false, true))));
785
- return kept.map((part) => part.value);
384
+ receivedParts(key, count) {
385
+ return authored.ask({ kind: 'replica.receivedParts', key, count });
786
386
  },
787
387
  async keepReceived(key, head, part) {
788
- await transacted(database, [RECEIVED, RECEIVED_PARTS], 'readwrite', (transaction) => {
789
- transaction.objectStore(RECEIVED).put({ key, head });
790
- if (part !== undefined)
791
- transaction.objectStore(RECEIVED_PARTS).put({ key, ...part });
388
+ await authored.ask({
389
+ kind: 'replica.receive',
390
+ key,
391
+ head: JSON.stringify(head),
392
+ ...(part === undefined
393
+ ? {}
394
+ : { part: { index: part.index, value: JSON.stringify(part.value) } }),
792
395
  });
793
396
  },
794
397
  async dropReceived(keys) {
795
- await transacted(database, [RECEIVED, RECEIVED_PARTS], 'readwrite', (transaction) => {
796
- for (const key of keys) {
797
- transaction.objectStore(RECEIVED).delete(key);
798
- transaction.objectStore(RECEIVED_PARTS).delete(IDBKeyRange.bound([key], [key, []]));
799
- }
800
- });
398
+ await authored.ask({ kind: 'replica.unreceive', keys });
801
399
  },
802
- async generation() {
803
- const held = await transacted(authored, FACTS, 'readonly', (transaction) => settled(transaction.objectStore(FACTS).get(GENERATION)));
804
- return held ?? null;
400
+ generation() {
401
+ return fact('generation');
805
402
  },
806
403
  async rememberGeneration(value) {
807
- await transacted(authored, FACTS, 'readwrite', (transaction) => {
808
- transaction.objectStore(FACTS).put(value, GENERATION);
809
- });
404
+ await authored.ask({ kind: 'authored.remember', name: 'generation', value });
810
405
  },
811
- close() {
812
- for (const held of [authored, database])
813
- void idle(held).then(() => held.close());
406
+ file(key, type) {
407
+ return authored.ask({ kind: 'authored.file', key, type });
814
408
  },
815
409
  };
816
410
  }