@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/README.md +314 -2
- package/dist/diff.cjs +1666 -0
- package/dist/diff.d.cts +126 -0
- package/dist/diff.d.ts +126 -0
- package/dist/diff.js +1463 -0
- package/dist/index.cjs +1124 -0
- package/dist/index.d.cts +74 -0
- package/dist/index.d.ts +74 -0
- package/dist/index.js +1097 -0
- package/dist/loro.cjs +2722 -0
- package/dist/loro.d.cts +115 -0
- package/dist/loro.d.ts +115 -0
- package/dist/loro.js +2710 -0
- package/package.json +70 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1097 @@
|
|
|
1
|
+
import { C as numbersEqual, D as validateAndNormalizeJsonValue, E as setOwnProp, O as validateJsonValue, S as isPlainObject, T as pathsOverlap, _ as assertNoLoneSurrogates, a as lisMask, b as hasLoneSurrogates, c as apply, d as DecodeError, f as I64_MAX, g as U64_MAX, h as MIN_SAFE_BIG, i as diffStringAt, k as valuesEqual, l as applyOp, m as MAX_SAFE_BIG, n as ANY_SEG, o as lisMovePairs, p as I64_MIN, r as diff, s as patternMatches, t as ANY_REST_SEG, u as ApplyError, v as assertValidUtf16Boundary, w as pathsEqual, x as hasOwn, y as assertValidUtf16Range } from "./diff.js";
|
|
2
|
+
import { encode } from "@msgpack/msgpack";
|
|
3
|
+
|
|
4
|
+
//#region src/codec.ts
|
|
5
|
+
const UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
|
|
6
|
+
var FloatToken = class {
|
|
7
|
+
value;
|
|
8
|
+
constructor(value) {
|
|
9
|
+
this.value = value;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
function checkNoLoneSurrogates(s, isPath = false) {
|
|
13
|
+
if (hasLoneSurrogates(s)) {
|
|
14
|
+
if (isPath) throw new DecodeError("InvalidPath", "path segment contains lone UTF-16 surrogate");
|
|
15
|
+
throw new DecodeError("InvalidFormat", "string contains lone UTF-16 surrogate");
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function isEscapeKey(k) {
|
|
19
|
+
return k === "$bytes" || k === "$esc";
|
|
20
|
+
}
|
|
21
|
+
const B64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
22
|
+
const B64_LOOKUP = (() => {
|
|
23
|
+
const table = new Int16Array(256).fill(-1);
|
|
24
|
+
for (let i = 0; i < 64; i++) table[B64_CHARS.charCodeAt(i)] = i;
|
|
25
|
+
return table;
|
|
26
|
+
})();
|
|
27
|
+
function encodeBase64(bytes) {
|
|
28
|
+
let out = "";
|
|
29
|
+
let i = 0;
|
|
30
|
+
for (; i + 2 < bytes.length; i += 3) {
|
|
31
|
+
const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
|
|
32
|
+
out += B64_CHARS[n >>> 18 & 63] + B64_CHARS[n >>> 12 & 63] + B64_CHARS[n >>> 6 & 63] + B64_CHARS[n & 63];
|
|
33
|
+
}
|
|
34
|
+
const rem = bytes.length - i;
|
|
35
|
+
if (rem === 1) {
|
|
36
|
+
const n = bytes[i];
|
|
37
|
+
out += B64_CHARS[n >>> 2 & 63] + B64_CHARS[n << 4 & 63] + "==";
|
|
38
|
+
} else if (rem === 2) {
|
|
39
|
+
const n = bytes[i] << 8 | bytes[i + 1];
|
|
40
|
+
out += B64_CHARS[n >>> 10 & 63] + B64_CHARS[n >>> 4 & 63] + B64_CHARS[n << 2 & 63] + "=";
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
function decodeB64Char(code) {
|
|
45
|
+
if (code >= 256) throw new DecodeError("InvalidBase64", "invalid base64 character");
|
|
46
|
+
const v = B64_LOOKUP[code];
|
|
47
|
+
if (v < 0) throw new DecodeError("InvalidBase64", "invalid base64 character");
|
|
48
|
+
return v;
|
|
49
|
+
}
|
|
50
|
+
function decodeBase64(s) {
|
|
51
|
+
if (s.length === 0) return new Uint8Array(0);
|
|
52
|
+
if (s.length % 4 !== 0) throw new DecodeError("InvalidBase64", "invalid base64 length");
|
|
53
|
+
let pad = 0;
|
|
54
|
+
if (s.charCodeAt(s.length - 1) === 61) pad = s.charCodeAt(s.length - 2) === 61 ? 2 : 1;
|
|
55
|
+
const outLen = s.length / 4 * 3 - pad;
|
|
56
|
+
const out = new Uint8Array(outLen);
|
|
57
|
+
let outPos = 0;
|
|
58
|
+
for (let i = 0; i < s.length; i += 4) {
|
|
59
|
+
const c0 = decodeB64Char(s.charCodeAt(i));
|
|
60
|
+
const c1 = decodeB64Char(s.charCodeAt(i + 1));
|
|
61
|
+
const isLast = i + 4 === s.length;
|
|
62
|
+
const c2 = isLast && pad >= 2 ? 0 : decodeB64Char(s.charCodeAt(i + 2));
|
|
63
|
+
const c3 = isLast && pad >= 1 ? 0 : decodeB64Char(s.charCodeAt(i + 3));
|
|
64
|
+
if (isLast) {
|
|
65
|
+
if (pad === 2 && (c1 & 15) !== 0) throw new DecodeError("InvalidBase64", "non-zero trailing padding bits");
|
|
66
|
+
if (pad === 1 && (c2 & 3) !== 0) throw new DecodeError("InvalidBase64", "non-zero trailing padding bits");
|
|
67
|
+
}
|
|
68
|
+
const n = c0 << 18 | c1 << 12 | c2 << 6 | c3;
|
|
69
|
+
if (outPos < outLen) out[outPos++] = n >>> 16 & 255;
|
|
70
|
+
if (outPos < outLen) out[outPos++] = n >>> 8 & 255;
|
|
71
|
+
if (outPos < outLen) out[outPos++] = n & 255;
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
function parseJsonLossless(input) {
|
|
76
|
+
let pos = 0;
|
|
77
|
+
const len = input.length;
|
|
78
|
+
function skipWs() {
|
|
79
|
+
while (pos < len) {
|
|
80
|
+
const c = input.charCodeAt(pos);
|
|
81
|
+
if (c === 32 || c === 10 || c === 13 || c === 9) pos++;
|
|
82
|
+
else break;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function parseValue() {
|
|
86
|
+
skipWs();
|
|
87
|
+
if (pos >= len) throw new DecodeError("Json", "unexpected end of JSON input");
|
|
88
|
+
const c = input.charCodeAt(pos);
|
|
89
|
+
if (c === 123) return parseObject();
|
|
90
|
+
if (c === 91) return parseArray();
|
|
91
|
+
if (c === 34) return parseString();
|
|
92
|
+
if (c === 116) return parseLiteral("true", true);
|
|
93
|
+
if (c === 102) return parseLiteral("false", false);
|
|
94
|
+
if (c === 110) return parseLiteral("null", null);
|
|
95
|
+
if (c === 45 || c >= 48 && c <= 57) return parseNumber();
|
|
96
|
+
throw new DecodeError("Json", `unexpected character '${input[pos]}' at position ${pos}`);
|
|
97
|
+
}
|
|
98
|
+
function parseLiteral(lit, val) {
|
|
99
|
+
if (input.startsWith(lit, pos)) {
|
|
100
|
+
pos += lit.length;
|
|
101
|
+
return val;
|
|
102
|
+
}
|
|
103
|
+
throw new DecodeError("Json", `expected '${lit}' at position ${pos}`);
|
|
104
|
+
}
|
|
105
|
+
function parseString() {
|
|
106
|
+
const start = pos;
|
|
107
|
+
pos++;
|
|
108
|
+
let hasEscape = false;
|
|
109
|
+
while (pos < len) {
|
|
110
|
+
const c = input.charCodeAt(pos);
|
|
111
|
+
if (c === 34) {
|
|
112
|
+
if (!hasEscape) {
|
|
113
|
+
const s = input.slice(start + 1, pos);
|
|
114
|
+
pos++;
|
|
115
|
+
checkNoLoneSurrogates(s);
|
|
116
|
+
return s;
|
|
117
|
+
}
|
|
118
|
+
pos++;
|
|
119
|
+
let parsed;
|
|
120
|
+
try {
|
|
121
|
+
parsed = JSON.parse(input.slice(start, pos));
|
|
122
|
+
} catch (err) {
|
|
123
|
+
throw new DecodeError("Json", `invalid string literal: ${String(err)}`);
|
|
124
|
+
}
|
|
125
|
+
checkNoLoneSurrogates(parsed);
|
|
126
|
+
return parsed;
|
|
127
|
+
}
|
|
128
|
+
if (c === 92) {
|
|
129
|
+
hasEscape = true;
|
|
130
|
+
pos += 2;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (c < 32) throw new DecodeError("Json", `unescaped control character in string at ${pos}`);
|
|
134
|
+
pos++;
|
|
135
|
+
}
|
|
136
|
+
throw new DecodeError("Json", "unterminated string literal");
|
|
137
|
+
}
|
|
138
|
+
function parseNumber() {
|
|
139
|
+
const start = pos;
|
|
140
|
+
if (input.charCodeAt(pos) === 45) pos++;
|
|
141
|
+
if (pos >= len) throw new DecodeError("Json", "invalid number");
|
|
142
|
+
if (input.charCodeAt(pos) === 48) pos++;
|
|
143
|
+
else if (input.charCodeAt(pos) >= 49 && input.charCodeAt(pos) <= 57) {
|
|
144
|
+
pos++;
|
|
145
|
+
while (pos < len && input.charCodeAt(pos) >= 48 && input.charCodeAt(pos) <= 57) pos++;
|
|
146
|
+
} else throw new DecodeError("Json", `invalid number at ${start}`);
|
|
147
|
+
let isFloat = false;
|
|
148
|
+
if (pos < len && input.charCodeAt(pos) === 46) {
|
|
149
|
+
isFloat = true;
|
|
150
|
+
pos++;
|
|
151
|
+
if (pos >= len || input.charCodeAt(pos) < 48 || input.charCodeAt(pos) > 57) throw new DecodeError("Json", `invalid fraction in number at ${start}`);
|
|
152
|
+
while (pos < len && input.charCodeAt(pos) >= 48 && input.charCodeAt(pos) <= 57) pos++;
|
|
153
|
+
}
|
|
154
|
+
if (pos < len && (input.charCodeAt(pos) === 101 || input.charCodeAt(pos) === 69)) {
|
|
155
|
+
isFloat = true;
|
|
156
|
+
pos++;
|
|
157
|
+
if (pos < len && (input.charCodeAt(pos) === 43 || input.charCodeAt(pos) === 45)) pos++;
|
|
158
|
+
if (pos >= len || input.charCodeAt(pos) < 48 || input.charCodeAt(pos) > 57) throw new DecodeError("Json", `invalid exponent in number at ${start}`);
|
|
159
|
+
while (pos < len && input.charCodeAt(pos) >= 48 && input.charCodeAt(pos) <= 57) pos++;
|
|
160
|
+
}
|
|
161
|
+
const raw = input.slice(start, pos);
|
|
162
|
+
if (!isFloat && raw !== "-0") {
|
|
163
|
+
const bi = BigInt(raw);
|
|
164
|
+
if (bi >= MIN_SAFE_BIG && bi <= MAX_SAFE_BIG) return Number(raw);
|
|
165
|
+
if (bi >= I64_MIN && bi <= U64_MAX) return bi;
|
|
166
|
+
}
|
|
167
|
+
const f = Number(raw);
|
|
168
|
+
if (!Number.isFinite(f)) throw new DecodeError("NonFiniteFloat", `number out of finite f64 range: ${raw}`);
|
|
169
|
+
return new FloatToken(Object.is(f, -0) ? 0 : f);
|
|
170
|
+
}
|
|
171
|
+
function parseArray() {
|
|
172
|
+
pos++;
|
|
173
|
+
const arr = [];
|
|
174
|
+
skipWs();
|
|
175
|
+
if (pos < len && input.charCodeAt(pos) === 93) {
|
|
176
|
+
pos++;
|
|
177
|
+
return arr;
|
|
178
|
+
}
|
|
179
|
+
while (true) {
|
|
180
|
+
arr.push(parseValue());
|
|
181
|
+
skipWs();
|
|
182
|
+
if (pos >= len) throw new DecodeError("Json", "unterminated array");
|
|
183
|
+
if (input.charCodeAt(pos) === 93) {
|
|
184
|
+
pos++;
|
|
185
|
+
return arr;
|
|
186
|
+
}
|
|
187
|
+
if (input.charCodeAt(pos) !== 44) throw new DecodeError("Json", `expected ',' or ']' at ${pos}`);
|
|
188
|
+
pos++;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function parseObject() {
|
|
192
|
+
pos++;
|
|
193
|
+
const obj = {};
|
|
194
|
+
skipWs();
|
|
195
|
+
if (pos < len && input.charCodeAt(pos) === 125) {
|
|
196
|
+
pos++;
|
|
197
|
+
return obj;
|
|
198
|
+
}
|
|
199
|
+
while (true) {
|
|
200
|
+
skipWs();
|
|
201
|
+
if (pos >= len || input.charCodeAt(pos) !== 34) throw new DecodeError("Json", `expected string key at ${pos}`);
|
|
202
|
+
const key = parseString();
|
|
203
|
+
skipWs();
|
|
204
|
+
if (pos >= len || input.charCodeAt(pos) !== 58) throw new DecodeError("Json", `expected ':' after key at ${pos}`);
|
|
205
|
+
pos++;
|
|
206
|
+
setOwnProp(obj, key, parseValue());
|
|
207
|
+
skipWs();
|
|
208
|
+
if (pos >= len) throw new DecodeError("Json", "unterminated object");
|
|
209
|
+
if (input.charCodeAt(pos) === 125) {
|
|
210
|
+
pos++;
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
if (input.charCodeAt(pos) !== 44) throw new DecodeError("Json", `expected ',' or '}' at ${pos}`);
|
|
214
|
+
pos++;
|
|
215
|
+
}
|
|
216
|
+
return obj;
|
|
217
|
+
}
|
|
218
|
+
const root = parseValue();
|
|
219
|
+
skipWs();
|
|
220
|
+
if (pos !== len) throw new DecodeError("Json", `trailing garbage after JSON at position ${pos}`);
|
|
221
|
+
return root;
|
|
222
|
+
}
|
|
223
|
+
function decodeRawJsonValue(raw, bytesMode) {
|
|
224
|
+
if (raw === null || typeof raw === "boolean") return raw;
|
|
225
|
+
if (typeof raw === "string") {
|
|
226
|
+
checkNoLoneSurrogates(raw);
|
|
227
|
+
return raw;
|
|
228
|
+
}
|
|
229
|
+
if (raw instanceof FloatToken) return raw.value;
|
|
230
|
+
if (typeof raw === "number") {
|
|
231
|
+
if (!Number.isFinite(raw)) throw new DecodeError("NonFiniteFloat", "non-finite float (NaN or Infinity) is forbidden");
|
|
232
|
+
return Object.is(raw, -0) ? 0 : raw;
|
|
233
|
+
}
|
|
234
|
+
if (typeof raw === "bigint") {
|
|
235
|
+
if (raw < I64_MIN || raw > U64_MAX) throw new DecodeError("InvalidFormat", `integer out of i64/u64 range: ${raw}`);
|
|
236
|
+
if (raw >= MIN_SAFE_BIG && raw <= MAX_SAFE_BIG) return Number(raw);
|
|
237
|
+
return raw;
|
|
238
|
+
}
|
|
239
|
+
if (raw instanceof Uint8Array) return raw;
|
|
240
|
+
if (Array.isArray(raw)) {
|
|
241
|
+
const out = new Array(raw.length);
|
|
242
|
+
for (let i = 0; i < raw.length; i++) out[i] = decodeRawJsonValue(raw[i], bytesMode);
|
|
243
|
+
return out;
|
|
244
|
+
}
|
|
245
|
+
if (isPlainObject(raw)) {
|
|
246
|
+
const keys = Object.keys(raw);
|
|
247
|
+
if (bytesMode === "tagged" && keys.length === 1) {
|
|
248
|
+
const k = keys[0];
|
|
249
|
+
if (k === "$bytes" && typeof raw.$bytes === "string") return decodeBase64(raw.$bytes);
|
|
250
|
+
if (k === "$esc" && isPlainObject(raw.$esc)) {
|
|
251
|
+
const innerKeys = Object.keys(raw.$esc);
|
|
252
|
+
if (innerKeys.length === 1 && isEscapeKey(innerKeys[0])) {
|
|
253
|
+
const innerK = innerKeys[0];
|
|
254
|
+
checkNoLoneSurrogates(innerK);
|
|
255
|
+
const out$1 = {};
|
|
256
|
+
setOwnProp(out$1, innerK, decodeRawJsonValue(raw.$esc[innerK], bytesMode));
|
|
257
|
+
return out$1;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const out = {};
|
|
262
|
+
for (let i = 0; i < keys.length; i++) {
|
|
263
|
+
const k = keys[i];
|
|
264
|
+
checkNoLoneSurrogates(k);
|
|
265
|
+
setOwnProp(out, k, decodeRawJsonValue(raw[k], bytesMode));
|
|
266
|
+
}
|
|
267
|
+
return out;
|
|
268
|
+
}
|
|
269
|
+
throw new DecodeError("InvalidFormat", `unsupported decoded value type: ${typeof raw}`);
|
|
270
|
+
}
|
|
271
|
+
function serializeJsonValue(val, bytesMode) {
|
|
272
|
+
if (val === null) return "null";
|
|
273
|
+
switch (typeof val) {
|
|
274
|
+
case "boolean": return val ? "true" : "false";
|
|
275
|
+
case "bigint":
|
|
276
|
+
if (val < I64_MIN || val > U64_MAX) throw new DecodeError("InvalidFormat", `bigint out of i64/u64 range: ${val}`);
|
|
277
|
+
return val.toString();
|
|
278
|
+
case "number":
|
|
279
|
+
if (!Number.isFinite(val)) throw new DecodeError("NonFiniteFloat", "non-finite float (NaN or Infinity) is forbidden");
|
|
280
|
+
return Object.is(val, -0) ? "0" : JSON.stringify(val);
|
|
281
|
+
case "string":
|
|
282
|
+
checkNoLoneSurrogates(val);
|
|
283
|
+
return JSON.stringify(val);
|
|
284
|
+
case "object":
|
|
285
|
+
if (val instanceof Uint8Array) {
|
|
286
|
+
if (bytesMode === "reject") throw new DecodeError("BytesRejected", "bytes cannot be encoded with bytesMode='reject'");
|
|
287
|
+
return `{"$bytes":${JSON.stringify(encodeBase64(val))}}`;
|
|
288
|
+
}
|
|
289
|
+
if (Array.isArray(val)) {
|
|
290
|
+
const parts = [];
|
|
291
|
+
for (let i = 0; i < val.length; i++) parts.push(serializeJsonValue(val[i], bytesMode));
|
|
292
|
+
return `[${parts.join(",")}]`;
|
|
293
|
+
}
|
|
294
|
+
if (isPlainObject(val)) {
|
|
295
|
+
const keys = Object.keys(val);
|
|
296
|
+
if (bytesMode === "tagged" && keys.length === 1 && isEscapeKey(keys[0])) {
|
|
297
|
+
const k = keys[0];
|
|
298
|
+
checkNoLoneSurrogates(k);
|
|
299
|
+
return `{"$esc":{${JSON.stringify(k)}:${serializeJsonValue(val[k], bytesMode)}}}`;
|
|
300
|
+
}
|
|
301
|
+
keys.sort();
|
|
302
|
+
const parts = [];
|
|
303
|
+
for (let i = 0; i < keys.length; i++) {
|
|
304
|
+
const k = keys[i];
|
|
305
|
+
checkNoLoneSurrogates(k);
|
|
306
|
+
parts.push(`${JSON.stringify(k)}:${serializeJsonValue(val[k], bytesMode)}`);
|
|
307
|
+
}
|
|
308
|
+
return `{${parts.join(",")}}`;
|
|
309
|
+
}
|
|
310
|
+
throw new DecodeError("InvalidFormat", "unsupported object value in JsonValue");
|
|
311
|
+
default: throw new DecodeError("InvalidFormat", `unsupported value type: ${typeof val}`);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function serializePath(path) {
|
|
315
|
+
const parts = [];
|
|
316
|
+
for (let i = 0; i < path.length; i++) {
|
|
317
|
+
const seg = path[i];
|
|
318
|
+
if (typeof seg === "string") {
|
|
319
|
+
checkNoLoneSurrogates(seg, true);
|
|
320
|
+
parts.push(JSON.stringify(seg));
|
|
321
|
+
} else if (typeof seg === "number" && Number.isSafeInteger(seg) && seg >= 0) parts.push(String(seg));
|
|
322
|
+
else throw new DecodeError("InvalidPath", `invalid path segment: ${String(seg)}`);
|
|
323
|
+
}
|
|
324
|
+
return `[${parts.join(",")}]`;
|
|
325
|
+
}
|
|
326
|
+
function parsePath(raw) {
|
|
327
|
+
if (!Array.isArray(raw)) throw new DecodeError("InvalidPath", "path must be an array");
|
|
328
|
+
const path = [];
|
|
329
|
+
for (let i = 0; i < raw.length; i++) {
|
|
330
|
+
const seg = raw[i];
|
|
331
|
+
if (typeof seg === "string") {
|
|
332
|
+
checkNoLoneSurrogates(seg, true);
|
|
333
|
+
path.push(seg);
|
|
334
|
+
} else if (typeof seg === "number" && Number.isSafeInteger(seg) && seg >= 0) path.push(seg);
|
|
335
|
+
else if (typeof seg === "bigint" && seg >= 0n && seg <= MAX_SAFE_BIG) path.push(Number(seg));
|
|
336
|
+
else throw new DecodeError("InvalidPath", `invalid path segment: ${String(seg)}`);
|
|
337
|
+
}
|
|
338
|
+
return path;
|
|
339
|
+
}
|
|
340
|
+
function parseNonNegSafeInt(raw, field) {
|
|
341
|
+
if (typeof raw === "number" && Number.isSafeInteger(raw) && raw >= 0) return raw;
|
|
342
|
+
if (typeof raw === "bigint" && raw >= 0n && raw <= MAX_SAFE_BIG) return Number(raw);
|
|
343
|
+
throw new DecodeError("InvalidFormat", `field '${field}' must be a non-negative safe integer`);
|
|
344
|
+
}
|
|
345
|
+
function checkEncodeNonNegSafeInt(val, field) {
|
|
346
|
+
if (!Number.isSafeInteger(val) || val < 0) throw new DecodeError("InvalidFormat", `field '${field}' must be a non-negative safe integer`);
|
|
347
|
+
return Object.is(val, -0) ? 0 : val;
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Serializes a {@link JsonPatch} to lossless wire JSON (preserving exact 64-bit `bigint` integers,
|
|
351
|
+
* rejecting non-finite floats / lone surrogates, and encoding `Uint8Array` per `options.bytesMode`).
|
|
352
|
+
* @throws {@link DecodeError} on invalid integers, floats, paths, or bytes.
|
|
353
|
+
*/
|
|
354
|
+
function encodeJson(patch, options = {}) {
|
|
355
|
+
const bytesMode = options.bytesMode ?? "tagged";
|
|
356
|
+
const ops = [];
|
|
357
|
+
for (let i = 0; i < patch.length; i++) {
|
|
358
|
+
const op = patch[i];
|
|
359
|
+
switch (op.op) {
|
|
360
|
+
case "set":
|
|
361
|
+
ops.push(`{"op":"set","path":${serializePath(op.path)},"value":${serializeJsonValue(op.value, bytesMode)}}`);
|
|
362
|
+
break;
|
|
363
|
+
case "unset":
|
|
364
|
+
ops.push(`{"op":"unset","path":${serializePath(op.path)}}`);
|
|
365
|
+
break;
|
|
366
|
+
case "arr_splice": {
|
|
367
|
+
const at = checkEncodeNonNegSafeInt(op.at, "at");
|
|
368
|
+
const del = checkEncodeNonNegSafeInt(op.del, "del");
|
|
369
|
+
if (at + del > Number.MAX_SAFE_INTEGER) throw new DecodeError("InvalidFormat", "arr_splice at + del exceeds MAX_SAFE_INTEGER");
|
|
370
|
+
const items = [];
|
|
371
|
+
for (let j = 0; j < op.items.length; j++) items.push(serializeJsonValue(op.items[j], bytesMode));
|
|
372
|
+
ops.push(`{"op":"arr_splice","path":${serializePath(op.path)},"at":${at},"del":${del},"items":[${items.join(",")}]}`);
|
|
373
|
+
break;
|
|
374
|
+
}
|
|
375
|
+
case "move":
|
|
376
|
+
ops.push(`{"op":"move","from":${serializePath(op.from)},"to":${serializePath(op.to)}}`);
|
|
377
|
+
break;
|
|
378
|
+
case "str_splice": {
|
|
379
|
+
const at = checkEncodeNonNegSafeInt(op.at, "at");
|
|
380
|
+
const del = checkEncodeNonNegSafeInt(op.del, "del");
|
|
381
|
+
if (at + del > Number.MAX_SAFE_INTEGER) throw new DecodeError("InvalidFormat", "str_splice at + del exceeds MAX_SAFE_INTEGER");
|
|
382
|
+
checkNoLoneSurrogates(op.ins);
|
|
383
|
+
ops.push(`{"op":"str_splice","path":${serializePath(op.path)},"at":${at},"del":${del},"ins":${JSON.stringify(op.ins)}}`);
|
|
384
|
+
break;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return `[${ops.join(",")}]`;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Parses wire JSON text back into a validated {@link JsonOp} array, restoring out-of-safe-range integers
|
|
392
|
+
* as `bigint` and `{"$bytes":"..."}` as `Uint8Array` (when `bytesMode` is `"tagged"`).
|
|
393
|
+
* @throws {@link DecodeError} on malformed JSON, unknown op names, or invalid values/paths.
|
|
394
|
+
*/
|
|
395
|
+
function decodeJson(input, options = {}) {
|
|
396
|
+
const bytesMode = options.bytesMode ?? "tagged";
|
|
397
|
+
const root = parseJsonLossless(input);
|
|
398
|
+
if (!Array.isArray(root)) throw new DecodeError("InvalidFormat", "patch root must be a JSON array");
|
|
399
|
+
const out = [];
|
|
400
|
+
for (let i = 0; i < root.length; i++) {
|
|
401
|
+
const item = root[i];
|
|
402
|
+
if (!isPlainObject(item)) throw new DecodeError("InvalidFormat", "each JSON op must be an object");
|
|
403
|
+
const opName = item.op;
|
|
404
|
+
if (typeof opName !== "string") throw new DecodeError("InvalidFormat", "op object missing string 'op' field");
|
|
405
|
+
switch (opName) {
|
|
406
|
+
case "set":
|
|
407
|
+
if (!hasOwn(item, "path")) throw new DecodeError("InvalidFormat", "set missing 'path'");
|
|
408
|
+
if (!hasOwn(item, "value")) throw new DecodeError("InvalidFormat", "set missing 'value'");
|
|
409
|
+
out.push({
|
|
410
|
+
op: "set",
|
|
411
|
+
path: parsePath(item.path),
|
|
412
|
+
value: decodeRawJsonValue(item.value, bytesMode)
|
|
413
|
+
});
|
|
414
|
+
break;
|
|
415
|
+
case "unset":
|
|
416
|
+
if (!hasOwn(item, "path")) throw new DecodeError("InvalidFormat", "unset missing 'path'");
|
|
417
|
+
out.push({
|
|
418
|
+
op: "unset",
|
|
419
|
+
path: parsePath(item.path)
|
|
420
|
+
});
|
|
421
|
+
break;
|
|
422
|
+
case "arr_splice":
|
|
423
|
+
if (!hasOwn(item, "path")) throw new DecodeError("InvalidFormat", "arr_splice missing 'path'");
|
|
424
|
+
if (!Array.isArray(item.items)) throw new DecodeError("InvalidFormat", "arr_splice missing array 'items'");
|
|
425
|
+
out.push({
|
|
426
|
+
op: "arr_splice",
|
|
427
|
+
path: parsePath(item.path),
|
|
428
|
+
at: parseNonNegSafeInt(item.at, "at"),
|
|
429
|
+
del: parseNonNegSafeInt(item.del, "del"),
|
|
430
|
+
items: item.items.map((v) => decodeRawJsonValue(v, bytesMode))
|
|
431
|
+
});
|
|
432
|
+
break;
|
|
433
|
+
case "move":
|
|
434
|
+
if (!hasOwn(item, "from")) throw new DecodeError("InvalidFormat", "move missing 'from'");
|
|
435
|
+
if (!hasOwn(item, "to")) throw new DecodeError("InvalidFormat", "move missing 'to'");
|
|
436
|
+
out.push({
|
|
437
|
+
op: "move",
|
|
438
|
+
from: parsePath(item.from),
|
|
439
|
+
to: parsePath(item.to)
|
|
440
|
+
});
|
|
441
|
+
break;
|
|
442
|
+
case "str_splice":
|
|
443
|
+
if (!hasOwn(item, "path")) throw new DecodeError("InvalidFormat", "str_splice missing 'path'");
|
|
444
|
+
if (typeof item.ins !== "string") throw new DecodeError("InvalidFormat", "str_splice missing string 'ins'");
|
|
445
|
+
checkNoLoneSurrogates(item.ins);
|
|
446
|
+
out.push({
|
|
447
|
+
op: "str_splice",
|
|
448
|
+
path: parsePath(item.path),
|
|
449
|
+
at: parseNonNegSafeInt(item.at, "at"),
|
|
450
|
+
del: parseNonNegSafeInt(item.del, "del"),
|
|
451
|
+
ins: item.ins
|
|
452
|
+
});
|
|
453
|
+
break;
|
|
454
|
+
default: throw new DecodeError("UnknownOpName", `unknown op name: ${opName}`);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return out;
|
|
458
|
+
}
|
|
459
|
+
function normalizeForMsgpack(val) {
|
|
460
|
+
if (val === null || typeof val === "boolean") return val;
|
|
461
|
+
if (typeof val === "string") {
|
|
462
|
+
checkNoLoneSurrogates(val);
|
|
463
|
+
return val;
|
|
464
|
+
}
|
|
465
|
+
if (typeof val === "number") {
|
|
466
|
+
if (!Number.isFinite(val)) throw new DecodeError("NonFiniteFloat", "non-finite float (NaN or Infinity) is forbidden");
|
|
467
|
+
if (Object.is(val, -0)) return 0;
|
|
468
|
+
if (Number.isSafeInteger(val) && (val >= 4294967296 || val < -2147483648)) return BigInt(val);
|
|
469
|
+
return val;
|
|
470
|
+
}
|
|
471
|
+
if (typeof val === "bigint") {
|
|
472
|
+
if (val < I64_MIN || val > U64_MAX) throw new DecodeError("InvalidFormat", `bigint out of i64/u64 range: ${val}`);
|
|
473
|
+
if (val >= -2147483648n && val <= 4294967295n) return Number(val);
|
|
474
|
+
return val;
|
|
475
|
+
}
|
|
476
|
+
if (val instanceof Uint8Array) return val;
|
|
477
|
+
if (Array.isArray(val)) {
|
|
478
|
+
const out = new Array(val.length);
|
|
479
|
+
for (let i = 0; i < val.length; i++) out[i] = normalizeForMsgpack(val[i]);
|
|
480
|
+
return out;
|
|
481
|
+
}
|
|
482
|
+
if (isPlainObject(val)) {
|
|
483
|
+
const keys = Object.keys(val).sort();
|
|
484
|
+
const out = {};
|
|
485
|
+
for (let i = 0; i < keys.length; i++) {
|
|
486
|
+
const k = keys[i];
|
|
487
|
+
checkNoLoneSurrogates(k);
|
|
488
|
+
setOwnProp(out, k, normalizeForMsgpack(val[k]));
|
|
489
|
+
}
|
|
490
|
+
return out;
|
|
491
|
+
}
|
|
492
|
+
throw new DecodeError("InvalidFormat", "unsupported object value in JsonValue");
|
|
493
|
+
}
|
|
494
|
+
function nonNegIntForMsgpack(n) {
|
|
495
|
+
const clean = Object.is(n, -0) ? 0 : n;
|
|
496
|
+
return clean >= 4294967296 ? BigInt(clean) : clean;
|
|
497
|
+
}
|
|
498
|
+
function pathForMsgpack(path) {
|
|
499
|
+
const out = new Array(path.length);
|
|
500
|
+
for (let i = 0; i < path.length; i++) {
|
|
501
|
+
const seg = path[i];
|
|
502
|
+
if (typeof seg === "string") {
|
|
503
|
+
checkNoLoneSurrogates(seg, true);
|
|
504
|
+
out[i] = seg;
|
|
505
|
+
} else if (typeof seg === "number" && Number.isSafeInteger(seg) && seg >= 0) out[i] = nonNegIntForMsgpack(seg);
|
|
506
|
+
else throw new DecodeError("InvalidPath", `invalid path segment: ${String(seg)}`);
|
|
507
|
+
}
|
|
508
|
+
return out;
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Encodes a {@link JsonPatch} into compact binary MessagePack op-tuples (`[opCode, ...]`)
|
|
512
|
+
* compatible with the Rust `loro-json-patch` codec.
|
|
513
|
+
* @throws {@link DecodeError} on invalid paths, values, or integer bounds.
|
|
514
|
+
*/
|
|
515
|
+
function encodeMsgpack(patch) {
|
|
516
|
+
const tuples = new Array(patch.length);
|
|
517
|
+
for (let i = 0; i < patch.length; i++) {
|
|
518
|
+
const op = patch[i];
|
|
519
|
+
switch (op.op) {
|
|
520
|
+
case "set":
|
|
521
|
+
tuples[i] = [
|
|
522
|
+
1,
|
|
523
|
+
pathForMsgpack(op.path),
|
|
524
|
+
normalizeForMsgpack(op.value)
|
|
525
|
+
];
|
|
526
|
+
break;
|
|
527
|
+
case "unset":
|
|
528
|
+
tuples[i] = [2, pathForMsgpack(op.path)];
|
|
529
|
+
break;
|
|
530
|
+
case "arr_splice": {
|
|
531
|
+
const at = checkEncodeNonNegSafeInt(op.at, "at");
|
|
532
|
+
const del = checkEncodeNonNegSafeInt(op.del, "del");
|
|
533
|
+
if (at + del > Number.MAX_SAFE_INTEGER) throw new DecodeError("InvalidFormat", "arr_splice at + del exceeds MAX_SAFE_INTEGER");
|
|
534
|
+
tuples[i] = [
|
|
535
|
+
3,
|
|
536
|
+
pathForMsgpack(op.path),
|
|
537
|
+
nonNegIntForMsgpack(at),
|
|
538
|
+
nonNegIntForMsgpack(del),
|
|
539
|
+
op.items.map((item) => normalizeForMsgpack(item))
|
|
540
|
+
];
|
|
541
|
+
break;
|
|
542
|
+
}
|
|
543
|
+
case "move":
|
|
544
|
+
tuples[i] = [
|
|
545
|
+
4,
|
|
546
|
+
pathForMsgpack(op.from),
|
|
547
|
+
pathForMsgpack(op.to)
|
|
548
|
+
];
|
|
549
|
+
break;
|
|
550
|
+
case "str_splice": {
|
|
551
|
+
const at = checkEncodeNonNegSafeInt(op.at, "at");
|
|
552
|
+
const del = checkEncodeNonNegSafeInt(op.del, "del");
|
|
553
|
+
if (at + del > Number.MAX_SAFE_INTEGER) throw new DecodeError("InvalidFormat", "str_splice at + del exceeds MAX_SAFE_INTEGER");
|
|
554
|
+
checkNoLoneSurrogates(op.ins);
|
|
555
|
+
tuples[i] = [
|
|
556
|
+
5,
|
|
557
|
+
pathForMsgpack(op.path),
|
|
558
|
+
nonNegIntForMsgpack(at),
|
|
559
|
+
nonNegIntForMsgpack(del),
|
|
560
|
+
op.ins
|
|
561
|
+
];
|
|
562
|
+
break;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
return encode(tuples, {
|
|
567
|
+
useBigInt64: true,
|
|
568
|
+
sortKeys: true
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
function decodeMsgpackRaw(bytes) {
|
|
572
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
573
|
+
const total = bytes.byteLength;
|
|
574
|
+
let pos = 0;
|
|
575
|
+
function need(n) {
|
|
576
|
+
if (pos + n > total) throw new DecodeError("MessagePack", "unexpected end of MessagePack input");
|
|
577
|
+
}
|
|
578
|
+
function readU8() {
|
|
579
|
+
need(1);
|
|
580
|
+
return view.getUint8(pos++);
|
|
581
|
+
}
|
|
582
|
+
function readU16() {
|
|
583
|
+
need(2);
|
|
584
|
+
const v = view.getUint16(pos, false);
|
|
585
|
+
pos += 2;
|
|
586
|
+
return v;
|
|
587
|
+
}
|
|
588
|
+
function readU32() {
|
|
589
|
+
need(4);
|
|
590
|
+
const v = view.getUint32(pos, false);
|
|
591
|
+
pos += 4;
|
|
592
|
+
return v;
|
|
593
|
+
}
|
|
594
|
+
function readI8() {
|
|
595
|
+
need(1);
|
|
596
|
+
return view.getInt8(pos++);
|
|
597
|
+
}
|
|
598
|
+
function readI16() {
|
|
599
|
+
need(2);
|
|
600
|
+
const v = view.getInt16(pos, false);
|
|
601
|
+
pos += 2;
|
|
602
|
+
return v;
|
|
603
|
+
}
|
|
604
|
+
function readI32() {
|
|
605
|
+
need(4);
|
|
606
|
+
const v = view.getInt32(pos, false);
|
|
607
|
+
pos += 4;
|
|
608
|
+
return v;
|
|
609
|
+
}
|
|
610
|
+
function readStr(byteLen) {
|
|
611
|
+
need(byteLen);
|
|
612
|
+
const slice = bytes.subarray(pos, pos + byteLen);
|
|
613
|
+
pos += byteLen;
|
|
614
|
+
try {
|
|
615
|
+
return UTF8_DECODER.decode(slice);
|
|
616
|
+
} catch (err) {
|
|
617
|
+
throw new DecodeError("MessagePack", `invalid UTF-8 string in MessagePack: ${String(err)}`);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
function readBin(byteLen) {
|
|
621
|
+
need(byteLen);
|
|
622
|
+
const out = bytes.slice(pos, pos + byteLen);
|
|
623
|
+
pos += byteLen;
|
|
624
|
+
return out;
|
|
625
|
+
}
|
|
626
|
+
function readArray(len) {
|
|
627
|
+
const arr = new Array(len);
|
|
628
|
+
for (let i = 0; i < len; i++) arr[i] = readValue();
|
|
629
|
+
return arr;
|
|
630
|
+
}
|
|
631
|
+
function readMap(len) {
|
|
632
|
+
const obj = {};
|
|
633
|
+
for (let i = 0; i < len; i++) {
|
|
634
|
+
const k = readValue();
|
|
635
|
+
if (typeof k !== "string") throw new DecodeError("InvalidFormat", "map keys must be strings");
|
|
636
|
+
setOwnProp(obj, k, readValue());
|
|
637
|
+
}
|
|
638
|
+
return obj;
|
|
639
|
+
}
|
|
640
|
+
function readValue() {
|
|
641
|
+
const b = readU8();
|
|
642
|
+
if (b <= 127) return b;
|
|
643
|
+
if (b >= 224) return b - 256;
|
|
644
|
+
if ((b & 240) === 128) return readMap(b & 15);
|
|
645
|
+
if ((b & 240) === 144) return readArray(b & 15);
|
|
646
|
+
if ((b & 224) === 160) return readStr(b & 31);
|
|
647
|
+
switch (b) {
|
|
648
|
+
case 192: return null;
|
|
649
|
+
case 193: throw new DecodeError("MessagePack", "encountered reserved 0xc1 byte");
|
|
650
|
+
case 194: return false;
|
|
651
|
+
case 195: return true;
|
|
652
|
+
case 196: return readBin(readU8());
|
|
653
|
+
case 197: return readBin(readU16());
|
|
654
|
+
case 198: return readBin(readU32());
|
|
655
|
+
case 199: {
|
|
656
|
+
const len = readU8();
|
|
657
|
+
const extType = readI8();
|
|
658
|
+
need(len);
|
|
659
|
+
throw new DecodeError("UnsupportedExtension", `custom MessagePack extension (${extType}) is forbidden`);
|
|
660
|
+
}
|
|
661
|
+
case 200: {
|
|
662
|
+
const len = readU16();
|
|
663
|
+
const extType = readI8();
|
|
664
|
+
need(len);
|
|
665
|
+
throw new DecodeError("UnsupportedExtension", `custom MessagePack extension (${extType}) is forbidden`);
|
|
666
|
+
}
|
|
667
|
+
case 201: {
|
|
668
|
+
const len = readU32();
|
|
669
|
+
const extType = readI8();
|
|
670
|
+
need(len);
|
|
671
|
+
throw new DecodeError("UnsupportedExtension", `custom MessagePack extension (${extType}) is forbidden`);
|
|
672
|
+
}
|
|
673
|
+
case 202: {
|
|
674
|
+
need(4);
|
|
675
|
+
const f = view.getFloat32(pos, false);
|
|
676
|
+
pos += 4;
|
|
677
|
+
if (!Number.isFinite(f)) throw new DecodeError("NonFiniteFloat", "non-finite float (NaN or Infinity) is forbidden");
|
|
678
|
+
return new FloatToken(Object.is(f, -0) ? 0 : f);
|
|
679
|
+
}
|
|
680
|
+
case 203: {
|
|
681
|
+
need(8);
|
|
682
|
+
const f = view.getFloat64(pos, false);
|
|
683
|
+
pos += 8;
|
|
684
|
+
if (!Number.isFinite(f)) throw new DecodeError("NonFiniteFloat", "non-finite float (NaN or Infinity) is forbidden");
|
|
685
|
+
return new FloatToken(Object.is(f, -0) ? 0 : f);
|
|
686
|
+
}
|
|
687
|
+
case 204: return readU8();
|
|
688
|
+
case 205: return readU16();
|
|
689
|
+
case 206: return readU32();
|
|
690
|
+
case 207: {
|
|
691
|
+
need(8);
|
|
692
|
+
const u = view.getBigUint64(pos, false);
|
|
693
|
+
pos += 8;
|
|
694
|
+
return u <= MAX_SAFE_BIG ? Number(u) : u;
|
|
695
|
+
}
|
|
696
|
+
case 208: return readI8();
|
|
697
|
+
case 209: return readI16();
|
|
698
|
+
case 210: return readI32();
|
|
699
|
+
case 211: {
|
|
700
|
+
need(8);
|
|
701
|
+
const i = view.getBigInt64(pos, false);
|
|
702
|
+
pos += 8;
|
|
703
|
+
return i >= MIN_SAFE_BIG && i <= MAX_SAFE_BIG ? Number(i) : i;
|
|
704
|
+
}
|
|
705
|
+
case 212:
|
|
706
|
+
case 213:
|
|
707
|
+
case 214:
|
|
708
|
+
case 215:
|
|
709
|
+
case 216: {
|
|
710
|
+
const extLen = 1 << b - 212;
|
|
711
|
+
const extType = readI8();
|
|
712
|
+
need(extLen);
|
|
713
|
+
throw new DecodeError("UnsupportedExtension", `custom MessagePack extension (${extType}) is forbidden`);
|
|
714
|
+
}
|
|
715
|
+
case 217: return readStr(readU8());
|
|
716
|
+
case 218: return readStr(readU16());
|
|
717
|
+
case 219: return readStr(readU32());
|
|
718
|
+
case 220: return readArray(readU16());
|
|
719
|
+
case 221: return readArray(readU32());
|
|
720
|
+
case 222: return readMap(readU16());
|
|
721
|
+
case 223: return readMap(readU32());
|
|
722
|
+
default: throw new DecodeError("MessagePack", `unexpected MessagePack tag 0x${b.toString(16)}`);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
const root = readValue();
|
|
726
|
+
if (pos !== total) throw new DecodeError("InvalidFormat", "trailing bytes after msgpack patch");
|
|
727
|
+
return root;
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Decodes compact binary MessagePack op-tuples back into validated {@link JsonOp} operations.
|
|
731
|
+
* @throws {@link DecodeError} on unknown op codes, unsupported MsgPack extensions, or trailing bytes.
|
|
732
|
+
*/
|
|
733
|
+
function decodeMsgpack(bytes) {
|
|
734
|
+
const root = decodeMsgpackRaw(bytes);
|
|
735
|
+
if (!Array.isArray(root)) throw new DecodeError("InvalidFormat", "msgpack patch root must be an array");
|
|
736
|
+
const out = [];
|
|
737
|
+
for (let i = 0; i < root.length; i++) {
|
|
738
|
+
const tuple = root[i];
|
|
739
|
+
if (!Array.isArray(tuple) || tuple.length === 0) throw new DecodeError("InvalidFormat", "each msgpack op must be a non-empty array");
|
|
740
|
+
const rawCode = tuple[0];
|
|
741
|
+
let code;
|
|
742
|
+
if (typeof rawCode === "number" && Number.isInteger(rawCode)) code = rawCode;
|
|
743
|
+
else if (typeof rawCode === "bigint" && rawCode >= I64_MIN && rawCode <= I64_MAX) code = rawCode;
|
|
744
|
+
else throw new DecodeError("InvalidFormat", "op code must be an integer");
|
|
745
|
+
if (code === 1 || code === 1n) {
|
|
746
|
+
if (tuple.length < 3) throw new DecodeError("InvalidFormat", "op 1 (set) requires at least 3 elements");
|
|
747
|
+
out.push({
|
|
748
|
+
op: "set",
|
|
749
|
+
path: parsePath(tuple[1]),
|
|
750
|
+
value: decodeRawJsonValue(tuple[2], "reject")
|
|
751
|
+
});
|
|
752
|
+
} else if (code === 2 || code === 2n) {
|
|
753
|
+
if (tuple.length < 2) throw new DecodeError("InvalidFormat", "op 2 (unset) requires at least 2 elements");
|
|
754
|
+
out.push({
|
|
755
|
+
op: "unset",
|
|
756
|
+
path: parsePath(tuple[1])
|
|
757
|
+
});
|
|
758
|
+
} else if (code === 3 || code === 3n) {
|
|
759
|
+
if (tuple.length < 5) throw new DecodeError("InvalidFormat", "op 3 (arr_splice) requires at least 5 elements");
|
|
760
|
+
const itemsRaw = tuple[4];
|
|
761
|
+
if (!Array.isArray(itemsRaw)) throw new DecodeError("InvalidFormat", "op 3 (arr_splice) items must be an array");
|
|
762
|
+
out.push({
|
|
763
|
+
op: "arr_splice",
|
|
764
|
+
path: parsePath(tuple[1]),
|
|
765
|
+
at: parseNonNegSafeInt(tuple[2], "at"),
|
|
766
|
+
del: parseNonNegSafeInt(tuple[3], "del"),
|
|
767
|
+
items: itemsRaw.map((v) => decodeRawJsonValue(v, "reject"))
|
|
768
|
+
});
|
|
769
|
+
} else if (code === 4 || code === 4n) {
|
|
770
|
+
if (tuple.length < 3) throw new DecodeError("InvalidFormat", "op 4 (move) requires at least 3 elements");
|
|
771
|
+
out.push({
|
|
772
|
+
op: "move",
|
|
773
|
+
from: parsePath(tuple[1]),
|
|
774
|
+
to: parsePath(tuple[2])
|
|
775
|
+
});
|
|
776
|
+
} else if (code === 5 || code === 5n) {
|
|
777
|
+
if (tuple.length < 5) throw new DecodeError("InvalidFormat", "op 5 (str_splice) requires at least 5 elements");
|
|
778
|
+
const ins = tuple[4];
|
|
779
|
+
if (typeof ins !== "string") throw new DecodeError("InvalidFormat", "op 5 (str_splice) ins must be a string");
|
|
780
|
+
checkNoLoneSurrogates(ins);
|
|
781
|
+
out.push({
|
|
782
|
+
op: "str_splice",
|
|
783
|
+
path: parsePath(tuple[1]),
|
|
784
|
+
at: parseNonNegSafeInt(tuple[2], "at"),
|
|
785
|
+
del: parseNonNegSafeInt(tuple[3], "del"),
|
|
786
|
+
ins
|
|
787
|
+
});
|
|
788
|
+
} else throw new DecodeError("UnknownOp", `unknown op code: ${String(code)}`, code);
|
|
789
|
+
}
|
|
790
|
+
return out;
|
|
791
|
+
}
|
|
792
|
+
/**
|
|
793
|
+
* Encodes one plain JSON value as MessagePack with the same value rules as the compact patch codec
|
|
794
|
+
* (sorted object keys, minimal integer widths, i64/u64 as bigint, `Uint8Array` as `bin`, no extension types).
|
|
795
|
+
*/
|
|
796
|
+
function encodeMsgpackValue(value) {
|
|
797
|
+
return encode(normalizeForMsgpack(value), {
|
|
798
|
+
useBigInt64: true,
|
|
799
|
+
sortKeys: true
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Decodes one MessagePack value with the same value rules as the compact patch codec: integers in the
|
|
804
|
+
* safe range are numbers, larger i64/u64 are bigint, `bin` is `Uint8Array`, extension types, non-finite
|
|
805
|
+
* floats and trailing bytes are rejected with `DecodeError`.
|
|
806
|
+
*/
|
|
807
|
+
function decodeMsgpackValue(bytes) {
|
|
808
|
+
return decodeRawJsonValue(decodeMsgpackRaw(bytes), "reject");
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
//#endregion
|
|
812
|
+
//#region src/compact.ts
|
|
813
|
+
function isPathValid(path) {
|
|
814
|
+
for (let i = 0; i < path.length; i++) {
|
|
815
|
+
const seg = path[i];
|
|
816
|
+
if (typeof seg === "string") {
|
|
817
|
+
if (hasLoneSurrogates(seg)) return false;
|
|
818
|
+
} else if (typeof seg !== "number" || !Number.isSafeInteger(seg) || seg < 0) return false;
|
|
819
|
+
}
|
|
820
|
+
return true;
|
|
821
|
+
}
|
|
822
|
+
function isValueValid(val) {
|
|
823
|
+
try {
|
|
824
|
+
validateJsonValue(val, 0);
|
|
825
|
+
return true;
|
|
826
|
+
} catch {
|
|
827
|
+
return false;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
function isOpStaticallyValid(op) {
|
|
831
|
+
switch (op.op) {
|
|
832
|
+
case "set": return isPathValid(op.path) && isValueValid(op.value);
|
|
833
|
+
case "unset": return op.path.length > 0 && typeof op.path[op.path.length - 1] === "string" && isPathValid(op.path);
|
|
834
|
+
case "arr_splice": return isPathValid(op.path) && Number.isSafeInteger(op.at) && op.at >= 0 && Number.isSafeInteger(op.del) && op.del >= 0 && op.at + op.del <= Number.MAX_SAFE_INTEGER && op.items.every(isValueValid);
|
|
835
|
+
case "move": return op.from.length > 0 && op.to.length > 0 && isPathValid(op.from) && isPathValid(op.to);
|
|
836
|
+
case "str_splice": return isPathValid(op.path) && Number.isSafeInteger(op.at) && op.at >= 0 && Number.isSafeInteger(op.del) && op.del >= 0 && op.at + op.del <= Number.MAX_SAFE_INTEGER && !hasLoneSurrogates(op.ins);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
function opTargetPath(op) {
|
|
840
|
+
switch (op.op) {
|
|
841
|
+
case "set":
|
|
842
|
+
case "unset":
|
|
843
|
+
case "arr_splice":
|
|
844
|
+
case "str_splice": return op.path;
|
|
845
|
+
case "move": return;
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
function pathPrefixKeys(path) {
|
|
849
|
+
const keys = new Array(path.length + 1);
|
|
850
|
+
let acc = "";
|
|
851
|
+
keys[0] = acc;
|
|
852
|
+
for (let i = 0; i < path.length; i++) {
|
|
853
|
+
const seg = path[i];
|
|
854
|
+
if (typeof seg === "string") acc += `k${seg.length}:${seg}`;
|
|
855
|
+
else acc += `i${seg};`;
|
|
856
|
+
keys[i + 1] = acc;
|
|
857
|
+
}
|
|
858
|
+
return keys;
|
|
859
|
+
}
|
|
860
|
+
var ConflictTracker = class {
|
|
861
|
+
barrierIdx = -1;
|
|
862
|
+
lastExact = /* @__PURE__ */ new Map();
|
|
863
|
+
lastTouch = /* @__PURE__ */ new Map();
|
|
864
|
+
maxDescendant = /* @__PURE__ */ new Map();
|
|
865
|
+
recordTouch(path, idx) {
|
|
866
|
+
const keys = pathPrefixKeys(path);
|
|
867
|
+
this.lastTouch.set(keys[keys.length - 1], idx);
|
|
868
|
+
for (let len = 0; len < keys.length - 1; len++) this.maxDescendant.set(keys[len], idx);
|
|
869
|
+
}
|
|
870
|
+
recordOp(idx, op, valid) {
|
|
871
|
+
if (!valid) {
|
|
872
|
+
this.barrierIdx = idx;
|
|
873
|
+
return;
|
|
874
|
+
}
|
|
875
|
+
if (op.op === "move") {
|
|
876
|
+
const fp = op.from.length > 0 && typeof op.from[op.from.length - 1] === "number" ? op.from.slice(0, -1) : op.from;
|
|
877
|
+
const tp = op.to.length > 0 && typeof op.to[op.to.length - 1] === "number" ? op.to.slice(0, -1) : op.to;
|
|
878
|
+
this.recordTouch(fp, idx);
|
|
879
|
+
this.recordTouch(tp, idx);
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
const keys = pathPrefixKeys(opTargetPath(op));
|
|
883
|
+
this.lastExact.set(keys[keys.length - 1], idx);
|
|
884
|
+
this.lastTouch.set(keys[keys.length - 1], idx);
|
|
885
|
+
for (let len = 0; len < keys.length - 1; len++) this.maxDescendant.set(keys[len], idx);
|
|
886
|
+
}
|
|
887
|
+
foldableCandidate(path) {
|
|
888
|
+
const keys = pathPrefixKeys(path);
|
|
889
|
+
const fullKey = keys[keys.length - 1];
|
|
890
|
+
const cand = this.lastExact.get(fullKey);
|
|
891
|
+
if (cand === void 0) return void 0;
|
|
892
|
+
if (this.barrierIdx > cand) return void 0;
|
|
893
|
+
for (let len = 0; len < keys.length; len++) {
|
|
894
|
+
const tIdx = this.lastTouch.get(keys[len]);
|
|
895
|
+
if (tIdx !== void 0 && tIdx > cand) return void 0;
|
|
896
|
+
}
|
|
897
|
+
const dIdx = this.maxDescendant.get(fullKey);
|
|
898
|
+
if (dIdx !== void 0 && dIdx > cand) return void 0;
|
|
899
|
+
return cand;
|
|
900
|
+
}
|
|
901
|
+
};
|
|
902
|
+
function tryMergeStrSplice(op1, op2) {
|
|
903
|
+
if (!pathsEqual(op1.path, op2.path)) return void 0;
|
|
904
|
+
const end1InPost = op1.at + op1.ins.length;
|
|
905
|
+
const end2 = op2.at + op2.del;
|
|
906
|
+
if (end1InPost > Number.MAX_SAFE_INTEGER || end2 > Number.MAX_SAFE_INTEGER) return;
|
|
907
|
+
if (op2.at === end1InPost) {
|
|
908
|
+
const newDel = op1.del + op2.del;
|
|
909
|
+
if (newDel > Number.MAX_SAFE_INTEGER) return void 0;
|
|
910
|
+
return {
|
|
911
|
+
op: "str_splice",
|
|
912
|
+
path: op1.path,
|
|
913
|
+
at: op1.at,
|
|
914
|
+
del: newDel,
|
|
915
|
+
ins: op1.ins + op2.ins
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
if (op2.at >= op1.at && end2 <= end1InPost) {
|
|
919
|
+
const localAt = op2.at - op1.at;
|
|
920
|
+
const localEnd = end2 - op1.at;
|
|
921
|
+
try {
|
|
922
|
+
assertValidUtf16Boundary(op1.ins, localAt, 0);
|
|
923
|
+
assertValidUtf16Boundary(op1.ins, localEnd, 0);
|
|
924
|
+
} catch {
|
|
925
|
+
return;
|
|
926
|
+
}
|
|
927
|
+
return {
|
|
928
|
+
op: "str_splice",
|
|
929
|
+
path: op1.path,
|
|
930
|
+
at: op1.at,
|
|
931
|
+
del: op1.del,
|
|
932
|
+
ins: op1.ins.slice(0, localAt) + op2.ins + op1.ins.slice(localEnd)
|
|
933
|
+
};
|
|
934
|
+
}
|
|
935
|
+
if (op2.at >= op1.at && op2.at <= end1InPost && end2 > end1InPost) {
|
|
936
|
+
const localAt = op2.at - op1.at;
|
|
937
|
+
try {
|
|
938
|
+
assertValidUtf16Boundary(op1.ins, localAt, 0);
|
|
939
|
+
} catch {
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
const extraDel = end2 - end1InPost;
|
|
943
|
+
const newDel = op1.del + extraDel;
|
|
944
|
+
if (newDel > Number.MAX_SAFE_INTEGER) return void 0;
|
|
945
|
+
return {
|
|
946
|
+
op: "str_splice",
|
|
947
|
+
path: op1.path,
|
|
948
|
+
at: op1.at,
|
|
949
|
+
del: newDel,
|
|
950
|
+
ins: op1.ins.slice(0, localAt) + op2.ins
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
if (op2.at <= op1.at && end2 >= op1.at) if (end2 <= end1InPost) {
|
|
954
|
+
const overlap = end2 - op1.at;
|
|
955
|
+
try {
|
|
956
|
+
assertValidUtf16Boundary(op1.ins, overlap, 0);
|
|
957
|
+
} catch {
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
const extraDel = op1.at - op2.at;
|
|
961
|
+
const newDel = op1.del + extraDel;
|
|
962
|
+
if (newDel > Number.MAX_SAFE_INTEGER) return void 0;
|
|
963
|
+
return {
|
|
964
|
+
op: "str_splice",
|
|
965
|
+
path: op1.path,
|
|
966
|
+
at: op2.at,
|
|
967
|
+
del: newDel,
|
|
968
|
+
ins: op2.ins + op1.ins.slice(overlap)
|
|
969
|
+
};
|
|
970
|
+
} else {
|
|
971
|
+
const extraDel = end2 - end1InPost + (op1.at - op2.at);
|
|
972
|
+
const newDel = op1.del + extraDel;
|
|
973
|
+
if (newDel > Number.MAX_SAFE_INTEGER) return void 0;
|
|
974
|
+
return {
|
|
975
|
+
op: "str_splice",
|
|
976
|
+
path: op1.path,
|
|
977
|
+
at: op2.at,
|
|
978
|
+
del: newDel,
|
|
979
|
+
ins: op2.ins
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
function tryFoldSamePath(prev, next) {
|
|
984
|
+
if (prev.op === "str_splice" && next.op === "str_splice") return tryMergeStrSplice(prev, next);
|
|
985
|
+
if (prev.op === "set" && next.op === "set" && pathsEqual(prev.path, next.path)) return {
|
|
986
|
+
op: "set",
|
|
987
|
+
path: next.path,
|
|
988
|
+
value: validateAndNormalizeJsonValue(next.value, 0)
|
|
989
|
+
};
|
|
990
|
+
if (prev.op === "set" && next.op === "unset" && next.path.length > 0 && typeof next.path[next.path.length - 1] === "string" && pathsEqual(prev.path, next.path)) return next;
|
|
991
|
+
if (prev.op === "unset" && next.op === "set" && next.path.length > 0 && typeof next.path[next.path.length - 1] === "string" && pathsEqual(prev.path, next.path)) return {
|
|
992
|
+
op: "set",
|
|
993
|
+
path: next.path,
|
|
994
|
+
value: validateAndNormalizeJsonValue(next.value, 0)
|
|
995
|
+
};
|
|
996
|
+
if (prev.op === "unset" && next.op === "unset" && pathsEqual(prev.path, next.path)) return prev;
|
|
997
|
+
if (prev.op === "set" && next.op === "str_splice" && pathsEqual(prev.path, next.path) && typeof prev.value === "string") try {
|
|
998
|
+
const nextVal = applyOp(prev.value, {
|
|
999
|
+
...next,
|
|
1000
|
+
path: []
|
|
1001
|
+
}, 0);
|
|
1002
|
+
return {
|
|
1003
|
+
op: "set",
|
|
1004
|
+
path: prev.path,
|
|
1005
|
+
value: nextVal
|
|
1006
|
+
};
|
|
1007
|
+
} catch {
|
|
1008
|
+
return;
|
|
1009
|
+
}
|
|
1010
|
+
if (prev.op === "set" && next.op === "arr_splice" && pathsEqual(prev.path, next.path) && Array.isArray(prev.value)) try {
|
|
1011
|
+
const nextVal = applyOp(prev.value, {
|
|
1012
|
+
...next,
|
|
1013
|
+
path: []
|
|
1014
|
+
}, 0);
|
|
1015
|
+
return {
|
|
1016
|
+
op: "set",
|
|
1017
|
+
path: prev.path,
|
|
1018
|
+
value: nextVal
|
|
1019
|
+
};
|
|
1020
|
+
} catch {
|
|
1021
|
+
return;
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
/**
|
|
1025
|
+
* Stateless O(M) compactor for slow consumers and streaming patches.
|
|
1026
|
+
* Preserves unvalidated non-root prefixes and statically invalid ops as barriers.
|
|
1027
|
+
*/
|
|
1028
|
+
function compact(patch) {
|
|
1029
|
+
let hasRootSnap = false;
|
|
1030
|
+
let rootSnap = null;
|
|
1031
|
+
const out = [];
|
|
1032
|
+
const tracker = new ConflictTracker();
|
|
1033
|
+
for (let i = 0; i < patch.length; i++) {
|
|
1034
|
+
const op = patch[i];
|
|
1035
|
+
if (!isOpStaticallyValid(op)) {
|
|
1036
|
+
if (hasRootSnap) {
|
|
1037
|
+
const snapOp = {
|
|
1038
|
+
op: "set",
|
|
1039
|
+
path: [],
|
|
1040
|
+
value: rootSnap
|
|
1041
|
+
};
|
|
1042
|
+
tracker.recordOp(out.length, snapOp, true);
|
|
1043
|
+
out.push(snapOp);
|
|
1044
|
+
hasRootSnap = false;
|
|
1045
|
+
}
|
|
1046
|
+
tracker.recordOp(out.length, op, false);
|
|
1047
|
+
out.push(op);
|
|
1048
|
+
continue;
|
|
1049
|
+
}
|
|
1050
|
+
if (op.op === "set" && op.path.length === 0) {
|
|
1051
|
+
hasRootSnap = true;
|
|
1052
|
+
rootSnap = validateAndNormalizeJsonValue(op.value, i);
|
|
1053
|
+
continue;
|
|
1054
|
+
}
|
|
1055
|
+
if (hasRootSnap) try {
|
|
1056
|
+
rootSnap = applyOp(rootSnap, op, i);
|
|
1057
|
+
continue;
|
|
1058
|
+
} catch {
|
|
1059
|
+
const snapOp = {
|
|
1060
|
+
op: "set",
|
|
1061
|
+
path: [],
|
|
1062
|
+
value: rootSnap
|
|
1063
|
+
};
|
|
1064
|
+
tracker.recordOp(out.length, snapOp, true);
|
|
1065
|
+
out.push(snapOp);
|
|
1066
|
+
hasRootSnap = false;
|
|
1067
|
+
tracker.recordOp(out.length, op, true);
|
|
1068
|
+
out.push(op);
|
|
1069
|
+
continue;
|
|
1070
|
+
}
|
|
1071
|
+
let folded = false;
|
|
1072
|
+
const path = opTargetPath(op);
|
|
1073
|
+
if (path !== void 0) {
|
|
1074
|
+
const candIdx = tracker.foldableCandidate(path);
|
|
1075
|
+
if (candIdx !== void 0) {
|
|
1076
|
+
const merged = tryFoldSamePath(out[candIdx], op);
|
|
1077
|
+
if (merged) {
|
|
1078
|
+
out[candIdx] = merged;
|
|
1079
|
+
folded = true;
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
if (!folded) {
|
|
1084
|
+
tracker.recordOp(out.length, op, true);
|
|
1085
|
+
out.push(op);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
if (hasRootSnap) out.push({
|
|
1089
|
+
op: "set",
|
|
1090
|
+
path: [],
|
|
1091
|
+
value: rootSnap
|
|
1092
|
+
});
|
|
1093
|
+
return out;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
//#endregion
|
|
1097
|
+
export { ANY_REST_SEG, ANY_SEG, ApplyError, DecodeError, apply, applyOp, assertNoLoneSurrogates, assertValidUtf16Boundary, assertValidUtf16Range, compact, decodeJson, decodeMsgpack, decodeMsgpackValue, diff, diffStringAt, encodeJson, encodeMsgpack, encodeMsgpackValue, isPlainObject, lisMask, lisMovePairs, numbersEqual, pathsEqual, pathsOverlap, patternMatches, validateJsonValue, valuesEqual };
|