@agentshouse/mdruntime 0.1.0-cf04ede9fb796 → 0.1.0-cf08ada271a7f

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 (172) hide show
  1. package/README.md +8 -8
  2. package/dist/acceptance.d.ts +0 -3
  3. package/dist/acceptance.d.ts.map +1 -1
  4. package/dist/acceptance.js +51 -131
  5. package/dist/actions.js +2 -2
  6. package/dist/adapter.d.ts +16 -44
  7. package/dist/adapter.d.ts.map +1 -1
  8. package/dist/bootstrap.d.ts +1 -1
  9. package/dist/bootstrap.d.ts.map +1 -1
  10. package/dist/bootstrap.js +6 -19
  11. package/dist/change-set.d.ts +4 -0
  12. package/dist/change-set.d.ts.map +1 -1
  13. package/dist/change-set.js +6 -0
  14. package/dist/change.d.ts.map +1 -1
  15. package/dist/change.js +4 -2
  16. package/dist/client.d.ts +3 -1
  17. package/dist/client.d.ts.map +1 -1
  18. package/dist/client.js +6 -4
  19. package/dist/collection.d.ts +22 -4
  20. package/dist/collection.d.ts.map +1 -1
  21. package/dist/collection.js +12 -2
  22. package/dist/compile.d.ts.map +1 -1
  23. package/dist/compile.js +15 -21
  24. package/dist/connection.d.ts.map +1 -1
  25. package/dist/connection.js +13 -13
  26. package/dist/conversation-live.d.ts +3 -4
  27. package/dist/conversation-live.d.ts.map +1 -1
  28. package/dist/conversation-live.js +2 -3
  29. package/dist/conversation.d.ts +4 -6
  30. package/dist/conversation.d.ts.map +1 -1
  31. package/dist/conversation.js +43 -71
  32. package/dist/declaration.d.ts +10 -0
  33. package/dist/declaration.d.ts.map +1 -0
  34. package/dist/declaration.js +24 -0
  35. package/dist/discovery.d.ts.map +1 -1
  36. package/dist/discovery.js +5 -3
  37. package/dist/expectation.d.ts +4 -2
  38. package/dist/expectation.d.ts.map +1 -1
  39. package/dist/expectation.js +33 -11
  40. package/dist/failure.d.ts +1 -0
  41. package/dist/failure.d.ts.map +1 -1
  42. package/dist/failure.js +3 -0
  43. package/dist/host.d.ts +17 -2
  44. package/dist/host.d.ts.map +1 -1
  45. package/dist/host.js +16 -4
  46. package/dist/index.d.ts +5 -3
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +4 -2
  49. package/dist/install.d.ts +0 -1
  50. package/dist/install.d.ts.map +1 -1
  51. package/dist/install.js +46 -59
  52. package/dist/job.d.ts +1 -29
  53. package/dist/job.d.ts.map +1 -1
  54. package/dist/job.js +2 -49
  55. package/dist/lifecycle.d.ts.map +1 -1
  56. package/dist/lifecycle.js +9 -6
  57. package/dist/listing.d.ts +4 -4
  58. package/dist/listing.d.ts.map +1 -1
  59. package/dist/listing.js +15 -22
  60. package/dist/live.d.ts.map +1 -1
  61. package/dist/live.js +3 -3
  62. package/dist/locks.d.ts.map +1 -1
  63. package/dist/locks.js +2 -1
  64. package/dist/lost.d.ts.map +1 -1
  65. package/dist/lost.js +3 -3
  66. package/dist/media.d.ts +1 -1
  67. package/dist/media.d.ts.map +1 -1
  68. package/dist/media.js +3 -3
  69. package/dist/memory.d.ts +4 -2
  70. package/dist/memory.d.ts.map +1 -1
  71. package/dist/memory.js +8 -6
  72. package/dist/messages.d.ts +0 -3
  73. package/dist/messages.d.ts.map +1 -1
  74. package/dist/messages.js +9 -29
  75. package/dist/model.d.ts +0 -1
  76. package/dist/model.d.ts.map +1 -1
  77. package/dist/model.js +0 -5
  78. package/dist/models.d.ts +4 -8
  79. package/dist/models.d.ts.map +1 -1
  80. package/dist/models.js +101 -126
  81. package/dist/observation.d.ts.map +1 -1
  82. package/dist/observation.js +12 -17
  83. package/dist/opened.js +3 -3
  84. package/dist/opening.d.ts.map +1 -1
  85. package/dist/opening.js +6 -4
  86. package/dist/overlay.d.ts +2 -1
  87. package/dist/overlay.d.ts.map +1 -1
  88. package/dist/overlay.js +32 -21
  89. package/dist/parts.d.ts +3 -52
  90. package/dist/parts.d.ts.map +1 -1
  91. package/dist/parts.js +15 -120
  92. package/dist/preparation.d.ts.map +1 -1
  93. package/dist/preparation.js +12 -5
  94. package/dist/queries.js +1 -1
  95. package/dist/query.d.ts +0 -1
  96. package/dist/query.d.ts.map +1 -1
  97. package/dist/questions.js +1 -1
  98. package/dist/queue.d.ts +39 -0
  99. package/dist/queue.d.ts.map +1 -0
  100. package/dist/queue.js +455 -0
  101. package/dist/reach.d.ts.map +1 -1
  102. package/dist/reach.js +5 -4
  103. package/dist/react.d.ts +4 -0
  104. package/dist/react.d.ts.map +1 -1
  105. package/dist/react.js +10 -1
  106. package/dist/reads.d.ts.map +1 -1
  107. package/dist/reads.js +4 -1
  108. package/dist/refresh.js +2 -2
  109. package/dist/refusal.d.ts.map +1 -1
  110. package/dist/refusal.js +3 -2
  111. package/dist/replica.d.ts +5 -11
  112. package/dist/replica.d.ts.map +1 -1
  113. package/dist/replica.js +13 -15
  114. package/dist/room-draft.d.ts +4 -6
  115. package/dist/room-draft.d.ts.map +1 -1
  116. package/dist/room-draft.js +36 -52
  117. package/dist/room-drafts.d.ts.map +1 -1
  118. package/dist/room-drafts.js +17 -16
  119. package/dist/rows.d.ts.map +1 -1
  120. package/dist/rows.js +3 -4
  121. package/dist/runtime.d.ts +5 -16
  122. package/dist/runtime.d.ts.map +1 -1
  123. package/dist/save.d.ts +41 -90
  124. package/dist/save.d.ts.map +1 -1
  125. package/dist/save.js +233 -116
  126. package/dist/saves.d.ts +2 -40
  127. package/dist/saves.d.ts.map +1 -1
  128. package/dist/saves.js +102 -697
  129. package/dist/seed.d.ts.map +1 -1
  130. package/dist/seed.js +0 -1
  131. package/dist/shared.d.ts +0 -5
  132. package/dist/shared.d.ts.map +1 -1
  133. package/dist/shared.js +4 -90
  134. package/dist/shown.d.ts +2 -1
  135. package/dist/shown.d.ts.map +1 -1
  136. package/dist/shown.js +15 -11
  137. package/dist/socket/rooms.d.ts +1 -4
  138. package/dist/socket/rooms.d.ts.map +1 -1
  139. package/dist/socket/session.d.ts +0 -1
  140. package/dist/socket/session.d.ts.map +1 -1
  141. package/dist/socket.d.ts +0 -1
  142. package/dist/socket.d.ts.map +1 -1
  143. package/dist/socket.js +2 -2
  144. package/dist/source.d.ts.map +1 -1
  145. package/dist/source.js +5 -4
  146. package/dist/store/records.d.ts +1 -3
  147. package/dist/store/records.d.ts.map +1 -1
  148. package/dist/store/records.js +2 -5
  149. package/dist/store/space.d.ts +1 -1
  150. package/dist/store/space.d.ts.map +1 -1
  151. package/dist/store/space.js +0 -2
  152. package/dist/store/watchers.js +1 -2
  153. package/dist/store.d.ts +1 -1
  154. package/dist/store.d.ts.map +1 -1
  155. package/dist/store.js +1 -1
  156. package/dist/stored.d.ts +1 -1
  157. package/dist/stored.d.ts.map +1 -1
  158. package/dist/stored.js +6 -6
  159. package/dist/surface.d.ts.map +1 -1
  160. package/dist/surface.js +4 -3
  161. package/dist/sync.d.ts.map +1 -1
  162. package/dist/sync.js +25 -27
  163. package/dist/tables.d.ts +0 -5
  164. package/dist/tables.d.ts.map +1 -1
  165. package/dist/tables.js +8 -11
  166. package/dist/tallies.js +5 -5
  167. package/dist/validation.d.ts.map +1 -1
  168. package/dist/validation.js +2 -2
  169. package/dist/wire.d.ts +4 -4
  170. package/dist/wire.d.ts.map +1 -1
  171. package/dist/wire.js +3 -3
  172. package/package.json +3 -2
package/dist/save.js CHANGED
@@ -1,11 +1,11 @@
1
- import { definitionOf } from './model.js';
2
- import { apply, ARRAY_INDEX, ATTACHMENT, links, parse, pointerSegments, references, relative, relativize, retarget, roomReferences, serialize, target, } from '@agentshouse/mdmodel';
1
+ import { apply, ARRAY_INDEX, ATTACHMENT, create, links, parse, pointerSegments, references, relative, relativize, retarget, roomReferences, serialize, target, } from '@agentshouse/mdmodel';
3
2
  import { immutable, leaving, queuedFile, departure, } from './change.js';
4
- import { collectionOf, documentsOf, governing, } from './collection.js';
5
- import { changeBatchIdentity } from './identity.js';
3
+ import { collectionOf, definitionsAt, documentsOf, governing, } from './collection.js';
4
+ import { changeBatchIdentity, roomDraftRevision } from './identity.js';
6
5
  import { overlaying } from './overlay.js';
7
- import { ancestors, authoredAt, covered, normalize } from './paths.js';
6
+ import { ancestors } from './paths.js';
8
7
  import { entriesIn, sorting } from './shared.js';
8
+ import { changedParts, changesOf, moveTarget, withdrawnDrafts, } from './room-draft.js';
9
9
  import { paced, ROW_WEIGHT, stepped } from './turn.js';
10
10
  import { validatedCollection } from './validation.js';
11
11
  function refuse(code, file, location) {
@@ -20,9 +20,6 @@ function refuse(code, file, location) {
20
20
  };
21
21
  }
22
22
  function repointed(document, definition, from, to, moves, settled) {
23
- const parsed = parse(document.content, from);
24
- if (!parsed.ok)
25
- return [];
26
23
  const changes = [];
27
24
  const names = new Set();
28
25
  for (const { pointer, value } of definition === undefined
@@ -45,13 +42,13 @@ function repointed(document, definition, from, to, moves, settled) {
45
42
  }
46
43
  if (changes.length === 0)
47
44
  return [];
48
- const applied = apply(parsed.document, changes);
45
+ const applied = apply(document, changes, definition);
49
46
  if (applied.outcome !== 'applied')
50
47
  return [];
51
48
  const next = applied.document;
52
49
  return [...names].map((name) => ({ kind: 'field', path: from, name, value: next.fields[name] }));
53
50
  }
54
- function edited(document, changes) {
51
+ function edited(document, changes, definition) {
55
52
  const parts = new Map();
56
53
  for (const change of changes) {
57
54
  if (change.kind === 'preamble')
@@ -66,7 +63,7 @@ function edited(document, changes) {
66
63
  }
67
64
  if (parts.size === 0)
68
65
  return document;
69
- const applied = apply(document, [...parts.values()]);
66
+ const applied = apply(document, [...parts.values()], definition);
70
67
  return applied.outcome === 'applied' ? applied.document : document;
71
68
  }
72
69
  function bodies(path, before, after) {
@@ -81,7 +78,7 @@ function bodies(path, before, after) {
81
78
  }
82
79
  return changes;
83
80
  }
84
- function relinks(path, moved, before, moves) {
81
+ function relinks(path, moved, before, moves, definition) {
85
82
  const changes = [];
86
83
  for (const link of links(before, path)) {
87
84
  const destination = moves.get(link.target) ?? link.target;
@@ -94,7 +91,7 @@ function relinks(path, moved, before, moves) {
94
91
  }
95
92
  if (changes.length === 0)
96
93
  return { kind: 'changes', changes: [] };
97
- const applied = apply(before, changes);
94
+ const applied = apply(before, changes, definition);
98
95
  if (applied.outcome === 'refuse') {
99
96
  return {
100
97
  kind: 'refused',
@@ -117,6 +114,15 @@ function relinks(path, moved, before, moves) {
117
114
  function partKey(change) {
118
115
  return change.kind === 'section' ? `section ${change.name}` : change.kind;
119
116
  }
117
+ const NAMES_A_SKIP_TESTS = 64;
118
+ const ENCODED = /[%&\\]/u;
119
+ function movedNames(moves) {
120
+ const names = new Set([...moves.keys()].map((path) => path.slice(path.lastIndexOf('/') + 1)));
121
+ return names.size > NAMES_A_SKIP_TESTS ? null : [...names];
122
+ }
123
+ function cannotLink(text, names) {
124
+ return names !== null && !ENCODED.test(text) && !names.some((name) => text.includes(name));
125
+ }
120
126
  function* rewrites(changes, visible) {
121
127
  const moves = new Map();
122
128
  const settled = new Set();
@@ -142,17 +148,20 @@ function* rewrites(changes, visible) {
142
148
  }
143
149
  if (moves.size === 0)
144
150
  return { kind: 'changes', changes };
151
+ const names = movedNames(moves);
145
152
  const merged = [...changes];
146
153
  const added = [];
147
154
  for (const [path, document] of yield* documentsOf(visible.collection)) {
148
155
  if (settled.has(path))
149
156
  continue;
150
157
  const moved = moves.get(path) ?? path;
151
- const definition = definitionOf(governing(visible.collection.composition, path), document.type);
158
+ const definition = definitionsAt(visible.collection.composition, path)(document.type);
152
159
  const repointing = repointed(document, definition, path, moved, moves, settled);
153
160
  added.push(...repointing);
154
161
  const own = parts.get(path) ?? [];
155
- const relinked = relinks(path, moved, edited(document, own.map((index) => merged[index])), moves);
162
+ const relinked = moved === path && own.length === 0 && cannotLink(document.content, names)
163
+ ? { kind: 'changes', changes: [] }
164
+ : relinks(path, moved, edited(document, own.map((index) => merged[index]), definition), moves, definition);
156
165
  if (relinked.kind === 'refused')
157
166
  return relinked;
158
167
  const keyed = new Map();
@@ -221,10 +230,10 @@ function crossed(document, definition, path, to) {
221
230
  }
222
231
  return changes;
223
232
  }
224
- function rewritten(path, document, changes) {
233
+ function rewritten(path, document, changes, definition) {
225
234
  if (changes.length === 0)
226
235
  return [];
227
- const applied = apply(document, changes);
236
+ const applied = apply(document, changes, definition);
228
237
  if (applied.outcome !== 'applied')
229
238
  return [];
230
239
  const after = applied.document;
@@ -239,7 +248,7 @@ function rewritten(path, document, changes) {
239
248
  function roomPathOf(handle, path) {
240
249
  return `/rooms/${handle}/${path}`;
241
250
  }
242
- export function* leavingRewritten(batch, visible) {
251
+ function* leavingRewritten(batch, visible) {
243
252
  const between = batch.between;
244
253
  if (between === undefined)
245
254
  return batch;
@@ -248,8 +257,8 @@ export function* leavingRewritten(batch, visible) {
248
257
  for (const [path, document] of yield* documentsOf(visible.collection)) {
249
258
  if (moved.has(path))
250
259
  continue;
251
- const definition = definitionOf(governing(visible.collection.composition, path), document.type);
252
- derived.push(...rewritten(path, document, crossed(document, definition, path, (named) => moved.get(named))));
260
+ const definition = definitionsAt(visible.collection.composition, path)(document.type);
261
+ derived.push(...rewritten(path, document, crossed(document, definition, path, (named) => moved.get(named)), definition));
253
262
  yield ROW_WEIGHT + visible.collection.text[path].length;
254
263
  }
255
264
  if (derived.length === 0)
@@ -291,7 +300,7 @@ function* incoming(collection, removed, candidates) {
291
300
  for (const [path, document] of candidates === null
292
301
  ? yield* documentsOf(collection)
293
302
  : read(candidates)) {
294
- const definition = definitionOf(governing(collection.composition, path), document.type);
303
+ const definition = definitionsAt(collection.composition, path)(document.type);
295
304
  for (const { value, to } of definition === undefined ? [] : references(document, definition)) {
296
305
  if (to.includes(ATTACHMENT))
297
306
  continue;
@@ -334,18 +343,9 @@ function guard(changes, input, removing) {
334
343
  const occupied = (path) => input.folders.has(path) ? path : (ancestors(path).find((one) => existing.has(one)) ?? null);
335
344
  for (const [index, change] of changes.entries()) {
336
345
  for (const path of affected(change)) {
337
- const normalized = normalize(path);
338
- if (normalized === null || normalized === '')
339
- return refuse('room-root', path);
340
- if (covered(input.providerOwnedPaths, normalized) ||
341
- (input.authoredPaths !== undefined && !authoredAt(input.authoredPaths, normalized))) {
342
- return refuse('provider-owned-path', normalized);
343
- }
344
- if (!input.pathRule(normalized))
345
- return refuse('invalid-path', normalized);
346
- for (const operation of change.kind === 'remove' ? removing : WRITE)
347
- if (!input.local && !covered(input.operations[operation], normalized))
348
- return refuse(`${operation}-grant`, normalized);
346
+ const refused = input.rule(path, change.kind === 'remove' ? removing : WRITE);
347
+ if (refused !== null)
348
+ return refuse(refused.code, refused.path);
349
349
  }
350
350
  if (change.kind === 'create' || change.kind === 'arrival') {
351
351
  const taken = existing.has(change.path) ? change.path : occupied(change.path);
@@ -406,9 +406,9 @@ function guard(changes, input, removing) {
406
406
  return null;
407
407
  }
408
408
  function unrevised(input, path) {
409
- return (!input.local && input.queued?.has(path) !== true && input.visible.revisions[path] === undefined);
409
+ return !input.local && !input.queued.has(path) && input.visible.revisions[path] === undefined;
410
410
  }
411
- export function queuedDocuments(queue) {
411
+ function queuedDocuments(queue) {
412
412
  const paths = new Set();
413
413
  for (const batch of queue) {
414
414
  for (const change of batch.changes) {
@@ -544,19 +544,16 @@ function* exceeding(limits, changes, effective, resulting) {
544
544
  function shellRelative(text, path, handle, definition) {
545
545
  if (!text.includes(`/rooms/${handle}/`))
546
546
  return null;
547
- const parsed = parse(text, path);
547
+ const parsed = parse(text, path, definition);
548
548
  if (!parsed.ok)
549
549
  return null;
550
550
  const result = relativize(parsed.document, path, handle, definition(parsed.document.type));
551
551
  return result.outcome === 'applied' && result.document.content !== text ? result.document : null;
552
552
  }
553
553
  function relativeField(path, name, value, handle, definition) {
554
- const opened = parse('---\n---\n');
555
- if (definition === undefined ||
556
- !opened.ok ||
557
- !JSON.stringify(value ?? null).includes(`/rooms/${handle}/`))
554
+ if (definition === undefined || !JSON.stringify(value ?? null).includes(`/rooms/${handle}/`))
558
555
  return value;
559
- const held = apply(opened.document, [{ kind: 'field', name, value, prior: undefined }]);
556
+ const held = apply(create(definition.name, definition), [{ kind: 'field', name, value, prior: undefined }], definition);
560
557
  if (held.outcome !== 'applied')
561
558
  return value;
562
559
  const result = relativize(held.document, path, handle, definition);
@@ -564,7 +561,7 @@ function relativeField(path, name, value, handle, definition) {
564
561
  }
565
562
  function relativeChanges(input) {
566
563
  const { handle, composition, visible } = input;
567
- const typed = (path) => (type) => definitionOf(governing(composition, path), type);
564
+ const typed = (path) => definitionsAt(composition, path);
568
565
  const body = (path, text) => shellRelative(text, path, handle, () => undefined)?.content ?? text;
569
566
  return input.changes.map((change) => {
570
567
  const definition = typed(change.path);
@@ -593,7 +590,7 @@ function relativeChanges(input) {
593
590
  });
594
591
  }
595
592
  function unqueueable(file) {
596
- return { kind: 'refused', refusal: { code: 'unknown-revision', retryable: false, file } };
593
+ return refuse('unknown-revision', file);
597
594
  }
598
595
  function isPart(change) {
599
596
  return change.kind === 'field' || change.kind === 'section' || change.kind === 'preamble';
@@ -601,8 +598,9 @@ function isPart(change) {
601
598
  function touched(change) {
602
599
  return change.kind === 'move' ? [change.path, change.to] : [change.path];
603
600
  }
604
- function partsApplied(content, path, changes) {
605
- const parsed = parse(content, path);
601
+ function partsApplied(content, path, changes, composition) {
602
+ const definitions = definitionsAt(composition, path);
603
+ const parsed = parse(content, path, definitions);
606
604
  if (!parsed.ok)
607
605
  return null;
608
606
  const document = parsed.document;
@@ -625,12 +623,12 @@ function partsApplied(content, path, changes) {
625
623
  else
626
624
  parts.set('preamble', { kind: 'preamble', value: change.value, prior: document.preamble });
627
625
  }
628
- const applied = apply(document, [...parts.values()]);
626
+ const applied = apply(document, [...parts.values()], definitions(document.type));
629
627
  return applied.outcome === 'applied' ? serialize(applied.document) : null;
630
628
  }
631
- function settledParts(changes, deferred) {
629
+ function settledParts(changes, deferred, composition) {
632
630
  for (const [held, parts] of deferred) {
633
- const content = partsApplied(held.content, held.path, parts);
631
+ const content = partsApplied(held.content, held.path, parts, composition);
634
632
  if (content === null)
635
633
  return held.path;
636
634
  changes[changes.indexOf(held)] = { ...held, content };
@@ -705,7 +703,9 @@ function* relinked(batch, move, before, after, appending) {
705
703
  for (const change of derived.changes) {
706
704
  if (change === move)
707
705
  continue;
708
- const unsettled = isPart(change) ? null : settledParts(changes, deferred);
706
+ const unsettled = isPart(change)
707
+ ? null
708
+ : settledParts(changes, deferred, after.collection.composition);
709
709
  if (unsettled !== null)
710
710
  return unqueueable(unsettled);
711
711
  const outcome = folded(changes, change, appending, deferred);
@@ -716,7 +716,7 @@ function* relinked(batch, move, before, after, appending) {
716
716
  if (outcome !== 'skipped')
717
717
  changed = true;
718
718
  }
719
- const unsettled = settledParts(changes, deferred);
719
+ const unsettled = settledParts(changes, deferred, after.collection.composition);
720
720
  if (unsettled !== null)
721
721
  return unqueueable(unsettled);
722
722
  if (!changed)
@@ -777,11 +777,10 @@ function withdrawnFile(batch, change, at) {
777
777
  ];
778
778
  return immutable({ ...batch, id: changeBatchIdentity(), changes, preconditions });
779
779
  }
780
- export function* requeuing(queue, changes, visible, changeable, state) {
780
+ function* requeuing(queue, changes, visible, changeable, state) {
781
781
  const next = [...queue];
782
782
  const origins = new Map();
783
783
  const withdrawn = new Map();
784
- const owners = new Set();
785
784
  const queued = new Set();
786
785
  const kept = [];
787
786
  const originOf = (batch) => origins.get(batch) ?? batch.id;
@@ -827,7 +826,6 @@ export function* requeuing(queue, changes, visible, changeable, state) {
827
826
  if (replaced !== null)
828
827
  origins.set(replaced, origin);
829
828
  }
830
- owners.add(originOf(owner));
831
829
  next.splice(index, following.length, ...rebuilt.filter((batch) => batch !== null));
832
830
  queued.add(change.path);
833
831
  }
@@ -837,56 +835,13 @@ export function* requeuing(queue, changes, visible, changeable, state) {
837
835
  changes: kept,
838
836
  queued,
839
837
  withdrawn,
840
- owners,
841
838
  };
842
839
  }
843
- function covering(precondition) {
844
- return precondition.kind === 'field' ||
845
- precondition.kind === 'section' ||
846
- precondition.kind === 'preamble'
847
- ? identity(precondition)
848
- : `path ${precondition.path}`;
849
- }
850
- export function joined(queue, owner, extra) {
851
- const later = new Set(queue.slice(queue.indexOf(owner) + 1).flatMap((batch) => batch.changes.flatMap(touched)));
852
- const clash = extra.changes.flatMap(touched).find((path) => later.has(path));
853
- if (clash !== undefined)
854
- return unqueueable(clash);
855
- const changes = [...owner.changes];
856
- const deferred = new Map();
857
- for (const change of extra.changes) {
858
- const unsettled = isPart(change) ? null : settledParts(changes, deferred);
859
- if (unsettled !== null)
860
- return unqueueable(unsettled);
861
- if (folded(changes, change, true, deferred) === 'refused')
862
- return unqueueable(change.path);
863
- }
864
- const unsettled = settledParts(changes, deferred);
865
- if (unsettled !== null)
866
- return unqueueable(unsettled);
867
- const held = new Set(owner.preconditions.map(covering));
868
- const written = new Set(owner.changes.flatMap((change) => change.kind === 'create' || change.kind === 'replace' ? [change.path] : []));
869
- const preconditions = [
870
- ...owner.preconditions,
871
- ...extra.preconditions.filter((precondition) => {
872
- const key = covering(precondition);
873
- return (!held.has(key) && (key === `path ${precondition.path}` || !written.has(precondition.path)));
874
- }),
875
- ];
876
- const batch = immutable({
877
- ...owner,
878
- ...(extra.validation === undefined ? {} : { validation: extra.validation }),
879
- id: changeBatchIdentity(),
880
- changes,
881
- preconditions,
882
- });
883
- return { kind: 'joined', batch, queue: queue.map((item) => (item === owner ? batch : item)) };
884
- }
885
- export function* limiting(queue, batch, limits, state) {
840
+ function* limiting(queue, batch, limits, state) {
886
841
  const at = queue.indexOf(batch);
887
842
  const rewritten = yield* providerRewritten(batch, yield* state(queue.slice(0, at)));
888
843
  const limited = yield* exceeding(limits, batch.changes, rewritten.changes, yield* state(queue.slice(0, at + 1)));
889
- return limited?.kind === 'refused' ? limited.refusal : null;
844
+ return limited?.refusal ?? null;
890
845
  }
891
846
  function typedText(content) {
892
847
  if (content === undefined)
@@ -912,7 +867,7 @@ function touchedLibrary(resulting, touched, composition) {
912
867
  if (binaries.has(path))
913
868
  known.set(path, { type: undefined, binary: true });
914
869
  else if (content !== undefined && content !== null) {
915
- const read = parse(content, path);
870
+ const read = parse(content, path, definitionsAt(composition, path));
916
871
  if (read.ok)
917
872
  known.set(path, { type: read.document.type ?? 'any', binary: false });
918
873
  await pace(content.length + ROW_WEIGHT);
@@ -976,10 +931,11 @@ function placed(reference) {
976
931
  function roomReferencesIn(path, content, composition) {
977
932
  if (content === undefined)
978
933
  return [];
979
- const parsed = parse(content, path);
934
+ const definitions = definitionsAt(composition, path);
935
+ const parsed = parse(content, path, definitions);
980
936
  if (!parsed.ok)
981
937
  return [];
982
- return roomReferences(parsed.document, definitionOf(governing(composition, path), parsed.document.type));
938
+ return roomReferences(parsed.document, definitions(parsed.document.type));
983
939
  }
984
940
  function* admittedRooms(changes, visible, resulting, composition) {
985
941
  const from = new Map();
@@ -1030,7 +986,7 @@ async function batching(input) {
1030
986
  return refusal;
1031
987
  const preconditions = await stepped(preconditionsOf(changes, input.visible, input.bases));
1032
988
  const predicted = await stepped(anticipated(changes, preconditions, rewritten.changes, input.visible));
1033
- const resulting = await stepped(overlaying(input.visible, [{ id: '', baseRoomVersion: input.baseRoomVersion, ...predicted }]));
989
+ const resulting = await stepped(overlaying(input.visible, [{ id: '', baseRoomVersion: input.baseRoomVersion, ...predicted }], input.composition));
1034
990
  const judged = await judging(input.visible, resulting, input.composition, input.validate, new Set(changes.filter((change) => change.kind === 'remove').map((change) => change.path)), [...new Set(predicted.changes.flatMap(affected))]);
1035
991
  if (judged.kind === 'refused')
1036
992
  return judged;
@@ -1052,7 +1008,7 @@ async function batching(input) {
1052
1008
  }),
1053
1009
  };
1054
1010
  }
1055
- export const MOVE_DOCUMENTS = 'move-documents';
1011
+ const MOVE_DOCUMENTS = 'move-documents';
1056
1012
  function heldAt(visible, path) {
1057
1013
  return visible.documents[path] !== undefined || visible.binaries[path] !== undefined;
1058
1014
  }
@@ -1061,7 +1017,7 @@ function arrivingText(path, to, source, moved) {
1061
1017
  const document = source.visible.collection.document(path);
1062
1018
  if (document === undefined)
1063
1019
  return content;
1064
- const definition = definitionOf(governing(source.composition, path), document.type);
1020
+ const definition = definitionsAt(source.composition, path)(document.type);
1065
1021
  const changes = crossed(document, definition, path, (named, href) => {
1066
1022
  const at = moved.get(named);
1067
1023
  if (at !== undefined)
@@ -1070,7 +1026,7 @@ function arrivingText(path, to, source, moved) {
1070
1026
  });
1071
1027
  if (changes.length === 0)
1072
1028
  return content;
1073
- const applied = apply(document, changes);
1029
+ const applied = apply(document, changes, definition);
1074
1030
  return applied.outcome === 'applied' ? serialize(applied.document) : content;
1075
1031
  }
1076
1032
  function arrivalOf({ path, to }, source, moved) {
@@ -1103,11 +1059,9 @@ function arrivalOf({ path, to }, source, moved) {
1103
1059
  };
1104
1060
  }
1105
1061
  async function moving(input) {
1106
- const { source, destination, moves, pathRule } = input;
1107
- if (moves.length === 0)
1108
- return refuse('no-change');
1062
+ const { source, destination, moves } = input;
1109
1063
  const removals = moves.map(({ path }) => ({ kind: 'remove', path }));
1110
- const leaves = guard(removals, { ...source, local: input.local, bases: [], pathRule }, MOVE_OUT);
1064
+ const leaves = guard(removals, { ...source, local: input.local, bases: [] }, MOVE_OUT);
1111
1065
  if (leaves !== null)
1112
1066
  return leaves;
1113
1067
  const uploading = moves.find(({ path }) => source.visible.binaries[path]?.state === 'pending');
@@ -1115,7 +1069,7 @@ async function moving(input) {
1115
1069
  return refuse('unknown-revision', uploading.path);
1116
1070
  const moved = new Map(moves.map(({ path, to }) => [path, to]));
1117
1071
  const arrivals = moves.map((move) => arrivalOf(move, source, moved));
1118
- const arrives = guard(arrivals, { ...destination, local: input.local, bases: [], pathRule }, WRITE);
1072
+ const arrives = guard(arrivals, { ...destination, local: input.local, bases: [] }, WRITE);
1119
1073
  if (arrives !== null)
1120
1074
  return arrives;
1121
1075
  const bound = input.providerLimits.find((limit) => limit.name === MOVE_DOCUMENTS)?.value;
@@ -1144,7 +1098,7 @@ async function moving(input) {
1144
1098
  between,
1145
1099
  };
1146
1100
  const effective = await stepped(leavingRewritten(leavingBatch, source.visible));
1147
- const left = await stepped(overlaying(source.visible, [effective]));
1101
+ const left = await stepped(overlaying(source.visible, [effective], source.composition));
1148
1102
  const sourceJudged = await judging(source.visible, left, source.composition, source.validate, new Set(moves.map(({ path }) => path)), [...new Set(effective.changes.map((change) => change.path))]);
1149
1103
  if (sourceJudged.kind === 'refused')
1150
1104
  return sourceJudged;
@@ -1156,7 +1110,7 @@ async function moving(input) {
1156
1110
  ...written,
1157
1111
  between,
1158
1112
  };
1159
- const arrived = await stepped(overlaying(destination.visible, [arrivingBatch]));
1113
+ const arrived = await stepped(overlaying(destination.visible, [arrivingBatch], destination.composition));
1160
1114
  const destinationJudged = await judging(destination.visible, arrived, destination.composition, destination.validate, new Set(), moves.map(({ to }) => to));
1161
1115
  if (destinationJudged.kind === 'refused')
1162
1116
  return destinationJudged;
@@ -1166,9 +1120,172 @@ async function moving(input) {
1166
1120
  return limited;
1167
1121
  return { kind: 'moved', leaving: immutable(leavingBatch), arriving: immutable(arrivingBatch) };
1168
1122
  }
1169
- export function buildMove(input) {
1170
- return moving(input);
1123
+ function changedUnderneath(saved, visible) {
1124
+ const parts = saved.flatMap(({ path, parts: held }) => changedParts(path, held, visible));
1125
+ return parts.length === 0
1126
+ ? null
1127
+ : { kind: 'refused', refusal: { code: 'changed-underneath', retryable: false, parts } };
1128
+ }
1129
+ function sideOf(room, visible) {
1130
+ const { record } = room;
1131
+ return {
1132
+ room: record.locator,
1133
+ handle: record.declaration.handle,
1134
+ baseRoomVersion: record.roomVersion,
1135
+ composition: room.composition,
1136
+ rule: room.rule,
1137
+ visible,
1138
+ folders: room.folders,
1139
+ queued: queuedDocuments(room.queue),
1140
+ unmodeled: !room.modelled,
1141
+ validate: room.validate,
1142
+ };
1143
+ }
1144
+ function carriedDrafts(ask, from, into) {
1145
+ return new Map(ask.saved.flatMap(({ path, parts }) => {
1146
+ const record = from.drafts.get(path);
1147
+ if (parts.move === undefined || record === undefined || ask.consumed.has(path))
1148
+ return [];
1149
+ const to = moveTarget(parts.move);
1150
+ if (into.drafts.has(to))
1151
+ return [];
1152
+ const locator = into.record.locator;
1153
+ return [[path, { ...record, locator, path: to, revision: roomDraftRevision() }]];
1154
+ }));
1155
+ }
1156
+ async function plannedMove(ask, source, into) {
1157
+ const destination = into.record.locator;
1158
+ const mixed = ask.saved.find(({ parts }) => Object.keys(parts).length !== 1 || parts.move?.room !== destination);
1159
+ if (mixed !== undefined)
1160
+ return refuse('mixed-room-move', mixed.path);
1161
+ const leavingVisible = await stepped(source.replay(source.queue));
1162
+ const changed = changedUnderneath(ask.saved, leavingVisible);
1163
+ if (changed !== null)
1164
+ return changed;
1165
+ const moves = ask.saved.map(({ path, parts }) => ({ path, to: moveTarget(parts.move) }));
1166
+ const built = await moving({
1167
+ source: sideOf(source, leavingVisible),
1168
+ destination: sideOf(into, await stepped(into.replay(into.queue))),
1169
+ moves,
1170
+ providerLimits: ask.providerLimits,
1171
+ local: ask.local,
1172
+ ...(ask.writtenBy === undefined ? {} : { writtenBy: ask.writtenBy }),
1173
+ });
1174
+ if (built.kind === 'refused')
1175
+ return built;
1176
+ const { id } = built.leaving;
1177
+ const carried = carriedDrafts(ask, source, into);
1178
+ return {
1179
+ kind: 'planned',
1180
+ identifier: id,
1181
+ rooms: [
1182
+ {
1183
+ locator: source.record.locator,
1184
+ queue: [...source.queue, built.leaving],
1185
+ saved: new Map([[id, ask.saved]]),
1186
+ consumed: [...ask.consumed, ...carried.keys()],
1187
+ carried: [],
1188
+ },
1189
+ {
1190
+ locator: destination,
1191
+ queue: [...into.queue, built.arriving],
1192
+ saved: new Map([
1193
+ [id, [...carried.values()].map(({ path }) => ({ path, parts: {} }))],
1194
+ ]),
1195
+ consumed: [],
1196
+ carried: [...carried.values()],
1197
+ },
1198
+ ],
1199
+ };
1200
+ }
1201
+ async function plannedWithin(ask, room) {
1202
+ const { record } = room;
1203
+ const visible = await stepped(room.replay(room.queue));
1204
+ const changed = changedUnderneath(ask.saved, visible);
1205
+ if (changed !== null)
1206
+ return changed;
1207
+ const parts = ask.saved.map(({ path, parts: held }) => changesOf(path, held));
1208
+ const changes = parts.flatMap(({ changes: made }) => made);
1209
+ const requeue = await stepped(requeuing(room.queue, changes, visible, (batch) => room.changeable.has(batch.id), room.replay));
1210
+ if (requeue.kind === 'refused')
1211
+ return requeue;
1212
+ const foreign = [...requeue.withdrawn.keys()].some((origin) => {
1213
+ const writer = room.queue.find((batch) => batch.id === origin)?.writtenBy;
1214
+ return writer?.app !== ask.writtenBy?.app || writer?.release !== ask.writtenBy?.release;
1215
+ });
1216
+ if (foreign)
1217
+ return unqueueable([...requeue.queued].at(-1));
1218
+ const input = {
1219
+ local: ask.local,
1220
+ baseRoomVersion: record.roomVersion,
1221
+ composition: room.composition,
1222
+ rule: room.rule,
1223
+ providerLimits: ask.providerLimits,
1224
+ handle: record.declaration.handle,
1225
+ visible,
1226
+ folders: room.folders,
1227
+ changes,
1228
+ bases: parts.flatMap(({ bases }) => bases),
1229
+ queued: queuedDocuments(room.queue),
1230
+ writtenBy: ask.writtenBy,
1231
+ unmodeled: !room.modelled,
1232
+ validate: room.validate,
1233
+ };
1234
+ const rewritten = requeue.withdrawn.size > 0;
1235
+ if (rewritten) {
1236
+ const whole = await batching({
1237
+ ...input,
1238
+ providerLimits: [],
1239
+ queued: new Set([...input.queued, ...requeue.queued]),
1240
+ });
1241
+ if (whole.kind === 'refused')
1242
+ return whole;
1243
+ }
1244
+ const own = !rewritten
1245
+ ? await batching(input)
1246
+ : requeue.changes.length === 0
1247
+ ? null
1248
+ : await batching({
1249
+ ...input,
1250
+ visible: await stepped(room.replay(requeue.queue)),
1251
+ changes: requeue.changes,
1252
+ queued: queuedDocuments(requeue.queue),
1253
+ });
1254
+ if (own?.kind === 'refused')
1255
+ return own;
1256
+ const queue = own === null ? requeue.queue : [...requeue.queue, own.batch];
1257
+ const saved = new Map();
1258
+ for (const [origin, rebuilt] of requeue.withdrawn) {
1259
+ if (rebuilt === null)
1260
+ continue;
1261
+ const limited = await stepped(limiting(queue, rebuilt, ask.providerLimits, room.replay));
1262
+ if (limited !== null)
1263
+ return { kind: 'refused', refusal: limited };
1264
+ saved.set(rebuilt.id, withdrawnDrafts(room.saved.get(origin) ?? [], changes));
1265
+ }
1266
+ if (own !== null) {
1267
+ saved.set(own.batch.id, ask.saved.filter(({ path }) => !requeue.queued.has(path)));
1268
+ }
1269
+ const carried = carriedDrafts(ask, room, room);
1270
+ return {
1271
+ kind: 'planned',
1272
+ identifier: own?.batch.id ??
1273
+ [...requeue.withdrawn].map(([origin, rebuilt]) => rebuilt?.id ?? origin).at(-1),
1274
+ rooms: [
1275
+ {
1276
+ locator: record.locator,
1277
+ queue,
1278
+ saved,
1279
+ consumed: [...ask.consumed, ...carried.keys()],
1280
+ carried: [...carried.values()],
1281
+ },
1282
+ ],
1283
+ };
1284
+ }
1285
+ export function destination(locator, saved) {
1286
+ const into = saved.find(({ parts }) => parts.move?.room !== undefined && parts.move.room !== locator);
1287
+ return into?.parts.move?.room ?? null;
1171
1288
  }
1172
- export function buildBatch(input) {
1173
- return batching(input);
1289
+ export function planSave(ask, room, into) {
1290
+ return into === undefined ? plannedWithin(ask, room) : plannedMove(ask, room, into);
1174
1291
  }
package/dist/saves.d.ts CHANGED
@@ -1,11 +1,9 @@
1
- import { type ChangeSet } from './change-set.js';
2
1
  import { type ChangeBatch, type WrittenBy } from './change.js';
3
2
  import { type AttachAnswer, type BinaryLinkAnswer, type HeldBinaryAnswer, type HeldShownAnswer } from './outcome.js';
4
- import { type HeldReplica, type ReplicaRecord, type Slice, type VisibleLayer } from './replica.js';
5
- import { type ReturnReason, type RoomDraftParts } from './room-draft.js';
3
+ import { type RoomDraftParts } from './room-draft.js';
6
4
  import type { Runtime } from './runtime.js';
7
5
  import { type SaveRefusal } from './save.js';
8
- import type { AuthoredWrite, CommittedWrite, PendingState, RoomCommit, RuntimeStore, Store, StoredEntry, View, Work } from './store.js';
6
+ import type { Store } from './store.js';
9
7
  export type SaveResult = {
10
8
  outcome: 'saved';
11
9
  identifier: string;
@@ -27,42 +25,6 @@ export type BinaryFileSurface = {
27
25
  attach(room: string, file: File): Promise<AttachAnswer>;
28
26
  part(file: string, part: number): Promise<Uint8Array | null>;
29
27
  };
30
- export type Leaving = {
31
- batch: ChangeBatch;
32
- returned: ReturnReason | null;
33
- };
34
- export declare function withdrawable(states: ReadonlyMap<string, PendingState>): (batch: ChangeBatch) => boolean;
35
- export declare function sliceAt(store: Store, record: ReplicaRecord, view: View, queue: readonly ChangeBatch[], extra?: Iterable<string>, moved?: Iterable<string>): Promise<Slice>;
36
- export declare function landedWhole(store: Store, locator: string, batch: ChangeBatch, confirmedLayer: Slice, current?: Readonly<Record<string, string>>): Promise<boolean>;
37
- export type Settling = {
38
- leaving?: readonly Leaving[];
39
- room?: boolean;
40
- view?: View;
41
- commit?: Pick<RoomCommit, 'published' | 'refreshed'>;
42
- changes?: {
43
- readonly set: readonly StoredEntry[];
44
- readonly removed: readonly string[];
45
- };
46
- };
47
- export declare function preparedAfter(runtime: Runtime, locator: string, answer: CommittedWrite): void;
48
- export declare function replayed(store: Store, record: ReplicaRecord, confirmedLayer: Slice, queue: readonly ChangeBatch[]): import("./turn.js").Later<import("./replica.js").Replayed>;
49
- export declare function overlayDiff(record: ReplicaRecord, before: HeldReplica | undefined, visible: VisibleLayer, touched: ReadonlySet<string>): Promise<{
50
- overlay: NonNullable<RoomCommit['overlay']>;
51
- touched: ReadonlySet<string>;
52
- }>;
53
- export type Settlement = {
54
- readonly locator: string;
55
- readonly left: readonly ChangeBatch[];
56
- readonly commit: {
57
- readonly rooms: readonly RoomCommit[];
58
- readonly writes: readonly AuthoredWrite[];
59
- };
60
- apply(answer: CommittedWrite): ChangeSet;
61
- };
62
- export declare function settle(runtime: Runtime, local: RuntimeStore, locator: string, work: Work, record: ReplicaRecord, queue: readonly ChangeBatch[], settling?: Settling): Promise<ChangeSet>;
63
- export declare function together(runtime: Runtime, local: RuntimeStore, settlements: readonly Settlement[]): Promise<ChangeSet>;
64
- export declare function settlement(runtime: Runtime, local: RuntimeStore, locator: string, work: Work, record: ReplicaRecord, queue: readonly ChangeBatch[], settling?: Settling): Promise<Settlement>;
65
- export declare function unpairing(runtime: Runtime, local: RuntimeStore, locator: string, batches: readonly ChangeBatch[]): Promise<Settlement>;
66
28
  export declare function saveRoomDrafts(runtime: Runtime, locator: string, named: readonly SavedRoomDraft[], writtenBy: WrittenBy | undefined): Promise<SaveResult>;
67
29
  export declare function saveParts(runtime: Runtime, locator: string, named: readonly SavedParts[], writtenBy: WrittenBy | undefined): Promise<SaveResult>;
68
30
  export declare function batchFile(store: Store, batch: ChangeBatch): (localId: string) => Promise<Blob>;