doxum 0.1.2 → 0.1.4

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 (48) hide show
  1. package/README.md +59 -27
  2. package/dist/{contract-DGkZcTiP.d.cts → contract-BsY1XLiG.d.ts} +2 -1
  3. package/dist/{contract-Dh3az8aN.d.ts → contract-D8kjdfqT.d.cts} +2 -1
  4. package/dist/{access-5D4KKFm7.js → dependency-C5_R1tvQ.js} +40 -262
  5. package/dist/dependency-C5_R1tvQ.js.map +1 -0
  6. package/dist/{access-z56fVqZ2.cjs → dependency-Dfzs3khk.cjs} +62 -344
  7. package/dist/dependency-Dfzs3khk.cjs.map +1 -0
  8. package/dist/driver-CNxqMVFH.cjs +69 -0
  9. package/dist/driver-CNxqMVFH.cjs.map +1 -0
  10. package/dist/driver-CbzfW5MR.js +46 -0
  11. package/dist/driver-CbzfW5MR.js.map +1 -0
  12. package/dist/index.cjs +2636 -46
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.js +2594 -4
  17. package/dist/index.js.map +1 -1
  18. package/dist/integration.cjs +2 -3
  19. package/dist/integration.cjs.map +1 -1
  20. package/dist/integration.d.cts +1 -1
  21. package/dist/integration.d.ts +1 -1
  22. package/dist/integration.js +1 -2
  23. package/dist/integration.js.map +1 -1
  24. package/dist/local-sync.cjs +154 -329
  25. package/dist/local-sync.cjs.map +1 -1
  26. package/dist/local-sync.d.cts +17 -22
  27. package/dist/local-sync.d.ts +17 -22
  28. package/dist/local-sync.js +149 -326
  29. package/dist/local-sync.js.map +1 -1
  30. package/dist/ownership-B-VAPcce.js +242 -0
  31. package/dist/ownership-B-VAPcce.js.map +1 -0
  32. package/dist/ownership-CU-9DKJQ.cjs +301 -0
  33. package/dist/ownership-CU-9DKJQ.cjs.map +1 -0
  34. package/package.json +1 -1
  35. package/skills/doxum-runtime/references/guide.en.md +52 -1
  36. package/skills/doxum-runtime/references/guide.zh-CN.md +46 -1
  37. package/skills/doxum-runtime/references/invariants.en.md +14 -4
  38. package/skills/doxum-runtime/references/invariants.zh-CN.md +1 -1
  39. package/dist/access-5D4KKFm7.js.map +0 -1
  40. package/dist/access-z56fVqZ2.cjs.map +0 -1
  41. package/dist/dependency-BRn1TRDi.js +0 -20
  42. package/dist/dependency-BRn1TRDi.js.map +0 -1
  43. package/dist/dependency-DmQXyj7q.cjs +0 -25
  44. package/dist/dependency-DmQXyj7q.cjs.map +0 -1
  45. package/dist/readable-B8E3FMq6.cjs +0 -2614
  46. package/dist/readable-B8E3FMq6.cjs.map +0 -1
  47. package/dist/readable-CIj02gIj.js +0 -2579
  48. package/dist/readable-CIj02gIj.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,6 +1,2596 @@
1
- import { A as read, B as optional, C as impact_target_exports, E as debugKey, F as dict, G as tree, H as schema, I as field, K as variant, L as list, O as nodeAt, P as profile, R as map, T as contains, U as single, V as record, W as table, a as schemaOf, c as documentReader, i as readWith, j as resolveAddress, k as overlaps, l as readerFor, o as DocumentDisposedError, r as documentOf, s as DocumentReentrancyError, z as object } from "./access-5D4KKFm7.js";
2
- import { a as decodeCommandFootprint, i as commandFootprint, n as createDocument, o as footprintsOverlap, r as registerProcessor, t as asReadable } from "./readable-CIj02gIj.js";
3
- import { t as createDependencyTracker } from "./dependency-BRn1TRDi.js";
1
+ import { A as optional, C as resolveLocated, D as list, E as field, F as tree, I as variant, M as schema, N as single, O as map, P as table, S as resolveAddress, T as dict, _ as debugKey, a as readWith, b as overlaps, c as DocumentReentrancyError, d as address$2, f as belongs, g as contains, h as impact_target_exports, i as documentOf, j as record, k as object, l as documentReader, m as id, n as accessOf, o as schemaOf, p as bucket, r as bindRuntimeAccess, s as DocumentDisposedError, t as createDependencyTracker, u as readerFor, v as locate, w as set$1, x as read, y as nodeAt$1 } from "./dependency-C5_R1tvQ.js";
2
+ import { a as isStablePayload, c as snapshotPayload, i as isRecord, l as transferPayload, n as deepEqual, o as ownPayload, r as isPlainObject, s as sameStructuralValue, t as cloneValue, u as profile } from "./ownership-B-VAPcce.js";
3
+ import { n as bindRuntimeDriver, r as disposeRuntimeDriver, t as assertRuntimeWritable } from "./driver-CbzfW5MR.js";
4
+ //#region core/src/impact.ts
5
+ const emptyCollectionImpact = Object.freeze({
6
+ kind: "incremental",
7
+ added: /* @__PURE__ */ new Set(),
8
+ removed: /* @__PURE__ */ new Set(),
9
+ updated: /* @__PURE__ */ new Set(),
10
+ orderChanged: false
11
+ });
12
+ const resetCollectionImpact = Object.freeze({ kind: "reset" });
13
+ const createImpact = (input) => {
14
+ const kind = input.reset ? "reset" : "incremental";
15
+ const paths = input.paths ?? input.operations.map((operation) => operation.at);
16
+ let pathBuckets;
17
+ const somePath = (address, test) => {
18
+ if (address.length === 0 || paths.length <= 8) return paths.some(test);
19
+ if (!pathBuckets) {
20
+ pathBuckets = /* @__PURE__ */ new Map();
21
+ for (const changed of paths) {
22
+ const first = changed[0];
23
+ const bucket = pathBuckets.get(first) ?? [];
24
+ bucket.push(changed);
25
+ pathBuckets.set(first, bucket);
26
+ }
27
+ }
28
+ if (pathBuckets.get(void 0)?.some(test)) return true;
29
+ return pathBuckets.get(address[0])?.some(test) ?? false;
30
+ };
31
+ const pathsAffect = (address) => address.length === 0 ? paths.length > 0 : somePath(address, (changed) => overlaps(changed, address));
32
+ let collectionCache;
33
+ const findCollection = (address) => input.collections?.find((entry) => entry.address.length === address.length && entry.address.every((segment, index) => segment === address[index]));
34
+ return {
35
+ kind,
36
+ operations: input.operations,
37
+ affects: (value) => {
38
+ profile.impact.affects();
39
+ if (kind === "reset") return true;
40
+ if (!belongs(value, input.schema)) return false;
41
+ if (pathsAffect(address$2(value))) return true;
42
+ if (value.kind === "collection") {
43
+ const collection = findCollection(address$2(value));
44
+ if (!collection) return false;
45
+ const id$1 = id(value);
46
+ if (id$1 !== void 0) return collection.added.has(id$1) || collection.removed.has(id$1) || collection.updated.has(id$1);
47
+ return collection.added.size > 0 || collection.removed.size > 0 || collection.updated.size > 0 || collection.orderChanged;
48
+ }
49
+ return false;
50
+ },
51
+ collection: (selector) => {
52
+ if (selector.schema !== input.schema) throw new Error("Collection selector belongs to another schema.");
53
+ if (kind === "reset") return resetCollectionImpact;
54
+ const cached = collectionCache?.find((entry) => entry.address.length === selector.address.length && entry.address.every((segment, index) => segment === selector.address[index]))?.value;
55
+ if (cached) return cached;
56
+ const exact = findCollection(selector.address);
57
+ if (somePath(selector.address, (changed) => contains(changed, selector.address) && changed.length < selector.address.length)) {
58
+ const reset = { kind: "reset" };
59
+ (collectionCache ??= []).push({
60
+ address: selector.address,
61
+ value: reset
62
+ });
63
+ return reset;
64
+ }
65
+ if (!exact) {
66
+ const empty = emptyCollectionImpact;
67
+ (collectionCache ??= []).push({
68
+ address: selector.address,
69
+ value: empty
70
+ });
71
+ return empty;
72
+ }
73
+ const incremental = {
74
+ kind: "incremental",
75
+ added: exact.added,
76
+ removed: exact.removed,
77
+ updated: exact.updated,
78
+ orderChanged: exact.orderChanged
79
+ };
80
+ (collectionCache ??= []).push({
81
+ address: selector.address,
82
+ value: incremental
83
+ });
84
+ return incremental;
85
+ }
86
+ };
87
+ };
88
+ //#endregion
89
+ //#region core/src/history.ts
90
+ const createHistory = (input) => {
91
+ const undos = [];
92
+ const redos = [];
93
+ const listeners = /* @__PURE__ */ new Set();
94
+ let state = Object.freeze({
95
+ undoDepth: 0,
96
+ redoDepth: 0
97
+ });
98
+ const current = () => {
99
+ if (state.undoDepth !== undos.length || state.redoDepth !== redos.length) state = Object.freeze({
100
+ undoDepth: undos.length,
101
+ redoDepth: redos.length
102
+ });
103
+ return state;
104
+ };
105
+ const emit = () => {
106
+ if (listeners.size === 0) return;
107
+ current();
108
+ Array.from(listeners).forEach((listener) => listener());
109
+ };
110
+ const clear = () => {
111
+ if (undos.length || redos.length) {
112
+ undos.length = 0;
113
+ redos.length = 0;
114
+ emit();
115
+ }
116
+ };
117
+ return {
118
+ api: {
119
+ current,
120
+ subscribe: (listener) => {
121
+ listeners.add(listener);
122
+ return () => listeners.delete(listener);
123
+ },
124
+ undo: () => {
125
+ const entry = undos.pop();
126
+ if (!entry) return {
127
+ status: "unchanged",
128
+ revision: input.revision()
129
+ };
130
+ const result = input.apply(entry.inverse);
131
+ if (result.status === "committed") {
132
+ redos.push(entry);
133
+ emit();
134
+ } else undos.push(entry);
135
+ return result;
136
+ },
137
+ redo: () => {
138
+ const entry = redos.pop();
139
+ if (!entry) return {
140
+ status: "unchanged",
141
+ revision: input.revision()
142
+ };
143
+ const result = input.apply(entry.operations);
144
+ if (result.status === "committed") {
145
+ undos.push(entry);
146
+ emit();
147
+ } else redos.push(entry);
148
+ return result;
149
+ },
150
+ clear
151
+ },
152
+ record: (operations, inverse) => {
153
+ if (input.capacity <= 0) return;
154
+ undos.push({
155
+ operations,
156
+ inverse
157
+ });
158
+ if (undos.length > input.capacity) undos.shift();
159
+ redos.length = 0;
160
+ emit();
161
+ },
162
+ invalidate: clear
163
+ };
164
+ };
165
+ //#endregion
166
+ //#region core/src/access/writer.ts
167
+ const schemaRoot = (schema) => object(schema.shape);
168
+ const emit = (sink, operation) => sink(operation);
169
+ const writerFor = (node, inputAddress, sink) => {
170
+ const address = Object.freeze(inputAddress);
171
+ if (node.kind === "field") return {
172
+ set: (value) => emit(sink, {
173
+ type: "field.set",
174
+ at: address,
175
+ value
176
+ }),
177
+ clear: node.optional ? () => emit(sink, {
178
+ type: "field.clear",
179
+ at: address
180
+ }) : void 0
181
+ };
182
+ if (node.kind === "dict" || node.kind === "record") return {
183
+ set: (key, value) => emit(sink, {
184
+ type: "dict.set",
185
+ at: address,
186
+ key,
187
+ value
188
+ }),
189
+ delete: (key) => emit(sink, {
190
+ type: "dict.delete",
191
+ at: address,
192
+ key
193
+ }),
194
+ replace: (value) => emit(sink, {
195
+ type: "dict.replace",
196
+ at: address,
197
+ value
198
+ })
199
+ };
200
+ if (node.kind === "list") return {
201
+ insert: (value, anchor) => emit(sink, {
202
+ type: "list.insert",
203
+ at: address,
204
+ key: node.keyOf(value),
205
+ value,
206
+ anchor
207
+ }),
208
+ move: (key, anchor) => emit(sink, {
209
+ type: "list.move",
210
+ at: address,
211
+ key,
212
+ anchor
213
+ }),
214
+ remove: (key) => emit(sink, {
215
+ type: "list.remove",
216
+ at: address,
217
+ key
218
+ }),
219
+ replace: (value) => emit(sink, {
220
+ type: "list.replace",
221
+ at: address,
222
+ value,
223
+ keys: value.map(node.keyOf)
224
+ })
225
+ };
226
+ if (node.kind === "tree") return {
227
+ insert: (treeNodeId, value, parentId, index) => emit(sink, {
228
+ type: "tree.insert",
229
+ at: address,
230
+ treeNodeId,
231
+ value,
232
+ parentId,
233
+ index
234
+ }),
235
+ move: (treeNodeId, parentId, index) => emit(sink, {
236
+ type: "tree.move",
237
+ at: address,
238
+ treeNodeId,
239
+ parentId,
240
+ index
241
+ }),
242
+ remove: (treeNodeId) => emit(sink, {
243
+ type: "tree.remove",
244
+ at: address,
245
+ treeNodeId
246
+ }),
247
+ set: (treeNodeId, value) => emit(sink, {
248
+ type: "tree.set",
249
+ at: address,
250
+ treeNodeId,
251
+ value
252
+ }),
253
+ replace: (value) => emit(sink, {
254
+ type: "tree.replace",
255
+ at: address,
256
+ value
257
+ })
258
+ };
259
+ if (node.kind === "table") {
260
+ let items;
261
+ return {
262
+ create: (input, anchor) => {
263
+ emit(sink, {
264
+ type: "entity.create",
265
+ at: address,
266
+ entries: (Array.isArray(input) ? input : [input]).map(({ id, value }) => ({
267
+ id,
268
+ value
269
+ })),
270
+ anchor
271
+ });
272
+ },
273
+ item: (id) => {
274
+ const cached = items?.get(id);
275
+ if (cached) return cached;
276
+ const writer = writerFor(node.value, [...address, id], sink);
277
+ (items ??= /* @__PURE__ */ new Map()).set(id, writer);
278
+ return writer;
279
+ },
280
+ remove: (input) => emit(sink, {
281
+ type: "entity.remove",
282
+ at: address,
283
+ ids: Array.isArray(input) ? [...input] : [input]
284
+ }),
285
+ move: (id, anchor) => emit(sink, {
286
+ type: "entity.move",
287
+ at: address,
288
+ id,
289
+ anchor
290
+ })
291
+ };
292
+ }
293
+ if (node.kind === "map") {
294
+ let items;
295
+ return {
296
+ create: (input) => {
297
+ emit(sink, {
298
+ type: "entity.create",
299
+ at: address,
300
+ entries: (Array.isArray(input) ? input : [input]).map(({ id, value }) => ({
301
+ id,
302
+ value
303
+ }))
304
+ });
305
+ },
306
+ item: (id) => {
307
+ const cached = items?.get(id);
308
+ if (cached) return cached;
309
+ const writer = writerFor(node.value, [...address, id], sink);
310
+ (items ??= /* @__PURE__ */ new Map()).set(id, writer);
311
+ return writer;
312
+ },
313
+ remove: (input) => emit(sink, {
314
+ type: "entity.remove",
315
+ at: address,
316
+ ids: Array.isArray(input) ? [...input] : [input]
317
+ })
318
+ };
319
+ }
320
+ if (node.kind === "single") return writerFor(node.value, address, sink);
321
+ if (node.kind === "variant") return { replace: (value) => emit(sink, {
322
+ type: "variant.replace",
323
+ at: address,
324
+ value
325
+ }) };
326
+ let children;
327
+ return new Proxy({}, { get: (_target, property) => {
328
+ if (typeof property !== "string" || !node.shape[property]) return void 0;
329
+ const cached = children?.get(property);
330
+ if (cached) return cached;
331
+ const writer = writerFor(node.shape[property], [...address, property], sink);
332
+ (children ??= /* @__PURE__ */ new Map()).set(property, writer);
333
+ return writer;
334
+ } });
335
+ };
336
+ const documentWriter = (schema, sink) => writerFor(schemaRoot(schema), [], sink);
337
+ //#endregion
338
+ //#region core/src/mutation/issue.ts
339
+ const ownAddress$1 = (address) => Object.freeze(address.slice());
340
+ const at$1 = (address, code, message, operation) => Object.freeze({
341
+ source: "mutation",
342
+ code,
343
+ address: ownAddress$1(address),
344
+ message,
345
+ ...operation === void 0 ? {} : { operation }
346
+ });
347
+ const from = (operation, code, message) => at$1(operation.at, code, message, operation.type);
348
+ const input = (code, message) => at$1([], code, message);
349
+ //#endregion
350
+ //#region core/src/mutation/anchor.ts
351
+ const length = (keys) => keys.length;
352
+ const keyAt = (keys, index) => Array.isArray(keys) ? keys[index] : keys.at(index);
353
+ const keyIndex = (keys, key) => Array.isArray(keys) ? keys.indexOf(key) : keys.index(key);
354
+ const keys = (values, keyOf) => ({
355
+ length: values.length,
356
+ at: (index) => index >= 0 && index < values.length ? keyOf(values[index]) : void 0,
357
+ index: (key) => {
358
+ for (let index = 0; index < values.length; index += 1) if (keyOf(values[index]) === key) return index;
359
+ return -1;
360
+ }
361
+ });
362
+ const index = (keys, anchor) => {
363
+ if (!anchor) return length(keys);
364
+ if ("at" in anchor) return anchor.at === "start" ? 0 : length(keys);
365
+ if ("before" in anchor) return keyIndex(keys, anchor.before);
366
+ return keyIndex(keys, anchor.after) + 1;
367
+ };
368
+ const at = (keys, position) => position <= 0 ? { at: "start" } : { after: keyAt(keys, position - 1) };
369
+ const valid = (keys, anchor) => {
370
+ if (!anchor) return true;
371
+ if (typeof anchor !== "object" || anchor === null) return false;
372
+ if (Number("at" in anchor) + Number("before" in anchor) + Number("after" in anchor) !== 1) return false;
373
+ if ("at" in anchor) return anchor.at === "start" || anchor.at === "end";
374
+ return keyIndex(keys, "before" in anchor ? anchor.before : anchor.after) >= 0;
375
+ };
376
+ const afterRemove = (keys, removedIndex, anchor) => {
377
+ const position = index(keys, anchor);
378
+ return position > removedIndex ? position - 1 : position;
379
+ };
380
+ const validPositions = (length, positions) => {
381
+ let previous = -1;
382
+ for (let index = 0; index < positions.length; index += 1) {
383
+ const position = positions[index];
384
+ if (!Number.isInteger(position) || position < 0 || position <= previous || position > length + index) return false;
385
+ previous = position;
386
+ }
387
+ return true;
388
+ };
389
+ const restore = (keys, inserted, positions) => {
390
+ const currentLength = keys.length;
391
+ if (inserted.length !== positions.length || !validPositions(currentLength, positions)) throw new Error("Ordered restore positions are invalid.");
392
+ let readIndex = currentLength - 1;
393
+ let insertedIndex = inserted.length - 1;
394
+ keys.length = currentLength + inserted.length;
395
+ for (let writeIndex = keys.length - 1; writeIndex >= 0; writeIndex -= 1) if (insertedIndex >= 0 && positions[insertedIndex] === writeIndex) {
396
+ keys[writeIndex] = inserted[insertedIndex];
397
+ insertedIndex -= 1;
398
+ } else {
399
+ keys[writeIndex] = keys[readIndex];
400
+ readIndex -= 1;
401
+ }
402
+ };
403
+ //#endregion
404
+ //#region core/src/mutation/execute-entity.ts
405
+ const resolveEntityCollection = (node, value) => {
406
+ if (node.kind === "table") {
407
+ if (!isRecord(value) || !Array.isArray(value.ids) || !isRecord(value.byId)) return { status: "invalid" };
408
+ return {
409
+ status: "resolved",
410
+ collection: {
411
+ kind: "table",
412
+ ids: value.ids,
413
+ byId: value.byId
414
+ }
415
+ };
416
+ }
417
+ return isRecord(value) ? {
418
+ status: "resolved",
419
+ collection: {
420
+ kind: "map",
421
+ byId: value
422
+ }
423
+ } : { status: "invalid" };
424
+ };
425
+ const rejected$4 = (operation, code, message) => ({
426
+ status: "rejected",
427
+ issue: from(operation, code, message)
428
+ });
429
+ const executeEntity = (target, operation, copyPayload) => {
430
+ if (target.node.kind !== "table" && target.node.kind !== "map") return rejected$4(operation, "invalid-address", "Collection target is invalid.");
431
+ const resolution = resolveEntityCollection(target.node, target.value);
432
+ if (resolution.status === "invalid") return rejected$4(operation, "invalid-address", "Collection target is invalid.");
433
+ const collection = resolution.collection;
434
+ const ids = collection.kind === "table" ? collection.ids : void 0;
435
+ if (operation.type === "entity.move" && collection.kind === "map") return rejected$4(operation, "invalid-operation", "Map entries are unordered.");
436
+ const byId = collection.byId;
437
+ if (operation.type === "entity.create") {
438
+ if (operation.entries.length === 0) return { status: "unchanged" };
439
+ const seen = /* @__PURE__ */ new Set();
440
+ for (const entry of operation.entries) {
441
+ if (seen.has(entry.id)) return rejected$4(operation, "duplicate-entity", "Entity ids must be unique within a batch.");
442
+ seen.add(entry.id);
443
+ if (Object.prototype.hasOwnProperty.call(byId, entry.id)) return rejected$4(operation, "duplicate-entity", `Entity '${entry.id}' already exists.`);
444
+ }
445
+ if (collection.kind === "map" && (operation.anchor || operation.positions)) return rejected$4(operation, "invalid-anchor", "Map entries do not support ordering metadata.");
446
+ if (ids && operation.positions) {
447
+ if (operation.positions.length !== operation.entries.length || !validPositions(ids.length, operation.positions)) return rejected$4(operation, "invalid-operation", "Entity restore positions are invalid.");
448
+ } else if (ids && !valid(ids, operation.anchor)) return rejected$4(operation, "invalid-anchor", "Collection anchor is invalid.");
449
+ for (const entry of operation.entries) byId[entry.id] = copyPayload ? cloneValue(entry.value, "canonical") : transferPayload(entry.value);
450
+ if (ids) if (operation.positions) restore(ids, operation.entries.map((entry) => entry.id), operation.positions);
451
+ else if (!operation.anchor || "at" in operation.anchor && operation.anchor.at === "end") for (const entry of operation.entries) ids.push(entry.id);
452
+ else {
453
+ const insertion = index(ids, operation.anchor);
454
+ const currentLength = ids.length;
455
+ ids.length = currentLength + operation.entries.length;
456
+ for (let index = currentLength - 1; index >= insertion; index -= 1) ids[index + operation.entries.length] = ids[index];
457
+ for (let index = 0; index < operation.entries.length; index += 1) ids[insertion + index] = operation.entries[index].id;
458
+ }
459
+ return {
460
+ status: "changed",
461
+ inverse: [{
462
+ type: "entity.remove",
463
+ at: operation.at,
464
+ ids: operation.entries.map((entry) => entry.id)
465
+ }]
466
+ };
467
+ }
468
+ if (operation.type === "entity.remove") {
469
+ if (operation.ids.length === 0) return { status: "unchanged" };
470
+ const seen = /* @__PURE__ */ new Set();
471
+ for (const id of operation.ids) {
472
+ if (seen.has(id)) return rejected$4(operation, "duplicate-entity", "Entity ids must be unique within a batch.");
473
+ seen.add(id);
474
+ if (!Object.prototype.hasOwnProperty.call(byId, id)) return rejected$4(operation, "missing-entity", `Entity '${id}' does not exist.`);
475
+ }
476
+ const entries = [];
477
+ const positions = [];
478
+ if (ids) {
479
+ const positionsById = /* @__PURE__ */ new Map();
480
+ for (let index = 0; index < ids.length; index += 1) {
481
+ const id = ids[index];
482
+ if (seen.has(id)) positionsById.set(id, index);
483
+ }
484
+ for (const id of operation.ids) if (!positionsById.has(id)) return rejected$4(operation, "invalid-collection", `Collection index is missing '${id}'.`);
485
+ let writeIndex = 0;
486
+ for (let index = 0; index < ids.length; index += 1) {
487
+ const id = ids[index];
488
+ if (seen.has(id)) {
489
+ entries.push({
490
+ id,
491
+ value: cloneValue(byId[id], "inverse")
492
+ });
493
+ positions.push(index);
494
+ delete byId[id];
495
+ } else ids[writeIndex++] = id;
496
+ }
497
+ ids.length = writeIndex;
498
+ } else for (const id of operation.ids) {
499
+ entries.push({
500
+ id,
501
+ value: cloneValue(byId[id], "inverse")
502
+ });
503
+ delete byId[id];
504
+ }
505
+ return {
506
+ status: "changed",
507
+ inverse: [{
508
+ type: "entity.create",
509
+ at: operation.at,
510
+ entries,
511
+ ...ids ? { positions } : {}
512
+ }]
513
+ };
514
+ }
515
+ const exists = Object.prototype.hasOwnProperty.call(byId, operation.id);
516
+ const position = ids?.indexOf(operation.id) ?? -1;
517
+ if (!exists) return rejected$4(operation, "missing-entity", `Entity '${operation.id}' does not exist.`);
518
+ if (!ids || position < 0) return rejected$4(operation, "invalid-collection", `Collection index is missing '${operation.id}'.`);
519
+ if (!valid(ids, operation.anchor)) return rejected$4(operation, "invalid-anchor", "Collection anchor is invalid.");
520
+ if (operation.anchor && ("before" in operation.anchor && operation.anchor.before === operation.id || "after" in operation.anchor && operation.anchor.after === operation.id)) return rejected$4(operation, "invalid-anchor", "An entity cannot be moved relative to itself.");
521
+ const nextIndex = afterRemove(ids, position, operation.anchor);
522
+ if (nextIndex === position) return { status: "unchanged" };
523
+ const inverse = {
524
+ type: "entity.move",
525
+ at: operation.at,
526
+ id: operation.id,
527
+ anchor: at(ids, position)
528
+ };
529
+ ids.splice(position, 1);
530
+ ids.splice(nextIndex, 0, operation.id);
531
+ return {
532
+ status: "changed",
533
+ inverse: [inverse]
534
+ };
535
+ };
536
+ //#endregion
537
+ //#region core/src/mutation/execute-list.ts
538
+ const rejected$3 = (operation, code, message) => ({
539
+ status: "rejected",
540
+ issue: from(operation, code, message)
541
+ });
542
+ const executeList = (target, operation, copyPayload) => {
543
+ if (!Array.isArray(target.value) || target.node.kind !== "list") return rejected$3(operation, "invalid-address", "List target is invalid.");
544
+ const list = target.value;
545
+ const orderedKeys = keys(list, target.node.keyOf);
546
+ const own = (value) => copyPayload ? ownPayload(value) : value;
547
+ if (operation.type === "list.replace") {
548
+ if (operation.keys.length !== operation.value.length) return rejected$3(operation, "invalid-list-keys", "List replacement keys are invalid.");
549
+ const seen = /* @__PURE__ */ new Set();
550
+ for (let index = 0; index < operation.value.length; index += 1) {
551
+ const key = operation.keys[index];
552
+ if (seen.has(key) || target.node.keyOf(operation.value[index]) !== key) return rejected$3(operation, "invalid-list-keys", "List replacement keys are invalid.");
553
+ seen.add(key);
554
+ }
555
+ if (sameStructuralValue(list, operation.value)) return { status: "unchanged" };
556
+ const keys = new Array(list.length);
557
+ for (let index = 0; index < list.length; index += 1) keys[index] = target.node.keyOf(list[index]);
558
+ const inverse = {
559
+ type: "list.replace",
560
+ at: operation.at,
561
+ value: cloneValue(list, "inverse"),
562
+ keys
563
+ };
564
+ const owned = own(operation.value);
565
+ list.length = owned.length;
566
+ for (let index = 0; index < owned.length; index += 1) list[index] = owned[index];
567
+ return {
568
+ status: "changed",
569
+ inverse: [inverse]
570
+ };
571
+ }
572
+ if (operation.type === "list.insert") {
573
+ if (target.node.keyOf(operation.value) !== operation.key) return rejected$3(operation, "invalid-list-key", "List item key does not match schema.");
574
+ if (orderedKeys.index(operation.key) >= 0) return rejected$3(operation, "duplicate-list-item", `List item '${operation.key}' already exists.`);
575
+ if (!valid(orderedKeys, operation.anchor)) return rejected$3(operation, "invalid-anchor", "List anchor is invalid.");
576
+ list.splice(index(orderedKeys, operation.anchor), 0, own(operation.value));
577
+ return {
578
+ status: "changed",
579
+ inverse: [{
580
+ type: "list.remove",
581
+ at: operation.at,
582
+ key: operation.key
583
+ }]
584
+ };
585
+ }
586
+ const position = orderedKeys.index(operation.key);
587
+ if (position < 0) return rejected$3(operation, "missing-list-item", `List item '${operation.key}' does not exist.`);
588
+ if (operation.type === "list.remove") {
589
+ const inverse = {
590
+ type: "list.insert",
591
+ at: operation.at,
592
+ key: operation.key,
593
+ value: cloneValue(list[position], "inverse"),
594
+ anchor: at(orderedKeys, position)
595
+ };
596
+ list.splice(position, 1);
597
+ return {
598
+ status: "changed",
599
+ inverse: [inverse]
600
+ };
601
+ }
602
+ if (!valid(orderedKeys, operation.anchor)) return rejected$3(operation, "invalid-anchor", "List anchor is invalid.");
603
+ if (operation.anchor && ("before" in operation.anchor && operation.anchor.before === operation.key || "after" in operation.anchor && operation.anchor.after === operation.key)) return rejected$3(operation, "invalid-anchor", "A list item cannot be moved relative to itself.");
604
+ const nextIndex = afterRemove(orderedKeys, position, operation.anchor);
605
+ if (nextIndex === position) return { status: "unchanged" };
606
+ const inverse = {
607
+ type: "list.move",
608
+ at: operation.at,
609
+ key: operation.key,
610
+ anchor: at(orderedKeys, position)
611
+ };
612
+ const [entry] = list.splice(position, 1);
613
+ list.splice(nextIndex, 0, entry);
614
+ return {
615
+ status: "changed",
616
+ inverse: [inverse]
617
+ };
618
+ };
619
+ //#endregion
620
+ //#region core/src/mutation/tree.ts
621
+ const has$1 = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
622
+ const validIndex = (index) => index === void 0 || Number.isInteger(index) && index >= 0;
623
+ const rejected$2 = (code, message) => ({
624
+ status: "rejected",
625
+ code,
626
+ message
627
+ });
628
+ const node = (tree, id) => tree.nodes[id];
629
+ const childIndex = (parent, id) => parent.children.indexOf(id);
630
+ const sameOrder$1 = (left, right) => {
631
+ if (left.length !== right.length) return false;
632
+ for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false;
633
+ return true;
634
+ };
635
+ const rootPresence = (id) => id === void 0 ? { status: "absent" } : {
636
+ status: "present",
637
+ id
638
+ };
639
+ const capture = (change, id, presence) => {
640
+ if (!change.nodes.has(id)) change.nodes.set(id, presence);
641
+ };
642
+ const without = (values, id) => {
643
+ const result = [];
644
+ for (const value of values) if (value !== id) result.push(value);
645
+ return result;
646
+ };
647
+ const inserted = (values, id, index) => {
648
+ const result = [...values];
649
+ result.splice(Math.min(index, result.length), 0, id);
650
+ return result;
651
+ };
652
+ const moved = (values, id, index) => {
653
+ const result = without(values, id);
654
+ result.splice(Math.min(index, result.length), 0, id);
655
+ return result;
656
+ };
657
+ const parentPresence = (tree, id, children) => {
658
+ const entry = node(tree, id);
659
+ return entry ? {
660
+ status: "present",
661
+ ...entry.parentId === void 0 ? {} : { parentId: entry.parentId },
662
+ children,
663
+ value: entry.value
664
+ } : { status: "absent" };
665
+ };
666
+ const restoreIncremental = (value, change) => {
667
+ if (!is(value)) return value;
668
+ if (change.root.status === "absent") delete value.rootId;
669
+ else value.rootId = change.root.id;
670
+ for (const [id, before] of change.nodes) {
671
+ if (before.status === "absent") {
672
+ delete value.nodes[id];
673
+ continue;
674
+ }
675
+ value.nodes[id] = {
676
+ ...before.parentId === void 0 ? {} : { parentId: before.parentId },
677
+ children: [...before.children],
678
+ value: before.value
679
+ };
680
+ }
681
+ return value;
682
+ };
683
+ const restoreChange = (value, change) => change.mode === "whole" ? ownPayload(change.value, "journal") : restoreIncremental(value, change);
684
+ const wholeChange = (inverse, previous) => {
685
+ if (!previous) return {
686
+ mode: "whole",
687
+ value: inverse.value
688
+ };
689
+ if (previous.mode === "whole") return previous;
690
+ return {
691
+ mode: "whole",
692
+ value: restoreIncremental(ownPayload(inverse.value, "journal"), previous)
693
+ };
694
+ };
695
+ const removedNodePresences = (inverses) => {
696
+ const children = /* @__PURE__ */ new Map();
697
+ for (const inverse of inverses) {
698
+ if (inverse.parentId === void 0) continue;
699
+ const entries = children.get(inverse.parentId);
700
+ const child = {
701
+ id: inverse.treeNodeId,
702
+ index: inverse.index ?? Number.MAX_SAFE_INTEGER
703
+ };
704
+ if (entries) entries.push(child);
705
+ else children.set(inverse.parentId, [child]);
706
+ }
707
+ const result = /* @__PURE__ */ new Map();
708
+ for (const inverse of inverses) {
709
+ const ordered = children.get(inverse.treeNodeId) ?? [];
710
+ ordered.sort((left, right) => left.index - right.index);
711
+ result.set(inverse.treeNodeId, {
712
+ status: "present",
713
+ ...inverse.parentId === void 0 ? {} : { parentId: inverse.parentId },
714
+ children: ordered.map((entry) => entry.id),
715
+ value: inverse.value
716
+ });
717
+ }
718
+ return result;
719
+ };
720
+ const recordChange = (previous, current, forward, inverses) => {
721
+ const replacement = inverses[0];
722
+ if (replacement?.type === "tree.replace") return wholeChange(replacement, previous);
723
+ if (previous?.mode === "whole") return previous;
724
+ const change = previous ?? {
725
+ mode: "incremental",
726
+ root: forward.type === "tree.insert" && forward.parentId === void 0 ? { status: "absent" } : forward.type === "tree.remove" && inverses[0]?.type === "tree.insert" ? rootPresence(inverses[0].parentId === void 0 ? inverses[0].treeNodeId : current.rootId) : rootPresence(current.rootId),
727
+ nodes: /* @__PURE__ */ new Map()
728
+ };
729
+ if (forward.type === "tree.insert") {
730
+ capture(change, forward.treeNodeId, { status: "absent" });
731
+ if (forward.parentId !== void 0) {
732
+ const parentNode = node(current, forward.parentId);
733
+ if (parentNode) capture(change, forward.parentId, parentPresence(current, forward.parentId, without(parentNode.children, forward.treeNodeId)));
734
+ }
735
+ return change;
736
+ }
737
+ if (forward.type === "tree.remove") {
738
+ const inserts = inverses.filter((inverse) => inverse.type === "tree.insert");
739
+ const removed = removedNodePresences(inserts);
740
+ for (const [id, presence] of removed) capture(change, id, presence);
741
+ const first = inserts[0];
742
+ if (first?.parentId !== void 0) {
743
+ const parentNode = node(current, first.parentId);
744
+ if (parentNode) capture(change, first.parentId, parentPresence(current, first.parentId, inserted(parentNode.children, first.treeNodeId, first.index ?? parentNode.children.length)));
745
+ }
746
+ return change;
747
+ }
748
+ if (forward.type === "tree.set") {
749
+ const inverse = inverses[0];
750
+ const entry = node(current, forward.treeNodeId);
751
+ if (entry && inverse?.type === "tree.set") capture(change, forward.treeNodeId, {
752
+ status: "present",
753
+ ...entry.parentId === void 0 ? {} : { parentId: entry.parentId },
754
+ children: [...entry.children],
755
+ value: inverse.value
756
+ });
757
+ return change;
758
+ }
759
+ if (forward.type === "tree.move") {
760
+ const inverse = inverses[0];
761
+ const entry = node(current, forward.treeNodeId);
762
+ if (!entry || inverse?.type !== "tree.move" || inverse.parentId === void 0) return change;
763
+ capture(change, forward.treeNodeId, {
764
+ status: "present",
765
+ parentId: inverse.parentId,
766
+ children: [...entry.children],
767
+ value: entry.value
768
+ });
769
+ const oldParent = node(current, inverse.parentId);
770
+ if (oldParent) {
771
+ const children = inverse.parentId === forward.parentId ? moved(oldParent.children, forward.treeNodeId, inverse.index ?? oldParent.children.length) : inserted(oldParent.children, forward.treeNodeId, inverse.index ?? oldParent.children.length);
772
+ capture(change, inverse.parentId, parentPresence(current, inverse.parentId, children));
773
+ }
774
+ if (forward.parentId !== void 0 && forward.parentId !== inverse.parentId) {
775
+ const nextParent = node(current, forward.parentId);
776
+ if (nextParent) capture(change, forward.parentId, parentPresence(current, forward.parentId, without(nextParent.children, forward.treeNodeId)));
777
+ }
778
+ }
779
+ return change;
780
+ };
781
+ const sameNodePresence = (before, value) => {
782
+ if (before.status === "absent") return value === void 0;
783
+ return value !== void 0 && before.parentId === value.parentId && sameOrder$1(before.children, value.children) && sameStructuralValue(before.value, value.value);
784
+ };
785
+ const changeChanged = (change, value) => {
786
+ if (change.mode === "whole") return !sameStructuralValue(change.value, value);
787
+ if (!is(value)) return true;
788
+ if ((change.root.status === "present" ? change.root.id : void 0) !== value.rootId) return true;
789
+ for (const [id, before] of change.nodes) if (!sameNodePresence(before, node(value, id))) return true;
790
+ return false;
791
+ };
792
+ const is = (value) => isRecord(value) && isRecord(value.nodes);
793
+ const contains$1 = (tree, id) => has$1(tree.nodes, id);
794
+ const validate = (value) => {
795
+ if (!is(value)) return false;
796
+ const ids = Object.keys(value.nodes);
797
+ if (ids.length === 0) return value.rootId === void 0;
798
+ if (typeof value.rootId !== "string" || !has$1(value.nodes, value.rootId)) return false;
799
+ for (const id of ids) {
800
+ const entry = value.nodes[id];
801
+ if (!isRecord(entry) || !Array.isArray(entry.children)) return false;
802
+ if (entry.children.some((child) => typeof child !== "string") || new Set(entry.children).size !== entry.children.length) return false;
803
+ if (entry.parentId !== void 0 && typeof entry.parentId !== "string") return false;
804
+ if (id === value.rootId) {
805
+ if (entry.parentId !== void 0) return false;
806
+ } else if (entry.parentId === void 0 || !has$1(value.nodes, entry.parentId)) return false;
807
+ for (const child of entry.children) {
808
+ const childNode = value.nodes[child];
809
+ if (!childNode || childNode.parentId !== id) return false;
810
+ }
811
+ }
812
+ const seen = /* @__PURE__ */ new Set();
813
+ const stack = [value.rootId];
814
+ while (stack.length) {
815
+ const id = stack.pop();
816
+ if (seen.has(id)) return false;
817
+ seen.add(id);
818
+ const entry = value.nodes[id];
819
+ if (!entry) return false;
820
+ for (const child of entry.children) stack.push(child);
821
+ }
822
+ return seen.size === ids.length;
823
+ };
824
+ const documentTreeError = (node, value, address) => {
825
+ if ("optional" in node && node.optional && value === void 0) return void 0;
826
+ if (node.kind === "tree") return validate(value) ? void 0 : address;
827
+ if (node.kind === "object") {
828
+ if (!isRecord(value)) return void 0;
829
+ for (const [key, child] of Object.entries(node.shape)) {
830
+ const error = documentTreeError(child, value[key], [...address, key]);
831
+ if (error) return error;
832
+ }
833
+ return;
834
+ }
835
+ if (node.kind === "single") return documentTreeError(node.value, value, address);
836
+ if (node.kind === "variant") {
837
+ if (!isRecord(value) || typeof value[node.tag] !== "string") return void 0;
838
+ const variant = node.variants[value[node.tag]];
839
+ return variant ? documentTreeError(variant, value, address) : void 0;
840
+ }
841
+ if (node.kind === "table") {
842
+ if (!isRecord(value) || !isRecord(value.byId)) return void 0;
843
+ for (const [id, entry] of Object.entries(value.byId)) {
844
+ const error = documentTreeError(node.value, entry, [...address, id]);
845
+ if (error) return error;
846
+ }
847
+ return;
848
+ }
849
+ if (node.kind === "map") {
850
+ if (!isRecord(value)) return void 0;
851
+ for (const [id, entry] of Object.entries(value)) {
852
+ const error = documentTreeError(node.value, entry, [...address, id]);
853
+ if (error) return error;
854
+ }
855
+ }
856
+ };
857
+ const invalidDocument = (schema, value) => documentTreeError({
858
+ kind: "object",
859
+ shape: schema.shape
860
+ }, value, []);
861
+ const replace = (current, operation) => {
862
+ if (!validate(operation.value)) return rejected$2("invalid-tree", "Tree replacement is malformed.");
863
+ if (sameStructuralValue(current, operation.value)) return { status: "unchanged" };
864
+ return {
865
+ status: "changed",
866
+ inverse: [{
867
+ type: "tree.replace",
868
+ at: operation.at,
869
+ value: cloneValue(current, "inverse")
870
+ }]
871
+ };
872
+ };
873
+ const insert = (tree, operation, value) => {
874
+ if (contains$1(tree, operation.treeNodeId)) return rejected$2("duplicate-tree-node", `Tree node '${operation.treeNodeId}' already exists.`);
875
+ if (!validIndex(operation.index)) return rejected$2("invalid-tree-index", "Tree index is invalid.");
876
+ if (tree.rootId === void 0) {
877
+ if (operation.parentId !== void 0) return rejected$2("missing-tree-parent", `Tree parent '${operation.parentId}' does not exist.`);
878
+ tree.nodes[operation.treeNodeId] = {
879
+ children: [],
880
+ value
881
+ };
882
+ tree.rootId = operation.treeNodeId;
883
+ } else {
884
+ if (operation.parentId === void 0) return rejected$2("invalid-tree", "A non-empty tree has exactly one root.");
885
+ const parentNode = node(tree, operation.parentId);
886
+ if (!parentNode) return rejected$2("missing-tree-parent", `Tree parent '${operation.parentId}' does not exist.`);
887
+ tree.nodes[operation.treeNodeId] = {
888
+ parentId: operation.parentId,
889
+ children: [],
890
+ value
891
+ };
892
+ parentNode.children.splice(Math.min(operation.index ?? parentNode.children.length, parentNode.children.length), 0, operation.treeNodeId);
893
+ }
894
+ return {
895
+ status: "changed",
896
+ inverse: [{
897
+ type: "tree.remove",
898
+ at: operation.at,
899
+ treeNodeId: operation.treeNodeId
900
+ }]
901
+ };
902
+ };
903
+ const set = (tree, operation, value) => {
904
+ const entry = node(tree, operation.treeNodeId);
905
+ if (!entry) return rejected$2("missing-tree-node", `Tree node '${operation.treeNodeId}' does not exist.`);
906
+ if (Object.is(entry.value, value)) return { status: "unchanged" };
907
+ const inverse = {
908
+ type: "tree.set",
909
+ at: operation.at,
910
+ treeNodeId: operation.treeNodeId,
911
+ value: cloneValue(entry.value, "inverse")
912
+ };
913
+ entry.value = value;
914
+ return {
915
+ status: "changed",
916
+ inverse: [inverse]
917
+ };
918
+ };
919
+ const remove = (tree, operation) => {
920
+ const first = node(tree, operation.treeNodeId);
921
+ if (!first) return rejected$2("missing-tree-node", `Tree node '${operation.treeNodeId}' does not exist.`);
922
+ const parentId = first.parentId;
923
+ const parentNode = parentId === void 0 ? void 0 : node(tree, parentId);
924
+ const originalIndex = parentNode ? childIndex(parentNode, operation.treeNodeId) : 0;
925
+ if (parentId !== void 0 && (!parentNode || originalIndex < 0) || parentId === void 0 && tree.rootId !== operation.treeNodeId) return rejected$2("invalid-tree", "Tree parent links are inconsistent.");
926
+ const entries = [];
927
+ const seen = /* @__PURE__ */ new Set();
928
+ const stack = [{
929
+ id: operation.treeNodeId,
930
+ parentId,
931
+ index: originalIndex
932
+ }];
933
+ while (stack.length) {
934
+ const frame = stack.pop();
935
+ const entry = node(tree, frame.id);
936
+ if (!entry || seen.has(frame.id) || entry.parentId !== frame.parentId) return rejected$2("invalid-tree", "Tree contains an invalid descendant.");
937
+ seen.add(frame.id);
938
+ entries.push({
939
+ id: frame.id,
940
+ parentId: frame.parentId,
941
+ index: frame.index,
942
+ value: cloneValue(entry.value, "inverse")
943
+ });
944
+ for (let index = entry.children.length - 1; index >= 0; index -= 1) {
945
+ const childId = entry.children[index];
946
+ const child = node(tree, childId);
947
+ if (!child || child.parentId !== frame.id) return rejected$2("invalid-tree", "Tree child links are inconsistent.");
948
+ stack.push({
949
+ id: childId,
950
+ parentId: frame.id,
951
+ index
952
+ });
953
+ }
954
+ }
955
+ if (parentNode) parentNode.children.splice(originalIndex, 1);
956
+ for (let index = entries.length - 1; index >= 0; index -= 1) delete tree.nodes[entries[index].id];
957
+ if (tree.rootId === operation.treeNodeId) delete tree.rootId;
958
+ return {
959
+ status: "changed",
960
+ inverse: entries.map((entry) => ({
961
+ type: "tree.insert",
962
+ at: operation.at,
963
+ treeNodeId: entry.id,
964
+ ...entry.parentId === void 0 ? {} : { parentId: entry.parentId },
965
+ index: entry.index,
966
+ value: entry.value
967
+ }))
968
+ };
969
+ };
970
+ const move = (tree, operation) => {
971
+ const entry = node(tree, operation.treeNodeId);
972
+ if (!entry) return rejected$2("missing-tree-node", `Tree node '${operation.treeNodeId}' does not exist.`);
973
+ if (!validIndex(operation.index)) return rejected$2("invalid-tree-index", "Tree index is invalid.");
974
+ if (tree.rootId === operation.treeNodeId) return rejected$2("invalid-tree", "The root cannot be moved.");
975
+ if (operation.parentId === void 0) return rejected$2("invalid-tree", "Only the root can have no parent.");
976
+ const nextParent = node(tree, operation.parentId);
977
+ if (!nextParent) return rejected$2("missing-tree-parent", `Tree parent '${operation.parentId}' does not exist.`);
978
+ if (operation.parentId === operation.treeNodeId) return rejected$2("tree-cycle", "A tree node cannot parent itself.");
979
+ const descendants = [operation.treeNodeId];
980
+ const seen = /* @__PURE__ */ new Set();
981
+ while (descendants.length) {
982
+ const id = descendants.pop();
983
+ if (seen.has(id)) return rejected$2("invalid-tree", "Tree contains a cycle.");
984
+ seen.add(id);
985
+ const current = node(tree, id);
986
+ if (!current) return rejected$2("invalid-tree", "Tree contains a missing node.");
987
+ for (const childId of current.children) {
988
+ const child = node(tree, childId);
989
+ if (!child || child.parentId !== id) return rejected$2("invalid-tree", "Tree child links are inconsistent.");
990
+ if (childId === operation.parentId) return rejected$2("tree-cycle", "Tree move would create a cycle.");
991
+ descendants.push(childId);
992
+ }
993
+ }
994
+ const parentId = entry.parentId;
995
+ const currentParent = parentId === void 0 ? void 0 : node(tree, parentId);
996
+ if (!currentParent || parentId === void 0) return rejected$2("invalid-tree", "Tree parent links are inconsistent.");
997
+ const originalIndex = childIndex(currentParent, operation.treeNodeId);
998
+ if (originalIndex < 0) return rejected$2("invalid-tree", "Tree parent links are inconsistent.");
999
+ let nextIndex = Math.min(operation.index ?? nextParent.children.length, nextParent.children.length);
1000
+ currentParent.children.splice(originalIndex, 1);
1001
+ if (parentId === operation.parentId && nextIndex > originalIndex) nextIndex -= 1;
1002
+ if (parentId === operation.parentId && nextIndex === originalIndex) {
1003
+ currentParent.children.splice(originalIndex, 0, operation.treeNodeId);
1004
+ return { status: "unchanged" };
1005
+ }
1006
+ nextParent.children.splice(nextIndex, 0, operation.treeNodeId);
1007
+ entry.parentId = operation.parentId;
1008
+ return {
1009
+ status: "changed",
1010
+ inverse: [{
1011
+ type: "tree.move",
1012
+ at: operation.at,
1013
+ treeNodeId: operation.treeNodeId,
1014
+ parentId,
1015
+ index: originalIndex
1016
+ }]
1017
+ };
1018
+ };
1019
+ //#endregion
1020
+ //#region core/src/mutation/execute-tree.ts
1021
+ const outcome = (operation, value) => value.status === "rejected" ? {
1022
+ status: "rejected",
1023
+ issue: from(operation, value.code, value.message)
1024
+ } : value;
1025
+ const executeTree = (root, target, operation, copyPayload) => {
1026
+ if (!is(target.value)) return {
1027
+ status: "rejected",
1028
+ issue: from(operation, "invalid-address", "Tree target is invalid.")
1029
+ };
1030
+ const own = (value) => copyPayload ? ownPayload(value) : value;
1031
+ if (operation.type === "tree.replace") {
1032
+ const result = replace(target.value, operation);
1033
+ if (result.status === "changed") set$1(root, operation.at, ownPayload(operation.value));
1034
+ return outcome(operation, result);
1035
+ }
1036
+ if (operation.type === "tree.insert") return outcome(operation, insert(target.value, operation, own(operation.value)));
1037
+ if (operation.type === "tree.set") return outcome(operation, set(target.value, operation, own(operation.value)));
1038
+ if (operation.type === "tree.remove") return outcome(operation, remove(target.value, operation));
1039
+ return outcome(operation, move(target.value, operation));
1040
+ };
1041
+ //#endregion
1042
+ //#region core/src/mutation/execute-value.ts
1043
+ const rejected$1 = (operation, code, message) => ({
1044
+ status: "rejected",
1045
+ issue: from(operation, code, message)
1046
+ });
1047
+ const executeValue = (target, operation, copyPayload) => {
1048
+ const own = (value) => copyPayload ? ownPayload(value) : value;
1049
+ if (operation.type === "field.set" || operation.type === "field.clear") {
1050
+ const existed = Object.prototype.hasOwnProperty.call(target.parent, target.key);
1051
+ if (operation.type === "field.clear") {
1052
+ if (target.node.kind !== "field" || !target.node.optional) return rejected$1(operation, "required-field", "Only optional fields can be cleared.");
1053
+ if (!existed) return { status: "unchanged" };
1054
+ const inverse = {
1055
+ type: "field.set",
1056
+ at: operation.at,
1057
+ value: target.value
1058
+ };
1059
+ delete target.parent[target.key];
1060
+ return {
1061
+ status: "changed",
1062
+ inverse: [inverse]
1063
+ };
1064
+ }
1065
+ if (existed && Object.is(target.value, operation.value)) return { status: "unchanged" };
1066
+ const inverse = existed ? {
1067
+ type: "field.set",
1068
+ at: operation.at,
1069
+ value: target.value
1070
+ } : {
1071
+ type: "field.clear",
1072
+ at: operation.at
1073
+ };
1074
+ target.parent[target.key] = operation.value;
1075
+ return {
1076
+ status: "changed",
1077
+ inverse: [inverse]
1078
+ };
1079
+ }
1080
+ if (operation.type === "variant.replace") {
1081
+ if (sameStructuralValue(target.value, operation.value)) return { status: "unchanged" };
1082
+ const inverse = {
1083
+ type: "variant.replace",
1084
+ at: operation.at,
1085
+ value: ownPayload(target.value, "inverse")
1086
+ };
1087
+ target.parent[target.key] = own(operation.value);
1088
+ return {
1089
+ status: "changed",
1090
+ inverse: [inverse]
1091
+ };
1092
+ }
1093
+ if (!isRecord(target.value)) return rejected$1(operation, "invalid-address", "Dictionary target is invalid.");
1094
+ if (operation.type === "dict.replace") {
1095
+ if (sameStructuralValue(target.value, operation.value)) return { status: "unchanged" };
1096
+ const inverse = {
1097
+ type: "dict.replace",
1098
+ at: operation.at,
1099
+ value: cloneValue(target.value, "inverse")
1100
+ };
1101
+ target.parent[target.key] = own(operation.value);
1102
+ return {
1103
+ status: "changed",
1104
+ inverse: [inverse]
1105
+ };
1106
+ }
1107
+ const existed = Object.prototype.hasOwnProperty.call(target.value, operation.key);
1108
+ if (operation.type === "dict.delete") {
1109
+ if (!existed) return { status: "unchanged" };
1110
+ const inverse = {
1111
+ type: "dict.set",
1112
+ at: operation.at,
1113
+ key: operation.key,
1114
+ value: target.value[operation.key]
1115
+ };
1116
+ delete target.value[operation.key];
1117
+ return {
1118
+ status: "changed",
1119
+ inverse: [inverse]
1120
+ };
1121
+ }
1122
+ if (existed && Object.is(target.value[operation.key], operation.value)) return { status: "unchanged" };
1123
+ const inverse = existed ? {
1124
+ type: "dict.set",
1125
+ at: operation.at,
1126
+ key: operation.key,
1127
+ value: target.value[operation.key]
1128
+ } : {
1129
+ type: "dict.delete",
1130
+ at: operation.at,
1131
+ key: operation.key
1132
+ };
1133
+ target.value[operation.key] = operation.value;
1134
+ return {
1135
+ status: "changed",
1136
+ inverse: [inverse]
1137
+ };
1138
+ };
1139
+ //#endregion
1140
+ //#region core/src/mutation/execute.ts
1141
+ const invalidTarget = (operation) => ({
1142
+ status: "rejected",
1143
+ issue: from(operation, "invalid-address", `Operation '${operation.type}' does not match the schema address.`)
1144
+ });
1145
+ const execute = (root, operation, target, copyPayload) => {
1146
+ if (operation.type === "field.set" || operation.type === "field.clear") return !target || target.node.kind !== "field" ? invalidTarget(operation) : executeValue(target, operation, copyPayload);
1147
+ if (operation.type === "variant.replace") return !target || target.node.kind !== "variant" ? invalidTarget(operation) : executeValue(target, operation, copyPayload);
1148
+ if (operation.type === "dict.set" || operation.type === "dict.delete" || operation.type === "dict.replace") return !target || target.node.kind !== "dict" && target.node.kind !== "record" ? invalidTarget(operation) : executeValue(target, operation, copyPayload);
1149
+ if (operation.type === "entity.create" || operation.type === "entity.remove" || operation.type === "entity.move") return !target || target.node.kind !== "table" && target.node.kind !== "map" ? invalidTarget(operation) : executeEntity(target, operation, copyPayload);
1150
+ if (operation.type === "list.insert" || operation.type === "list.move" || operation.type === "list.remove" || operation.type === "list.replace") return !target || target.node.kind !== "list" ? invalidTarget(operation) : executeList(target, operation, copyPayload);
1151
+ if (operation.type === "tree.insert" || operation.type === "tree.move" || operation.type === "tree.remove" || operation.type === "tree.set" || operation.type === "tree.replace") return !target || target.node.kind !== "tree" ? invalidTarget(operation) : executeTree(root, target, operation, copyPayload);
1152
+ return {
1153
+ status: "rejected",
1154
+ issue: from(operation, "unknown-operation", "Unknown document operation.")
1155
+ };
1156
+ };
1157
+ //#endregion
1158
+ //#region core/src/mutation/journal.ts
1159
+ const indexNode = () => ({ children: /* @__PURE__ */ new Map() });
1160
+ const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
1161
+ const sameAddress$1 = (left, right) => {
1162
+ if (left.length !== right.length) return false;
1163
+ for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false;
1164
+ return true;
1165
+ };
1166
+ const sameOrder = (left, right) => {
1167
+ if (left.length !== right.length) return false;
1168
+ for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false;
1169
+ return true;
1170
+ };
1171
+ const replaceArray = (target, value) => {
1172
+ target.length = value.length;
1173
+ for (let index = 0; index < value.length; index += 1) target[index] = value[index];
1174
+ };
1175
+ const present = (value) => ({
1176
+ status: "present",
1177
+ value
1178
+ });
1179
+ const absent = Object.freeze({ status: "absent" });
1180
+ const inverseMismatch = (operation) => {
1181
+ throw new Error(`Mutation inverse does not match '${operation.type}'.`);
1182
+ };
1183
+ const ownsDescendant = (subject, address) => {
1184
+ if (subject.address.length >= address.length) return false;
1185
+ if (subject.kind === "variant") return true;
1186
+ if (subject.kind !== "entity") return false;
1187
+ return subject.entries.has(address[subject.address.length]);
1188
+ };
1189
+ const nodeAt = (root, address) => {
1190
+ let node = root;
1191
+ for (const segment of address) {
1192
+ node = node.children.get(segment);
1193
+ if (!node) return void 0;
1194
+ }
1195
+ return node;
1196
+ };
1197
+ const indexedSubjects = (root, address) => {
1198
+ const start = nodeAt(root, address);
1199
+ if (!start) return [];
1200
+ const subjects = [];
1201
+ const stack = [start];
1202
+ while (stack.length) {
1203
+ const node = stack.pop();
1204
+ if (!node) break;
1205
+ if (node.subject) subjects.push(node.subject);
1206
+ for (const child of node.children.values()) stack.push(child);
1207
+ }
1208
+ return subjects;
1209
+ };
1210
+ const writePresence = (root, address, before) => {
1211
+ const target = locate(root, address);
1212
+ if (!target) return;
1213
+ if (before.status === "present") target.parent[target.key] = before.value;
1214
+ else if (Array.isArray(target.parent)) target.parent.splice(Number(target.key), 1);
1215
+ else delete target.parent[String(target.key)];
1216
+ };
1217
+ const writeContainer = (root, address, value) => {
1218
+ const target = locate(root, address);
1219
+ if (!target) return;
1220
+ target.parent[target.key] = value;
1221
+ };
1222
+ const restoreDict = (value, state) => {
1223
+ if (state.mode === "whole") {
1224
+ for (const key of Object.keys(value)) delete value[key];
1225
+ for (const [key, entry] of Object.entries(state.value)) value[key] = entry;
1226
+ return;
1227
+ }
1228
+ for (const [key, before] of state.entries) if (before.status === "present") value[key] = before.value;
1229
+ else delete value[key];
1230
+ };
1231
+ const restoreList = (value, subject) => {
1232
+ if (subject.state.mode === "whole") {
1233
+ replaceArray(value, subject.state.value);
1234
+ return;
1235
+ }
1236
+ const entries = /* @__PURE__ */ new Map();
1237
+ for (const entry of value) entries.set(subject.node.keyOf(entry), entry);
1238
+ for (const [key, before] of subject.state.items) if (before.status === "present") entries.set(key, before.value);
1239
+ else entries.delete(key);
1240
+ const restored = new Array(subject.state.order.length);
1241
+ for (let index = 0; index < subject.state.order.length; index += 1) restored[index] = entries.get(subject.state.order[index]);
1242
+ replaceArray(value, restored);
1243
+ };
1244
+ const entityCollection = (subject, value) => resolveEntityCollection(subject.node, value);
1245
+ const restoreEntity = (value, subject) => {
1246
+ const resolution = entityCollection(subject, value);
1247
+ if (resolution.status === "invalid") return;
1248
+ const collection = resolution.collection;
1249
+ for (const [id, before] of subject.entries) if (before.status === "present") collection.byId[id] = before.value;
1250
+ else delete collection.byId[id];
1251
+ if (collection.kind !== "table") return;
1252
+ if (subject.order.kind === "tracked") {
1253
+ replaceArray(collection.ids, subject.order.before);
1254
+ return;
1255
+ }
1256
+ if (subject.order.kind === "stable") restoreEntityOrder(collection.ids, subject.order.inverses);
1257
+ };
1258
+ const restoreRootSubject = (value, subject) => {
1259
+ if (subject.kind === "value") return subject.before.status === "present" ? subject.before.value : void 0;
1260
+ if (subject.kind === "variant") return subject.before;
1261
+ if (subject.kind === "dict") {
1262
+ if (isRecord(value)) restoreDict(value, subject.state);
1263
+ return value;
1264
+ }
1265
+ if (subject.kind === "entity") {
1266
+ restoreEntity(value, subject);
1267
+ return value;
1268
+ }
1269
+ if (subject.kind === "list") {
1270
+ if (Array.isArray(value)) restoreList(value, subject);
1271
+ return value;
1272
+ }
1273
+ return restoreChange(value, subject.state);
1274
+ };
1275
+ const restoreSubject = (value, prefix, subject) => {
1276
+ if (sameAddress$1(prefix, subject.address)) return restoreRootSubject(value, subject);
1277
+ const address = subject.address.slice(prefix.length);
1278
+ if (subject.kind === "value") {
1279
+ writePresence(value, address, subject.before);
1280
+ return value;
1281
+ }
1282
+ if (subject.kind === "variant") {
1283
+ writeContainer(value, address, subject.before);
1284
+ return value;
1285
+ }
1286
+ const current = read(value, address);
1287
+ if (subject.kind === "dict") {
1288
+ if (isRecord(current)) restoreDict(current, subject.state);
1289
+ return value;
1290
+ }
1291
+ if (subject.kind === "entity") {
1292
+ restoreEntity(current, subject);
1293
+ return value;
1294
+ }
1295
+ if (subject.kind === "list") {
1296
+ if (Array.isArray(current)) restoreList(current, subject);
1297
+ return value;
1298
+ }
1299
+ const restored = restoreChange(current, subject.state);
1300
+ if (restored !== current) writeContainer(value, address, restored);
1301
+ return value;
1302
+ };
1303
+ const valueChanged = (root, subject) => {
1304
+ const target = locate(root, subject.address);
1305
+ const exists = !!target && hasOwn(target.parent, target.key);
1306
+ if (subject.before.status === "absent") return exists;
1307
+ return !exists || !Object.is(subject.before.value, target?.value);
1308
+ };
1309
+ const dictChanged = (root, subject) => {
1310
+ const value = read(root, subject.address);
1311
+ if (!isRecord(value)) return true;
1312
+ if (subject.state.mode === "whole") return !sameStructuralValue(subject.state.value, value);
1313
+ for (const [key, before] of subject.state.entries) {
1314
+ const exists = hasOwn(value, key);
1315
+ if (before.status === "absent" ? exists : !exists || !Object.is(before.value, value[key])) return true;
1316
+ }
1317
+ return false;
1318
+ };
1319
+ const listChanged = (root, subject) => {
1320
+ const value = read(root, subject.address);
1321
+ if (!Array.isArray(value)) return true;
1322
+ if (subject.state.mode === "whole") return !sameStructuralValue(subject.state.value, value);
1323
+ const positions = /* @__PURE__ */ new Map();
1324
+ const order = new Array(value.length);
1325
+ for (let index = 0; index < value.length; index += 1) {
1326
+ const key = subject.node.keyOf(value[index]);
1327
+ order[index] = key;
1328
+ positions.set(key, index);
1329
+ }
1330
+ if (!sameOrder(subject.state.order, order)) return true;
1331
+ for (const [key, before] of subject.state.items) {
1332
+ const position = positions.get(key);
1333
+ if (before.status === "absent") {
1334
+ if (position !== void 0) return true;
1335
+ } else if (position === void 0 || !sameStructuralValue(before.value, value[position])) return true;
1336
+ }
1337
+ return false;
1338
+ };
1339
+ const commonOrderChanged = (before, after) => {
1340
+ const finalPositions = /* @__PURE__ */ new Map();
1341
+ for (let index = 0; index < after.length; index += 1) finalPositions.set(after[index], index);
1342
+ let previous = -1;
1343
+ for (const id of before) {
1344
+ const position = finalPositions.get(id);
1345
+ if (position === void 0) continue;
1346
+ if (position < previous) return true;
1347
+ previous = position;
1348
+ }
1349
+ return false;
1350
+ };
1351
+ const analyzeEntity = (root, subject) => {
1352
+ const resolution = entityCollection(subject, read(root, subject.address));
1353
+ const added = /* @__PURE__ */ new Set();
1354
+ const removed = /* @__PURE__ */ new Set();
1355
+ const updated = /* @__PURE__ */ new Set();
1356
+ if (resolution.status === "invalid") return {
1357
+ changed: true,
1358
+ added,
1359
+ removed,
1360
+ updated,
1361
+ orderChanged: false
1362
+ };
1363
+ const collection = resolution.collection;
1364
+ for (const [id, before] of subject.entries) {
1365
+ const exists = hasOwn(collection.byId, id);
1366
+ if (before.status === "absent") {
1367
+ if (exists) added.add(id);
1368
+ } else if (!exists) removed.add(id);
1369
+ else if (!sameStructuralValue(before.value, collection.byId[id])) updated.add(id);
1370
+ }
1371
+ const beforeOrder = subject.order.kind === "tracked" ? subject.order.before : void 0;
1372
+ const finalOrder = collection.kind === "table" ? collection.ids : [];
1373
+ const netOrderChanged = beforeOrder !== void 0 && !sameOrder(beforeOrder, finalOrder);
1374
+ return {
1375
+ changed: added.size > 0 || removed.size > 0 || updated.size > 0 || netOrderChanged,
1376
+ added,
1377
+ removed,
1378
+ updated,
1379
+ orderChanged: beforeOrder !== void 0 && commonOrderChanged(beforeOrder, finalOrder)
1380
+ };
1381
+ };
1382
+ const subjectChanged = (root, subject) => {
1383
+ if (subject.kind === "value") return valueChanged(root, subject);
1384
+ if (subject.kind === "variant") return !sameStructuralValue(subject.before, read(root, subject.address));
1385
+ if (subject.kind === "dict") return dictChanged(root, subject);
1386
+ if (subject.kind === "list") return listChanged(root, subject);
1387
+ return changeChanged(subject.state, read(root, subject.address));
1388
+ };
1389
+ const listOrderBefore = (value, node, inverse) => {
1390
+ const order = value.map(node.keyOf);
1391
+ if (inverse.type === "list.remove") return order.filter((key) => key !== inverse.key);
1392
+ if (inverse.type === "list.insert") {
1393
+ order.splice(index(order, inverse.anchor), 0, inverse.key);
1394
+ return order;
1395
+ }
1396
+ if (inverse.type === "list.move") {
1397
+ const position = order.indexOf(inverse.key);
1398
+ if (position >= 0) order.splice(position, 1);
1399
+ order.splice(index(order, inverse.anchor), 0, inverse.key);
1400
+ }
1401
+ return order;
1402
+ };
1403
+ const recordListPresence = (state, inverse) => {
1404
+ if (inverse.type === "list.remove" && !state.items.has(inverse.key)) state.items.set(inverse.key, absent);
1405
+ else if (inverse.type === "list.insert" && !state.items.has(inverse.key)) state.items.set(inverse.key, present(inverse.value));
1406
+ };
1407
+ const entityOrderInverse = (operation, inverse) => {
1408
+ if (inverse.type === "entity.remove") return {
1409
+ kind: "remove",
1410
+ ids: inverse.ids
1411
+ };
1412
+ if (inverse.type === "entity.create") {
1413
+ if (!inverse.positions || inverse.positions.length !== inverse.entries.length) return inverseMismatch(operation);
1414
+ return {
1415
+ kind: "restore",
1416
+ ids: inverse.entries.map((entry) => entry.id),
1417
+ positions: inverse.positions
1418
+ };
1419
+ }
1420
+ if (inverse.type === "entity.move") return {
1421
+ kind: "move",
1422
+ id: inverse.id,
1423
+ ...inverse.anchor ? { anchor: inverse.anchor } : {}
1424
+ };
1425
+ return inverseMismatch(operation);
1426
+ };
1427
+ const removeEntityIds = (order, ids) => {
1428
+ const removed = new Set(ids);
1429
+ let writeIndex = 0;
1430
+ for (const id of order) if (!removed.has(id)) order[writeIndex++] = id;
1431
+ order.length = writeIndex;
1432
+ };
1433
+ const restoreEntityOrder = (order, inverses) => {
1434
+ for (let index = inverses.length - 1; index >= 0; index -= 1) {
1435
+ const inverse = inverses[index];
1436
+ if (inverse.kind === "remove") {
1437
+ removeEntityIds(order, inverse.ids);
1438
+ continue;
1439
+ }
1440
+ if (inverse.kind === "restore") {
1441
+ restore(order, inverse.ids, inverse.positions);
1442
+ continue;
1443
+ }
1444
+ const position = order.indexOf(inverse.id);
1445
+ if (position < 0 || !valid(order, inverse.anchor)) throw new Error(`Entity order inverse cannot restore '${inverse.id}'.`);
1446
+ const nextIndex = afterRemove(order, position, inverse.anchor);
1447
+ order.splice(position, 1);
1448
+ order.splice(nextIndex, 0, inverse.id);
1449
+ }
1450
+ };
1451
+ const treeOperation = (operation) => operation.type.startsWith("tree.");
1452
+ const createChangeJournal = (root) => {
1453
+ const active = /* @__PURE__ */ new Set();
1454
+ const index = indexNode();
1455
+ const buckets = /* @__PURE__ */ new Map();
1456
+ const add = (subject) => {
1457
+ active.add(subject);
1458
+ const candidates = buckets.get(subject.addressHash);
1459
+ if (candidates) candidates.push(subject);
1460
+ else buckets.set(subject.addressHash, [subject]);
1461
+ let node = index;
1462
+ for (const segment of subject.address) {
1463
+ const existing = node.children.get(segment);
1464
+ if (existing) node = existing;
1465
+ else {
1466
+ const created = indexNode();
1467
+ node.children.set(segment, created);
1468
+ node = created;
1469
+ }
1470
+ }
1471
+ if (node.subject) throw new Error(`Change journal already owns '${subject.address.join(".")}'.`);
1472
+ node.subject = subject;
1473
+ profile.journal.subject();
1474
+ return subject;
1475
+ };
1476
+ const remove = (subject) => {
1477
+ if (!active.delete(subject)) return;
1478
+ const candidates = buckets.get(subject.addressHash);
1479
+ if (candidates) {
1480
+ const position = candidates.indexOf(subject);
1481
+ if (position >= 0) candidates.splice(position, 1);
1482
+ if (candidates.length === 0) buckets.delete(subject.addressHash);
1483
+ }
1484
+ const nodes = [index];
1485
+ let node = index;
1486
+ for (const segment of subject.address) {
1487
+ const child = node.children.get(segment);
1488
+ if (!child) return;
1489
+ nodes.push(child);
1490
+ node = child;
1491
+ }
1492
+ if (node.subject === subject) delete node.subject;
1493
+ for (let position = subject.address.length - 1; position >= 0; position -= 1) {
1494
+ const child = nodes[position + 1];
1495
+ if (child.subject || child.children.size > 0) break;
1496
+ nodes[position].children.delete(subject.address[position]);
1497
+ }
1498
+ };
1499
+ function find(kind, address, addressHash) {
1500
+ const candidates = buckets.get(addressHash) ?? [];
1501
+ for (const subject of candidates) {
1502
+ profile.journal.comparison();
1503
+ if (subject.kind === kind && sameAddress$1(subject.address, address)) return subject;
1504
+ }
1505
+ }
1506
+ const ownerOf = (address) => {
1507
+ let node = index;
1508
+ for (let position = 0; position < address.length; position += 1) {
1509
+ if (node.subject && ownsDescendant(node.subject, address)) return node.subject;
1510
+ const child = node.children.get(address[position]);
1511
+ if (!child) return void 0;
1512
+ node = child;
1513
+ }
1514
+ };
1515
+ const absorb = (value, address) => {
1516
+ const subjects = indexedSubjects(index, address);
1517
+ if (subjects.length === 0) return value;
1518
+ subjects.sort((left, right) => left.address.length - right.address.length);
1519
+ let before = ownPayload(value, "journal");
1520
+ for (const subject of subjects) before = restoreSubject(before, address, subject);
1521
+ for (const subject of subjects) {
1522
+ remove(subject);
1523
+ profile.journal.absorbed();
1524
+ }
1525
+ return before;
1526
+ };
1527
+ const base = (resolved, operation) => ({
1528
+ address: operation.at,
1529
+ addressHash: resolved.addressHash,
1530
+ ...resolved.collection ? { collection: resolved.collection } : {}
1531
+ });
1532
+ const recordValue = (resolved, operation, inverse) => {
1533
+ if (find("value", operation.at, resolved.addressHash)) return;
1534
+ const first = inverse[0];
1535
+ if (first?.type !== "field.set" && first?.type !== "field.clear") return inverseMismatch(operation);
1536
+ add({
1537
+ ...base(resolved, operation),
1538
+ kind: "value",
1539
+ before: first.type === "field.set" ? present(first.value) : absent
1540
+ });
1541
+ };
1542
+ const recordVariant = (resolved, operation, inverse) => {
1543
+ if (find("variant", operation.at, resolved.addressHash)) return;
1544
+ const first = inverse[0];
1545
+ if (first?.type !== "variant.replace") return inverseMismatch(operation);
1546
+ add({
1547
+ ...base(resolved, operation),
1548
+ kind: "variant",
1549
+ before: absorb(first.value, operation.at)
1550
+ });
1551
+ };
1552
+ const recordDict = (resolved, operation, inverse) => {
1553
+ const first = inverse[0];
1554
+ if (!first) return inverseMismatch(operation);
1555
+ const subject = find("dict", operation.at, resolved.addressHash) ?? add({
1556
+ ...base(resolved, operation),
1557
+ kind: "dict",
1558
+ state: {
1559
+ mode: "incremental",
1560
+ entries: /* @__PURE__ */ new Map()
1561
+ }
1562
+ });
1563
+ if (subject.state.mode === "whole") return;
1564
+ if (first.type === "dict.replace") {
1565
+ const value = ownPayload(first.value, "journal");
1566
+ restoreDict(value, subject.state);
1567
+ subject.state = {
1568
+ mode: "whole",
1569
+ value
1570
+ };
1571
+ return;
1572
+ }
1573
+ if (first.type !== "dict.set" && first.type !== "dict.delete") return inverseMismatch(operation);
1574
+ if (!subject.state.entries.has(first.key)) subject.state.entries.set(first.key, first.type === "dict.set" ? present(first.value) : absent);
1575
+ };
1576
+ const recordList = (resolved, operation, inverse) => {
1577
+ if (resolved.node.kind !== "list") return inverseMismatch(operation);
1578
+ const first = inverse[0];
1579
+ if (!first) return inverseMismatch(operation);
1580
+ let subject = find("list", operation.at, resolved.addressHash);
1581
+ if (!subject) {
1582
+ if (first.type === "list.replace") {
1583
+ add({
1584
+ ...base(resolved, operation),
1585
+ kind: "list",
1586
+ node: resolved.node,
1587
+ state: {
1588
+ mode: "whole",
1589
+ value: first.value
1590
+ }
1591
+ });
1592
+ return;
1593
+ }
1594
+ const value = read(root, operation.at);
1595
+ if (!Array.isArray(value)) return inverseMismatch(operation);
1596
+ subject = add({
1597
+ ...base(resolved, operation),
1598
+ kind: "list",
1599
+ node: resolved.node,
1600
+ state: {
1601
+ mode: "incremental",
1602
+ items: /* @__PURE__ */ new Map(),
1603
+ order: listOrderBefore(value, resolved.node, first)
1604
+ }
1605
+ });
1606
+ }
1607
+ if (subject.state.mode === "whole") return;
1608
+ if (first.type === "list.replace") {
1609
+ const value = Array.from(ownPayload(first.value, "journal"));
1610
+ restoreList(value, subject);
1611
+ subject.state = {
1612
+ mode: "whole",
1613
+ value
1614
+ };
1615
+ return;
1616
+ }
1617
+ if (first.type !== "list.insert" && first.type !== "list.move" && first.type !== "list.remove") return inverseMismatch(operation);
1618
+ recordListPresence(subject.state, first);
1619
+ };
1620
+ const trackEntityOrder = (subject, collection) => {
1621
+ if (subject.order.kind !== "stable") return;
1622
+ profile.journal.orderSnapshot(collection.ids.length);
1623
+ const before = [...collection.ids];
1624
+ restoreEntityOrder(before, subject.order.inverses);
1625
+ subject.order = {
1626
+ kind: "tracked",
1627
+ before
1628
+ };
1629
+ };
1630
+ const recordEntity = (resolved, operation, inverse) => {
1631
+ if (resolved.node.kind !== "table" && resolved.node.kind !== "map") return inverseMismatch(operation);
1632
+ const resolution = resolveEntityCollection(resolved.node, read(root, operation.at));
1633
+ if (resolution.status === "invalid") return inverseMismatch(operation);
1634
+ const collection = resolution.collection;
1635
+ const subject = find("entity", operation.at, resolved.addressHash) ?? add({
1636
+ ...base(resolved, operation),
1637
+ kind: "entity",
1638
+ node: resolved.node,
1639
+ entries: /* @__PURE__ */ new Map(),
1640
+ order: collection.kind === "table" ? {
1641
+ kind: "stable",
1642
+ inverses: []
1643
+ } : { kind: "unordered" }
1644
+ });
1645
+ const first = inverse[0];
1646
+ if (!first) return inverseMismatch(operation);
1647
+ if (collection.kind === "table" && subject.order.kind === "stable") subject.order.inverses.push(entityOrderInverse(operation, first));
1648
+ if (first.type === "entity.remove") {
1649
+ for (const id of first.ids) if (!subject.entries.has(id)) subject.entries.set(id, absent);
1650
+ if (collection.kind === "table" && first.ids.some((id) => subject.entries.get(id)?.status === "present")) trackEntityOrder(subject, collection);
1651
+ return;
1652
+ }
1653
+ if (first.type === "entity.create") {
1654
+ for (const entry of first.entries) {
1655
+ if (subject.entries.has(entry.id)) continue;
1656
+ const address = [...operation.at, entry.id];
1657
+ subject.entries.set(entry.id, present(absorb(entry.value, address)));
1658
+ }
1659
+ return;
1660
+ }
1661
+ if (first.type === "entity.move") {
1662
+ if (collection.kind === "table" && subject.entries.get(first.id)?.status !== "absent") trackEntityOrder(subject, collection);
1663
+ return;
1664
+ }
1665
+ return inverseMismatch(operation);
1666
+ };
1667
+ const recordTree = (resolved, operation, inverse) => {
1668
+ const current = read(root, operation.at);
1669
+ if (!is(current)) return inverseMismatch(operation);
1670
+ const inverses = inverse.filter(treeOperation);
1671
+ if (inverses.length === 0 || inverses.length !== inverse.length) return inverseMismatch(operation);
1672
+ const subject = find("tree", operation.at, resolved.addressHash);
1673
+ const state = recordChange(subject?.state, current, operation, inverses);
1674
+ if (subject) subject.state = state;
1675
+ else add({
1676
+ ...base(resolved, operation),
1677
+ kind: "tree",
1678
+ state
1679
+ });
1680
+ };
1681
+ return {
1682
+ record: (resolved, operation, inverse) => {
1683
+ profile.batch.journalRecord();
1684
+ if (ownerOf(operation.at)) return;
1685
+ if (operation.type === "field.set" || operation.type === "field.clear") {
1686
+ recordValue(resolved, operation, inverse);
1687
+ return;
1688
+ }
1689
+ if (operation.type === "variant.replace") {
1690
+ recordVariant(resolved, operation, inverse);
1691
+ return;
1692
+ }
1693
+ if (operation.type === "dict.set" || operation.type === "dict.delete" || operation.type === "dict.replace") {
1694
+ recordDict(resolved, operation, inverse);
1695
+ return;
1696
+ }
1697
+ if (operation.type === "entity.create" || operation.type === "entity.remove" || operation.type === "entity.move") {
1698
+ recordEntity(resolved, operation, inverse);
1699
+ return;
1700
+ }
1701
+ if (operation.type === "list.insert" || operation.type === "list.move" || operation.type === "list.remove" || operation.type === "list.replace") {
1702
+ recordList(resolved, operation, inverse);
1703
+ return;
1704
+ }
1705
+ recordTree(resolved, operation, inverse);
1706
+ },
1707
+ finish: () => {
1708
+ const changed = [];
1709
+ const entityChanges = /* @__PURE__ */ new Map();
1710
+ for (const subject of active) {
1711
+ profile.journal.comparison();
1712
+ if (subject.kind === "entity") {
1713
+ const analysis = analyzeEntity(root, subject);
1714
+ if (!analysis.changed) continue;
1715
+ entityChanges.set(subject, analysis);
1716
+ changed.push(subject);
1717
+ } else if (subjectChanged(root, subject)) changed.push(subject);
1718
+ }
1719
+ if (changed.length === 0) return { status: "unchanged" };
1720
+ const collections = [];
1721
+ const collectionBuckets = /* @__PURE__ */ new Map();
1722
+ const changeAt = (address, addressHash) => {
1723
+ const candidates = collectionBuckets.get(addressHash) ?? [];
1724
+ collectionBuckets.set(addressHash, candidates);
1725
+ let change = candidates.find((entry) => sameAddress$1(entry.address, address));
1726
+ if (!change) {
1727
+ change = {
1728
+ address,
1729
+ added: /* @__PURE__ */ new Set(),
1730
+ removed: /* @__PURE__ */ new Set(),
1731
+ updated: /* @__PURE__ */ new Set(),
1732
+ orderChanged: false
1733
+ };
1734
+ candidates.push(change);
1735
+ collections.push(change);
1736
+ }
1737
+ return change;
1738
+ };
1739
+ for (const subject of changed) {
1740
+ if (subject.kind === "entity") {
1741
+ const analysis = entityChanges.get(subject);
1742
+ if (analysis) {
1743
+ const change = changeAt(subject.address, subject.addressHash);
1744
+ analysis.added.forEach((id) => change.added.add(id));
1745
+ analysis.removed.forEach((id) => change.removed.add(id));
1746
+ analysis.updated.forEach((id) => change.updated.add(id));
1747
+ if (analysis.orderChanged) change.orderChanged = true;
1748
+ }
1749
+ }
1750
+ for (let collection = subject.collection; collection; collection = collection.parent) changeAt(collection.address, collection.addressHash).updated.add(collection.id);
1751
+ }
1752
+ for (const change of collections) {
1753
+ change.added.forEach((id) => change.updated.delete(id));
1754
+ change.removed.forEach((id) => change.updated.delete(id));
1755
+ }
1756
+ return {
1757
+ status: "changed",
1758
+ paths: Object.freeze(changed.map((subject) => subject.address)),
1759
+ collections
1760
+ };
1761
+ }
1762
+ };
1763
+ };
1764
+ //#endregion
1765
+ //#region core/src/mutation/operation.ts
1766
+ const has = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
1767
+ const stringArray = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
1768
+ const positions = (value) => Array.isArray(value) && value.every((entry) => Number.isInteger(entry) && entry >= 0);
1769
+ const address$1 = (value) => stringArray(value);
1770
+ const anchor = (value) => {
1771
+ if (!isRecord(value)) return false;
1772
+ if (Number(has(value, "at")) + Number(has(value, "before")) + Number(has(value, "after")) !== 1) return false;
1773
+ if (has(value, "at")) return value.at === "start" || value.at === "end";
1774
+ return typeof (has(value, "before") ? value.before : value.after) === "string";
1775
+ };
1776
+ const optionalAnchor = (value) => !has(value, "anchor") || value.anchor === void 0 || anchor(value.anchor);
1777
+ const optionalParent = (value) => !has(value, "parentId") || value.parentId === void 0 || typeof value.parentId === "string";
1778
+ const optionalIndex = (value) => !has(value, "index") || value.index === void 0 || Number.isInteger(value.index) && value.index >= 0;
1779
+ const entries = (value) => Array.isArray(value) && value.every((entry) => isRecord(entry) && typeof entry.id === "string" && has(entry, "value"));
1780
+ const decoded = (operation) => ({
1781
+ status: "decoded",
1782
+ operation
1783
+ });
1784
+ const rejected = (code, message) => ({
1785
+ status: "rejected",
1786
+ issue: input(code, message)
1787
+ });
1788
+ const decode = (input) => {
1789
+ if (!isRecord(input)) return rejected("invalid-operation", "Operation must be an object.");
1790
+ if (!address$1(input.at)) return rejected("invalid-address", "Operation address is malformed.");
1791
+ if (typeof input.type !== "string") return rejected("invalid-operation", "Operation type must be a string.");
1792
+ switch (input.type) {
1793
+ case "field.set":
1794
+ case "variant.replace": return has(input, "value") ? decoded(input) : rejected("invalid-operation", "Operation value is required.");
1795
+ case "field.clear": return decoded(input);
1796
+ case "dict.set": return typeof input.key === "string" && has(input, "value") ? decoded(input) : rejected("invalid-operation", "Dictionary set requires a string key and value.");
1797
+ case "dict.delete": return typeof input.key === "string" ? decoded(input) : rejected("invalid-operation", "Dictionary delete requires a string key.");
1798
+ case "dict.replace": return isRecord(input.value) ? decoded(input) : rejected("invalid-operation", "Dictionary replacement must be an object.");
1799
+ case "entity.create": return entries(input.entries) && optionalAnchor(input) && (!has(input, "positions") || input.positions === void 0 || positions(input.positions)) ? decoded(input) : rejected("invalid-operation", "Entity create payload is malformed.");
1800
+ case "entity.remove": return stringArray(input.ids) ? decoded(input) : rejected("invalid-operation", "Entity remove requires string ids.");
1801
+ case "entity.move": return typeof input.id === "string" && optionalAnchor(input) ? decoded(input) : rejected("invalid-operation", "Entity move payload is malformed.");
1802
+ case "list.insert": return typeof input.key === "string" && has(input, "value") && optionalAnchor(input) ? decoded(input) : rejected("invalid-operation", "List insert payload is malformed.");
1803
+ case "list.move": return typeof input.key === "string" && optionalAnchor(input) ? decoded(input) : rejected("invalid-operation", "List move payload is malformed.");
1804
+ case "list.remove": return typeof input.key === "string" ? decoded(input) : rejected("invalid-operation", "List remove requires a string key.");
1805
+ case "list.replace": return Array.isArray(input.value) && stringArray(input.keys) ? decoded(input) : rejected("invalid-operation", "List replacement payload is malformed.");
1806
+ case "tree.insert": return typeof input.treeNodeId === "string" && optionalParent(input) && optionalIndex(input) ? decoded(input) : rejected("invalid-operation", "Tree insert payload is malformed.");
1807
+ case "tree.move": return typeof input.treeNodeId === "string" && optionalParent(input) && optionalIndex(input) ? decoded(input) : rejected("invalid-operation", "Tree move payload is malformed.");
1808
+ case "tree.remove": return typeof input.treeNodeId === "string" ? decoded(input) : rejected("invalid-operation", "Tree remove requires a node id.");
1809
+ case "tree.set": return typeof input.treeNodeId === "string" && has(input, "value") ? decoded(input) : rejected("invalid-operation", "Tree set payload is malformed.");
1810
+ case "tree.replace": return has(input, "value") ? decoded(input) : rejected("invalid-operation", "Tree replacement value is required.");
1811
+ default: return rejected("unknown-operation", "Unknown document operation.");
1812
+ }
1813
+ };
1814
+ const decodeBatch = (input$1) => Array.isArray(input$1) ? {
1815
+ status: "decoded",
1816
+ operations: input$1
1817
+ } : {
1818
+ status: "rejected",
1819
+ issue: input("invalid-operation", "Operation batch must be an array.")
1820
+ };
1821
+ const ownAddress = (value) => {
1822
+ if (Object.isFrozen(value)) return value;
1823
+ profile.address.arrayCopied();
1824
+ return Object.freeze(value.slice());
1825
+ };
1826
+ const structuralPayload = (value) => Array.isArray(value) || isPlainObject(value);
1827
+ const normalize = (operation) => {
1828
+ profile.mutation.normalized();
1829
+ const copy = {
1830
+ ...operation,
1831
+ at: ownAddress(operation.at)
1832
+ };
1833
+ if (copy.anchor) copy.anchor = Object.freeze({ ...copy.anchor });
1834
+ if (copy.keys) copy.keys = Object.freeze([...copy.keys]);
1835
+ if (copy.entries) copy.entries = Object.freeze(copy.entries.map((entry) => Object.freeze({ ...entry })));
1836
+ if (copy.ids) copy.ids = Object.freeze([...copy.ids]);
1837
+ if (copy.positions) copy.positions = Object.freeze([...copy.positions]);
1838
+ return Object.freeze(copy);
1839
+ };
1840
+ const publish = (operation) => {
1841
+ if (operation.type === "entity.create" && operation.entries.every((entry) => !structuralPayload(entry.value) || isStablePayload(entry.value))) return operation;
1842
+ if ("value" in operation && (!structuralPayload(operation.value) || isStablePayload(operation.value))) return operation;
1843
+ const copy = { ...operation };
1844
+ if (copy.entries) copy.entries = Object.freeze(copy.entries.map((entry) => Object.freeze({
1845
+ id: entry.id,
1846
+ value: structuralPayload(entry.value) ? isStablePayload(entry.value) ? entry.value : snapshotPayload(entry.value, "commit") : entry.value
1847
+ })));
1848
+ else if ("value" in copy && structuralPayload(copy.value)) copy.value = isStablePayload(copy.value) ? copy.value : snapshotPayload(copy.value, "commit");
1849
+ return Object.freeze(copy);
1850
+ };
1851
+ const requiresPayloadCopy = (operation) => {
1852
+ if (operation.type === "entity.create") return operation.entries.some((entry) => isStablePayload(entry.value));
1853
+ return "value" in operation && isStablePayload(operation.value);
1854
+ };
1855
+ const inverse = (operation) => {
1856
+ const copy = { ...operation };
1857
+ if (copy.anchor) copy.anchor = Object.freeze({ ...copy.anchor });
1858
+ if (copy.keys) copy.keys = Object.freeze([...copy.keys]);
1859
+ if (copy.entries) copy.entries = Object.freeze(copy.entries.map((entry) => Object.freeze({
1860
+ id: entry.id,
1861
+ value: structuralPayload(entry.value) ? isStablePayload(entry.value) ? entry.value : snapshotPayload(entry.value, "inverse") : entry.value
1862
+ })));
1863
+ if (copy.ids) copy.ids = Object.freeze([...copy.ids]);
1864
+ if (copy.positions) copy.positions = Object.freeze([...copy.positions]);
1865
+ if ("value" in copy && structuralPayload(copy.value)) {
1866
+ const payload = copy;
1867
+ payload.value = isStablePayload(payload.value) ? payload.value : snapshotPayload(payload.value, "inverse");
1868
+ }
1869
+ return Object.freeze(copy);
1870
+ };
1871
+ //#endregion
1872
+ //#region core/src/mutation/session.ts
1873
+ const createMutationSession = (root, schema, options = {}) => {
1874
+ const steps = [];
1875
+ const journal = createChangeJournal(root);
1876
+ let state = "active";
1877
+ const rollback = () => {
1878
+ if (state === "rolled-back") return;
1879
+ for (let stepIndex = steps.length - 1; stepIndex >= 0; stepIndex -= 1) for (const inverse of steps[stepIndex].inverse) {
1880
+ const result = execute(root, inverse, resolveLocated(schema, root, inverse.at), true);
1881
+ if (result.status === "rejected") throw new Error(`Document rollback failed: ${result.issue.message}`);
1882
+ }
1883
+ state = "rolled-back";
1884
+ };
1885
+ return {
1886
+ apply: (input) => {
1887
+ if (state !== "active") throw new Error("Mutation session is closed.");
1888
+ profile.batch.operation();
1889
+ const decoded = decode(input);
1890
+ if (decoded.status === "rejected") {
1891
+ profile.batch.rejected();
1892
+ return decoded.issue;
1893
+ }
1894
+ const normalized = normalize(decoded.operation);
1895
+ profile.batch.entry(normalized.type === "entity.create" ? normalized.entries.length : normalized.type === "entity.remove" ? normalized.ids.length : 1);
1896
+ const resolved = resolveLocated(schema, root, normalized.at);
1897
+ if (resolved?.collection) profile.batch.collectionResolved();
1898
+ profile.mutation.executed();
1899
+ const result = execute(root, normalized, resolved, options.copyPayload === true || requiresPayloadCopy(normalized));
1900
+ if (result.status === "rejected") {
1901
+ profile.batch.rejected();
1902
+ return result.issue;
1903
+ }
1904
+ if (result.status === "unchanged") return void 0;
1905
+ const published = publish(normalized);
1906
+ const group = [];
1907
+ for (const rawInverse of result.inverse) {
1908
+ const inverse$1 = inverse(rawInverse);
1909
+ group.push(inverse$1);
1910
+ profile.mutation.inverse();
1911
+ profile.batch.inverse();
1912
+ }
1913
+ steps.push({
1914
+ forward: published,
1915
+ inverse: Object.freeze(group)
1916
+ });
1917
+ try {
1918
+ if (!resolved) throw new Error(`Changed operation '${normalized.type}' was not resolved.`);
1919
+ journal.record(resolved, normalized, result.inverse);
1920
+ } catch (error) {
1921
+ rollback();
1922
+ throw error;
1923
+ }
1924
+ },
1925
+ finish: () => {
1926
+ if (state !== "active") throw new Error("Mutation session is closed.");
1927
+ const changes = journal.finish();
1928
+ state = "finished";
1929
+ if (changes.status === "unchanged") return { status: "unchanged" };
1930
+ let inverseCount = 0;
1931
+ for (const step of steps) inverseCount += step.inverse.length;
1932
+ const inverse = new Array(inverseCount);
1933
+ let writeIndex = 0;
1934
+ for (let stepIndex = steps.length - 1; stepIndex >= 0; stepIndex -= 1) for (const entry of steps[stepIndex].inverse) inverse[writeIndex++] = entry;
1935
+ return {
1936
+ status: "changed",
1937
+ operations: Object.freeze(steps.map((step) => step.forward)),
1938
+ inverse: Object.freeze(inverse),
1939
+ paths: changes.paths,
1940
+ collections: changes.collections
1941
+ };
1942
+ },
1943
+ rollback
1944
+ };
1945
+ };
1946
+ const mutateOperations = (root, schema, operations, options = {}) => {
1947
+ const decodedBatch = decodeBatch(operations);
1948
+ if (decodedBatch.status === "rejected") return {
1949
+ status: "rejected",
1950
+ issues: Object.freeze([decodedBatch.issue])
1951
+ };
1952
+ const session = createMutationSession(root, schema, options);
1953
+ for (const input of decodedBatch.operations) {
1954
+ const issue = session.apply(input);
1955
+ if (!issue) continue;
1956
+ session.rollback();
1957
+ return {
1958
+ status: "rejected",
1959
+ issues: Object.freeze([issue])
1960
+ };
1961
+ }
1962
+ return session.finish();
1963
+ };
1964
+ //#endregion
1965
+ //#region core/src/mutation/footprint.ts
1966
+ const sameAddress = (left, right) => left.length === right.length && left.every((segment, index) => segment === right[index]);
1967
+ const containsAddress = (parent, child) => parent.length <= child.length && parent.every((segment, index) => segment === child[index]);
1968
+ const address = (value) => Array.isArray(value) && value.every((segment) => typeof segment === "string") ? Object.freeze(value.slice()) : void 0;
1969
+ const targetKey = (target) => {
1970
+ const at = target.at.join("\0");
1971
+ if (target.kind === "dictionary-key" || target.kind === "list-item") return `${target.kind}:${at}:${target.key}`;
1972
+ if (target.kind === "entity" || target.kind === "tree-node") return `${target.kind}:${at}:${target.id}`;
1973
+ return `${target.kind}:${at}`;
1974
+ };
1975
+ const freezeTarget = (target) => Object.freeze({
1976
+ ...target,
1977
+ at: Object.freeze(target.at.slice())
1978
+ });
1979
+ const add = (targets, target) => {
1980
+ const stable = freezeTarget(target);
1981
+ targets.set(targetKey(stable), stable);
1982
+ };
1983
+ const commandFootprint = (operations) => {
1984
+ const targets = /* @__PURE__ */ new Map();
1985
+ for (const operation of operations) switch (operation.type) {
1986
+ case "field.set":
1987
+ case "field.clear":
1988
+ case "variant.replace":
1989
+ add(targets, {
1990
+ kind: "value",
1991
+ at: operation.at
1992
+ });
1993
+ break;
1994
+ case "dict.replace":
1995
+ add(targets, {
1996
+ kind: "dictionary",
1997
+ at: operation.at
1998
+ });
1999
+ break;
2000
+ case "dict.set":
2001
+ case "dict.delete":
2002
+ add(targets, {
2003
+ kind: "dictionary-key",
2004
+ at: operation.at,
2005
+ key: operation.key
2006
+ });
2007
+ break;
2008
+ case "entity.create":
2009
+ add(targets, {
2010
+ kind: "collection",
2011
+ at: operation.at
2012
+ });
2013
+ for (const entry of operation.entries) add(targets, {
2014
+ kind: "entity",
2015
+ at: operation.at,
2016
+ id: entry.id
2017
+ });
2018
+ break;
2019
+ case "entity.remove":
2020
+ add(targets, {
2021
+ kind: "collection",
2022
+ at: operation.at
2023
+ });
2024
+ for (const id of operation.ids) add(targets, {
2025
+ kind: "entity",
2026
+ at: operation.at,
2027
+ id
2028
+ });
2029
+ break;
2030
+ case "entity.move":
2031
+ add(targets, {
2032
+ kind: "collection",
2033
+ at: operation.at
2034
+ });
2035
+ add(targets, {
2036
+ kind: "entity",
2037
+ at: operation.at,
2038
+ id: operation.id
2039
+ });
2040
+ break;
2041
+ case "list.insert":
2042
+ case "list.move":
2043
+ case "list.remove":
2044
+ add(targets, {
2045
+ kind: "list",
2046
+ at: operation.at
2047
+ });
2048
+ add(targets, {
2049
+ kind: "list-item",
2050
+ at: operation.at,
2051
+ key: operation.key
2052
+ });
2053
+ break;
2054
+ case "list.replace":
2055
+ add(targets, {
2056
+ kind: "list",
2057
+ at: operation.at
2058
+ });
2059
+ for (const key of operation.keys) add(targets, {
2060
+ kind: "list-item",
2061
+ at: operation.at,
2062
+ key
2063
+ });
2064
+ break;
2065
+ case "tree.insert":
2066
+ case "tree.move":
2067
+ case "tree.remove":
2068
+ case "tree.set":
2069
+ add(targets, {
2070
+ kind: "tree",
2071
+ at: operation.at
2072
+ });
2073
+ add(targets, {
2074
+ kind: "tree-node",
2075
+ at: operation.at,
2076
+ id: operation.treeNodeId
2077
+ });
2078
+ break;
2079
+ case "tree.replace":
2080
+ add(targets, {
2081
+ kind: "tree",
2082
+ at: operation.at
2083
+ });
2084
+ break;
2085
+ }
2086
+ return Object.freeze(Array.from(targets.values()));
2087
+ };
2088
+ const overlapsValueAndEntity = (value, entity) => containsAddress([...entity.at, entity.id], value.at) || containsAddress(value.at, [...entity.at, entity.id]);
2089
+ const targetsOverlap = (left, right) => {
2090
+ if (left.kind === "value" && right.kind === "value") return containsAddress(left.at, right.at) || containsAddress(right.at, left.at);
2091
+ if (left.kind === "value" && right.kind === "entity") return overlapsValueAndEntity(left, right);
2092
+ if (left.kind === "entity" && right.kind === "value") return overlapsValueAndEntity(right, left);
2093
+ if (left.kind === "dictionary" && right.kind === "dictionary") return sameAddress(left.at, right.at);
2094
+ if (left.kind === "dictionary" && right.kind === "dictionary-key") return sameAddress(left.at, right.at);
2095
+ if (left.kind === "dictionary-key" && right.kind === "dictionary") return sameAddress(left.at, right.at);
2096
+ if (left.kind === "dictionary-key" && right.kind === "dictionary-key") return sameAddress(left.at, right.at) && left.key === right.key;
2097
+ if (left.kind === "collection" && right.kind === "collection") return sameAddress(left.at, right.at);
2098
+ if (left.kind === "collection" && right.kind === "entity") return sameAddress(left.at, right.at);
2099
+ if (left.kind === "entity" && right.kind === "collection") return sameAddress(left.at, right.at);
2100
+ if (left.kind === "entity" && right.kind === "entity") return sameAddress(left.at, right.at) && left.id === right.id;
2101
+ if (left.kind === "list" && (right.kind === "list" || right.kind === "list-item")) return sameAddress(left.at, right.at);
2102
+ if (right.kind === "list" && left.kind === "list-item") return sameAddress(left.at, right.at);
2103
+ if (left.kind === "list-item" && right.kind === "list-item") return sameAddress(left.at, right.at) && left.key === right.key;
2104
+ if (left.kind === "tree" && (right.kind === "tree" || right.kind === "tree-node")) return sameAddress(left.at, right.at);
2105
+ if (right.kind === "tree" && left.kind === "tree-node") return sameAddress(left.at, right.at);
2106
+ if (left.kind === "tree-node" && right.kind === "tree-node") return sameAddress(left.at, right.at) && left.id === right.id;
2107
+ return false;
2108
+ };
2109
+ const footprintsOverlap = (left, right) => left.some((leftTarget) => right.some((rightTarget) => targetsOverlap(leftTarget, rightTarget)));
2110
+ const decodedTarget = (value) => {
2111
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
2112
+ const record = value;
2113
+ const at = address(record.at);
2114
+ if (!at || typeof record.kind !== "string") return void 0;
2115
+ switch (record.kind) {
2116
+ case "value":
2117
+ case "dictionary":
2118
+ case "collection":
2119
+ case "list":
2120
+ case "tree": return freezeTarget({
2121
+ kind: record.kind,
2122
+ at
2123
+ });
2124
+ case "dictionary-key":
2125
+ case "list-item": return typeof record.key === "string" ? freezeTarget({
2126
+ kind: record.kind,
2127
+ at,
2128
+ key: record.key
2129
+ }) : void 0;
2130
+ case "entity":
2131
+ case "tree-node": return typeof record.id === "string" ? freezeTarget({
2132
+ kind: record.kind,
2133
+ at,
2134
+ id: record.id
2135
+ }) : void 0;
2136
+ default: return;
2137
+ }
2138
+ };
2139
+ const decodeCommandFootprint = (value) => {
2140
+ if (!Array.isArray(value)) return void 0;
2141
+ const targets = /* @__PURE__ */ new Map();
2142
+ for (const entry of value) {
2143
+ const target = decodedTarget(entry);
2144
+ if (!target) return void 0;
2145
+ targets.set(targetKey(target), target);
2146
+ }
2147
+ return Object.freeze(Array.from(targets.values()));
2148
+ };
2149
+ //#endregion
2150
+ //#region core/src/runtime/notification.ts
2151
+ const ROOT_BUCKET = Symbol("document-root");
2152
+ const notifications = /* @__PURE__ */ new WeakMap();
2153
+ const key = (value) => bucket(value) ?? ROOT_BUCKET;
2154
+ const createNotification = (runtime) => {
2155
+ const notification = {
2156
+ root: /* @__PURE__ */ new Set(),
2157
+ filtered: /* @__PURE__ */ new Set(),
2158
+ buckets: /* @__PURE__ */ new Map(),
2159
+ processors: [],
2160
+ candidates: /* @__PURE__ */ new Set(),
2161
+ rootSnapshot: [],
2162
+ notifying: false
2163
+ };
2164
+ notifications.set(runtime, notification);
2165
+ return notification;
2166
+ };
2167
+ const notificationOf = (runtime) => {
2168
+ const value = notifications.get(runtime);
2169
+ if (!value) throw new Error("Unknown Doxum runtime.");
2170
+ return value;
2171
+ };
2172
+ const shareNotification = (source, target) => {
2173
+ notifications.set(target, notificationOf(source));
2174
+ };
2175
+ const registerProcessor = (runtime, processor) => {
2176
+ const notification = notificationOf(runtime);
2177
+ const entry = {
2178
+ processor,
2179
+ active: true
2180
+ };
2181
+ notification.processors.push(entry);
2182
+ return () => {
2183
+ if (!entry.active) return;
2184
+ entry.active = false;
2185
+ if (!notification.notifying) {
2186
+ const index = notification.processors.indexOf(entry);
2187
+ if (index >= 0) notification.processors.splice(index, 1);
2188
+ }
2189
+ };
2190
+ };
2191
+ const subscribeRoot = (notification, listener) => {
2192
+ const entry = {
2193
+ listener,
2194
+ active: true
2195
+ };
2196
+ notification.root.add(entry);
2197
+ return () => {
2198
+ entry.active = false;
2199
+ if (!notification.notifying) notification.root.delete(entry);
2200
+ };
2201
+ };
2202
+ const subscribeTargets = (notification, targets, listener) => {
2203
+ const entry = {
2204
+ targets: Object.freeze(targets.slice()),
2205
+ listener,
2206
+ active: true
2207
+ };
2208
+ notification.filtered.add(entry);
2209
+ const keys = new Set(targets.map(key));
2210
+ keys.forEach((key) => {
2211
+ const bucket = notification.buckets.get(key) ?? /* @__PURE__ */ new Set();
2212
+ bucket.add(entry);
2213
+ notification.buckets.set(key, bucket);
2214
+ });
2215
+ return () => {
2216
+ if (!entry.active) return;
2217
+ entry.active = false;
2218
+ if (notification.notifying) return;
2219
+ notification.filtered.delete(entry);
2220
+ keys.forEach((key) => {
2221
+ const bucket = notification.buckets.get(key);
2222
+ bucket?.delete(entry);
2223
+ if (bucket?.size === 0) notification.buckets.delete(key);
2224
+ });
2225
+ };
2226
+ };
2227
+ const notify = (notification, commit) => {
2228
+ notification.notifying = true;
2229
+ const errors = [];
2230
+ const call = (listener) => {
2231
+ try {
2232
+ listener(commit);
2233
+ } catch (error) {
2234
+ errors.push(Object.freeze({
2235
+ phase: "listener",
2236
+ error
2237
+ }));
2238
+ }
2239
+ };
2240
+ try {
2241
+ const processorCount = notification.processors.length;
2242
+ for (let index = 0; index < processorCount; index += 1) {
2243
+ const entry = notification.processors[index];
2244
+ if (!entry?.active) continue;
2245
+ try {
2246
+ entry.processor.process(commit);
2247
+ } catch (error) {
2248
+ errors.push(Object.freeze({
2249
+ phase: "processor",
2250
+ error
2251
+ }));
2252
+ }
2253
+ }
2254
+ for (let index = 0; index < processorCount; index += 1) {
2255
+ const entry = notification.processors[index];
2256
+ if (!entry?.active) continue;
2257
+ try {
2258
+ entry.processor.flush();
2259
+ } catch (error) {
2260
+ errors.push(Object.freeze({
2261
+ phase: "flush",
2262
+ error
2263
+ }));
2264
+ }
2265
+ }
2266
+ const candidates = notification.candidates;
2267
+ candidates.clear();
2268
+ if (commit.impact.kind === "reset") notification.filtered.forEach((entry) => candidates.add(entry));
2269
+ else for (const operation of commit.operations) {
2270
+ const key = operation.at[0] ?? ROOT_BUCKET;
2271
+ notification.buckets.get(key)?.forEach((entry) => candidates.add(entry));
2272
+ notification.buckets.get(ROOT_BUCKET)?.forEach((entry) => candidates.add(entry));
2273
+ }
2274
+ candidates.forEach((entry) => {
2275
+ if (entry.active && entry.targets.some(commit.impact.affects)) call(entry.listener);
2276
+ });
2277
+ const rootSnapshot = notification.rootSnapshot;
2278
+ rootSnapshot.length = 0;
2279
+ notification.root.forEach((entry) => rootSnapshot.push(entry));
2280
+ for (const entry of rootSnapshot) if (entry.active) call(entry.listener);
2281
+ } finally {
2282
+ notification.notifying = false;
2283
+ let writeIndex = 0;
2284
+ for (const entry of notification.processors) if (entry.active) notification.processors[writeIndex++] = entry;
2285
+ notification.processors.length = writeIndex;
2286
+ notification.root.forEach((entry) => {
2287
+ if (!entry.active) notification.root.delete(entry);
2288
+ });
2289
+ notification.filtered.forEach((entry) => {
2290
+ if (!entry.active) notification.filtered.delete(entry);
2291
+ });
2292
+ notification.buckets.forEach((bucket, key) => {
2293
+ bucket.forEach((entry) => {
2294
+ if (!entry.active) bucket.delete(entry);
2295
+ });
2296
+ if (bucket.size === 0) notification.buckets.delete(key);
2297
+ });
2298
+ }
2299
+ return Object.freeze(errors);
2300
+ };
2301
+ const disposeNotification = (notification) => {
2302
+ notification.root.clear();
2303
+ notification.filtered.clear();
2304
+ notification.buckets.clear();
2305
+ notification.processors.length = 0;
2306
+ notification.candidates.clear();
2307
+ notification.rootSnapshot.length = 0;
2308
+ };
2309
+ //#endregion
2310
+ //#region core/src/runtime.ts
2311
+ var RejectedUpdate = class extends Error {
2312
+ issues;
2313
+ constructor(issues) {
2314
+ super("Document update rejected.");
2315
+ this.issues = Object.freeze(issues.slice());
2316
+ }
2317
+ };
2318
+ const EMPTY = Object.freeze([]);
2319
+ const publishDiagnostic = (value) => Object.freeze({
2320
+ ...value,
2321
+ ...value.address === void 0 ? {} : { address: Object.freeze(value.address.slice()) }
2322
+ });
2323
+ const createDocument = (input) => {
2324
+ const initialTreeError = invalidDocument(input.schema, input.initial);
2325
+ if (initialTreeError) throw new TypeError(`Initial document contains an invalid tree at '${initialTreeError.join(".")}'.`);
2326
+ profile.clone.initialDocument();
2327
+ const state = {
2328
+ schema: input.schema,
2329
+ document: cloneValue(input.initial, "initial"),
2330
+ disposed: false
2331
+ };
2332
+ let revision = 0;
2333
+ let busy = false;
2334
+ let runtime;
2335
+ let notification;
2336
+ const assertWritable = (intent) => {
2337
+ if (state.disposed) throw new DocumentDisposedError();
2338
+ if (busy) throw new DocumentReentrancyError();
2339
+ assertRuntimeWritable(runtime, intent);
2340
+ };
2341
+ const runTransaction = (session, run) => {
2342
+ let reports;
2343
+ let active = true;
2344
+ const transaction = {
2345
+ read: documentReader(input.schema, () => state.document, () => active),
2346
+ write: documentWriter(input.schema, (operation) => {
2347
+ if (!active) throw new Error("Document writer is no longer active.");
2348
+ const rejected = session.apply(operation);
2349
+ if (rejected) throw new RejectedUpdate([rejected]);
2350
+ }),
2351
+ reject: (diagnostic) => {
2352
+ throw new RejectedUpdate((Array.isArray(diagnostic) ? diagnostic : [diagnostic]).map((entry) => publishDiagnostic(entry)));
2353
+ },
2354
+ report: (diagnostic) => {
2355
+ if (!active) throw new Error("Document transaction is no longer active.");
2356
+ (reports ??= []).push(publishDiagnostic(diagnostic));
2357
+ }
2358
+ };
2359
+ try {
2360
+ const value = run(transaction);
2361
+ if (value !== null && typeof value === "object" && typeof value.then === "function") throw new TypeError("Document update callback must be synchronous.");
2362
+ return {
2363
+ value,
2364
+ reports: Object.freeze(reports ? reports.slice() : EMPTY)
2365
+ };
2366
+ } finally {
2367
+ active = false;
2368
+ }
2369
+ };
2370
+ const impactFor = (batch, kind) => createImpact({
2371
+ schema: input.schema,
2372
+ operations: batch.operations,
2373
+ paths: batch.paths,
2374
+ collections: batch.collections,
2375
+ reset: kind === "replace"
2376
+ });
2377
+ const history = createHistory({
2378
+ capacity: input.history === false ? 0 : Math.max(0, input.history?.capacity ?? 100),
2379
+ revision: () => revision,
2380
+ apply: (operations) => applyBatch(operations, "history", false)
2381
+ });
2382
+ const publish = (batch, source, kind, recordHistory) => {
2383
+ revision += 1;
2384
+ const commit = Object.freeze({
2385
+ revision,
2386
+ kind,
2387
+ source,
2388
+ operations: batch.operations,
2389
+ inverse: batch.inverse,
2390
+ impact: impactFor(batch, kind)
2391
+ });
2392
+ if (kind === "replace" || source === "remote") history.invalidate();
2393
+ else if (recordHistory && (source === "local" || source === "system")) history.record(batch.operations, batch.inverse);
2394
+ busy = true;
2395
+ let observerErrors;
2396
+ try {
2397
+ observerErrors = notify(notification, commit);
2398
+ } finally {
2399
+ busy = false;
2400
+ }
2401
+ return {
2402
+ status: "committed",
2403
+ commit,
2404
+ observerErrors
2405
+ };
2406
+ };
2407
+ function applyBatch(operations, source, recordHistory) {
2408
+ assertWritable({
2409
+ kind: "apply",
2410
+ source
2411
+ });
2412
+ const batch = mutateOperations(state.document, input.schema, operations, { copyPayload: source === "history" });
2413
+ if (batch.status === "rejected") return {
2414
+ status: "rejected",
2415
+ issues: batch.issues,
2416
+ revision
2417
+ };
2418
+ if (batch.status === "unchanged") return {
2419
+ status: "unchanged",
2420
+ revision
2421
+ };
2422
+ return publish(batch, source, "operations", recordHistory);
2423
+ }
2424
+ runtime = {
2425
+ schema: input.schema,
2426
+ address: {
2427
+ resolve: (address) => resolveAddress(input.schema, address, state.document),
2428
+ read: (address) => read(state.document, address),
2429
+ contains,
2430
+ overlaps,
2431
+ debugKey
2432
+ },
2433
+ revision: () => revision,
2434
+ update: (run, options) => {
2435
+ const source = options?.source ?? "local";
2436
+ assertWritable({
2437
+ kind: "update",
2438
+ source
2439
+ });
2440
+ busy = true;
2441
+ const session = createMutationSession(state.document, input.schema);
2442
+ let committed = false;
2443
+ try {
2444
+ const { value, reports } = runTransaction(session, run);
2445
+ const batch = session.finish();
2446
+ if (batch.status === "unchanged") return {
2447
+ status: "unchanged",
2448
+ value,
2449
+ revision,
2450
+ reports
2451
+ };
2452
+ if (batch.status === "rejected") return {
2453
+ status: "rejected",
2454
+ issues: batch.issues,
2455
+ revision
2456
+ };
2457
+ const result = publish(batch, source, "operations", options?.history ?? true);
2458
+ committed = true;
2459
+ return {
2460
+ status: "committed",
2461
+ value,
2462
+ commit: result.commit,
2463
+ reports,
2464
+ observerErrors: result.observerErrors
2465
+ };
2466
+ } catch (error) {
2467
+ try {
2468
+ if (!committed) session.rollback();
2469
+ } finally {
2470
+ busy = false;
2471
+ }
2472
+ if (error instanceof RejectedUpdate) return {
2473
+ status: "rejected",
2474
+ issues: error.issues,
2475
+ revision
2476
+ };
2477
+ throw error;
2478
+ } finally {
2479
+ busy = false;
2480
+ }
2481
+ },
2482
+ prepare: (run) => {
2483
+ assertWritable({ kind: "prepare" });
2484
+ busy = true;
2485
+ const session = createMutationSession(state.document, input.schema);
2486
+ try {
2487
+ const { value, reports } = runTransaction(session, run);
2488
+ const batch = session.finish();
2489
+ if (batch.status === "unchanged") {
2490
+ session.rollback();
2491
+ return {
2492
+ status: "unchanged",
2493
+ value,
2494
+ reports
2495
+ };
2496
+ }
2497
+ if (batch.status === "rejected") {
2498
+ session.rollback();
2499
+ return {
2500
+ status: "rejected",
2501
+ issues: batch.issues
2502
+ };
2503
+ }
2504
+ const impact = impactFor(batch, "operations");
2505
+ session.rollback();
2506
+ return {
2507
+ status: "prepared",
2508
+ value,
2509
+ operations: batch.operations,
2510
+ inverse: batch.inverse,
2511
+ impact,
2512
+ footprint: commandFootprint(batch.operations),
2513
+ reports
2514
+ };
2515
+ } catch (error) {
2516
+ try {
2517
+ session.rollback();
2518
+ } finally {
2519
+ busy = false;
2520
+ }
2521
+ if (error instanceof RejectedUpdate) return {
2522
+ status: "rejected",
2523
+ issues: error.issues
2524
+ };
2525
+ throw error;
2526
+ } finally {
2527
+ busy = false;
2528
+ }
2529
+ },
2530
+ apply: (operations, options) => applyBatch(operations, options?.source ?? "local", options?.history ?? true),
2531
+ replace: (document, options) => {
2532
+ const source = options?.source ?? "system";
2533
+ assertWritable({
2534
+ kind: "replace",
2535
+ source
2536
+ });
2537
+ const invalidTree = invalidDocument(input.schema, document);
2538
+ if (invalidTree) return {
2539
+ status: "rejected",
2540
+ issues: [at$1(invalidTree, "invalid-tree", "Document replacement contains an invalid tree.")],
2541
+ revision
2542
+ };
2543
+ if (deepEqual(state.document, document)) return {
2544
+ status: "unchanged",
2545
+ revision
2546
+ };
2547
+ state.document = cloneValue(document, "replace");
2548
+ return publish({
2549
+ status: "changed",
2550
+ operations: EMPTY,
2551
+ inverse: EMPTY,
2552
+ paths: EMPTY,
2553
+ collections: EMPTY
2554
+ }, source, "replace", false);
2555
+ },
2556
+ snapshot: () => {
2557
+ if (state.disposed) throw new DocumentDisposedError();
2558
+ return cloneValue(state.document, "snapshot");
2559
+ },
2560
+ subscribe: ((targetOrListener, listener) => {
2561
+ if (state.disposed) throw new DocumentDisposedError();
2562
+ if (typeof targetOrListener === "function") return subscribeRoot(notification, targetOrListener);
2563
+ const targets = Array.isArray(targetOrListener) ? targetOrListener : [targetOrListener];
2564
+ if (targets.length === 0 || !listener) throw new TypeError("Filtered subscribe requires at least one target and a listener.");
2565
+ return subscribeTargets(notification, targets, listener);
2566
+ }),
2567
+ history: history.api,
2568
+ dispose: () => {
2569
+ if (state.disposed) return;
2570
+ state.disposed = true;
2571
+ disposeNotification(notification);
2572
+ history.api.clear();
2573
+ disposeRuntimeDriver(runtime);
2574
+ }
2575
+ };
2576
+ bindRuntimeAccess(runtime, state);
2577
+ bindRuntimeDriver(runtime);
2578
+ notification = createNotification(runtime);
2579
+ return runtime;
2580
+ };
2581
+ //#endregion
2582
+ //#region core/src/runtime/readable.ts
2583
+ const asReadable = (runtime) => {
2584
+ const readable = {
2585
+ address: runtime.address,
2586
+ revision: runtime.revision,
2587
+ subscribe: runtime.subscribe
2588
+ };
2589
+ bindRuntimeAccess(readable, accessOf(runtime));
2590
+ shareNotification(runtime, readable);
2591
+ return Object.freeze(readable);
2592
+ };
2593
+ //#endregion
4
2594
  //#region core/src/projection/select.ts
5
2595
  const select = (runtime, selector) => readWith(runtime, selector);
6
2596
  //#endregion
@@ -12,7 +2602,7 @@ const createCollectionView = (input) => {
12
2602
  const itemListeners = /* @__PURE__ */ new Map();
13
2603
  const itemReadables = /* @__PURE__ */ new Map();
14
2604
  let disposed = false;
15
- const sourceNode = nodeAt(input.source.schema, input.source.address);
2605
+ const sourceNode = nodeAt$1(input.source.schema, input.source.address);
16
2606
  const entryNode = sourceNode?.kind === "table" || sourceNode?.kind === "map" ? sourceNode.value : {
17
2607
  kind: "object",
18
2608
  shape: {}