@loro-dev/json-patch 0.0.0-stage → 0.1.0

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.
package/dist/loro.cjs ADDED
@@ -0,0 +1,2722 @@
1
+ const require_diff = require('./diff.cjs');
2
+ let loro_crdt = require("loro-crdt");
3
+ loro_crdt = require_diff.__toESM(loro_crdt);
4
+
5
+ //#region src/loro.ts
6
+ /** Sentinel {@link LoroNodeKind} storing a subtree or string as an atomic `LoroValue` instead of a CRDT container. */
7
+ const LoroValueKind = { kind: "Value" };
8
+ /** Helper returning `{ kind: "Container", containerType }` for {@link LoroSchema} rules. */
9
+ function containerKind(containerType) {
10
+ return {
11
+ kind: "Container",
12
+ containerType
13
+ };
14
+ }
15
+ const VALID_CONTAINER_TYPES = new Set([
16
+ "Map",
17
+ "List",
18
+ "MovableList",
19
+ "Text",
20
+ "Tree",
21
+ "Counter"
22
+ ]);
23
+ function isContainerTypeStr(s) {
24
+ return VALID_CONTAINER_TYPES.has(s);
25
+ }
26
+ function parseContainerTypeFromCid(cid) {
27
+ const colonIdx = cid.lastIndexOf(":");
28
+ if (colonIdx === -1) return void 0;
29
+ const t = cid.slice(colonIdx + 1);
30
+ return isContainerTypeStr(t) ? t : void 0;
31
+ }
32
+ function rootContainerId(name, ctype) {
33
+ return `cid:root-${name}:${ctype}`;
34
+ }
35
+ function docHasExistingContainer(doc, cid, shallowCache) {
36
+ if (cid.startsWith("cid:root-") && !cid.startsWith("cid:root-🤝")) {
37
+ const colonIdx = cid.lastIndexOf(":");
38
+ const rootName = colonIdx !== -1 ? cid.slice(9, colonIdx) : cid.slice(9);
39
+ const shallow = shallowCache ?? doc.getShallowValue();
40
+ return require_diff.hasOwn(shallow, rootName) && shallow[rootName] === cid;
41
+ }
42
+ return doc.hasContainer(cid);
43
+ }
44
+ /**
45
+ * Declarative schema controlling how JSON paths map to `LoroDoc` containers vs atomic `LoroValue`s
46
+ * during {@link applyJsonPatchToLoro}, {@link loroToJson}, and {@link diffLoroJson}.
47
+ */
48
+ var LoroSchema = class LoroSchema {
49
+ roots;
50
+ rules;
51
+ defaultObject;
52
+ defaultArray;
53
+ defaultString;
54
+ constructor(config = {}) {
55
+ const map = /* @__PURE__ */ new Map();
56
+ if (config.roots instanceof Map) for (const [k, v] of config.roots.entries()) map.set(k, v);
57
+ else if (config.roots) {
58
+ const rec = config.roots;
59
+ const keys = Object.keys(rec).sort();
60
+ for (let i = 0; i < keys.length; i++) map.set(keys[i], rec[keys[i]]);
61
+ }
62
+ this.roots = map;
63
+ this.rules = config.rules ? config.rules.slice() : [];
64
+ this.defaultObject = config.defaultObject ?? containerKind("Map");
65
+ this.defaultArray = config.defaultArray ?? containerKind("List");
66
+ this.defaultString = config.defaultString ?? LoroValueKind;
67
+ }
68
+ root(name, containerType) {
69
+ const nextRoots = new Map(this.roots);
70
+ nextRoots.set(name, containerType);
71
+ return new LoroSchema({
72
+ roots: nextRoots,
73
+ rules: this.rules,
74
+ defaultObject: this.defaultObject,
75
+ defaultArray: this.defaultArray,
76
+ defaultString: this.defaultString
77
+ });
78
+ }
79
+ rule(pattern, kind) {
80
+ return new LoroSchema({
81
+ roots: this.roots,
82
+ rules: [...this.rules, {
83
+ pattern,
84
+ kind
85
+ }],
86
+ defaultObject: this.defaultObject,
87
+ defaultArray: this.defaultArray,
88
+ defaultString: this.defaultString
89
+ });
90
+ }
91
+ withDefaultObject(kind) {
92
+ return new LoroSchema({
93
+ roots: this.roots,
94
+ rules: this.rules,
95
+ defaultObject: kind,
96
+ defaultArray: this.defaultArray,
97
+ defaultString: this.defaultString
98
+ });
99
+ }
100
+ withDefaultArray(kind) {
101
+ return new LoroSchema({
102
+ roots: this.roots,
103
+ rules: this.rules,
104
+ defaultObject: this.defaultObject,
105
+ defaultArray: kind,
106
+ defaultString: this.defaultString
107
+ });
108
+ }
109
+ withDefaultString(kind) {
110
+ return new LoroSchema({
111
+ roots: this.roots,
112
+ rules: this.rules,
113
+ defaultObject: this.defaultObject,
114
+ defaultArray: this.defaultArray,
115
+ defaultString: kind
116
+ });
117
+ }
118
+ static discover(doc) {
119
+ const shallow = doc.getShallowValue();
120
+ const roots = /* @__PURE__ */ new Map();
121
+ const names = Object.keys(shallow).sort();
122
+ for (let i = 0; i < names.length; i++) {
123
+ const name = names[i];
124
+ const cid = shallow[name];
125
+ if (typeof cid === "string") {
126
+ const maybeType = parseContainerTypeFromCid(cid);
127
+ if (maybeType) roots.set(name, maybeType);
128
+ }
129
+ }
130
+ return new LoroSchema({ roots });
131
+ }
132
+ explicitKindAt(path) {
133
+ for (let i = 0; i < this.rules.length; i++) if (require_diff.patternMatches(this.rules[i].pattern, path)) return this.rules[i].kind;
134
+ }
135
+ kindForNewValue(path, val) {
136
+ const explicit = this.explicitKindAt(path);
137
+ if (explicit) return explicit;
138
+ if (require_diff.isPlainObject(val)) return this.defaultObject;
139
+ if (Array.isArray(val)) return this.defaultArray;
140
+ if (typeof val === "string") return this.defaultString;
141
+ return LoroValueKind;
142
+ }
143
+ };
144
+ /** Error thrown when applying JSON patches to or projecting from a `LoroDoc`. */
145
+ var LoroApplyError = class extends Error {
146
+ kind;
147
+ opIndex;
148
+ constructor(kind, message, opIndex) {
149
+ super(opIndex !== void 0 ? `op #${opIndex}: ${message}` : message);
150
+ this.name = "LoroApplyError";
151
+ this.kind = kind;
152
+ this.opIndex = opIndex;
153
+ }
154
+ };
155
+ function isLoroContainer(v) {
156
+ return v instanceof loro_crdt.LoroMap || v instanceof loro_crdt.LoroList || v instanceof loro_crdt.LoroMovableList || v instanceof loro_crdt.LoroText || v instanceof loro_crdt.LoroTree || v instanceof loro_crdt.LoroCounter;
157
+ }
158
+ function emptyContainerJson(ctype) {
159
+ switch (ctype) {
160
+ case "Map": return {};
161
+ case "List":
162
+ case "MovableList":
163
+ case "Tree": return [];
164
+ case "Text": return "";
165
+ case "Counter": return 0;
166
+ }
167
+ }
168
+ /** Projects an atomic `loro-crdt` `Value` into a {@link JsonValue}. */
169
+ function projectLoroValue(val) {
170
+ if (val === null || val === void 0) return null;
171
+ if (typeof val === "boolean" || typeof val === "string") return val;
172
+ if (typeof val === "number") {
173
+ if (!Number.isFinite(val)) throw new LoroApplyError("Value", "non-finite float in LoroValue");
174
+ return Object.is(val, -0) ? 0 : val;
175
+ }
176
+ if (typeof val === "bigint") return val;
177
+ if (isLoroContainer(val)) return projectContainer(val);
178
+ if (val instanceof Uint8Array) return new Uint8Array(val);
179
+ if (Array.isArray(val)) return val.map((item) => projectLoroValue(item));
180
+ if (typeof val === "object") {
181
+ const obj = val;
182
+ const out = {};
183
+ const keys = Object.keys(obj).sort();
184
+ for (let i = 0; i < keys.length; i++) {
185
+ const k = keys[i];
186
+ require_diff.setOwnProp(out, k, projectLoroValue(obj[k]));
187
+ }
188
+ return out;
189
+ }
190
+ throw new LoroApplyError("Value", `unsupported Loro value type: ${typeof val}`);
191
+ }
192
+ function projectMap(map) {
193
+ const entries = map.entries().sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
194
+ const out = {};
195
+ for (let i = 0; i < entries.length; i++) {
196
+ const [k, v] = entries[i];
197
+ require_diff.setOwnProp(out, k, isLoroContainer(v) ? projectContainer(v) : projectLoroValue(v));
198
+ }
199
+ return out;
200
+ }
201
+ function projectTreeNode(node) {
202
+ const meta = projectMap(node.data);
203
+ const childrenNodes = node.children() ?? [];
204
+ const children = new Array(childrenNodes.length);
205
+ for (let i = 0; i < childrenNodes.length; i++) children[i] = projectTreeNode(childrenNodes[i]);
206
+ return {
207
+ children,
208
+ id: node.id,
209
+ meta
210
+ };
211
+ }
212
+ /** Recursively projects a `LoroDoc` container (`Map`, `List`, `MovableList`, `Text`, `Tree`, `Counter`) into JSON. */
213
+ function projectContainer(container) {
214
+ if (container instanceof loro_crdt.LoroMap) return projectMap(container);
215
+ if (container instanceof loro_crdt.LoroList || container instanceof loro_crdt.LoroMovableList) {
216
+ const items = container.toArray();
217
+ const out = new Array(items.length);
218
+ for (let i = 0; i < items.length; i++) {
219
+ const item = items[i];
220
+ out[i] = isLoroContainer(item) ? projectContainer(item) : projectLoroValue(item);
221
+ }
222
+ return out;
223
+ }
224
+ if (container instanceof loro_crdt.LoroText) return container.toString();
225
+ if (container instanceof loro_crdt.LoroTree) return container.roots().map((node) => projectTreeNode(node));
226
+ if (container instanceof loro_crdt.LoroCounter) {
227
+ const v = container.value;
228
+ if (!Number.isFinite(v)) throw new LoroApplyError("Value", "non-finite counter value");
229
+ return Object.is(v, -0) ? 0 : v;
230
+ }
231
+ throw new LoroApplyError("Loro", "unknown container instance");
232
+ }
233
+ /** Projects a container identified by `cid`, returning the empty default JSON shape if not yet materialized. */
234
+ function projectContainerById(doc, cid, fallbackType) {
235
+ if (!docHasExistingContainer(doc, cid)) {
236
+ if (fallbackType) return emptyContainerJson(fallbackType);
237
+ const t = parseContainerTypeFromCid(cid);
238
+ return t ? emptyContainerJson(t) : null;
239
+ }
240
+ const c = doc.getContainerById(cid);
241
+ if (!c) return fallbackType ? emptyContainerJson(fallbackType) : null;
242
+ return projectContainer(c);
243
+ }
244
+ /**
245
+ * Projects all roots in `doc` matching `schema` (or discovered shallow roots if omitted) into a plain {@link JsonObject}.
246
+ */
247
+ function loroToJson(doc, schema) {
248
+ const effective = schema ?? LoroSchema.discover(doc);
249
+ const rootNames = Array.from(effective.roots.keys()).sort();
250
+ const shallow = doc.getShallowValue();
251
+ const out = {};
252
+ for (let i = 0; i < rootNames.length; i++) {
253
+ const name = rootNames[i];
254
+ const ctype = effective.roots.get(name);
255
+ const cid = rootContainerId(name, ctype);
256
+ if (!docHasExistingContainer(doc, cid, shallow)) require_diff.setOwnProp(out, name, emptyContainerJson(ctype));
257
+ else {
258
+ const container = doc.getContainerById(cid);
259
+ require_diff.setOwnProp(out, name, container ? projectContainer(container) : emptyContainerJson(ctype));
260
+ }
261
+ }
262
+ return out;
263
+ }
264
+ /** Converts a {@link JsonValue} into a primitive/nested `loro-crdt` `Value`. */
265
+ function jsonToLoroValue(val) {
266
+ if (val === null) return null;
267
+ if (typeof val === "boolean" || typeof val === "string") return val;
268
+ if (typeof val === "number") {
269
+ if (!Number.isFinite(val)) throw new LoroApplyError("Value", "non-finite float is forbidden");
270
+ return Object.is(val, -0) ? 0 : val;
271
+ }
272
+ if (typeof val === "bigint") {
273
+ if (val < require_diff.MIN_SAFE_BIG || val > require_diff.MAX_SAFE_BIG) throw new LoroApplyError("Value", `integer ${val} out of safe range for lossless Loro bridging`);
274
+ return Number(val);
275
+ }
276
+ if (val instanceof Uint8Array) return new Uint8Array(val);
277
+ if (Array.isArray(val)) return val.map((item) => jsonToLoroValue(item));
278
+ if (require_diff.isPlainObject(val)) {
279
+ const out = {};
280
+ const keys = Object.keys(val);
281
+ for (let i = 0; i < keys.length; i++) {
282
+ const k = keys[i];
283
+ require_diff.setOwnProp(out, k, jsonToLoroValue(val[k]));
284
+ }
285
+ return out;
286
+ }
287
+ throw new LoroApplyError("Value", `unsupported JsonValue type: ${typeof val}`);
288
+ }
289
+ function frontiersEqual(a, b) {
290
+ if (a.length === 0 && b.length === 0) return true;
291
+ if (a.length === 1 && b.length === 1) return a[0].peer === b[0].peer && a[0].counter === b[0].counter;
292
+ const mapA = /* @__PURE__ */ new Map();
293
+ for (let i = 0; i < a.length; i++) mapA.set(a[i].peer, a[i].counter);
294
+ const mapB = /* @__PURE__ */ new Map();
295
+ for (let i = 0; i < b.length; i++) mapB.set(b[i].peer, b[i].counter);
296
+ if (mapA.size !== mapB.size) return false;
297
+ for (const [peer, counter] of mapA.entries()) if (mapB.get(peer) !== counter) return false;
298
+ return true;
299
+ }
300
+ function markAncestors(doc, cid, dirtyAncestors, shallowCache) {
301
+ if (!docHasExistingContainer(doc, cid, shallowCache)) return;
302
+ let cur = doc.getContainerById(cid);
303
+ while (cur) {
304
+ let parent;
305
+ try {
306
+ parent = cur.parent();
307
+ } catch {
308
+ parent = void 0;
309
+ }
310
+ if (!parent) break;
311
+ dirtyAncestors.add(parent.id);
312
+ cur = parent;
313
+ }
314
+ }
315
+ function prependOpPath(op, prefix) {
316
+ switch (op.op) {
317
+ case "set": return {
318
+ op: "set",
319
+ path: [...prefix, ...op.path],
320
+ value: op.value
321
+ };
322
+ case "unset": return {
323
+ op: "unset",
324
+ path: [...prefix, ...op.path]
325
+ };
326
+ case "arr_splice": return {
327
+ op: "arr_splice",
328
+ path: [...prefix, ...op.path],
329
+ at: op.at,
330
+ del: op.del,
331
+ items: op.items
332
+ };
333
+ case "move": return {
334
+ op: "move",
335
+ from: [...prefix, ...op.from],
336
+ to: [...prefix, ...op.to]
337
+ };
338
+ case "str_splice": return {
339
+ op: "str_splice",
340
+ path: [...prefix, ...op.path],
341
+ at: op.at,
342
+ del: op.del,
343
+ ins: op.ins
344
+ };
345
+ }
346
+ }
347
+ const f64HashBuf = /* @__PURE__ */ new ArrayBuffer(8);
348
+ const f64HashView = new DataView(f64HashBuf);
349
+ function hashJsonForAlign(val) {
350
+ let h1 = 2166136261;
351
+ let h2 = 16777619;
352
+ function hashStr(s) {
353
+ for (let i = 0; i < s.length; i++) {
354
+ h1 = Math.imul(h1 ^ s.charCodeAt(i), 16777619);
355
+ h2 = Math.imul(h2 ^ s.charCodeAt(i), 2246822519);
356
+ }
357
+ }
358
+ function visit(v) {
359
+ if (v === null) {
360
+ h1 = Math.imul(h1 ^ 1, 16777619);
361
+ return;
362
+ }
363
+ if (typeof v === "boolean") {
364
+ h1 = Math.imul(h1 ^ (v ? 2 : 3), 16777619);
365
+ return;
366
+ }
367
+ if (typeof v === "number" || typeof v === "bigint") {
368
+ if (typeof v === "bigint") hashStr(`n:${v}`);
369
+ else {
370
+ const norm = v === 0 ? 0 : v;
371
+ if (Number.isFinite(norm) && Number.isInteger(norm) && norm >= -0x8000000000000000 && norm < 0x10000000000000000) hashStr(`n:${BigInt(norm)}`);
372
+ else {
373
+ f64HashView.setFloat64(0, norm, false);
374
+ hashStr(`f:${f64HashView.getUint32(0, false).toString(16)}:${f64HashView.getUint32(4, false).toString(16)}`);
375
+ }
376
+ }
377
+ return;
378
+ }
379
+ if (typeof v === "string") {
380
+ h1 = Math.imul(h1 ^ 5, 16777619);
381
+ hashStr(v);
382
+ return;
383
+ }
384
+ if (v instanceof Uint8Array) {
385
+ h1 = Math.imul(h1 ^ 6 ^ v.byteLength, 16777619);
386
+ for (let i = 0; i < v.byteLength; i++) h1 = Math.imul(h1 ^ v[i], 16777619);
387
+ return;
388
+ }
389
+ if (Array.isArray(v)) {
390
+ h1 = Math.imul(h1 ^ 7 ^ v.length, 16777619);
391
+ for (let i = 0; i < v.length; i++) visit(v[i]);
392
+ return;
393
+ }
394
+ if (require_diff.isPlainObject(v)) {
395
+ const ks = Object.keys(v).sort();
396
+ h1 = Math.imul(h1 ^ 8 ^ ks.length, 16777619);
397
+ for (let i = 0; i < ks.length; i++) {
398
+ hashStr(ks[i]);
399
+ visit(v[ks[i]]);
400
+ }
401
+ }
402
+ }
403
+ visit(val);
404
+ return `${h1 >>> 0}:${h2 >>> 0}`;
405
+ }
406
+ /**
407
+ * Computes minimal CRDT-aware {@link JsonOp}s describing state changes between `fromFrontiers` and `toFrontiers`.
408
+ */
409
+ function diffLoroJson(doc, fromFrontiers, toFrontiers, schema) {
410
+ const fromCopy = fromFrontiers.slice();
411
+ const toCopy = toFrontiers.slice();
412
+ if (frontiersEqual(fromCopy, toCopy)) return [];
413
+ const diffBatch = doc.diff(fromCopy, toCopy, false);
414
+ const oplogF = doc.oplogFrontiers();
415
+ const stateMatchesOplog = frontiersEqual(doc.frontiers(), oplogF);
416
+ const docFrom = stateMatchesOplog && frontiersEqual(fromCopy, oplogF) ? doc : doc.forkAt(fromCopy);
417
+ const docTo = stateMatchesOplog && frontiersEqual(toCopy, oplogF) ? doc : doc.forkAt(toCopy);
418
+ const shallowFrom = docFrom.getShallowValue();
419
+ const shallowTo = docTo.getShallowValue();
420
+ const diffMap = /* @__PURE__ */ new Map();
421
+ const changedCids = /* @__PURE__ */ new Set();
422
+ const dirtyAncestors = /* @__PURE__ */ new Set();
423
+ for (let i = 0; i < diffBatch.length; i++) {
424
+ const [cid, d] = diffBatch[i];
425
+ changedCids.add(cid);
426
+ diffMap.set(cid, d);
427
+ markAncestors(docTo, cid, dirtyAncestors, shallowTo);
428
+ markAncestors(docFrom, cid, dirtyAncestors, shallowFrom);
429
+ }
430
+ const ops = [];
431
+ const rootNames = Array.from(schema.roots.keys()).sort();
432
+ for (let i = 0; i < rootNames.length; i++) {
433
+ const name = rootNames[i];
434
+ const ctype = schema.roots.get(name);
435
+ const cid = rootContainerId(name, ctype);
436
+ const existsFrom = docHasExistingContainer(docFrom, cid, shallowFrom);
437
+ const existsTo = docHasExistingContainer(docTo, cid, shallowTo);
438
+ if (!changedCids.has(cid) && !dirtyAncestors.has(cid) && existsFrom === existsTo) continue;
439
+ diffContainerById(docFrom, docTo, shallowFrom, shallowTo, cid, ctype, [name], changedCids, dirtyAncestors, diffMap, ops);
440
+ }
441
+ return ops;
442
+ }
443
+ function diffContainerById(docFrom, docTo, shallowFrom, shallowTo, cid, expectedType, path, changedCids, dirtyAncestors, diffMap, ops) {
444
+ const hasFrom = docHasExistingContainer(docFrom, cid, shallowFrom);
445
+ const hasTo = docHasExistingContainer(docTo, cid, shallowTo);
446
+ if (!changedCids.has(cid) && !dirtyAncestors.has(cid) && hasFrom === hasTo) return;
447
+ const ctype = expectedType ?? parseContainerTypeFromCid(cid) ?? "Map";
448
+ if (!hasFrom && !hasTo) return;
449
+ if (hasFrom && !hasTo) {
450
+ const cFrom$1 = docFrom.getContainerById(cid);
451
+ const jFrom = cFrom$1 ? projectContainer(cFrom$1) : emptyContainerJson(ctype);
452
+ const jTo = emptyContainerJson(ctype);
453
+ if (!require_diff.valuesEqual(jFrom, jTo)) {
454
+ const subOps = require_diff.diff(jFrom, jTo);
455
+ for (let i = 0; i < subOps.length; i++) ops.push(prependOpPath(subOps[i], path));
456
+ }
457
+ return;
458
+ }
459
+ if (!hasFrom && hasTo) {
460
+ const jFrom = emptyContainerJson(ctype);
461
+ const cTo$1 = docTo.getContainerById(cid);
462
+ const jTo = cTo$1 ? projectContainer(cTo$1) : jFrom;
463
+ if (!require_diff.valuesEqual(jFrom, jTo)) {
464
+ const subOps = require_diff.diff(jFrom, jTo);
465
+ for (let i = 0; i < subOps.length; i++) ops.push(prependOpPath(subOps[i], path));
466
+ }
467
+ return;
468
+ }
469
+ const cFrom = docFrom.getContainerById(cid);
470
+ const cTo = docTo.getContainerById(cid);
471
+ if (!cFrom || !cTo) return;
472
+ diffContainer(docFrom, docTo, cFrom, cTo, path, changedCids, dirtyAncestors, diffMap, ops);
473
+ }
474
+ function diffContainer(docFrom, docTo, cFrom, cTo, path, changedCids, dirtyAncestors, diffMap, ops) {
475
+ if (cFrom instanceof loro_crdt.LoroMap && cTo instanceof loro_crdt.LoroMap) {
476
+ diffMapContainer(docFrom, docTo, cFrom, cTo, path, changedCids, dirtyAncestors, diffMap, ops);
477
+ return;
478
+ }
479
+ if (cFrom instanceof loro_crdt.LoroList && cTo instanceof loro_crdt.LoroList) {
480
+ diffListContainer(docFrom, docTo, cFrom, cTo, path, changedCids, dirtyAncestors, diffMap, ops);
481
+ return;
482
+ }
483
+ if (cFrom instanceof loro_crdt.LoroMovableList && cTo instanceof loro_crdt.LoroMovableList) {
484
+ diffMovableListContainer(docFrom, docTo, cFrom, cTo, path, changedCids, dirtyAncestors, diffMap, ops);
485
+ return;
486
+ }
487
+ if (cFrom instanceof loro_crdt.LoroText && cTo instanceof loro_crdt.LoroText) {
488
+ diffTextContainer(cFrom, cTo, path, diffMap, ops);
489
+ return;
490
+ }
491
+ if (cFrom instanceof loro_crdt.LoroTree && cTo instanceof loro_crdt.LoroTree) {
492
+ diffTreeContainer(docFrom, docTo, cFrom, cTo, path, changedCids, dirtyAncestors, diffMap, ops);
493
+ return;
494
+ }
495
+ if (cFrom instanceof loro_crdt.LoroCounter && cTo instanceof loro_crdt.LoroCounter) {
496
+ const v1 = Object.is(cFrom.value, -0) ? 0 : cFrom.value;
497
+ const v2 = Object.is(cTo.value, -0) ? 0 : cTo.value;
498
+ if (v1 !== v2) ops.push({
499
+ op: "set",
500
+ path: path.slice(),
501
+ value: v2
502
+ });
503
+ return;
504
+ }
505
+ const j1 = projectContainer(cFrom);
506
+ const j2 = projectContainer(cTo);
507
+ if (!require_diff.valuesEqual(j1, j2)) ops.push({
508
+ op: "set",
509
+ path: path.slice(),
510
+ value: j2
511
+ });
512
+ }
513
+ function diffMapContainer(docFrom, docTo, mapFrom, mapTo, path, changedCids, dirtyAncestors, diffMap, ops) {
514
+ const fromMap = /* @__PURE__ */ new Map();
515
+ const fromEntries = mapFrom.entries();
516
+ for (let i = 0; i < fromEntries.length; i++) fromMap.set(fromEntries[i][0], fromEntries[i][1]);
517
+ const toMap = /* @__PURE__ */ new Map();
518
+ const toEntries = mapTo.entries();
519
+ for (let i = 0; i < toEntries.length; i++) toMap.set(toEntries[i][0], toEntries[i][1]);
520
+ const fromKeys = Array.from(fromMap.keys()).sort();
521
+ for (let i = 0; i < fromKeys.length; i++) {
522
+ const k = fromKeys[i];
523
+ if (!toMap.has(k)) ops.push({
524
+ op: "unset",
525
+ path: [...path, k]
526
+ });
527
+ }
528
+ const toKeys = Array.from(toMap.keys()).sort();
529
+ for (let i = 0; i < toKeys.length; i++) {
530
+ const k = toKeys[i];
531
+ const vocTo = toMap.get(k);
532
+ path.push(k);
533
+ if (!fromMap.has(k)) ops.push({
534
+ op: "set",
535
+ path: path.slice(),
536
+ value: isLoroContainer(vocTo) ? projectContainer(vocTo) : projectLoroValue(vocTo)
537
+ });
538
+ else diffVocPair(docFrom, docTo, fromMap.get(k), vocTo, path, changedCids, dirtyAncestors, diffMap, ops);
539
+ path.pop();
540
+ }
541
+ }
542
+ function diffVocPair(docFrom, docTo, vocFrom, vocTo, path, changedCids, dirtyAncestors, diffMap, ops) {
543
+ if (isLoroContainer(vocFrom) && isLoroContainer(vocTo) && vocFrom.id === vocTo.id) {
544
+ if (changedCids.has(vocFrom.id) || dirtyAncestors.has(vocFrom.id)) diffContainer(docFrom, docTo, vocFrom, vocTo, path, changedCids, dirtyAncestors, diffMap, ops);
545
+ return;
546
+ }
547
+ if (!isLoroContainer(vocFrom) && !isLoroContainer(vocTo)) {
548
+ const j1$1 = projectLoroValue(vocFrom);
549
+ const j2$1 = projectLoroValue(vocTo);
550
+ if (!require_diff.valuesEqual(j1$1, j2$1)) {
551
+ const subOps = diffPureValue(j1$1, j2$1);
552
+ for (let i = 0; i < subOps.length; i++) ops.push(prependOpPath(subOps[i], path));
553
+ }
554
+ return;
555
+ }
556
+ const j1 = isLoroContainer(vocFrom) ? projectContainer(vocFrom) : projectLoroValue(vocFrom);
557
+ const j2 = isLoroContainer(vocTo) ? projectContainer(vocTo) : projectLoroValue(vocTo);
558
+ if (!require_diff.valuesEqual(j1, j2)) ops.push({
559
+ op: "set",
560
+ path: path.slice(),
561
+ value: j2
562
+ });
563
+ }
564
+ function diffPureValue(oldVal, newVal) {
565
+ return require_diff.diff(oldVal, newVal);
566
+ }
567
+ function diffTextContainer(textFrom, textTo, path, diffMap, ops) {
568
+ const sFrom = textFrom.toString();
569
+ const sTo = textTo.toString();
570
+ if (sFrom === sTo) return;
571
+ const diff$1 = diffMap.get(textTo.id);
572
+ if (diff$1 && diff$1.type === "text") {
573
+ let cur = sFrom;
574
+ let cursor = 0;
575
+ const localOps = [];
576
+ let ok = true;
577
+ for (let i = 0; i < diff$1.diff.length; i++) {
578
+ const d = diff$1.diff[i];
579
+ if (d.retain !== void 0) {
580
+ cursor += d.retain;
581
+ if (cursor > cur.length) {
582
+ ok = false;
583
+ break;
584
+ }
585
+ } else if (d.delete !== void 0) {
586
+ if (d.delete > 0) {
587
+ if (cursor + d.delete > cur.length) {
588
+ ok = false;
589
+ break;
590
+ }
591
+ try {
592
+ require_diff.assertValidUtf16Range(cur, cursor, d.delete, 0);
593
+ } catch {
594
+ ok = false;
595
+ break;
596
+ }
597
+ cur = cur.slice(0, cursor) + cur.slice(cursor + d.delete);
598
+ const prev = localOps[localOps.length - 1];
599
+ if (prev && prev.op === "str_splice" && cursor === prev.at + prev.ins.length) localOps[localOps.length - 1] = {
600
+ ...prev,
601
+ del: prev.del + d.delete
602
+ };
603
+ else localOps.push({
604
+ op: "str_splice",
605
+ path: path.slice(),
606
+ at: cursor,
607
+ del: d.delete,
608
+ ins: ""
609
+ });
610
+ }
611
+ } else if (d.insert !== void 0) {
612
+ if (d.insert.length > 0) {
613
+ cur = cur.slice(0, cursor) + d.insert + cur.slice(cursor);
614
+ const prev = localOps[localOps.length - 1];
615
+ if (prev && prev.op === "str_splice" && cursor === prev.at + prev.ins.length) localOps[localOps.length - 1] = {
616
+ ...prev,
617
+ ins: prev.ins + d.insert
618
+ };
619
+ else localOps.push({
620
+ op: "str_splice",
621
+ path: path.slice(),
622
+ at: cursor,
623
+ del: 0,
624
+ ins: d.insert
625
+ });
626
+ cursor += d.insert.length;
627
+ }
628
+ }
629
+ }
630
+ if (ok && cur === sTo) {
631
+ for (let i = 0; i < localOps.length; i++) ops.push(localOps[i]);
632
+ return;
633
+ }
634
+ }
635
+ require_diff.diffStringAt(path, sFrom, sTo, ops);
636
+ }
637
+ function diffListContainer(docFrom, docTo, listFrom, listTo, path, changedCids, dirtyAncestors, diffMap, ops) {
638
+ const fromItems = listFrom.toArray();
639
+ const toItems = listTo.toArray();
640
+ const retainedChildren = [];
641
+ const diff$1 = diffMap.get(listTo.id);
642
+ if (diff$1 && diff$1.type === "list") {
643
+ let oldIdx = 0;
644
+ let curIdx = 0;
645
+ for (let i = 0; i < diff$1.diff.length; i++) {
646
+ const delta = diff$1.diff[i];
647
+ if (delta.retain !== void 0) {
648
+ for (let k = 0; k < delta.retain; k++) {
649
+ const v1 = fromItems[oldIdx + k];
650
+ const v2 = toItems[curIdx + k];
651
+ if (isLoroContainer(v1) && isLoroContainer(v2) && v1.id === v2.id) retainedChildren.push({
652
+ fromC: v1,
653
+ toC: v2,
654
+ idx: curIdx + k
655
+ });
656
+ }
657
+ oldIdx += delta.retain;
658
+ curIdx += delta.retain;
659
+ } else if (delta.delete !== void 0) {
660
+ if (delta.delete > 0) {
661
+ ops.push({
662
+ op: "arr_splice",
663
+ path: path.slice(),
664
+ at: curIdx,
665
+ del: delta.delete,
666
+ items: []
667
+ });
668
+ oldIdx += delta.delete;
669
+ }
670
+ } else if (delta.insert !== void 0) {
671
+ const insLen = delta.insert.length;
672
+ if (insLen > 0) {
673
+ const projected = new Array(insLen);
674
+ for (let k = 0; k < insLen; k++) {
675
+ const v2 = toItems[curIdx + k];
676
+ projected[k] = isLoroContainer(v2) ? projectContainer(v2) : projectLoroValue(v2);
677
+ }
678
+ const prev = ops[ops.length - 1];
679
+ if (prev && prev.op === "arr_splice" && prev.items.length === 0 && prev.at === curIdx && require_diff.pathsEqual(prev.path, path)) ops[ops.length - 1] = {
680
+ ...prev,
681
+ items: projected
682
+ };
683
+ else ops.push({
684
+ op: "arr_splice",
685
+ path: path.slice(),
686
+ at: curIdx,
687
+ del: 0,
688
+ items: projected
689
+ });
690
+ curIdx += insLen;
691
+ }
692
+ }
693
+ }
694
+ const tailLen = Math.min(fromItems.length - oldIdx, toItems.length - curIdx);
695
+ for (let k = 0; k < tailLen; k++) {
696
+ const v1 = fromItems[oldIdx + k];
697
+ const v2 = toItems[curIdx + k];
698
+ if (isLoroContainer(v1) && isLoroContainer(v2) && v1.id === v2.id) retainedChildren.push({
699
+ fromC: v1,
700
+ toC: v2,
701
+ idx: curIdx + k
702
+ });
703
+ }
704
+ } else for (let i = 0; i < toItems.length && i < fromItems.length; i++) {
705
+ const v1 = fromItems[i];
706
+ const v2 = toItems[i];
707
+ if (isLoroContainer(v1) && isLoroContainer(v2) && v1.id === v2.id) retainedChildren.push({
708
+ fromC: v1,
709
+ toC: v2,
710
+ idx: i
711
+ });
712
+ }
713
+ for (let i = 0; i < retainedChildren.length; i++) {
714
+ const { fromC, toC, idx } = retainedChildren[i];
715
+ if (changedCids.has(toC.id) || dirtyAncestors.has(toC.id)) {
716
+ path.push(idx);
717
+ diffContainer(docFrom, docTo, fromC, toC, path, changedCids, dirtyAncestors, diffMap, ops);
718
+ path.pop();
719
+ }
720
+ }
721
+ }
722
+ function diffMovableListContainer(docFrom, docTo, mlFrom, mlTo, path, changedCids, dirtyAncestors, diffMap, ops) {
723
+ const fromItems = mlFrom.toArray();
724
+ const toItems = mlTo.toArray();
725
+ const lenFrom = fromItems.length;
726
+ const lenTo = toItems.length;
727
+ const oldToNew = new Array(lenFrom).fill(-1);
728
+ const newToOld = new Array(lenTo).fill(-1);
729
+ const cidMap = /* @__PURE__ */ new Map();
730
+ for (let i$1 = 0; i$1 < lenFrom; i$1++) {
731
+ const item = fromItems[i$1];
732
+ if (isLoroContainer(item)) cidMap.set(item.id, i$1);
733
+ }
734
+ for (let j$1 = 0; j$1 < lenTo; j$1++) {
735
+ const item = toItems[j$1];
736
+ if (isLoroContainer(item)) {
737
+ const oi = cidMap.get(item.id);
738
+ if (oi !== void 0) {
739
+ oldToNew[oi] = j$1;
740
+ newToOld[j$1] = oi;
741
+ }
742
+ }
743
+ }
744
+ const cursorMap = /* @__PURE__ */ new Map();
745
+ for (let i$1 = 0; i$1 < lenFrom; i$1++) {
746
+ if (oldToNew[i$1] !== -1) continue;
747
+ const pos = mlFrom.getCursor(i$1, 0)?.pos();
748
+ if (pos) {
749
+ const k = `${pos.peer}:${pos.counter}`;
750
+ if (!cursorMap.has(k)) cursorMap.set(k, i$1);
751
+ }
752
+ }
753
+ for (let j$1 = 0; j$1 < lenTo; j$1++) {
754
+ if (newToOld[j$1] !== -1) continue;
755
+ const pos = mlTo.getCursor(j$1, 0)?.pos();
756
+ if (pos) {
757
+ const k = `${pos.peer}:${pos.counter}`;
758
+ const oi = cursorMap.get(k);
759
+ if (oi !== void 0 && oldToNew[oi] === -1) {
760
+ oldToNew[oi] = j$1;
761
+ newToOld[j$1] = oi;
762
+ }
763
+ }
764
+ }
765
+ const fromJsonCache = new Array(lenFrom);
766
+ const toJsonCache = new Array(lenTo);
767
+ const getFromJson = (i$1) => {
768
+ if (fromJsonCache[i$1] === void 0) {
769
+ const v = fromItems[i$1];
770
+ fromJsonCache[i$1] = isLoroContainer(v) ? projectContainer(v) : projectLoroValue(v);
771
+ }
772
+ return fromJsonCache[i$1];
773
+ };
774
+ const getToJson = (j$1) => {
775
+ if (toJsonCache[j$1] === void 0) {
776
+ const v = toItems[j$1];
777
+ toJsonCache[j$1] = isLoroContainer(v) ? projectContainer(v) : projectLoroValue(v);
778
+ }
779
+ return toJsonCache[j$1];
780
+ };
781
+ const buckets = /* @__PURE__ */ new Map();
782
+ for (let i$1 = lenFrom - 1; i$1 >= 0; i$1--) {
783
+ if (oldToNew[i$1] !== -1) continue;
784
+ const h = hashJsonForAlign(getFromJson(i$1));
785
+ let q = buckets.get(h);
786
+ if (!q) {
787
+ q = [];
788
+ buckets.set(h, q);
789
+ }
790
+ q.push(i$1);
791
+ }
792
+ for (let j$1 = 0; j$1 < lenTo; j$1++) {
793
+ if (newToOld[j$1] !== -1) continue;
794
+ const targetVal = getToJson(j$1);
795
+ const h = hashJsonForAlign(targetVal);
796
+ const q = buckets.get(h);
797
+ if (!q) continue;
798
+ for (let qi = q.length - 1; qi >= 0; qi--) {
799
+ const oi = q[qi];
800
+ if (require_diff.valuesEqual(getFromJson(oi), targetVal)) {
801
+ if (qi === q.length - 1) q.pop();
802
+ else q.splice(qi, 1);
803
+ oldToNew[oi] = j$1;
804
+ newToOld[j$1] = oi;
805
+ break;
806
+ }
807
+ }
808
+ }
809
+ let i = lenFrom;
810
+ while (i > 0) {
811
+ i--;
812
+ if (oldToNew[i] === -1) {
813
+ let delCnt = 1;
814
+ while (i > 0 && oldToNew[i - 1] === -1) {
815
+ i--;
816
+ delCnt++;
817
+ }
818
+ ops.push({
819
+ op: "arr_splice",
820
+ path: path.slice(),
821
+ at: i,
822
+ del: delCnt,
823
+ items: []
824
+ });
825
+ }
826
+ }
827
+ const oldIdxToCompact = new Array(lenFrom).fill(-1);
828
+ let compactCnt = 0;
829
+ for (let oi = 0; oi < lenFrom; oi++) if (oldToNew[oi] !== -1) oldIdxToCompact[oi] = compactCnt++;
830
+ const targetSeq = [];
831
+ for (let nj = 0; nj < lenTo; nj++) {
832
+ const oi = newToOld[nj];
833
+ if (oi !== -1) targetSeq.push(oldIdxToCompact[oi]);
834
+ }
835
+ if (compactCnt > 1) {
836
+ const pairs = require_diff.lisMovePairs(targetSeq);
837
+ for (let m = 0; m < pairs.length; m++) {
838
+ const [fromIdx, toIdx] = pairs[m];
839
+ ops.push({
840
+ op: "move",
841
+ from: [...path, fromIdx],
842
+ to: [...path, toIdx]
843
+ });
844
+ }
845
+ }
846
+ let j = 0;
847
+ while (j < lenTo) if (newToOld[j] === -1) {
848
+ const start = j;
849
+ const items = [];
850
+ while (j < lenTo && newToOld[j] === -1) {
851
+ items.push(getToJson(j));
852
+ j++;
853
+ }
854
+ ops.push({
855
+ op: "arr_splice",
856
+ path: path.slice(),
857
+ at: start,
858
+ del: 0,
859
+ items
860
+ });
861
+ } else j++;
862
+ for (let nj = 0; nj < lenTo; nj++) {
863
+ const oi = newToOld[nj];
864
+ if (oi === -1) continue;
865
+ path.push(nj);
866
+ diffVocPair(docFrom, docTo, fromItems[oi], toItems[nj], path, changedCids, dirtyAncestors, diffMap, ops);
867
+ path.pop();
868
+ }
869
+ }
870
+ function buildDiffSimTree(tree) {
871
+ function wrap(nodes) {
872
+ return nodes.map((n) => ({
873
+ id: n.id,
874
+ children: wrap(n.children() ?? [])
875
+ }));
876
+ }
877
+ return wrap(tree.roots());
878
+ }
879
+ function collectDiffTreeIds(nodes, out) {
880
+ for (let i = 0; i < nodes.length; i++) {
881
+ out.add(nodes[i].id);
882
+ collectDiffTreeIds(nodes[i].children, out);
883
+ }
884
+ }
885
+ function anyDiffTreeDescIn(node, set) {
886
+ for (let i = 0; i < node.children.length; i++) {
887
+ const c = node.children[i];
888
+ if (set.has(c.id) || anyDiffTreeDescIn(c, set)) return true;
889
+ }
890
+ return false;
891
+ }
892
+ function findDiffTreeNodePath(nodes, target, prefix) {
893
+ for (let i = 0; i < nodes.length; i++) {
894
+ if (nodes[i].id === target) return [...prefix, i];
895
+ const found = findDiffTreeNodePath(nodes[i].children, target, [
896
+ ...prefix,
897
+ i,
898
+ "children"
899
+ ]);
900
+ if (found) return found;
901
+ }
902
+ }
903
+ function takeDiffTreeNode(nodes, target) {
904
+ for (let i = 0; i < nodes.length; i++) {
905
+ if (nodes[i].id === target) return nodes.splice(i, 1)[0];
906
+ const found = takeDiffTreeNode(nodes[i].children, target);
907
+ if (found) return found;
908
+ }
909
+ }
910
+ function findDiffTreeChildren(roots, parentId) {
911
+ if (parentId === void 0) return roots;
912
+ function findNode(nodes) {
913
+ for (let i = 0; i < nodes.length; i++) {
914
+ if (nodes[i].id === parentId) return nodes[i];
915
+ const f = findNode(nodes[i].children);
916
+ if (f) return f;
917
+ }
918
+ }
919
+ return findNode(roots)?.children;
920
+ }
921
+ function diffTreeParentChildrenPath(roots, treePath, parentId) {
922
+ if (parentId === void 0) return {
923
+ path: treePath.slice(),
924
+ len: roots.length
925
+ };
926
+ const np = findDiffTreeNodePath(roots, parentId, treePath.slice());
927
+ if (!np) return void 0;
928
+ const list = findDiffTreeChildren(roots, parentId);
929
+ return {
930
+ path: [...np, "children"],
931
+ len: list ? list.length : 0
932
+ };
933
+ }
934
+ function diffTreeContainer(docFrom, docTo, treeFrom, treeTo, treePath, changedCids, dirtyAncestors, diffMap, ops) {
935
+ const curRoots = buildDiffSimTree(treeFrom);
936
+ const toRoots = buildDiffSimTree(treeTo);
937
+ const oldIds = /* @__PURE__ */ new Set();
938
+ collectDiffTreeIds(curRoots, oldIds);
939
+ const newIds = /* @__PURE__ */ new Set();
940
+ collectDiffTreeIds(toRoots, newIds);
941
+ const placedWhole = /* @__PURE__ */ new Set();
942
+ function placePreorder(parentId, targetNodes) {
943
+ for (let i = 0; i < targetNodes.length; i++) {
944
+ const tn = targetNodes[i];
945
+ if (placedWhole.has(tn.id)) continue;
946
+ if (!oldIds.has(tn.id)) {
947
+ const parentInfo = diffTreeParentChildrenPath(curRoots, treePath, parentId);
948
+ if (!anyDiffTreeDescIn(tn, oldIds)) {
949
+ const fullNode = treeTo.getNodeByID(tn.id);
950
+ ops.push({
951
+ op: "arr_splice",
952
+ path: parentInfo.path,
953
+ at: parentInfo.len,
954
+ del: 0,
955
+ items: [projectTreeNode(fullNode)]
956
+ });
957
+ findDiffTreeChildren(curRoots, parentId).push({
958
+ id: tn.id,
959
+ children: tn.children.slice()
960
+ });
961
+ collectDiffTreeIds([tn], placedWhole);
962
+ continue;
963
+ } else {
964
+ const nodeTo = treeTo.getNodeByID(tn.id);
965
+ const shell = {
966
+ children: [],
967
+ id: tn.id,
968
+ meta: projectMap(nodeTo.data)
969
+ };
970
+ ops.push({
971
+ op: "arr_splice",
972
+ path: parentInfo.path,
973
+ at: parentInfo.len,
974
+ del: 0,
975
+ items: [shell]
976
+ });
977
+ findDiffTreeChildren(curRoots, parentId).push({
978
+ id: tn.id,
979
+ children: []
980
+ });
981
+ }
982
+ } else if (!findDiffTreeChildren(curRoots, parentId).some((s) => s.id === tn.id)) {
983
+ const fromPath = findDiffTreeNodePath(curRoots, tn.id, treePath.slice());
984
+ const moved = takeDiffTreeNode(curRoots, tn.id);
985
+ const toInfo = diffTreeParentChildrenPath(curRoots, treePath, parentId);
986
+ ops.push({
987
+ op: "move",
988
+ from: fromPath,
989
+ to: [...toInfo.path, toInfo.len]
990
+ });
991
+ findDiffTreeChildren(curRoots, parentId).push(moved);
992
+ }
993
+ placePreorder(tn.id, tn.children);
994
+ }
995
+ }
996
+ placePreorder(void 0, toRoots);
997
+ function deleteDoomed(childrenPath, nodes) {
998
+ let idx = nodes.length;
999
+ while (idx > 0) {
1000
+ idx--;
1001
+ if (!newIds.has(nodes[idx].id)) {
1002
+ let delCnt = 1;
1003
+ while (idx > 0 && !newIds.has(nodes[idx - 1].id)) {
1004
+ idx--;
1005
+ delCnt++;
1006
+ }
1007
+ ops.push({
1008
+ op: "arr_splice",
1009
+ path: childrenPath.slice(),
1010
+ at: idx,
1011
+ del: delCnt,
1012
+ items: []
1013
+ });
1014
+ nodes.splice(idx, delCnt);
1015
+ } else deleteDoomed([
1016
+ ...childrenPath,
1017
+ idx,
1018
+ "children"
1019
+ ], nodes[idx].children);
1020
+ }
1021
+ }
1022
+ deleteDoomed(treePath.slice(), curRoots);
1023
+ function reorderAndDiffMeta(childrenPath, curNodes, targetNodes) {
1024
+ if (targetNodes.length > 1) {
1025
+ const curIdxMap = /* @__PURE__ */ new Map();
1026
+ for (let i = 0; i < curNodes.length; i++) curIdxMap.set(curNodes[i].id, i);
1027
+ const targetSeq = targetNodes.map((tn) => curIdxMap.get(tn.id));
1028
+ const pairs = require_diff.lisMovePairs(targetSeq);
1029
+ if (pairs.length > 0) {
1030
+ for (let m = 0; m < pairs.length; m++) {
1031
+ const [fromIdx, toIdx] = pairs[m];
1032
+ ops.push({
1033
+ op: "move",
1034
+ from: [...childrenPath, fromIdx],
1035
+ to: [...childrenPath, toIdx]
1036
+ });
1037
+ }
1038
+ const reordered = new Array(targetSeq.length);
1039
+ for (let i = 0; i < targetSeq.length; i++) reordered[i] = curNodes[targetSeq[i]];
1040
+ for (let i = 0; i < reordered.length; i++) curNodes[i] = reordered[i];
1041
+ }
1042
+ }
1043
+ for (let i = 0; i < targetNodes.length; i++) {
1044
+ const cn = curNodes[i];
1045
+ const tn = targetNodes[i];
1046
+ if (!placedWhole.has(tn.id)) {
1047
+ const nodePath = [...childrenPath, i];
1048
+ if (oldIds.has(tn.id)) {
1049
+ const metaFrom = treeFrom.getNodeByID(tn.id).data;
1050
+ const metaTo = treeTo.getNodeByID(tn.id).data;
1051
+ const metaId = metaTo.id;
1052
+ if (changedCids.has(metaId) || dirtyAncestors.has(metaId)) diffMapContainer(docFrom, docTo, metaFrom, metaTo, [...nodePath, "meta"], changedCids, dirtyAncestors, diffMap, ops);
1053
+ }
1054
+ reorderAndDiffMeta([...nodePath, "children"], cn.children, tn.children);
1055
+ }
1056
+ }
1057
+ }
1058
+ reorderAndDiffMeta(treePath.slice(), curRoots, toRoots);
1059
+ }
1060
+ function normZeroF64(v) {
1061
+ return v === 0 ? 0 : v;
1062
+ }
1063
+ function computeCounterSteps(cur, targetV) {
1064
+ const rawD1 = targetV - cur;
1065
+ const d1 = normZeroF64(Number.isFinite(rawD1) ? rawD1 : -cur);
1066
+ const mid = cur + d1;
1067
+ const d2 = normZeroF64(targetV - mid);
1068
+ if (Number.isFinite(d1) && Number.isFinite(d2) && mid + d2 === targetV) return {
1069
+ d1,
1070
+ d2
1071
+ };
1072
+ }
1073
+ function validateCounterTarget(value, cur, opIndex) {
1074
+ let rawTarget;
1075
+ if (typeof value === "number") rawTarget = value;
1076
+ else if (typeof value === "bigint") {
1077
+ if (value < require_diff.MIN_SAFE_BIG || value > require_diff.MAX_SAFE_BIG) throw new LoroApplyError("Value", `integer ${value} out of safe range for lossless Loro counter`, opIndex);
1078
+ rawTarget = Number(value);
1079
+ } else throw new LoroApplyError("SchemaViolation", "LoroCounter requires numeric value", opIndex);
1080
+ if (!Number.isFinite(rawTarget)) throw new LoroApplyError("Value", "non-finite float is forbidden", opIndex);
1081
+ const target = normZeroF64(rawTarget);
1082
+ const steps = computeCounterSteps(cur, target);
1083
+ if (!steps) throw new LoroApplyError("Value", "non-finite counter delta", opIndex);
1084
+ return {
1085
+ target,
1086
+ d1: steps.d1,
1087
+ d2: steps.d2
1088
+ };
1089
+ }
1090
+ function checkSafeSpliceBounds(at, del, len, opIndex) {
1091
+ if (!Number.isSafeInteger(at) || at < 0 || !Number.isSafeInteger(del) || del < 0) throw new require_diff.ApplyError("IndexOutOfBounds", opIndex, "invalid splice bounds");
1092
+ const end = at + del;
1093
+ if (!Number.isSafeInteger(end) || at > len || end > len) throw new require_diff.ApplyError("IndexOutOfBounds", opIndex, `arr_splice range ${at}..${end} out of bounds for length ${len}`);
1094
+ return end;
1095
+ }
1096
+ function spliceInPlace(arr, at, del, items) {
1097
+ if (items.length < 32768) {
1098
+ arr.splice(at, del, ...items);
1099
+ return;
1100
+ }
1101
+ const tail = arr.slice(at + del);
1102
+ arr.length = at;
1103
+ for (let i = 0; i < items.length; i++) arr.push(items[i]);
1104
+ for (let i = 0; i < tail.length; i++) arr.push(tail[i]);
1105
+ }
1106
+ function stepThroughTree(treeRoots, rest, opIndex) {
1107
+ let curList = treeRoots;
1108
+ let i = 0;
1109
+ while (true) {
1110
+ if (i >= rest.length) throw new LoroApplyError("SchemaViolation", "cannot address LoroTree children directly in this operation", opIndex);
1111
+ const nodeIdx = rest[i];
1112
+ if (typeof nodeIdx !== "number" || !Number.isSafeInteger(nodeIdx) || nodeIdx < 0) throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Array index");
1113
+ if (nodeIdx >= curList.length) throw new require_diff.ApplyError("IndexOutOfBounds", opIndex, `index ${nodeIdx} out of bounds for length ${curList.length}`);
1114
+ const node = curList[nodeIdx];
1115
+ i++;
1116
+ if (i >= rest.length) throw new LoroApplyError("SchemaViolation", "cannot address LoroTree node directly in this operation", opIndex);
1117
+ const field = rest[i];
1118
+ if (typeof field !== "string") throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Object key");
1119
+ if (field === "children") {
1120
+ i++;
1121
+ curList = node.children;
1122
+ } else if (field === "meta") {
1123
+ i++;
1124
+ return {
1125
+ metaNode: node.meta,
1126
+ consumed: i
1127
+ };
1128
+ } else if (field === "id") throw new LoroApplyError("SchemaViolation", "cannot modify or traverse LoroTree node 'id'", opIndex);
1129
+ else throw new LoroApplyError("SchemaViolation", `unknown field '${field}' on LoroTree node`, opIndex);
1130
+ }
1131
+ }
1132
+ var SimDoc = class {
1133
+ doc;
1134
+ shallowRoots;
1135
+ roots = /* @__PURE__ */ new Map();
1136
+ constructor(doc, schema) {
1137
+ this.doc = doc;
1138
+ this.shallowRoots = doc.getShallowValue();
1139
+ for (const [name, ctype] of schema.roots.entries()) this.roots.set(name, {
1140
+ kind: "Lazy",
1141
+ cid: rootContainerId(name, ctype),
1142
+ ctype
1143
+ });
1144
+ }
1145
+ materialize(node) {
1146
+ if (node.kind !== "Lazy") return node;
1147
+ return this.loadContainer(node.cid, node.ctype);
1148
+ }
1149
+ emptySim(ctype) {
1150
+ switch (ctype) {
1151
+ case "Map": return {
1152
+ kind: "Map",
1153
+ entries: /* @__PURE__ */ new Map()
1154
+ };
1155
+ case "List": return {
1156
+ kind: "List",
1157
+ items: [],
1158
+ isMovable: false
1159
+ };
1160
+ case "MovableList": return {
1161
+ kind: "List",
1162
+ items: [],
1163
+ isMovable: true
1164
+ };
1165
+ case "Text": return {
1166
+ kind: "Text",
1167
+ text: ""
1168
+ };
1169
+ case "Tree": return {
1170
+ kind: "Tree",
1171
+ roots: []
1172
+ };
1173
+ case "Counter": return {
1174
+ kind: "Counter",
1175
+ value: 0
1176
+ };
1177
+ }
1178
+ }
1179
+ loadContainer(cid, ctype) {
1180
+ if (!docHasExistingContainer(this.doc, cid, this.shallowRoots)) return this.emptySim(ctype);
1181
+ const c = this.doc.getContainerById(cid);
1182
+ if (!c) return this.emptySim(ctype);
1183
+ if (c instanceof loro_crdt.LoroMap) return {
1184
+ kind: "Map",
1185
+ entries: this.loadMap(c)
1186
+ };
1187
+ if (c instanceof loro_crdt.LoroList) return {
1188
+ kind: "List",
1189
+ items: c.toArray().map((item) => this.vocToSim(item)),
1190
+ isMovable: false
1191
+ };
1192
+ if (c instanceof loro_crdt.LoroMovableList) return {
1193
+ kind: "List",
1194
+ items: c.toArray().map((item) => this.vocToSim(item)),
1195
+ isMovable: true
1196
+ };
1197
+ if (c instanceof loro_crdt.LoroText) return {
1198
+ kind: "Text",
1199
+ text: c.toString()
1200
+ };
1201
+ if (c instanceof loro_crdt.LoroTree) {
1202
+ const wrapNodes = (nodes) => nodes.map((n) => ({
1203
+ id: n.id,
1204
+ meta: {
1205
+ kind: "Map",
1206
+ entries: this.loadMap(n.data)
1207
+ },
1208
+ children: wrapNodes(n.children() ?? [])
1209
+ }));
1210
+ return {
1211
+ kind: "Tree",
1212
+ roots: wrapNodes(c.roots())
1213
+ };
1214
+ }
1215
+ if (c instanceof loro_crdt.LoroCounter) {
1216
+ const v = c.value;
1217
+ if (!Number.isFinite(v)) throw new LoroApplyError("Value", "non-finite counter value");
1218
+ return {
1219
+ kind: "Counter",
1220
+ value: Object.is(v, -0) ? 0 : v
1221
+ };
1222
+ }
1223
+ return this.emptySim(ctype);
1224
+ }
1225
+ loadMap(map) {
1226
+ const out = /* @__PURE__ */ new Map();
1227
+ const entries = map.entries();
1228
+ for (let i = 0; i < entries.length; i++) out.set(entries[i][0], this.vocToSim(entries[i][1]));
1229
+ return out;
1230
+ }
1231
+ vocToSim(voc) {
1232
+ if (isLoroContainer(voc)) return {
1233
+ kind: "Lazy",
1234
+ cid: voc.id,
1235
+ ctype: voc.kind()
1236
+ };
1237
+ return {
1238
+ kind: "Atomic",
1239
+ value: projectLoroValue(voc)
1240
+ };
1241
+ }
1242
+ simToJson(node) {
1243
+ const mat = this.materialize(node);
1244
+ switch (mat.kind) {
1245
+ case "Map": {
1246
+ const out = {};
1247
+ const keys = Array.from(mat.entries.keys()).sort();
1248
+ for (let i = 0; i < keys.length; i++) {
1249
+ const k = keys[i];
1250
+ require_diff.setOwnProp(out, k, this.simToJson(mat.entries.get(k)));
1251
+ }
1252
+ return out;
1253
+ }
1254
+ case "List": return mat.items.map((item) => this.simToJson(item));
1255
+ case "Text": return mat.text;
1256
+ case "Tree": return mat.roots.map((n) => this.simTreeToJson(n));
1257
+ case "Counter": return mat.value;
1258
+ case "Atomic": return mat.value;
1259
+ }
1260
+ }
1261
+ simTreeToJson(node) {
1262
+ const meta = this.simToJson(node.meta);
1263
+ return {
1264
+ children: node.children.map((c) => this.simTreeToJson(c)),
1265
+ id: node.id ?? "",
1266
+ meta
1267
+ };
1268
+ }
1269
+ buildSimForNewValue(val, path, schema, opIndex) {
1270
+ const normVal = require_diff.validateAndNormalizeJsonValue(val, opIndex);
1271
+ const kind = schema.kindForNewValue(path, normVal);
1272
+ if (kind.kind === "Value") {
1273
+ jsonToLoroValue(normVal);
1274
+ return {
1275
+ kind: "Atomic",
1276
+ value: normVal
1277
+ };
1278
+ }
1279
+ switch (kind.containerType) {
1280
+ case "Map": {
1281
+ if (!require_diff.isPlainObject(normVal)) throw new LoroApplyError("SchemaViolation", "schema expects LoroMap (Object)", opIndex);
1282
+ const entries = /* @__PURE__ */ new Map();
1283
+ const keys = Object.keys(normVal);
1284
+ for (let i = 0; i < keys.length; i++) {
1285
+ const k = keys[i];
1286
+ entries.set(k, this.buildSimForNewValue(normVal[k], [...path, k], schema, opIndex));
1287
+ }
1288
+ return {
1289
+ kind: "Map",
1290
+ entries
1291
+ };
1292
+ }
1293
+ case "List":
1294
+ case "MovableList": {
1295
+ if (!Array.isArray(normVal)) throw new LoroApplyError("SchemaViolation", "schema expects LoroList/MovableList (Array)", opIndex);
1296
+ const items = new Array(normVal.length);
1297
+ for (let i = 0; i < normVal.length; i++) items[i] = this.buildSimForNewValue(normVal[i], [...path, i], schema, opIndex);
1298
+ return {
1299
+ kind: "List",
1300
+ items,
1301
+ isMovable: kind.containerType === "MovableList"
1302
+ };
1303
+ }
1304
+ case "Text":
1305
+ if (typeof normVal !== "string") throw new LoroApplyError("SchemaViolation", "schema expects LoroText (String)", opIndex);
1306
+ return {
1307
+ kind: "Text",
1308
+ text: normVal
1309
+ };
1310
+ case "Tree": {
1311
+ if (!Array.isArray(normVal)) throw new LoroApplyError("SchemaViolation", "schema expects LoroTree (Array)", opIndex);
1312
+ const roots = new Array(normVal.length);
1313
+ for (let i = 0; i < normVal.length; i++) roots[i] = this.buildSimTreeNode(normVal[i], [...path, i], schema, opIndex);
1314
+ return {
1315
+ kind: "Tree",
1316
+ roots
1317
+ };
1318
+ }
1319
+ case "Counter": {
1320
+ const { target } = validateCounterTarget(normVal, 0, opIndex);
1321
+ return {
1322
+ kind: "Counter",
1323
+ value: target
1324
+ };
1325
+ }
1326
+ }
1327
+ }
1328
+ buildSimTreeNode(val, nodePath, schema, opIndex) {
1329
+ if (!require_diff.isPlainObject(val)) throw new LoroApplyError("SchemaViolation", "LoroTree node must be an Object", opIndex);
1330
+ const keys = Object.keys(val);
1331
+ for (let i = 0; i < keys.length; i++) {
1332
+ const k = keys[i];
1333
+ if (k !== "id" && k !== "meta" && k !== "children") throw new LoroApplyError("SchemaViolation", `unknown top-level field '${k}' on LoroTree node`, opIndex);
1334
+ }
1335
+ let id;
1336
+ if (require_diff.hasOwn(val, "id")) {
1337
+ if (typeof val.id !== "string") throw new LoroApplyError("SchemaViolation", "LoroTree node 'id' must be a String", opIndex);
1338
+ id = val.id;
1339
+ }
1340
+ if (!require_diff.hasOwn(val, "meta")) throw new LoroApplyError("SchemaViolation", "LoroTree node requires 'meta' Object", opIndex);
1341
+ const metaVal = val.meta;
1342
+ if (!require_diff.isPlainObject(metaVal)) throw new LoroApplyError("SchemaViolation", "LoroTree node 'meta' must be an Object", opIndex);
1343
+ const metaEntries = /* @__PURE__ */ new Map();
1344
+ const mk = Object.keys(metaVal);
1345
+ for (let i = 0; i < mk.length; i++) {
1346
+ const k = mk[i];
1347
+ metaEntries.set(k, this.buildSimForNewValue(metaVal[k], [
1348
+ ...nodePath,
1349
+ "meta",
1350
+ k
1351
+ ], schema, opIndex));
1352
+ }
1353
+ if (!require_diff.hasOwn(val, "children")) throw new LoroApplyError("SchemaViolation", "LoroTree node requires 'children' Array", opIndex);
1354
+ const childrenVal = val.children;
1355
+ if (!Array.isArray(childrenVal)) throw new LoroApplyError("SchemaViolation", "LoroTree node 'children' must be an Array", opIndex);
1356
+ const children = new Array(childrenVal.length);
1357
+ for (let i = 0; i < childrenVal.length; i++) children[i] = this.buildSimTreeNode(childrenVal[i], [
1358
+ ...nodePath,
1359
+ "children",
1360
+ i
1361
+ ], schema, opIndex);
1362
+ return {
1363
+ id,
1364
+ meta: {
1365
+ kind: "Map",
1366
+ entries: metaEntries
1367
+ },
1368
+ children
1369
+ };
1370
+ }
1371
+ resolveRoot(rootName, opIndex) {
1372
+ const raw = this.roots.get(rootName);
1373
+ if (!raw) throw new LoroApplyError("SchemaViolation", `unknown root container '${rootName}'`, opIndex);
1374
+ const mat = this.materialize(raw);
1375
+ if (mat !== raw) this.roots.set(rootName, mat);
1376
+ return mat;
1377
+ }
1378
+ resolveNode(path, opIndex) {
1379
+ if (path.length === 0) throw new LoroApplyError("SchemaViolation", "root path [] is protected", opIndex);
1380
+ const first = path[0];
1381
+ if (typeof first !== "string") throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Object key at root");
1382
+ let cur = this.resolveRoot(first, opIndex);
1383
+ let i = 1;
1384
+ while (i < path.length) if (cur.kind === "Map") {
1385
+ const seg = path[i];
1386
+ if (typeof seg !== "string") throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Object key");
1387
+ const child = cur.entries.get(seg);
1388
+ if (!child) throw new require_diff.ApplyError("MissingPath", opIndex, `missing object key "${seg}"`);
1389
+ const mat = this.materialize(child);
1390
+ if (mat !== child) cur.entries.set(seg, mat);
1391
+ cur = mat;
1392
+ i++;
1393
+ } else if (cur.kind === "List") {
1394
+ const seg = path[i];
1395
+ if (typeof seg !== "number" || !Number.isSafeInteger(seg) || seg < 0) throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected non-negative Array index");
1396
+ if (seg >= cur.items.length) throw new require_diff.ApplyError("IndexOutOfBounds", opIndex, `index ${seg} out of bounds for length ${cur.items.length}`);
1397
+ const child = cur.items[seg];
1398
+ const mat = this.materialize(child);
1399
+ if (mat !== child) cur.items[seg] = mat;
1400
+ cur = mat;
1401
+ i++;
1402
+ } else if (cur.kind === "Tree") {
1403
+ const { metaNode, consumed } = stepThroughTree(cur.roots, path.slice(i), opIndex);
1404
+ cur = metaNode;
1405
+ i += consumed;
1406
+ } else throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Object or Array container");
1407
+ return cur;
1408
+ }
1409
+ /**
1410
+ * Returns `{ treeLen, treePath }` only when `path` targets a structural element of a
1411
+ * `SimNode::Tree` (roots, node, children, id, unknown field, or whole `meta` with empty subpath).
1412
+ * If `path` continues past `"meta"`, it steps into `node.meta` and keeps scanning for nested trees.
1413
+ */
1414
+ findStructuralTreePrefix(path, opIndex, forArrSplice = false) {
1415
+ if (path.length === 0 || typeof path[0] !== "string") return void 0;
1416
+ const rootName = path[0];
1417
+ if (!this.roots.has(rootName)) throw new LoroApplyError("SchemaViolation", `unknown root container '${rootName}'`, opIndex);
1418
+ let cur = this.resolveRoot(rootName, opIndex);
1419
+ let i = 1;
1420
+ while (true) {
1421
+ if (cur.kind === "Tree") {
1422
+ const treePath = path.slice(0, i);
1423
+ const rest = path.slice(i);
1424
+ if (rest.length === 0) {
1425
+ if (!forArrSplice && i > 1) return;
1426
+ return {
1427
+ treeLen: i,
1428
+ treePath
1429
+ };
1430
+ }
1431
+ let curList = cur.roots;
1432
+ let j = 0;
1433
+ let steppedMeta;
1434
+ while (true) {
1435
+ if (j >= rest.length) return {
1436
+ treeLen: i,
1437
+ treePath
1438
+ };
1439
+ const nodeIdx = rest[j];
1440
+ if (typeof nodeIdx !== "number" || !Number.isSafeInteger(nodeIdx) || nodeIdx < 0) return {
1441
+ treeLen: i,
1442
+ treePath
1443
+ };
1444
+ if (nodeIdx >= curList.length) return {
1445
+ treeLen: i,
1446
+ treePath
1447
+ };
1448
+ const node = curList[nodeIdx];
1449
+ j++;
1450
+ if (j >= rest.length) return {
1451
+ treeLen: i,
1452
+ treePath
1453
+ };
1454
+ const field = rest[j];
1455
+ if (typeof field !== "string") return {
1456
+ treeLen: i,
1457
+ treePath
1458
+ };
1459
+ if (field === "children") {
1460
+ j++;
1461
+ curList = node.children;
1462
+ } else if (field === "meta") {
1463
+ j++;
1464
+ if (j === rest.length) return {
1465
+ treeLen: i,
1466
+ treePath
1467
+ };
1468
+ steppedMeta = {
1469
+ metaNode: node.meta,
1470
+ consumed: j
1471
+ };
1472
+ break;
1473
+ } else return {
1474
+ treeLen: i,
1475
+ treePath
1476
+ };
1477
+ }
1478
+ cur = steppedMeta.metaNode;
1479
+ i += steppedMeta.consumed;
1480
+ continue;
1481
+ }
1482
+ if (i >= path.length) return;
1483
+ const seg = path[i];
1484
+ if (cur.kind === "Map") {
1485
+ if (typeof seg !== "string") return void 0;
1486
+ const child = cur.entries.get(seg);
1487
+ if (!child) return void 0;
1488
+ const mat = this.materialize(child);
1489
+ if (mat !== child) cur.entries.set(seg, mat);
1490
+ cur = mat;
1491
+ i++;
1492
+ } else if (cur.kind === "List") {
1493
+ if (typeof seg !== "number" || !Number.isSafeInteger(seg) || seg < 0) return void 0;
1494
+ if (seg >= cur.items.length) return void 0;
1495
+ const child = cur.items[seg];
1496
+ const mat = this.materialize(child);
1497
+ if (mat !== child) cur.items[seg] = mat;
1498
+ cur = mat;
1499
+ i++;
1500
+ } else return;
1501
+ }
1502
+ }
1503
+ /**
1504
+ * Returns slot index `slotIdx` where `path[..slotIdx]` is the enclosing container
1505
+ * and `path[slotIdx]` holds an `Atomic` value (including through `LoroTree` node `meta` maps).
1506
+ */
1507
+ findAtomicPrefix(path) {
1508
+ if (path.length < 2 || typeof path[0] !== "string") return void 0;
1509
+ if (!this.roots.has(path[0])) return void 0;
1510
+ let cur = this.resolveRoot(path[0], 0);
1511
+ let i = 1;
1512
+ while (i + 1 < path.length) if (cur.kind === "Map") {
1513
+ const seg = path[i];
1514
+ if (typeof seg !== "string") return void 0;
1515
+ const child = cur.entries.get(seg);
1516
+ if (!child) return void 0;
1517
+ const mat = this.materialize(child);
1518
+ if (mat !== child) cur.entries.set(seg, mat);
1519
+ cur = mat;
1520
+ if (cur.kind === "Atomic") return i;
1521
+ i++;
1522
+ } else if (cur.kind === "List") {
1523
+ const seg = path[i];
1524
+ if (typeof seg !== "number" || !Number.isSafeInteger(seg) || seg < 0) return void 0;
1525
+ if (seg >= cur.items.length) return void 0;
1526
+ const child = cur.items[seg];
1527
+ const mat = this.materialize(child);
1528
+ if (mat !== child) cur.items[seg] = mat;
1529
+ cur = mat;
1530
+ if (cur.kind === "Atomic") return i;
1531
+ i++;
1532
+ } else if (cur.kind === "Tree") {
1533
+ let curList = cur.roots;
1534
+ let j = i;
1535
+ let stepped;
1536
+ while (true) {
1537
+ if (j >= path.length) return void 0;
1538
+ const nodeIdx = path[j];
1539
+ if (typeof nodeIdx !== "number" || !Number.isSafeInteger(nodeIdx) || nodeIdx < 0) return;
1540
+ if (nodeIdx >= curList.length) return void 0;
1541
+ const node = curList[nodeIdx];
1542
+ j++;
1543
+ if (j >= path.length) return void 0;
1544
+ const field = path[j];
1545
+ if (typeof field !== "string") return void 0;
1546
+ if (field === "children") {
1547
+ j++;
1548
+ curList = node.children;
1549
+ } else if (field === "meta") {
1550
+ j++;
1551
+ stepped = node.meta;
1552
+ break;
1553
+ } else return;
1554
+ }
1555
+ cur = stepped;
1556
+ i = j;
1557
+ } else return;
1558
+ }
1559
+ };
1560
+ function resolveTreeTarget(treeRoots, rest, opIndex) {
1561
+ if (rest.length === 0) return {
1562
+ type: "Children",
1563
+ parentIndices: [],
1564
+ children: treeRoots
1565
+ };
1566
+ let curList = treeRoots;
1567
+ const indices = [];
1568
+ let i = 0;
1569
+ while (true) {
1570
+ if (i >= rest.length) return {
1571
+ type: "Children",
1572
+ parentIndices: indices,
1573
+ children: curList
1574
+ };
1575
+ const nodeIdx = rest[i];
1576
+ if (typeof nodeIdx !== "number" || !Number.isSafeInteger(nodeIdx) || nodeIdx < 0) throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Array index in tree path");
1577
+ if (nodeIdx >= curList.length) throw new require_diff.ApplyError("IndexOutOfBounds", opIndex, `tree index ${nodeIdx} out of bounds for length ${curList.length}`);
1578
+ indices.push(nodeIdx);
1579
+ const node = curList[nodeIdx];
1580
+ i++;
1581
+ if (i === rest.length) return {
1582
+ type: "Node",
1583
+ nodeIndices: indices
1584
+ };
1585
+ const field = rest[i];
1586
+ if (typeof field !== "string") throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Object key on tree node");
1587
+ if (field === "children") {
1588
+ i++;
1589
+ if (i === rest.length) return {
1590
+ type: "Children",
1591
+ parentIndices: indices,
1592
+ children: node.children
1593
+ };
1594
+ curList = node.children;
1595
+ } else if (field === "meta") {
1596
+ i++;
1597
+ return {
1598
+ type: "Meta",
1599
+ nodeIndices: indices,
1600
+ node,
1601
+ subPath: rest.slice(i)
1602
+ };
1603
+ } else if (field === "id") throw new LoroApplyError("SchemaViolation", "cannot modify or traverse LoroTree node 'id'", opIndex);
1604
+ else throw new LoroApplyError("SchemaViolation", `unknown field '${field}' on LoroTree node`, opIndex);
1605
+ }
1606
+ }
1607
+ function treeMetaPath(treePath, nodeIndices) {
1608
+ const out = treePath.slice();
1609
+ for (let i = 0; i < nodeIndices.length; i++) {
1610
+ if (i > 0) out.push("children");
1611
+ out.push(nodeIndices[i]);
1612
+ }
1613
+ out.push("meta");
1614
+ return out;
1615
+ }
1616
+ function takeSimTreeNode(roots, indices) {
1617
+ if (indices.length === 1) return roots.splice(indices[0], 1)[0];
1618
+ let cur = roots[indices[0]];
1619
+ for (let i = 1; i < indices.length - 1; i++) cur = cur.children[indices[i]];
1620
+ return cur.children.splice(indices[indices.length - 1], 1)[0];
1621
+ }
1622
+ function insertSimTreeNode(roots, indices, node) {
1623
+ if (indices.length === 1) {
1624
+ roots.splice(indices[0], 0, node);
1625
+ return;
1626
+ }
1627
+ let cur = roots[indices[0]];
1628
+ for (let i = 1; i < indices.length - 1; i++) cur = cur.children[indices[i]];
1629
+ cur.children.splice(indices[indices.length - 1], 0, node);
1630
+ }
1631
+ function readAtSubPath(root, subPath, opIndex) {
1632
+ let cur = root;
1633
+ for (let i = 0; i < subPath.length; i++) {
1634
+ const seg = subPath[i];
1635
+ if (typeof seg === "string") {
1636
+ if (!require_diff.isPlainObject(cur)) throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Object");
1637
+ if (!require_diff.hasOwn(cur, seg)) throw new require_diff.ApplyError("MissingPath", opIndex, `missing object key "${seg}"`);
1638
+ cur = cur[seg];
1639
+ } else {
1640
+ if (!Array.isArray(cur)) throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Array");
1641
+ if (!Number.isSafeInteger(seg) || seg < 0 || seg >= cur.length) throw new require_diff.ApplyError("IndexOutOfBounds", opIndex, `index ${seg} out of bounds for length ${cur.length}`);
1642
+ cur = cur[seg];
1643
+ }
1644
+ }
1645
+ return cur;
1646
+ }
1647
+ function takeFromAtomicValue(atomicVal, subPath, opIndex) {
1648
+ if (subPath.length === 0) throw new require_diff.ApplyError("InvalidPath", opIndex, "expected non-empty subpath inside atomic value");
1649
+ const extracted = readAtSubPath(atomicVal, subPath, opIndex);
1650
+ const last = subPath[subPath.length - 1];
1651
+ return {
1652
+ extracted,
1653
+ updated: require_diff.apply(atomicVal, [typeof last === "string" ? {
1654
+ op: "unset",
1655
+ path: subPath
1656
+ } : {
1657
+ op: "arr_splice",
1658
+ path: subPath.slice(0, -1),
1659
+ at: last,
1660
+ del: 1,
1661
+ items: []
1662
+ }])
1663
+ };
1664
+ }
1665
+ function assertValidPathSegments(path, opIndex) {
1666
+ for (let i = 0; i < path.length; i++) {
1667
+ const s = path[i];
1668
+ if (typeof s === "string") {
1669
+ require_diff.assertNoLoneSurrogates(s, opIndex);
1670
+ continue;
1671
+ }
1672
+ if (typeof s === "number" && Number.isSafeInteger(s) && s >= 0) continue;
1673
+ throw new require_diff.ApplyError("InvalidPath", opIndex, `invalid path segment: ${String(s)}`);
1674
+ }
1675
+ }
1676
+ function planPatch(doc, patch, options) {
1677
+ const mode = options.mode ?? "strict";
1678
+ const schema = options.schema;
1679
+ const sim = new SimDoc(doc, schema);
1680
+ const planned = [];
1681
+ for (let opIndex = 0; opIndex < patch.length; opIndex++) {
1682
+ const op = patch[opIndex];
1683
+ try {
1684
+ planSingleOp(sim, op, opIndex, schema, mode, planned);
1685
+ } catch (err) {
1686
+ if (err instanceof LoroApplyError) {
1687
+ if (err.opIndex === void 0) throw new LoroApplyError(err.kind, err.message, opIndex);
1688
+ throw err;
1689
+ }
1690
+ if (err instanceof require_diff.ApplyError) throw new LoroApplyError("Patch", err.message, opIndex);
1691
+ throw new LoroApplyError("Loro", String(err), opIndex);
1692
+ }
1693
+ }
1694
+ return planned;
1695
+ }
1696
+ function planSingleOp(sim, op, opIndex, schema, mode, planned) {
1697
+ switch (op.op) {
1698
+ case "set": {
1699
+ assertValidPathSegments(op.path, opIndex);
1700
+ const val = require_diff.validateAndNormalizeJsonValue(op.value, opIndex);
1701
+ if (op.path.length === 0) throw new LoroApplyError("SchemaViolation", "cannot replace entire document root (path = [])", opIndex);
1702
+ if (op.path.length === 1) {
1703
+ const rootName = op.path[0];
1704
+ if (typeof rootName !== "string") throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Object key at root");
1705
+ const ctype = schema.roots.get(rootName);
1706
+ if (!ctype) throw new LoroApplyError("SchemaViolation", `unknown root container '${rootName}'`, opIndex);
1707
+ if (ctype === "Counter") {
1708
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot directly set LoroCounter in strict mode", opIndex);
1709
+ const node = sim.resolveNode(op.path, opIndex);
1710
+ if (node.kind !== "Counter") throw new LoroApplyError("Loro", "expected counter node", opIndex);
1711
+ const { target, d1, d2 } = validateCounterTarget(val, node.value, opIndex);
1712
+ if (node.value !== target) {
1713
+ node.value = target;
1714
+ planned.push({
1715
+ type: "CounterSet",
1716
+ counterPath: op.path,
1717
+ d1,
1718
+ d2,
1719
+ target
1720
+ });
1721
+ }
1722
+ return;
1723
+ }
1724
+ const rootSchema = new LoroSchema({
1725
+ roots: schema.roots,
1726
+ rules: [{
1727
+ pattern: [rootName],
1728
+ kind: containerKind(ctype)
1729
+ }, ...schema.rules],
1730
+ defaultObject: schema.defaultObject,
1731
+ defaultArray: schema.defaultArray,
1732
+ defaultString: schema.defaultString
1733
+ });
1734
+ const newSim = sim.buildSimForNewValue(val, op.path, rootSchema, opIndex);
1735
+ sim.roots.set(rootName, newSim);
1736
+ planned.push({
1737
+ type: "ReplaceRoot",
1738
+ root: rootName,
1739
+ value: val
1740
+ });
1741
+ return;
1742
+ }
1743
+ const treePrefix = sim.findStructuralTreePrefix(op.path, opIndex);
1744
+ if (treePrefix) {
1745
+ const { treeLen, treePath } = treePrefix;
1746
+ const rest = op.path.slice(treeLen);
1747
+ const treeNode = sim.resolveNode(treePath, opIndex);
1748
+ if (treeNode.kind !== "Tree") throw new LoroApplyError("Loro", "expected tree", opIndex);
1749
+ const target = resolveTreeTarget(treeNode.roots, rest, opIndex);
1750
+ if (target.type === "Children") throw new LoroApplyError("SchemaViolation", "use arr_splice or move on LoroTree children, not set", opIndex);
1751
+ if (target.type === "Node") throw new LoroApplyError("SchemaViolation", "cannot overwrite LoroTree node directly with set", opIndex);
1752
+ if (target.subPath.length !== 0) throw new LoroApplyError("SchemaViolation", "unexpected non-empty meta subpath in structural tree target", opIndex);
1753
+ if (!require_diff.isPlainObject(val)) throw new LoroApplyError("SchemaViolation", "LoroTree node 'meta' must be an Object", opIndex);
1754
+ const newMetaEntries = /* @__PURE__ */ new Map();
1755
+ const keys = Object.keys(val);
1756
+ for (let i = 0; i < keys.length; i++) {
1757
+ const k = keys[i];
1758
+ newMetaEntries.set(k, sim.buildSimForNewValue(val[k], [...op.path, k], schema, opIndex));
1759
+ }
1760
+ target.node.meta = {
1761
+ kind: "Map",
1762
+ entries: newMetaEntries
1763
+ };
1764
+ planned.push({
1765
+ type: "TreeMetaReplace",
1766
+ treePath,
1767
+ nodeIndices: target.nodeIndices,
1768
+ value: val
1769
+ });
1770
+ return;
1771
+ }
1772
+ const atomicEnd = sim.findAtomicPrefix(op.path);
1773
+ if (atomicEnd !== void 0) {
1774
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot partially mutate inside atomic LoroValue in strict mode", opIndex);
1775
+ const containerPath = op.path.slice(0, atomicEnd);
1776
+ const seg = op.path[atomicEnd];
1777
+ const subPath = op.path.slice(atomicEnd + 1);
1778
+ const node = sim.resolveNode(op.path.slice(0, atomicEnd + 1), opIndex);
1779
+ if (node.kind !== "Atomic") throw new LoroApplyError("Loro", "expected atomic", opIndex);
1780
+ const trial = require_diff.apply(node.value, [{
1781
+ op: "set",
1782
+ path: subPath,
1783
+ value: val
1784
+ }]);
1785
+ jsonToLoroValue(trial);
1786
+ node.value = trial;
1787
+ planned.push({
1788
+ type: "WriteAtomic",
1789
+ containerPath,
1790
+ seg,
1791
+ value: trial
1792
+ });
1793
+ return;
1794
+ }
1795
+ const parentPath = op.path.slice(0, -1);
1796
+ const last = op.path[op.path.length - 1];
1797
+ const parent = sim.resolveNode(parentPath, opIndex);
1798
+ if (parent.kind === "Map") {
1799
+ if (typeof last !== "string") throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Object key");
1800
+ const existingRaw = parent.entries.get(last);
1801
+ if (existingRaw) {
1802
+ const existing = sim.materialize(existingRaw);
1803
+ if (existing !== existingRaw) parent.entries.set(last, existing);
1804
+ if (existing.kind === "Counter") {
1805
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot directly set LoroCounter in strict mode", opIndex);
1806
+ const { target, d1, d2 } = validateCounterTarget(val, existing.value, opIndex);
1807
+ if (existing.value !== target) {
1808
+ existing.value = target;
1809
+ planned.push({
1810
+ type: "CounterSet",
1811
+ counterPath: op.path,
1812
+ d1,
1813
+ d2,
1814
+ target
1815
+ });
1816
+ }
1817
+ return;
1818
+ }
1819
+ }
1820
+ parent.entries.set(last, sim.buildSimForNewValue(val, op.path, schema, opIndex));
1821
+ planned.push({
1822
+ type: "MapSet",
1823
+ mapPath: parentPath,
1824
+ key: last,
1825
+ value: val
1826
+ });
1827
+ } else if (parent.kind === "List") {
1828
+ if (typeof last !== "number" || !Number.isSafeInteger(last) || last < 0) throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Array index");
1829
+ if (last >= parent.items.length) throw new require_diff.ApplyError("IndexOutOfBounds", opIndex, `index ${last} out of bounds for length ${parent.items.length}`);
1830
+ const existingRaw = parent.items[last];
1831
+ const existing = sim.materialize(existingRaw);
1832
+ if (existing.kind === "Counter") {
1833
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot directly set LoroCounter in strict mode", opIndex);
1834
+ const { target, d1, d2 } = validateCounterTarget(val, existing.value, opIndex);
1835
+ if (existing.value !== target) {
1836
+ existing.value = target;
1837
+ planned.push({
1838
+ type: "CounterSet",
1839
+ counterPath: op.path,
1840
+ d1,
1841
+ d2,
1842
+ target
1843
+ });
1844
+ }
1845
+ return;
1846
+ }
1847
+ parent.items[last] = sim.buildSimForNewValue(val, op.path, schema, opIndex);
1848
+ planned.push({
1849
+ type: "ListSet",
1850
+ listPath: parentPath,
1851
+ index: last,
1852
+ value: val,
1853
+ isMovable: parent.isMovable
1854
+ });
1855
+ } else throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Object or Array");
1856
+ return;
1857
+ }
1858
+ case "unset": {
1859
+ assertValidPathSegments(op.path, opIndex);
1860
+ if (op.path.length === 0) throw new require_diff.ApplyError("InvalidPath", opIndex, "unset requires non-empty path");
1861
+ if (op.path.length === 1) throw new LoroApplyError("SchemaViolation", "cannot unset root container", opIndex);
1862
+ const last = op.path[op.path.length - 1];
1863
+ if (typeof last !== "string") throw new require_diff.ApplyError("TypeMismatch", opIndex, "unset last segment must be Object key");
1864
+ const treePrefix = sim.findStructuralTreePrefix(op.path, opIndex);
1865
+ if (treePrefix) {
1866
+ const { treeLen, treePath } = treePrefix;
1867
+ const rest = op.path.slice(treeLen);
1868
+ const treeNode = sim.resolveNode(treePath, opIndex);
1869
+ if (treeNode.kind === "Tree") resolveTreeTarget(treeNode.roots, rest, opIndex);
1870
+ throw new LoroApplyError("SchemaViolation", "cannot unset LoroTree node, structural field, or 'meta'", opIndex);
1871
+ }
1872
+ const atomicEnd = sim.findAtomicPrefix(op.path);
1873
+ if (atomicEnd !== void 0) {
1874
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot unset inside atomic LoroValue in strict mode", opIndex);
1875
+ const containerPath = op.path.slice(0, atomicEnd);
1876
+ const seg = op.path[atomicEnd];
1877
+ const subPath = op.path.slice(atomicEnd + 1);
1878
+ const node = sim.resolveNode(op.path.slice(0, atomicEnd + 1), opIndex);
1879
+ if (node.kind !== "Atomic") throw new LoroApplyError("Loro", "expected atomic", opIndex);
1880
+ const trial = require_diff.apply(node.value, [{
1881
+ op: "unset",
1882
+ path: subPath
1883
+ }]);
1884
+ jsonToLoroValue(trial);
1885
+ node.value = trial;
1886
+ planned.push({
1887
+ type: "WriteAtomic",
1888
+ containerPath,
1889
+ seg,
1890
+ value: trial
1891
+ });
1892
+ return;
1893
+ }
1894
+ const parentPath = op.path.slice(0, -1);
1895
+ const parent = sim.resolveNode(parentPath, opIndex);
1896
+ if (parent.kind !== "Map") throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Object");
1897
+ if (parent.entries.delete(last)) planned.push({
1898
+ type: "MapUnset",
1899
+ mapPath: parentPath,
1900
+ key: last
1901
+ });
1902
+ return;
1903
+ }
1904
+ case "arr_splice": {
1905
+ assertValidPathSegments(op.path, opIndex);
1906
+ const normItems = new Array(op.items.length);
1907
+ for (let i = 0; i < op.items.length; i++) normItems[i] = require_diff.validateAndNormalizeJsonValue(op.items[i], opIndex);
1908
+ if (op.path.length === 0) throw new LoroApplyError("SchemaViolation", "arr_splice cannot target document root []", opIndex);
1909
+ const treePrefix = sim.findStructuralTreePrefix(op.path, opIndex, true);
1910
+ if (treePrefix) {
1911
+ const { treeLen, treePath } = treePrefix;
1912
+ const rest = op.path.slice(treeLen);
1913
+ const treeNode = sim.resolveNode(treePath, opIndex);
1914
+ if (treeNode.kind !== "Tree") throw new LoroApplyError("Loro", "expected tree", opIndex);
1915
+ const target$1 = resolveTreeTarget(treeNode.roots, rest, opIndex);
1916
+ if (target$1.type === "Children") {
1917
+ checkSafeSpliceBounds(op.at, op.del, target$1.children.length, opIndex);
1918
+ const newNodes$1 = new Array(normItems.length);
1919
+ for (let i = 0; i < normItems.length; i++) newNodes$1[i] = sim.buildSimTreeNode(normItems[i], [...op.path, op.at + i], schema, opIndex);
1920
+ spliceInPlace(target$1.children, op.at, op.del, newNodes$1);
1921
+ if (op.del > 0 || normItems.length > 0) planned.push({
1922
+ type: "TreeSplice",
1923
+ treePath,
1924
+ parentIndices: target$1.parentIndices,
1925
+ at: op.at,
1926
+ del: op.del,
1927
+ items: normItems
1928
+ });
1929
+ return;
1930
+ }
1931
+ throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Array");
1932
+ }
1933
+ const atomicEnd = sim.findAtomicPrefix(op.path);
1934
+ if (atomicEnd !== void 0) {
1935
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot arr_splice atomic LoroValue::List in strict mode", opIndex);
1936
+ const containerPath = op.path.slice(0, atomicEnd);
1937
+ const seg = op.path[atomicEnd];
1938
+ const subPath = op.path.slice(atomicEnd + 1);
1939
+ const node = sim.resolveNode(op.path.slice(0, atomicEnd + 1), opIndex);
1940
+ if (node.kind !== "Atomic") throw new LoroApplyError("Loro", "expected atomic", opIndex);
1941
+ const trial = require_diff.apply(node.value, [{
1942
+ op: "arr_splice",
1943
+ path: subPath,
1944
+ at: op.at,
1945
+ del: op.del,
1946
+ items: normItems
1947
+ }]);
1948
+ jsonToLoroValue(trial);
1949
+ node.value = trial;
1950
+ planned.push({
1951
+ type: "WriteAtomic",
1952
+ containerPath,
1953
+ seg,
1954
+ value: trial
1955
+ });
1956
+ return;
1957
+ }
1958
+ const target = sim.resolveNode(op.path, opIndex);
1959
+ if (target.kind === "Atomic" && Array.isArray(target.value)) {
1960
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot arr_splice atomic LoroValue::List in strict mode; use LoroList or LoroMovableList", opIndex);
1961
+ const trial = require_diff.apply(target.value, [{
1962
+ op: "arr_splice",
1963
+ path: [],
1964
+ at: op.at,
1965
+ del: op.del,
1966
+ items: normItems
1967
+ }]);
1968
+ jsonToLoroValue(trial);
1969
+ target.value = trial;
1970
+ planned.push({
1971
+ type: "WriteAtomic",
1972
+ containerPath: op.path.slice(0, -1),
1973
+ seg: op.path[op.path.length - 1],
1974
+ value: trial
1975
+ });
1976
+ return;
1977
+ }
1978
+ if (target.kind !== "List") throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Array");
1979
+ checkSafeSpliceBounds(op.at, op.del, target.items.length, opIndex);
1980
+ const newNodes = new Array(normItems.length);
1981
+ for (let i = 0; i < normItems.length; i++) newNodes[i] = sim.buildSimForNewValue(normItems[i], [...op.path, op.at + i], schema, opIndex);
1982
+ spliceInPlace(target.items, op.at, op.del, newNodes);
1983
+ if (op.del > 0 || normItems.length > 0) planned.push({
1984
+ type: "ListSplice",
1985
+ listPath: op.path,
1986
+ at: op.at,
1987
+ del: op.del,
1988
+ items: normItems,
1989
+ isMovable: target.isMovable
1990
+ });
1991
+ return;
1992
+ }
1993
+ case "move": {
1994
+ assertValidPathSegments(op.from, opIndex);
1995
+ assertValidPathSegments(op.to, opIndex);
1996
+ if (op.from.length === 0 || op.to.length === 0) throw new require_diff.ApplyError("InvalidPath", opIndex, "move requires non-empty from and to paths");
1997
+ if (op.from.length === 1 || op.to.length === 1) throw new LoroApplyError("SchemaViolation", "cannot move root container", opIndex);
1998
+ const fromTree = sim.findStructuralTreePrefix(op.from, opIndex, false);
1999
+ if (require_diff.pathsEqual(op.from, op.to)) {
2000
+ if (fromTree) {
2001
+ const tn = sim.resolveNode(fromTree.treePath, opIndex);
2002
+ if (tn.kind !== "Tree") throw new LoroApplyError("Loro", "expected tree", opIndex);
2003
+ if (resolveTreeTarget(tn.roots, op.from.slice(fromTree.treeLen), opIndex).type !== "Node") throw new LoroApplyError("SchemaViolation", "LoroTree move 'from' must address a tree node", opIndex);
2004
+ return;
2005
+ }
2006
+ const atomicEnd = sim.findAtomicPrefix(op.from);
2007
+ if (atomicEnd !== void 0) {
2008
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot move inside atomic LoroValue in strict mode", opIndex);
2009
+ const subPath = op.from.slice(atomicEnd + 1);
2010
+ const node = sim.resolveNode(op.from.slice(0, atomicEnd + 1), opIndex);
2011
+ if (node.kind !== "Atomic") throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Object or Array");
2012
+ require_diff.apply(node.value, [{
2013
+ op: "move",
2014
+ from: subPath,
2015
+ to: subPath
2016
+ }]);
2017
+ return;
2018
+ }
2019
+ sim.resolveNode(op.from, opIndex);
2020
+ return;
2021
+ }
2022
+ if (fromTree) {
2023
+ const fRest = op.from.slice(fromTree.treeLen);
2024
+ const treeNode = sim.resolveNode(fromTree.treePath, opIndex);
2025
+ if (treeNode.kind !== "Tree") throw new LoroApplyError("Loro", "expected tree", opIndex);
2026
+ const fromTarget = resolveTreeTarget(treeNode.roots, fRest, opIndex);
2027
+ if (fromTarget.type !== "Node") throw new LoroApplyError("SchemaViolation", "LoroTree move 'from' must address a tree node", opIndex);
2028
+ const fromIndices = fromTarget.nodeIndices;
2029
+ const taken = takeSimTreeNode(treeNode.roots, fromIndices);
2030
+ let toTree;
2031
+ try {
2032
+ toTree = sim.findStructuralTreePrefix(op.to, opIndex, false);
2033
+ } catch (err) {
2034
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2035
+ throw err;
2036
+ }
2037
+ if (!toTree) {
2038
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2039
+ throw new LoroApplyError("SchemaViolation", "cannot move between LoroTree structure and non-tree container", opIndex);
2040
+ }
2041
+ if (!require_diff.pathsEqual(fromTree.treePath, toTree.treePath)) {
2042
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2043
+ throw new LoroApplyError("SchemaViolation", "cannot move tree node across different LoroTree containers", opIndex);
2044
+ }
2045
+ const tRest = op.to.slice(toTree.treeLen);
2046
+ const toLast = tRest[tRest.length - 1];
2047
+ if (typeof toLast !== "number" || !Number.isSafeInteger(toLast) || toLast < 0) {
2048
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2049
+ throw new LoroApplyError("SchemaViolation", "LoroTree move 'to' must end with child index", opIndex);
2050
+ }
2051
+ const tParentRest = tRest.slice(0, -1);
2052
+ let toTarget;
2053
+ try {
2054
+ toTarget = resolveTreeTarget(treeNode.roots, tParentRest, opIndex);
2055
+ } catch (err) {
2056
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2057
+ throw err;
2058
+ }
2059
+ if (toTarget.type !== "Children") {
2060
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2061
+ throw new LoroApplyError("SchemaViolation", "LoroTree move 'to' parent must be tree root or node children", opIndex);
2062
+ }
2063
+ if (toLast > toTarget.children.length) {
2064
+ const len = toTarget.children.length;
2065
+ insertSimTreeNode(treeNode.roots, fromIndices, taken);
2066
+ throw new require_diff.ApplyError("IndexOutOfBounds", opIndex, `index ${toLast} out of bounds for length ${len}`);
2067
+ }
2068
+ toTarget.children.splice(toLast, 0, taken);
2069
+ planned.push({
2070
+ type: "TreeMove",
2071
+ treePath: fromTree.treePath,
2072
+ fromIndices,
2073
+ newParentIndices: toTarget.parentIndices,
2074
+ toIndex: toLast
2075
+ });
2076
+ return;
2077
+ }
2078
+ const fAtomic = sim.findAtomicPrefix(op.from);
2079
+ const fLast = op.from[op.from.length - 1];
2080
+ const fParent = op.from.slice(0, -1);
2081
+ const tLast = op.to[op.to.length - 1];
2082
+ const tParent = op.to.slice(0, -1);
2083
+ if (fAtomic === void 0 && require_diff.pathsEqual(fParent, tParent) && typeof fLast === "number" && typeof tLast === "number") {
2084
+ const parentNode = sim.resolveNode(fParent, opIndex);
2085
+ if (parentNode.kind === "List") {
2086
+ if (!parentNode.isMovable && mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot move within plain LoroList in strict mode; use MovableList", opIndex);
2087
+ const len = parentNode.items.length;
2088
+ if (fLast >= len) throw new require_diff.ApplyError("IndexOutOfBounds", opIndex, `index ${fLast} out of bounds for length ${len}`);
2089
+ const [val] = parentNode.items.splice(fLast, 1);
2090
+ if (tLast > parentNode.items.length) {
2091
+ const midLen = parentNode.items.length;
2092
+ parentNode.items.splice(fLast, 0, val);
2093
+ throw new require_diff.ApplyError("IndexOutOfBounds", opIndex, `index ${tLast} out of bounds for length ${midLen}`);
2094
+ }
2095
+ if (parentNode.isMovable) {
2096
+ parentNode.items.splice(tLast, 0, val);
2097
+ planned.push({
2098
+ type: "MovableListMove",
2099
+ listPath: fParent,
2100
+ from: fLast,
2101
+ to: tLast
2102
+ });
2103
+ } else {
2104
+ const movedJson$1 = sim.simToJson(val);
2105
+ const newSim$1 = sim.buildSimForNewValue(movedJson$1, op.to, schema, opIndex);
2106
+ parentNode.items.splice(tLast, 0, newSim$1);
2107
+ planned.push({
2108
+ type: "ListPermissiveMove",
2109
+ listPath: fParent,
2110
+ from: fLast,
2111
+ to: tLast,
2112
+ movedValue: movedJson$1
2113
+ });
2114
+ }
2115
+ return;
2116
+ }
2117
+ }
2118
+ let movedJson;
2119
+ let srcAtomic;
2120
+ let srcDel;
2121
+ if (fAtomic !== void 0) {
2122
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot move inside atomic LoroValue in strict mode", opIndex);
2123
+ const containerPath = op.from.slice(0, fAtomic);
2124
+ const seg = op.from[fAtomic];
2125
+ const subFrom = op.from.slice(fAtomic + 1);
2126
+ const node = sim.resolveNode(op.from.slice(0, fAtomic + 1), opIndex);
2127
+ if (node.kind !== "Atomic") throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Object or Array");
2128
+ const { extracted, updated } = takeFromAtomicValue(node.value, subFrom, opIndex);
2129
+ jsonToLoroValue(updated);
2130
+ node.value = updated;
2131
+ srcAtomic = {
2132
+ containerPath,
2133
+ seg,
2134
+ value: updated
2135
+ };
2136
+ movedJson = extracted;
2137
+ } else {
2138
+ const { node: taken, isMovable } = takeSimGeneric(sim, op.from, opIndex);
2139
+ if (taken.kind !== "Atomic" && mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot move CRDT subcontainer across containers in strict mode", opIndex);
2140
+ srcDel = typeof fLast === "string" ? {
2141
+ type: "MapUnset",
2142
+ mapPath: fParent,
2143
+ key: fLast
2144
+ } : {
2145
+ type: "ListSplice",
2146
+ listPath: fParent,
2147
+ at: fLast,
2148
+ del: 1,
2149
+ items: [],
2150
+ isMovable
2151
+ };
2152
+ movedJson = sim.simToJson(taken);
2153
+ }
2154
+ if (sim.findStructuralTreePrefix(op.to, opIndex, false)) throw new LoroApplyError("SchemaViolation", "cannot move between LoroTree structure and non-tree container", opIndex);
2155
+ const tAtomic = sim.findAtomicPrefix(op.to);
2156
+ if (tAtomic !== void 0) {
2157
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot move inside atomic LoroValue in strict mode", opIndex);
2158
+ const containerPath = op.to.slice(0, tAtomic);
2159
+ const seg = op.to[tAtomic];
2160
+ const subTo = op.to.slice(tAtomic + 1);
2161
+ const node = sim.resolveNode(op.to.slice(0, tAtomic + 1), opIndex);
2162
+ if (node.kind !== "Atomic") throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected Object or Array");
2163
+ const subLast = subTo[subTo.length - 1];
2164
+ const insertOp = typeof subLast === "string" ? {
2165
+ op: "set",
2166
+ path: subTo,
2167
+ value: movedJson
2168
+ } : {
2169
+ op: "arr_splice",
2170
+ path: subTo.slice(0, -1),
2171
+ at: subLast,
2172
+ del: 0,
2173
+ items: [movedJson]
2174
+ };
2175
+ const trial = require_diff.apply(node.value, [insertOp]);
2176
+ jsonToLoroValue(trial);
2177
+ node.value = trial;
2178
+ if (srcAtomic) {
2179
+ if (!require_diff.pathsEqual(srcAtomic.containerPath, containerPath) || srcAtomic.seg !== seg) planned.push({
2180
+ type: "WriteAtomic",
2181
+ containerPath: srcAtomic.containerPath,
2182
+ seg: srcAtomic.seg,
2183
+ value: srcAtomic.value
2184
+ });
2185
+ } else if (srcDel) planned.push(srcDel);
2186
+ planned.push({
2187
+ type: "WriteAtomic",
2188
+ containerPath,
2189
+ seg,
2190
+ value: trial
2191
+ });
2192
+ return;
2193
+ }
2194
+ if (srcAtomic) {
2195
+ planned.push({
2196
+ type: "WriteAtomic",
2197
+ containerPath: srcAtomic.containerPath,
2198
+ seg: srcAtomic.seg,
2199
+ value: srcAtomic.value
2200
+ });
2201
+ const parent = sim.resolveNode(tParent, opIndex);
2202
+ if (parent.kind === "Map" && typeof tLast === "string") {
2203
+ const existingRaw = parent.entries.get(tLast);
2204
+ if (existingRaw) {
2205
+ const existing = sim.materialize(existingRaw);
2206
+ if (existing !== existingRaw) parent.entries.set(tLast, existing);
2207
+ if (existing.kind === "Counter") throw new LoroApplyError("SchemaViolation", "cannot overwrite LoroCounter via cross-container move", opIndex);
2208
+ }
2209
+ parent.entries.set(tLast, sim.buildSimForNewValue(movedJson, op.to, schema, opIndex));
2210
+ planned.push({
2211
+ type: "MapSet",
2212
+ mapPath: tParent,
2213
+ key: tLast,
2214
+ value: movedJson
2215
+ });
2216
+ return;
2217
+ }
2218
+ if (parent.kind === "List" && typeof tLast === "number") {
2219
+ if (tLast > parent.items.length) throw new require_diff.ApplyError("IndexOutOfBounds", opIndex, `index ${tLast} out of bounds for length ${parent.items.length}`);
2220
+ parent.items.splice(tLast, 0, sim.buildSimForNewValue(movedJson, op.to, schema, opIndex));
2221
+ planned.push({
2222
+ type: "ListSplice",
2223
+ listPath: tParent,
2224
+ at: tLast,
2225
+ del: 0,
2226
+ items: [movedJson],
2227
+ isMovable: parent.isMovable
2228
+ });
2229
+ return;
2230
+ }
2231
+ throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected compatible container");
2232
+ }
2233
+ const newSim = sim.buildSimForNewValue(movedJson, op.to, schema, opIndex);
2234
+ insertSimGeneric(sim, op.to, newSim, opIndex, mode);
2235
+ planned.push({
2236
+ type: "CrossMove",
2237
+ fromContainer: fParent,
2238
+ fromSeg: fLast,
2239
+ toContainer: tParent,
2240
+ toSeg: tLast,
2241
+ movedValue: movedJson
2242
+ });
2243
+ return;
2244
+ }
2245
+ case "str_splice": {
2246
+ assertValidPathSegments(op.path, opIndex);
2247
+ require_diff.assertNoLoneSurrogates(op.ins, opIndex);
2248
+ if (op.path.length === 0) throw new LoroApplyError("SchemaViolation", "str_splice cannot target document root []", opIndex);
2249
+ const treePrefix = sim.findStructuralTreePrefix(op.path, opIndex);
2250
+ if (treePrefix) {
2251
+ const { treeLen, treePath } = treePrefix;
2252
+ const rest = op.path.slice(treeLen);
2253
+ const treeNode = sim.resolveNode(treePath, opIndex);
2254
+ if (treeNode.kind === "Tree") resolveTreeTarget(treeNode.roots, rest, opIndex);
2255
+ throw new LoroApplyError("SchemaViolation", "str_splice cannot target LoroTree structure, 'meta', or 'id'", opIndex);
2256
+ }
2257
+ const atomicEnd = sim.findAtomicPrefix(op.path);
2258
+ if (atomicEnd !== void 0) {
2259
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot str_splice inside atomic LoroValue in strict mode", opIndex);
2260
+ const containerPath = op.path.slice(0, atomicEnd);
2261
+ const seg = op.path[atomicEnd];
2262
+ const subPath = op.path.slice(atomicEnd + 1);
2263
+ const node = sim.resolveNode(op.path.slice(0, atomicEnd + 1), opIndex);
2264
+ if (node.kind !== "Atomic") throw new LoroApplyError("Loro", "expected atomic", opIndex);
2265
+ const trial = require_diff.apply(node.value, [{
2266
+ op: "str_splice",
2267
+ path: subPath,
2268
+ at: op.at,
2269
+ del: op.del,
2270
+ ins: op.ins
2271
+ }]);
2272
+ jsonToLoroValue(trial);
2273
+ node.value = trial;
2274
+ planned.push({
2275
+ type: "WriteAtomic",
2276
+ containerPath,
2277
+ seg,
2278
+ value: trial
2279
+ });
2280
+ return;
2281
+ }
2282
+ const target = sim.resolveNode(op.path, opIndex);
2283
+ if (target.kind === "Text") {
2284
+ const end = require_diff.assertValidUtf16Range(target.text, op.at, op.del, opIndex);
2285
+ target.text = target.text.slice(0, op.at) + op.ins + target.text.slice(end);
2286
+ if (op.del > 0 || op.ins.length > 0) planned.push({
2287
+ type: "TextSplice",
2288
+ textPath: op.path,
2289
+ at: op.at,
2290
+ del: op.del,
2291
+ ins: op.ins
2292
+ });
2293
+ return;
2294
+ }
2295
+ if (target.kind === "Atomic" && typeof target.value === "string") {
2296
+ if (mode === "strict") throw new LoroApplyError("SchemaViolation", "cannot str_splice atomic LoroValue::String in strict mode; use LoroText container", opIndex);
2297
+ const end = require_diff.assertValidUtf16Range(target.value, op.at, op.del, opIndex);
2298
+ target.value = target.value.slice(0, op.at) + op.ins + target.value.slice(end);
2299
+ planned.push({
2300
+ type: "WriteAtomic",
2301
+ containerPath: op.path.slice(0, -1),
2302
+ seg: op.path[op.path.length - 1],
2303
+ value: target.value
2304
+ });
2305
+ return;
2306
+ }
2307
+ throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected String");
2308
+ }
2309
+ }
2310
+ }
2311
+ function takeSimGeneric(sim, path, opIndex) {
2312
+ const last = path[path.length - 1];
2313
+ const parent = sim.resolveNode(path.slice(0, -1), opIndex);
2314
+ if (parent.kind === "Map" && typeof last === "string") {
2315
+ const child = parent.entries.get(last);
2316
+ if (!child) throw new require_diff.ApplyError("MissingPath", opIndex, `missing object key "${last}"`);
2317
+ parent.entries.delete(last);
2318
+ return {
2319
+ node: sim.materialize(child),
2320
+ isMovable: false
2321
+ };
2322
+ }
2323
+ if (parent.kind === "List" && typeof last === "number") {
2324
+ if (last >= parent.items.length) throw new require_diff.ApplyError("IndexOutOfBounds", opIndex, `index ${last} out of bounds`);
2325
+ const [child] = parent.items.splice(last, 1);
2326
+ return {
2327
+ node: sim.materialize(child),
2328
+ isMovable: parent.isMovable
2329
+ };
2330
+ }
2331
+ throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected compatible container");
2332
+ }
2333
+ function insertSimGeneric(sim, path, node, opIndex, mode) {
2334
+ const last = path[path.length - 1];
2335
+ const parent = sim.resolveNode(path.slice(0, -1), opIndex);
2336
+ if (parent.kind === "Map" && typeof last === "string") {
2337
+ if (mode === "strict") {
2338
+ const existingRaw = parent.entries.get(last);
2339
+ if (existingRaw) {
2340
+ const existing = sim.materialize(existingRaw);
2341
+ if (existing !== existingRaw) parent.entries.set(last, existing);
2342
+ if (existing.kind === "Counter") throw new LoroApplyError("SchemaViolation", "cannot overwrite LoroCounter in strict mode", opIndex);
2343
+ }
2344
+ }
2345
+ parent.entries.set(last, node);
2346
+ return;
2347
+ }
2348
+ if (parent.kind === "List" && typeof last === "number") {
2349
+ if (last > parent.items.length) throw new require_diff.ApplyError("IndexOutOfBounds", opIndex, `index ${last} out of bounds`);
2350
+ parent.items.splice(last, 0, node);
2351
+ return;
2352
+ }
2353
+ throw new require_diff.ApplyError("TypeMismatch", opIndex, "expected compatible container");
2354
+ }
2355
+ function getRootContainer(doc, name, ctype) {
2356
+ switch (ctype) {
2357
+ case "Map": return doc.getMap(name);
2358
+ case "List": return doc.getList(name);
2359
+ case "MovableList": return doc.getMovableList(name);
2360
+ case "Text": return doc.getText(name);
2361
+ case "Tree": return doc.getTree(name);
2362
+ case "Counter": return doc.getCounter(name);
2363
+ }
2364
+ }
2365
+ function newDetachedContainer(ctype) {
2366
+ switch (ctype) {
2367
+ case "Map": return new loro_crdt.LoroMap();
2368
+ case "List": return new loro_crdt.LoroList();
2369
+ case "MovableList": return new loro_crdt.LoroMovableList();
2370
+ case "Text": return new loro_crdt.LoroText();
2371
+ case "Tree": return new loro_crdt.LoroTree();
2372
+ case "Counter": return new loro_crdt.LoroCounter();
2373
+ }
2374
+ }
2375
+ function resolveDocContainer(doc, schema, path) {
2376
+ const rootName = path[0];
2377
+ let cur = getRootContainer(doc, rootName, schema.roots.get(rootName));
2378
+ let i = 1;
2379
+ while (i < path.length) if (cur instanceof loro_crdt.LoroMap) {
2380
+ const k = path[i];
2381
+ cur = cur.get(k);
2382
+ i++;
2383
+ } else if (cur instanceof loro_crdt.LoroList || cur instanceof loro_crdt.LoroMovableList) {
2384
+ const idx = path[i];
2385
+ cur = cur.get(idx);
2386
+ i++;
2387
+ } else if (cur instanceof loro_crdt.LoroTree) {
2388
+ let curNode;
2389
+ while (i < path.length) {
2390
+ const seg = path[i];
2391
+ if (typeof seg === "number") {
2392
+ curNode = curNode === void 0 ? cur.roots()[seg] : (curNode.children() ?? [])[seg];
2393
+ i++;
2394
+ } else if (seg === "children") i++;
2395
+ else if (seg === "meta") {
2396
+ i++;
2397
+ cur = curNode.data;
2398
+ break;
2399
+ }
2400
+ }
2401
+ } else throw new LoroApplyError("Loro", "unexpected non-branch container during execute");
2402
+ return cur;
2403
+ }
2404
+ function treeNodeAtIndices(tree, indices) {
2405
+ let node = tree.roots()[indices[0]];
2406
+ for (let i = 1; i < indices.length; i++) node = (node.children() ?? [])[indices[i]];
2407
+ return node;
2408
+ }
2409
+ function treeParentIdAtMidIndices(tree, takenId, indices) {
2410
+ if (indices.length === 0) return void 0;
2411
+ let cur = tree.roots().filter((n) => n.id !== takenId)[indices[0]];
2412
+ for (let i = 1; i < indices.length; i++) cur = (cur.children() ?? []).filter((n) => n.id !== takenId)[indices[i]];
2413
+ return cur.id;
2414
+ }
2415
+ function populateContainerFromJson(container, fullPath, value, schema, createdTreeIds) {
2416
+ if (container instanceof loro_crdt.LoroMap) {
2417
+ const obj = value;
2418
+ const existingKeys = container.keys();
2419
+ for (let i = 0; i < existingKeys.length; i++) {
2420
+ const k = existingKeys[i];
2421
+ if (!require_diff.hasOwn(obj, k)) container.delete(k);
2422
+ }
2423
+ const keys = Object.keys(obj).sort();
2424
+ for (let i = 0; i < keys.length; i++) {
2425
+ const k = keys[i];
2426
+ setMapEntry(container, k, [...fullPath, k], obj[k], schema, createdTreeIds);
2427
+ }
2428
+ return;
2429
+ }
2430
+ if (container instanceof loro_crdt.LoroList) {
2431
+ const arr = value;
2432
+ if (container.length > 0) container.delete(0, container.length);
2433
+ for (let i = 0; i < arr.length; i++) insertListEntry(container, i, [...fullPath, i], arr[i], schema, createdTreeIds);
2434
+ return;
2435
+ }
2436
+ if (container instanceof loro_crdt.LoroMovableList) {
2437
+ const arr = value;
2438
+ if (container.length > 0) container.delete(0, container.length);
2439
+ for (let i = 0; i < arr.length; i++) insertMovableListEntry(container, i, [...fullPath, i], arr[i], schema, createdTreeIds);
2440
+ return;
2441
+ }
2442
+ if (container instanceof loro_crdt.LoroText) {
2443
+ const s = value;
2444
+ container.splice(0, container.length, s);
2445
+ return;
2446
+ }
2447
+ if (container instanceof loro_crdt.LoroTree) {
2448
+ if (!container.isFractionalIndexEnabled()) container.enableFractionalIndex(0);
2449
+ const roots = container.roots();
2450
+ for (let i = 0; i < roots.length; i++) container.delete(roots[i].id);
2451
+ const arr = value;
2452
+ for (let i = 0; i < arr.length; i++) createTreeNodeFromJson(container, void 0, i, [...fullPath, i], arr[i], schema, createdTreeIds);
2453
+ return;
2454
+ }
2455
+ if (container instanceof loro_crdt.LoroCounter) {
2456
+ const cur = container.value;
2457
+ const { target, d1, d2 } = validateCounterTarget(value, cur, 0);
2458
+ if (cur !== target) {
2459
+ if (d1 !== 0) container.increment(d1);
2460
+ if (d2 !== 0) container.increment(d2);
2461
+ const rem = normZeroF64(target - container.value);
2462
+ if (rem !== 0 && Number.isFinite(rem)) container.increment(rem);
2463
+ }
2464
+ }
2465
+ }
2466
+ function setMapEntry(map, key, fullPath, value, schema, createdTreeIds) {
2467
+ const kind = schema.kindForNewValue(fullPath, value);
2468
+ if (kind.kind === "Value") map.set(key, jsonToLoroValue(value));
2469
+ else populateContainerFromJson(map.setContainer(key, newDetachedContainer(kind.containerType)), fullPath, value, schema, createdTreeIds);
2470
+ }
2471
+ function insertListEntry(list, index, fullPath, value, schema, createdTreeIds) {
2472
+ const kind = schema.kindForNewValue(fullPath, value);
2473
+ if (kind.kind === "Value") list.insert(index, jsonToLoroValue(value));
2474
+ else populateContainerFromJson(list.insertContainer(index, newDetachedContainer(kind.containerType)), fullPath, value, schema, createdTreeIds);
2475
+ }
2476
+ function insertMovableListEntry(ml, index, fullPath, value, schema, createdTreeIds) {
2477
+ const kind = schema.kindForNewValue(fullPath, value);
2478
+ if (kind.kind === "Value") ml.insert(index, jsonToLoroValue(value));
2479
+ else populateContainerFromJson(ml.insertContainer(index, newDetachedContainer(kind.containerType)), fullPath, value, schema, createdTreeIds);
2480
+ }
2481
+ function setMovableListEntry(ml, index, fullPath, value, schema, createdTreeIds) {
2482
+ const kind = schema.kindForNewValue(fullPath, value);
2483
+ if (kind.kind === "Value") ml.set(index, jsonToLoroValue(value));
2484
+ else populateContainerFromJson(ml.setContainer(index, newDetachedContainer(kind.containerType)), fullPath, value, schema, createdTreeIds);
2485
+ }
2486
+ function createTreeNodeFromJson(tree, parentId, index, nodePath, value, schema, createdTreeIds) {
2487
+ if (!tree.isFractionalIndexEnabled()) tree.enableFractionalIndex(0);
2488
+ const obj = value;
2489
+ const specifiedId = require_diff.hasOwn(obj, "id") && typeof obj.id === "string" ? obj.id : void 0;
2490
+ const newNode = tree.createNode(parentId, index);
2491
+ createdTreeIds.push({
2492
+ specifiedId,
2493
+ assignedId: newNode.id
2494
+ });
2495
+ if (require_diff.hasOwn(obj, "meta") && obj.meta !== void 0) populateContainerFromJson(newNode.data, [...nodePath, "meta"], obj.meta, schema, createdTreeIds);
2496
+ if (require_diff.hasOwn(obj, "children") && Array.isArray(obj.children)) for (let i = 0; i < obj.children.length; i++) createTreeNodeFromJson(tree, newNode.id, i, [
2497
+ ...nodePath,
2498
+ "children",
2499
+ i
2500
+ ], obj.children[i], schema, createdTreeIds);
2501
+ }
2502
+ function executePlan(doc, plan, schema) {
2503
+ if (plan.length === 0) return {
2504
+ changed: false,
2505
+ createdTreeIds: []
2506
+ };
2507
+ doc.commit();
2508
+ const vvBefore = doc.oplogVersion();
2509
+ const createdTreeIds = [];
2510
+ for (let sIdx = 0; sIdx < plan.length; sIdx++) {
2511
+ const step = plan[sIdx];
2512
+ switch (step.type) {
2513
+ case "ReplaceRoot": {
2514
+ const path = [step.root];
2515
+ populateContainerFromJson(resolveDocContainer(doc, schema, path), path, step.value, schema, createdTreeIds);
2516
+ break;
2517
+ }
2518
+ case "MapSet":
2519
+ setMapEntry(resolveDocContainer(doc, schema, step.mapPath), step.key, [...step.mapPath, step.key], step.value, schema, createdTreeIds);
2520
+ break;
2521
+ case "MapUnset":
2522
+ resolveDocContainer(doc, schema, step.mapPath).delete(step.key);
2523
+ break;
2524
+ case "ListSet": {
2525
+ const fp = [...step.listPath, step.index];
2526
+ if (step.isMovable) setMovableListEntry(resolveDocContainer(doc, schema, step.listPath), step.index, fp, step.value, schema, createdTreeIds);
2527
+ else {
2528
+ const l = resolveDocContainer(doc, schema, step.listPath);
2529
+ l.delete(step.index, 1);
2530
+ insertListEntry(l, step.index, fp, step.value, schema, createdTreeIds);
2531
+ }
2532
+ break;
2533
+ }
2534
+ case "ListSplice":
2535
+ if (step.isMovable) {
2536
+ const ml = resolveDocContainer(doc, schema, step.listPath);
2537
+ if (step.del > 0) ml.delete(step.at, step.del);
2538
+ for (let i = 0; i < step.items.length; i++) insertMovableListEntry(ml, step.at + i, [...step.listPath, step.at + i], step.items[i], schema, createdTreeIds);
2539
+ } else {
2540
+ const l = resolveDocContainer(doc, schema, step.listPath);
2541
+ if (step.del > 0) l.delete(step.at, step.del);
2542
+ for (let i = 0; i < step.items.length; i++) insertListEntry(l, step.at + i, [...step.listPath, step.at + i], step.items[i], schema, createdTreeIds);
2543
+ }
2544
+ break;
2545
+ case "MovableListMove":
2546
+ resolveDocContainer(doc, schema, step.listPath).move(step.from, step.to);
2547
+ break;
2548
+ case "ListPermissiveMove": {
2549
+ const l = resolveDocContainer(doc, schema, step.listPath);
2550
+ l.delete(step.from, 1);
2551
+ insertListEntry(l, step.to, [...step.listPath, step.to], step.movedValue, schema, createdTreeIds);
2552
+ break;
2553
+ }
2554
+ case "TextSplice":
2555
+ resolveDocContainer(doc, schema, step.textPath).splice(step.at, step.del, step.ins);
2556
+ break;
2557
+ case "TreeSplice": {
2558
+ const tree = resolveDocContainer(doc, schema, step.treePath);
2559
+ if (!tree.isFractionalIndexEnabled()) tree.enableFractionalIndex(0);
2560
+ const parentNode = step.parentIndices.length === 0 ? void 0 : treeNodeAtIndices(tree, step.parentIndices);
2561
+ if (step.del > 0) {
2562
+ const children = parentNode ? parentNode.children() ?? [] : tree.roots();
2563
+ for (let i = 0; i < step.del; i++) tree.delete(children[step.at + i].id);
2564
+ }
2565
+ const basePath = treeMetaPath(step.treePath, step.parentIndices);
2566
+ basePath.pop();
2567
+ if (step.parentIndices.length > 0) basePath.push("children");
2568
+ for (let i = 0; i < step.items.length; i++) createTreeNodeFromJson(tree, parentNode?.id, step.at + i, [...basePath, step.at + i], step.items[i], schema, createdTreeIds);
2569
+ break;
2570
+ }
2571
+ case "TreeMove": {
2572
+ const tree = resolveDocContainer(doc, schema, step.treePath);
2573
+ if (!tree.isFractionalIndexEnabled()) tree.enableFractionalIndex(0);
2574
+ const targetNode = treeNodeAtIndices(tree, step.fromIndices);
2575
+ const newParentId = treeParentIdAtMidIndices(tree, targetNode.id, step.newParentIndices);
2576
+ tree.move(targetNode.id, newParentId, step.toIndex);
2577
+ break;
2578
+ }
2579
+ case "TreeMetaReplace": {
2580
+ const targetNode = treeNodeAtIndices(resolveDocContainer(doc, schema, step.treePath), step.nodeIndices);
2581
+ const mp = treeMetaPath(step.treePath, step.nodeIndices);
2582
+ populateContainerFromJson(targetNode.data, mp, step.value, schema, createdTreeIds);
2583
+ break;
2584
+ }
2585
+ case "CounterSet": {
2586
+ const c = resolveDocContainer(doc, schema, step.counterPath);
2587
+ if (step.d1 !== 0) c.increment(step.d1);
2588
+ if (step.d2 !== 0) c.increment(step.d2);
2589
+ const rem = normZeroF64(step.target - c.value);
2590
+ if (rem !== 0 && Number.isFinite(rem)) c.increment(rem);
2591
+ break;
2592
+ }
2593
+ case "WriteAtomic": {
2594
+ const c = resolveDocContainer(doc, schema, step.containerPath);
2595
+ const lv = jsonToLoroValue(step.value);
2596
+ if (c instanceof loro_crdt.LoroMap && typeof step.seg === "string") c.set(step.seg, lv);
2597
+ else if (c instanceof loro_crdt.LoroList && typeof step.seg === "number") {
2598
+ c.delete(step.seg, 1);
2599
+ c.insert(step.seg, lv);
2600
+ } else if (c instanceof loro_crdt.LoroMovableList && typeof step.seg === "number") c.set(step.seg, lv);
2601
+ break;
2602
+ }
2603
+ case "CrossMove": {
2604
+ const src = resolveDocContainer(doc, schema, step.fromContainer);
2605
+ if (src instanceof loro_crdt.LoroMap && typeof step.fromSeg === "string") src.delete(step.fromSeg);
2606
+ else if ((src instanceof loro_crdt.LoroList || src instanceof loro_crdt.LoroMovableList) && typeof step.fromSeg === "number") src.delete(step.fromSeg, 1);
2607
+ const dst = resolveDocContainer(doc, schema, step.toContainer);
2608
+ const fp = [...step.toContainer, step.toSeg];
2609
+ if (dst instanceof loro_crdt.LoroMap && typeof step.toSeg === "string") setMapEntry(dst, step.toSeg, fp, step.movedValue, schema, createdTreeIds);
2610
+ else if (dst instanceof loro_crdt.LoroList && typeof step.toSeg === "number") insertListEntry(dst, step.toSeg, fp, step.movedValue, schema, createdTreeIds);
2611
+ else if (dst instanceof loro_crdt.LoroMovableList && typeof step.toSeg === "number") insertMovableListEntry(dst, step.toSeg, fp, step.movedValue, schema, createdTreeIds);
2612
+ break;
2613
+ }
2614
+ }
2615
+ }
2616
+ doc.commit();
2617
+ return {
2618
+ changed: doc.oplogVersion().compare(vvBefore) !== 0,
2619
+ createdTreeIds
2620
+ };
2621
+ }
2622
+ function wrapLoroOp(fn) {
2623
+ try {
2624
+ return fn();
2625
+ } catch (err) {
2626
+ if (err instanceof LoroApplyError) throw err;
2627
+ throw new LoroApplyError("Loro", err instanceof Error ? err.message : String(err));
2628
+ }
2629
+ }
2630
+ const U64_MAX_PEER = 18446744073709551615n;
2631
+ /**
2632
+ * Validates `patch` against `doc` and `options.schema`, then applies all CRDT mutations atomically.
2633
+ * @throws {@link LoroApplyError} on schema violations, invalid patches, or detached `LoroDoc`.
2634
+ */
2635
+ function applyJsonPatchToLoro(doc, patch, options) {
2636
+ if (doc.isDetached()) throw new LoroApplyError("SchemaViolation", "cannot apply patch to a detached LoroDoc", 0);
2637
+ if (patch.length === 0) return {
2638
+ changed: false,
2639
+ createdTreeIds: []
2640
+ };
2641
+ const plan = planPatch(doc, patch, options);
2642
+ return wrapLoroOp(() => executePlan(doc, plan, options.schema));
2643
+ }
2644
+ /**
2645
+ * Rebases/applies `patch` starting from `baseFrontiers` on `doc`, committing CRDT ops under optional `peerId`.
2646
+ * @throws {@link LoroApplyError} on conflicts, schema violations, or peer ID conflict.
2647
+ */
2648
+ function applyJsonPatchAt(doc, baseFrontiers, patch, options, peerId) {
2649
+ if (doc.isDetached()) throw new LoroApplyError("SchemaViolation", "cannot apply patch to a detached LoroDoc", 0);
2650
+ doc.commit();
2651
+ if (frontiersEqual(doc.oplogFrontiers(), baseFrontiers)) {
2652
+ const plan = planPatch(doc, patch, options);
2653
+ if (plan.length === 0) return {
2654
+ changed: false,
2655
+ createdTreeIds: []
2656
+ };
2657
+ const prevPeer = doc.peerIdStr;
2658
+ if (peerId !== void 0) wrapLoroOp(() => doc.setPeerId(peerId));
2659
+ try {
2660
+ return wrapLoroOp(() => executePlan(doc, plan, options.schema));
2661
+ } finally {
2662
+ if (peerId !== void 0) try {
2663
+ doc.setPeerId(prevPeer);
2664
+ } catch {}
2665
+ }
2666
+ }
2667
+ return wrapLoroOp(() => {
2668
+ const forked = doc.forkAt(baseFrontiers.slice());
2669
+ const docVv = doc.oplogVersion();
2670
+ const forkVv = forked.oplogVersion();
2671
+ const docVvMap = docVv.toJSON();
2672
+ const forkVvMap = forkVv.toJSON();
2673
+ let chosenPeer;
2674
+ if (peerId !== void 0) {
2675
+ if ((docVv.get(peerId) ?? 0) > (forkVv.get(peerId) ?? 0)) throw new LoroApplyError("PeerIdConflict", `peerId ${String(peerId)} already has newer operations in target doc`);
2676
+ chosenPeer = peerId;
2677
+ } else {
2678
+ let maxPeer = 0n;
2679
+ for (const p of docVvMap.keys()) {
2680
+ const b = BigInt(p);
2681
+ if (b > maxPeer && b !== U64_MAX_PEER) maxPeer = b;
2682
+ }
2683
+ for (const p of forkVvMap.keys()) {
2684
+ const b = BigInt(p);
2685
+ if (b > maxPeer && b !== U64_MAX_PEER) maxPeer = b;
2686
+ }
2687
+ let candidate = maxPeer + 1n & U64_MAX_PEER;
2688
+ while (candidate === U64_MAX_PEER || candidate === 0n || docVvMap.has(String(candidate)) || forkVvMap.has(String(candidate))) candidate = candidate + 1n & U64_MAX_PEER;
2689
+ chosenPeer = String(candidate);
2690
+ }
2691
+ forked.setPeerId(chosenPeer);
2692
+ const vvBefore = forked.oplogVersion();
2693
+ const applied = applyJsonPatchToLoro(forked, patch, options);
2694
+ if (forked.oplogVersion().compare(vvBefore) === 0) return {
2695
+ changed: false,
2696
+ createdTreeIds: applied.createdTreeIds
2697
+ };
2698
+ const updates = forked.export({
2699
+ mode: "update",
2700
+ from: vvBefore
2701
+ });
2702
+ doc.import(updates);
2703
+ return {
2704
+ changed: doc.oplogVersion().compare(docVv) !== 0,
2705
+ createdTreeIds: applied.createdTreeIds
2706
+ };
2707
+ });
2708
+ }
2709
+
2710
+ //#endregion
2711
+ exports.LoroApplyError = LoroApplyError;
2712
+ exports.LoroSchema = LoroSchema;
2713
+ exports.LoroValueKind = LoroValueKind;
2714
+ exports.applyJsonPatchAt = applyJsonPatchAt;
2715
+ exports.applyJsonPatchToLoro = applyJsonPatchToLoro;
2716
+ exports.containerKind = containerKind;
2717
+ exports.diffLoroJson = diffLoroJson;
2718
+ exports.jsonToLoroValue = jsonToLoroValue;
2719
+ exports.loroToJson = loroToJson;
2720
+ exports.projectContainer = projectContainer;
2721
+ exports.projectContainerById = projectContainerById;
2722
+ exports.projectLoroValue = projectLoroValue;