seroval 1.7.10 → 1.8.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.
Files changed (73) hide show
  1. package/dist/dev/index.cjs +58 -3893
  2. package/dist/dev/index.d.cts +5 -834
  3. package/dist/dev/index.d.ts +5 -834
  4. package/dist/dev/index.js +4 -3847
  5. package/dist/dev/read-Bn_ffmiS.d.ts +14 -0
  6. package/dist/dev/read-CfSVIjp6.js +455 -0
  7. package/dist/dev/read-CgzYPh_Q.d.cts +14 -0
  8. package/dist/dev/read-DvIuZ2yx.cjs +478 -0
  9. package/dist/dev/read.cjs +45 -0
  10. package/dist/dev/read.d.cts +17 -0
  11. package/dist/dev/read.d.ts +17 -0
  12. package/dist/dev/read.js +3 -0
  13. package/dist/dev/shared-Cf-Bmoy-.js +1010 -0
  14. package/dist/dev/shared-DTMVoS-y.d.ts +749 -0
  15. package/dist/dev/shared-DWx3Bwb6.cjs +1410 -0
  16. package/dist/dev/shared-Dju99SLx.d.cts +749 -0
  17. package/dist/dev/shared.cjs +40 -0
  18. package/dist/dev/shared.d.cts +2 -0
  19. package/dist/dev/shared.d.ts +2 -0
  20. package/dist/dev/shared.js +1 -0
  21. package/dist/dev/typed-array-C3haUQv_.js +72 -0
  22. package/dist/dev/typed-array-DUH_YsNc.cjs +101 -0
  23. package/dist/dev/validator-CxDhXc0k.d.cts +28 -0
  24. package/dist/dev/validator-CxDhXc0k.d.ts +28 -0
  25. package/dist/dev/validator.cjs +54 -0
  26. package/dist/dev/validator.d.cts +2 -0
  27. package/dist/dev/validator.d.ts +2 -0
  28. package/dist/dev/validator.js +45 -0
  29. package/dist/dev/write-BKJsV31u.js +2354 -0
  30. package/dist/dev/write-C0KqlAXN.d.ts +86 -0
  31. package/dist/dev/write-DGOp2jqo.cjs +2425 -0
  32. package/dist/dev/write-KxJKA4_p.d.cts +86 -0
  33. package/dist/dev/write.cjs +54 -0
  34. package/dist/dev/write.d.cts +4 -0
  35. package/dist/dev/write.d.ts +4 -0
  36. package/dist/dev/write.js +3 -0
  37. package/dist/index.cjs +58 -3877
  38. package/dist/index.d.cts +5 -834
  39. package/dist/index.d.ts +5 -834
  40. package/dist/index.js +4 -3831
  41. package/dist/read-Bn_ffmiS.d.ts +14 -0
  42. package/dist/read-CD88YElZ.cjs +478 -0
  43. package/dist/read-CSKXLr9t.js +455 -0
  44. package/dist/read-CgzYPh_Q.d.cts +14 -0
  45. package/dist/read.cjs +45 -0
  46. package/dist/read.d.cts +17 -0
  47. package/dist/read.d.ts +17 -0
  48. package/dist/read.js +3 -0
  49. package/dist/shared-DJIVyqa9.js +994 -0
  50. package/dist/shared-DTMVoS-y.d.ts +749 -0
  51. package/dist/shared-Dju99SLx.d.cts +749 -0
  52. package/dist/shared-u-KYXAax.cjs +1394 -0
  53. package/dist/shared.cjs +40 -0
  54. package/dist/shared.d.cts +2 -0
  55. package/dist/shared.d.ts +2 -0
  56. package/dist/shared.js +1 -0
  57. package/dist/typed-array-BWH0IKxT.js +72 -0
  58. package/dist/typed-array-BkSwWNFI.cjs +101 -0
  59. package/dist/validator-CxDhXc0k.d.cts +28 -0
  60. package/dist/validator-CxDhXc0k.d.ts +28 -0
  61. package/dist/validator.cjs +54 -0
  62. package/dist/validator.d.cts +2 -0
  63. package/dist/validator.d.ts +2 -0
  64. package/dist/validator.js +45 -0
  65. package/dist/write-B_hZaAwC.js +2354 -0
  66. package/dist/write-C0KqlAXN.d.ts +86 -0
  67. package/dist/write-CMi0CxOu.cjs +2425 -0
  68. package/dist/write-KxJKA4_p.d.cts +86 -0
  69. package/dist/write.cjs +54 -0
  70. package/dist/write.d.cts +4 -0
  71. package/dist/write.d.ts +4 -0
  72. package/dist/write.js +3 -0
  73. package/package.json +97 -1
@@ -1,3894 +1,59 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region src/core/compat.ts
3
- /**
4
- * Public feature bits for `disabledFeatures`. Stays a runtime `enum` so the
5
- * published declaration is unchanged for consumers. Its values must match
6
- * the internal bits (checked by test/feature.test.ts).
7
- */
8
- let Feature = /* @__PURE__ */ function(Feature) {
9
- Feature[Feature["AggregateError"] = 1] = "AggregateError";
10
- /**
11
- * @deprecated Has no effect. Output follows the syntax of the build seroval
12
- * runs in: arrow functions, or `function` expressions in an ES5 build.
13
- */
14
- Feature[Feature["ArrowFunction"] = 2] = "ArrowFunction";
15
- Feature[Feature["ErrorPrototypeStack"] = 4] = "ErrorPrototypeStack";
16
- Feature[Feature["ObjectAssign"] = 8] = "ObjectAssign";
17
- Feature[Feature["BigIntTypedArray"] = 16] = "BigIntTypedArray";
18
- Feature[Feature["RegExp"] = 32] = "RegExp";
19
- Feature[Feature["Temporal"] = 64] = "Temporal";
20
- return Feature;
21
- }({});
22
- //#endregion
23
- //#region src/core/symbols.ts
24
- const SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
25
- const SYM_HAS_INSTANCE = Symbol.hasInstance;
26
- const SYM_IS_CONCAT_SPREADABLE = Symbol.isConcatSpreadable;
27
- const SYM_ITERATOR = Symbol.iterator;
28
- const SYM_MATCH = Symbol.match;
29
- const SYM_MATCH_ALL = Symbol.matchAll;
30
- const SYM_REPLACE = Symbol.replace;
31
- const SYM_SEARCH = Symbol.search;
32
- const SYM_SPECIES = Symbol.species;
33
- const SYM_SPLIT = Symbol.split;
34
- const SYM_TO_PRIMITIVE = Symbol.toPrimitive;
35
- const SYM_TO_STRING_TAG = Symbol.toStringTag;
36
- const SYM_UNSCOPABLES = Symbol.unscopables;
37
- //#endregion
38
- //#region src/core/constants.ts
39
- const TEMPORAL_TYPE_NAME = {
40
- [0]: "Instant",
41
- [1]: "Duration",
42
- [2]: "PlainDate",
43
- [3]: "PlainDateTime",
44
- [4]: "PlainMonthDay",
45
- [5]: "PlainTime",
46
- [6]: "PlainYearMonth",
47
- [7]: "ZonedDateTime"
48
- };
49
- const SYMBOL_REF = {
50
- [0]: SYM_ASYNC_ITERATOR,
51
- [1]: SYM_HAS_INSTANCE,
52
- [2]: SYM_IS_CONCAT_SPREADABLE,
53
- [3]: SYM_ITERATOR,
54
- [4]: SYM_MATCH,
55
- [5]: SYM_MATCH_ALL,
56
- [6]: SYM_REPLACE,
57
- [7]: SYM_SEARCH,
58
- [8]: SYM_SPECIES,
59
- [9]: SYM_SPLIT,
60
- [10]: SYM_TO_PRIMITIVE,
61
- [11]: SYM_TO_STRING_TAG,
62
- [12]: SYM_UNSCOPABLES
63
- };
64
- function createSymbolStringTable() {
65
- const result = {};
66
- for (let i = 0; i <= 12; i++) result[i] = SYMBOL_REF[i].description;
67
- return result;
68
- }
69
- const SYMBOL_STRING = /* @__PURE__ */ createSymbolStringTable();
70
- function createInverseSymbolTable() {
71
- const result = {};
72
- for (let i = 0; i <= 12; i++) result[SYMBOL_REF[i]] = i;
73
- return result;
74
- }
75
- const INV_SYMBOL_REF = /* @__PURE__ */ createInverseSymbolTable();
76
- const CONSTANT_STRING = {
77
- [2]: "!0",
78
- [3]: "!1",
79
- [1]: "void 0",
80
- [0]: "null",
81
- [4]: "-0",
82
- [5]: "1/0",
83
- [6]: "-1/0",
84
- [7]: "0/0"
85
- };
86
- const CONSTANT_VAL = {
87
- [2]: true,
88
- [3]: false,
89
- [1]: void 0,
90
- [0]: null,
91
- [4]: -0,
92
- [5]: Infinity,
93
- [6]: -Infinity,
94
- [7]: NaN
95
- };
96
- const ERROR_CONSTRUCTOR = {
97
- [0]: Error,
98
- [1]: EvalError,
99
- [2]: RangeError,
100
- [3]: ReferenceError,
101
- [4]: SyntaxError,
102
- [5]: TypeError,
103
- [6]: URIError
104
- };
105
- function createErrorConstructorStringTable() {
106
- const result = {};
107
- for (let i = 0; i <= 6; i++) result[i] = ERROR_CONSTRUCTOR[i].name;
108
- return result;
109
- }
110
- const ERROR_CONSTRUCTOR_STRING = /* @__PURE__ */ createErrorConstructorStringTable();
111
- //#endregion
112
- //#region src/core/node.ts
113
- function createSerovalNode(t, i, s, c, m, p, e, a, f, b, o, l) {
114
- if (c === void 0 && m === void 0 && p === void 0 && e === void 0 && a === void 0 && f === void 0 && b === void 0 && o === void 0 && l === void 0) return {
115
- t,
116
- i,
117
- s
118
- };
119
- return {
120
- t,
121
- i,
122
- s,
123
- c,
124
- m,
125
- p,
126
- e,
127
- a,
128
- f,
129
- b,
130
- o,
131
- l
132
- };
133
- }
134
- //#endregion
135
- //#region src/core/literals.ts
136
- function createConstantNode(value) {
137
- return createSerovalNode(2, void 0, value);
138
- }
139
- const TRUE_NODE = /* @__PURE__ */ createConstantNode(2);
140
- const FALSE_NODE = /* @__PURE__ */ createConstantNode(3);
141
- const UNDEFINED_NODE = /* @__PURE__ */ createConstantNode(1);
142
- const NULL_NODE = /* @__PURE__ */ createConstantNode(0);
143
- const NEG_ZERO_NODE = /* @__PURE__ */ createConstantNode(4);
144
- const INFINITY_NODE = /* @__PURE__ */ createConstantNode(5);
145
- const NEG_INFINITY_NODE = /* @__PURE__ */ createConstantNode(6);
146
- const NAN_NODE = /* @__PURE__ */ createConstantNode(7);
147
- //#endregion
148
- //#region src/core/string.ts
149
- const MIN_JSON_STRINGIFY_LENGTH = 64;
150
- const NEEDS_ESCAPE = /["\\\n\r\b\t\f<\u2028\u2029]/;
151
- const JSON_ESCAPE_DIFFERENCES = /[\x00-\x07\x0b\x0e-\x1f\ud800-\udfff]/;
152
- const LESS_THAN = /</g;
153
- const LINE_SEPARATOR = /\u2028/g;
154
- const PARAGRAPH_SEPARATOR = /\u2029/g;
155
- function escapeCharCode(code) {
156
- switch (code) {
157
- case 34: return "\\\"";
158
- case 92: return "\\\\";
159
- case 10: return "\\n";
160
- case 13: return "\\r";
161
- case 8: return "\\b";
162
- case 9: return "\\t";
163
- case 12: return "\\f";
164
- case 60: return "\\x3C";
165
- case 8232: return "\\u2028";
166
- case 8233: return "\\u2029";
167
- default: return;
168
- }
169
- }
170
- function serializeString(input) {
171
- const str = "" + input;
172
- if (!NEEDS_ESCAPE.test(str)) return str;
173
- if (str.length >= MIN_JSON_STRINGIFY_LENGTH && !JSON_ESCAPE_DIFFERENCES.test(str)) {
174
- let result = JSON.stringify(str).slice(1, -1);
175
- if (result.includes("<")) result = result.replace(LESS_THAN, "\\x3C");
176
- if (result.includes("\u2028")) result = result.replace(LINE_SEPARATOR, "\\u2028");
177
- if (result.includes("\u2029")) result = result.replace(PARAGRAPH_SEPARATOR, "\\u2029");
178
- return result;
179
- }
180
- let result = "";
181
- let lastPos = 0;
182
- let replacement;
183
- for (let i = 0, len = str.length; i < len; i++) {
184
- replacement = escapeCharCode(str.charCodeAt(i));
185
- if (replacement) {
186
- result += str.slice(lastPos, i) + replacement;
187
- lastPos = i + 1;
188
- }
189
- }
190
- return result + str.slice(lastPos);
191
- }
192
- const JSON_COMPATIBLE = /^(?:[^"\\\x00-\x1f]|\\["\\nrbtf])*$/;
193
- const ESCAPE_SEQUENCE = /(\\\\|\\"|\\n|\\r|\\b|\\t|\\f|\\u2028|\\u2029|\\x3C)/g;
194
- function deserializeString(str) {
195
- if (typeof str !== "string") return str.replace(ESCAPE_SEQUENCE, deserializeString);
196
- let index = str.indexOf("\\");
197
- if (index === -1) return str;
198
- if (JSON_COMPATIBLE.test(str)) return JSON.parse("\"" + str + "\"");
199
- let result = "";
200
- let lastPos = 0;
201
- const last = str.length - 1;
202
- while (index !== -1 && index < last) {
203
- let replacement;
204
- let length = 2;
205
- switch (str.charCodeAt(index + 1)) {
206
- case 92:
207
- replacement = "\\";
208
- break;
209
- case 34:
210
- replacement = "\"";
211
- break;
212
- case 110:
213
- replacement = "\n";
214
- break;
215
- case 114:
216
- replacement = "\r";
217
- break;
218
- case 98:
219
- replacement = "\b";
220
- break;
221
- case 116:
222
- replacement = " ";
223
- break;
224
- case 102:
225
- replacement = "\f";
226
- break;
227
- case 120:
228
- if (str.startsWith("3C", index + 2)) {
229
- replacement = "<";
230
- length = 4;
231
- }
232
- break;
233
- case 117: if (str.startsWith("2028", index + 2)) {
234
- replacement = "\u2028";
235
- length = 6;
236
- } else if (str.startsWith("2029", index + 2)) {
237
- replacement = "\u2029";
238
- length = 6;
239
- }
240
- }
241
- if (replacement) {
242
- result += str.slice(lastPos, index) + replacement;
243
- lastPos = index + length;
244
- index = str.indexOf("\\", lastPos);
245
- } else index = str.indexOf("\\", index + 1);
246
- }
247
- return result + str.slice(lastPos);
248
- }
249
- //#endregion
250
- //#region src/core/errors.ts
251
- function objectToString(value) {
252
- return Object.prototype.toString.call(value);
253
- }
254
- function getErrorMessageDev(type, cause) {
255
- if (cause instanceof Error) return `Seroval caught an error during the ${type} process.
256
-
257
- ${cause.name}
258
- ${cause.message}
259
-
260
- - For more information, please check the "cause" property of this error.
261
- - If you believe this is an error in Seroval, please submit an issue at https://github.com/lxsmnsyc/seroval/issues/new`;
262
- return `Seroval caught an error during the ${type} process.
263
-
264
- "${objectToString(cause)}"
265
-
266
- For more information, please check the "cause" property of this error.`;
267
- }
268
- var SerovalError = class extends Error {
269
- constructor(type, cause) {
270
- super(getErrorMessageDev(type, cause));
271
- this.cause = cause;
272
- }
273
- };
274
- var SerovalParserError = class extends SerovalError {
275
- constructor(cause) {
276
- super("parsing", cause);
277
- }
278
- };
279
- var SerovalSerializationError = class extends SerovalError {
280
- constructor(cause) {
281
- super("serialization", cause);
282
- }
283
- };
284
- var SerovalDeserializationError = class extends SerovalError {
285
- constructor(cause) {
286
- super("deserialization", cause);
287
- }
288
- };
289
- var SerovalUnsupportedTypeError = class extends Error {
290
- constructor(value) {
291
- super(`The value ${objectToString(value)} of type "${typeof value}" cannot be parsed/serialized.
292
-
293
- There are few workarounds for this problem:
294
- - Transform the value in a way that it can be serialized.
295
- - If the reference is present on multiple runtimes (isomorphic), you can use the Reference API to map the references.`);
296
- this.value = value;
297
- }
298
- };
299
- var SerovalUnsupportedNodeError = class extends Error {
300
- constructor(node) {
301
- super("Unsupported node type \"" + node.t + "\".");
302
- }
303
- };
304
- var SerovalMissingPluginError = class extends Error {
305
- constructor(tag) {
306
- super("Missing plugin for tag \"" + tag + "\".");
307
- }
308
- };
309
- var SerovalMissingInstanceError = class extends Error {
310
- constructor(tag) {
311
- super("Missing \"" + tag + "\" instance.");
312
- }
313
- };
314
- /**
315
- * @deprecated Not thrown by seroval. A missing `createReference` key throws
316
- * {@link SerovalMissingReferenceForIdError} instead.
317
- */
318
- var SerovalMissingReferenceError = class extends Error {
319
- constructor(value) {
320
- super("Missing reference for the value \"" + objectToString(value) + "\" of type \"" + typeof value + "\"");
321
- this.value = value;
322
- }
323
- };
324
- var SerovalMissingReferenceForIdError = class extends Error {
325
- constructor(id) {
326
- super("Missing reference for id \"" + serializeString(id) + "\"");
327
- }
328
- };
329
- var SerovalUnknownTypedArrayError = class extends Error {
330
- constructor(name) {
331
- super("Unknown TypedArray \"" + name + "\"");
332
- }
333
- };
334
- var SerovalMalformedNodeError = class extends Error {
335
- constructor(node) {
336
- super("Malformed node type \"" + node.t + "\".");
337
- }
338
- };
339
- var SerovalConflictedNodeIdError = class extends Error {
340
- constructor(node) {
341
- super("Conflicted node id \"" + node.i + "\".");
342
- }
343
- };
344
- var SerovalDepthLimitError = class extends Error {
345
- constructor(limit) {
346
- super("Depth limit of " + limit + " reached");
347
- }
348
- };
349
- var SerovalAbortedError = class extends Error {
350
- constructor() {
351
- super("Cross deserializer has been aborted.");
352
- }
353
- };
354
- const LIVE_STREAM_ERROR_MESSAGES = {
355
- consumed: "Live stream already has a consumer",
356
- pending: "Live stream already has a pending event",
357
- reading: "Live stream already has a pending read",
358
- closed: "Live stream is closed"
359
- };
360
- var SerovalLiveStreamError = class extends Error {
361
- constructor(reason) {
362
- super(LIVE_STREAM_ERROR_MESSAGES[reason]);
363
- this.reason = reason;
364
- }
365
- };
366
- //#endregion
367
- //#region src/core/utils/error.ts
368
- function getErrorConstructor(error) {
369
- for (let i = 1; i <= 6; i++) if (error instanceof ERROR_CONSTRUCTOR[i]) return i;
370
- return 0;
371
- }
372
- function getErrorOptions(error, features) {
373
- const options = Object.create(null);
374
- const construct = ERROR_CONSTRUCTOR_STRING[getErrorConstructor(error)];
375
- if (error.name !== construct) options.name = error.name;
376
- else if (error.constructor.name !== construct) options.name = error.constructor.name;
377
- for (const name of Object.getOwnPropertyNames(error)) if (name !== "name" && name !== "message" && (name !== "stack" || features & 4)) options[name] = error[name];
378
- return options;
379
- }
380
- //#endregion
381
- //#region src/core/utils/get-object-flag.ts
382
- function getObjectFlag(obj) {
383
- if (Object.isExtensible(obj)) return 0;
384
- if (Object.isFrozen(obj)) return 3;
385
- if (Object.isSealed(obj)) return 2;
386
- return 1;
387
- }
388
- //#endregion
389
- //#region src/core/utils/typed-array.ts
390
- function getTypedArrayConstructor(name) {
391
- switch (name) {
392
- case "Int8Array": return Int8Array;
393
- case "Int16Array": return Int16Array;
394
- case "Int32Array": return Int32Array;
395
- case "Uint8Array": return Uint8Array;
396
- case "Uint16Array": return Uint16Array;
397
- case "Uint32Array": return Uint32Array;
398
- case "Uint8ClampedArray": return Uint8ClampedArray;
399
- case "Float32Array": return Float32Array;
400
- case "Float64Array": return Float64Array;
401
- case "BigInt64Array": return BigInt64Array;
402
- case "BigUint64Array": return BigUint64Array;
403
- default: throw new SerovalUnknownTypedArrayError(name);
404
- }
405
- }
406
- let typedArrayNameGetter;
407
- function getTypedArrayName(value) {
408
- if (!typedArrayNameGetter) typedArrayNameGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Int8Array.prototype), Symbol.toStringTag).get;
409
- return typedArrayNameGetter.call(value);
410
- }
411
- let typedArrayGetters;
412
- let dataViewGetters;
413
- function getAccessor(proto, key) {
414
- return Object.getOwnPropertyDescriptor(proto, key).get;
415
- }
416
- function getViewGetters(proto, lengthKey) {
417
- return {
418
- buffer: getAccessor(proto, "buffer"),
419
- byteOffset: getAccessor(proto, "byteOffset"),
420
- byteLength: getAccessor(proto, "byteLength"),
421
- length: getAccessor(proto, lengthKey)
422
- };
423
- }
424
- function readArrayBufferView(value, isDataView) {
425
- let getters;
426
- if (isDataView) getters = dataViewGetters ?? (dataViewGetters = getViewGetters(DataView.prototype, "byteLength"));
427
- else getters = typedArrayGetters ?? (typedArrayGetters = getViewGetters(Object.getPrototypeOf(Int8Array.prototype), "length"));
428
- return {
429
- buffer: getters.buffer.call(value),
430
- byteOffset: getters.byteOffset.call(value),
431
- byteLength: getters.byteLength.call(value),
432
- length: getters.length.call(value)
433
- };
434
- }
435
- //#endregion
436
- //#region src/core/base-primitives.ts
437
- function createNumberNode(value) {
438
- switch (value) {
439
- case Number.POSITIVE_INFINITY: return INFINITY_NODE;
440
- case Number.NEGATIVE_INFINITY: return NEG_INFINITY_NODE;
441
- }
442
- if (value !== value) return NAN_NODE;
443
- if (Object.is(value, -0)) return NEG_ZERO_NODE;
444
- return createSerovalNode(0, void 0, value);
445
- }
446
- function createStringNode(value) {
447
- return createSerovalNode(1, void 0, serializeString(value));
448
- }
449
- function createBigIntNode(current) {
450
- return createSerovalNode(3, void 0, "" + current);
451
- }
452
- function createIndexedValueNode(id) {
453
- return createSerovalNode(4, id);
454
- }
455
- const getDateTime = Date.prototype.getTime;
456
- const getDateISOString = Date.prototype.toISOString;
457
- function createDateNode(id, current) {
458
- const timestamp = getDateTime.call(current);
459
- return createSerovalNode(5, id, timestamp === timestamp ? getDateISOString.call(current) : "");
460
- }
461
- function createTemporalNode(id, type, temporalClass, current) {
462
- return createSerovalNode(36, id, temporalClass.prototype.toString.call(current), type);
463
- }
464
- const getRegExpSource = Object.getOwnPropertyDescriptor(RegExp.prototype, "source").get;
465
- const getRegExpFlags = Object.getOwnPropertyDescriptor(RegExp.prototype, "flags").get;
466
- function createRegExpNode(id, current) {
467
- return createSerovalNode(6, id, void 0, serializeString(getRegExpSource.call(current)), getRegExpFlags.call(current));
468
- }
469
- function createWKSymbolNode(id, current) {
470
- return createSerovalNode(17, id, INV_SYMBOL_REF[current]);
471
- }
472
- function createReferenceNode(id, referenceId) {
473
- return createSerovalNode(18, id, serializeString(referenceId));
474
- }
475
- function createPluginNode(id, tag, value) {
476
- return createSerovalNode(25, id, value, serializeString(tag));
477
- }
478
- function createArrayNode(id, current, parsedItems) {
479
- return createSerovalNode(9, id, void 0, void 0, void 0, void 0, void 0, parsedItems, void 0, void 0, getObjectFlag(current));
480
- }
481
- function createBoxedNode(id, boxed) {
482
- return createSerovalNode(21, id, void 0, void 0, void 0, void 0, void 0, void 0, boxed);
483
- }
484
- const MAX_TYPED_ARRAY_LENGTH = 1e6;
485
- /**
486
- * Rejects a sparse array with more holes than the typed array limit. Each hole
487
- * still costs a node and output, however few elements the array holds.
488
- */
489
- function assertArrayHoles(current) {
490
- const len = current.length;
491
- if (len > MAX_TYPED_ARRAY_LENGTH && len - Object.keys(current).length > MAX_TYPED_ARRAY_LENGTH) throw new SerovalUnsupportedTypeError(current);
492
- }
493
- function createViewNode(type, id, current, view, buffer) {
494
- const isDataView = type === 20;
495
- const size = view.length;
496
- if (size > MAX_TYPED_ARRAY_LENGTH) throw new SerovalUnsupportedTypeError(current);
497
- return createSerovalNode(type, id, void 0, isDataView ? void 0 : getTypedArrayName(current), void 0, void 0, void 0, void 0, buffer, view.byteOffset, void 0, size);
498
- }
499
- function createErrorNode(type, id, current, options) {
500
- return createSerovalNode(type, id, getErrorConstructor(current), void 0, serializeString(current.message), options);
501
- }
502
- function createSetNode(id, items) {
503
- return createSerovalNode(7, id, void 0, void 0, void 0, void 0, void 0, items);
504
- }
505
- function createIteratorFactoryInstanceNode(type, factory, items) {
506
- return createSerovalNode(type, void 0, void 0, void 0, void 0, void 0, void 0, [factory, items]);
507
- }
508
- function createStreamConstructorNode(id, factory, sequence, live) {
509
- return createSerovalNode(31, id, void 0, void 0, void 0, void 0, void 0, sequence, factory, void 0, void 0, live);
510
- }
511
- function createStreamEventNode(type, id, parsed) {
512
- return createSerovalNode(type, id, void 0, void 0, void 0, void 0, void 0, void 0, parsed);
513
- }
514
- function createSequenceNode(id, sequence, throwAt, doneAt) {
515
- return createSerovalNode(35, id, throwAt, void 0, void 0, void 0, void 0, sequence, void 0, void 0, void 0, doneAt);
516
- }
517
- //#endregion
518
- //#region src/core/live-stream.ts
519
- const BRAND = /* @__PURE__ */ Symbol("LiveStream");
520
- function isLiveStream(value) {
521
- return value != null && value[BRAND] === true;
522
- }
523
- /**
524
- * A single-consumer stream for incremental serialization. Unlike
525
- * `createStream`, it keeps no history: at most one event is held, and the
526
- * producer operation that sent it settles only when the consumer accepts it.
527
- *
528
- * An internal class rather than a tagged POJO: identity is checked with
529
- * `isLiveStream`, which untrusted input cannot forge. The class is exported
530
- * because bundlers cannot drop an unexported top-level class.
531
- */
532
- var LiveStream = class {
533
- constructor(options) {
534
- this[BRAND] = true;
535
- this.consumed = false;
536
- this.closed = false;
537
- this.cancelled = false;
538
- this.options = options;
539
- }
540
- deliver(reader, record) {
541
- record.delivered = true;
542
- reader.resolve({
543
- event: record.event,
544
- accept: () => {
545
- if (this.pending === record && record.delivered) {
546
- const terminal = record.event.type !== "next";
547
- record.event = void 0;
548
- this.pending = void 0;
549
- const resolve = record.resolve;
550
- record.resolve = void 0;
551
- record.reject = void 0;
552
- if (terminal) {
553
- this.closed = true;
554
- this.options = void 0;
555
- const waiter = this.waiting;
556
- this.waiting = void 0;
557
- waiter?.reject(new SerovalLiveStreamError("closed"));
558
- }
559
- resolve?.();
560
- }
561
- }
562
- });
563
- }
564
- /** @internal */
565
- push(event) {
566
- if (this.cancelled) return Promise.reject(this.cancelReason);
567
- if (this.closed) return Promise.reject(new SerovalLiveStreamError("closed"));
568
- if (this.pending) return Promise.reject(new SerovalLiveStreamError("pending"));
569
- return new Promise((resolve, reject) => {
570
- const record = {
571
- event,
572
- delivered: false,
573
- resolve,
574
- reject
575
- };
576
- this.pending = record;
577
- if (this.waiting) {
578
- const waiter = this.waiting;
579
- this.waiting = void 0;
580
- this.deliver(waiter, record);
581
- }
582
- });
583
- }
584
- cancel(reason) {
585
- if (this.cancelled || this.closed) return;
586
- this.cancelled = true;
587
- this.cancelReason = reason;
588
- const record = this.pending;
589
- const waiter = this.waiting;
590
- this.pending = void 0;
591
- this.waiting = void 0;
592
- const callbackOwner = this.options;
593
- this.options = void 0;
594
- if (record) {
595
- record.event = void 0;
596
- const reject = record.reject;
597
- record.resolve = void 0;
598
- record.reject = void 0;
599
- reject?.(reason);
600
- }
601
- if (waiter) waiter.reject(reason);
602
- callbackOwner?.onCancel?.(reason);
603
- }
604
- read() {
605
- if (this.cancelled) return Promise.reject(this.cancelReason);
606
- if (this.closed) return Promise.reject(new SerovalLiveStreamError("closed"));
607
- if (this.waiting) return Promise.reject(new SerovalLiveStreamError("reading"));
608
- return new Promise((resolve, reject) => {
609
- const next = {
610
- resolve,
611
- reject
612
- };
613
- if (this.pending && !this.pending.delivered) this.deliver(next, this.pending);
614
- else this.waiting = next;
615
- });
616
- }
617
- consume() {
618
- if (this.consumed) throw new SerovalLiveStreamError("consumed");
619
- this.consumed = true;
620
- return {
621
- read: () => this.read(),
622
- cancel: (reason) => this.cancel(reason)
623
- };
624
- }
625
- /**
626
- * Consumes the stream through a replay-style listener, accepting each
627
- * event as soon as it has been delivered. Use `consume` or `pump` when
628
- * acceptance must wait for processing.
629
- */
630
- on(listener) {
631
- const wrap = (key) => (value, accept) => {
632
- listener[key](value);
633
- accept();
634
- };
635
- return this.pump({
636
- next: wrap("next"),
637
- throw: wrap("throw"),
638
- return: wrap("return")
639
- });
640
- }
641
- /**
642
- * Consumes the stream into a sink that controls acceptance. Returns the
643
- * cancel function.
644
- * @internal
645
- */
646
- pump(sink) {
647
- const consumer = this.consume();
648
- let current = sink;
649
- function next() {
650
- consumer.read().then((delivery) => {
651
- const target = current;
652
- if (!target) return;
653
- const event = delivery.event;
654
- let failure;
655
- let failed = false;
656
- try {
657
- failure = target[event.type](event.type === "throw" ? event.error : event.value, delivery.accept);
658
- } catch (error) {
659
- failed = true;
660
- failure = error;
661
- }
662
- if (failed || failure !== void 0) {
663
- current = void 0;
664
- try {
665
- consumer.cancel(failure);
666
- } finally {
667
- target.done?.();
668
- }
669
- return;
670
- }
671
- if (event.type === "next") {
672
- next();
673
- return;
674
- }
675
- current = void 0;
676
- target.done?.();
677
- }, (reason) => {
678
- const target = current;
679
- current = void 0;
680
- target?.error?.(reason);
681
- });
682
- }
683
- next();
684
- return consumer.cancel;
685
- }
686
- };
687
- /**
688
- * Creates a live stream and the producer that writes to it.
689
- */
690
- function createLiveStream(options) {
691
- const stream = new LiveStream(options);
692
- return {
693
- stream,
694
- producer: {
695
- write(value) {
696
- return stream.push({
697
- type: "next",
698
- value
699
- });
700
- },
701
- close(value) {
702
- return stream.push({
703
- type: "return",
704
- value
705
- });
706
- },
707
- fail(error) {
708
- return stream.push({
709
- type: "throw",
710
- error
711
- });
712
- }
713
- }
714
- };
715
- }
716
- //#endregion
717
- //#region src/core/opaque-reference.ts
718
- /**
719
- * An opaque reference allows hiding values from the serializer.
720
- */
721
- var OpaqueReference = class {
722
- constructor(value, replacement) {
723
- this.value = value;
724
- this.replacement = replacement;
725
- }
726
- };
727
- //#endregion
728
- //#region src/core/constructors.ts
729
- const PROMISE_CONSTRUCTOR = () => {
730
- const resolver = {
731
- p: 0,
732
- s: 0,
733
- f: 0
734
- };
735
- resolver.p = new Promise((resolve, reject) => {
736
- resolver.s = resolve;
737
- resolver.f = reject;
738
- });
739
- return resolver;
740
- };
741
- const PROMISE_SUCCESS = (resolver, data) => {
742
- resolver.s(data);
743
- resolver.p.s = 1;
744
- resolver.p.v = data;
745
- };
746
- const PROMISE_FAILURE = (resolver, data) => {
747
- resolver.f(data);
748
- resolver.p.s = 2;
749
- resolver.p.v = data;
750
- };
751
- const SERIALIZED_PROMISE_CONSTRUCTOR = /* @__PURE__ */ PROMISE_CONSTRUCTOR.toString();
752
- const SERIALIZED_PROMISE_SUCCESS = /* @__PURE__ */ PROMISE_SUCCESS.toString();
753
- const SERIALIZED_PROMISE_FAILURE = /* @__PURE__ */ PROMISE_FAILURE.toString();
754
- const STREAM_CONSTRUCTOR = (live) => {
755
- const buffer = [];
756
- const listeners = [];
757
- let alive = true;
758
- let success = false;
759
- let count = 0;
760
- const internal = {
761
- flush(value, mode, x) {
762
- live > 1 || buffer.push(value);
763
- for (x = 0; x < count; x++) {
764
- const listener = listeners[x];
765
- if (listener) listener[mode](value);
766
- }
767
- },
768
- up(listener, x, z, current) {
769
- for (x = 0, z = buffer.length; x < z; x++) {
770
- current = buffer[x];
771
- if (!alive && x === z - 1) listener[success ? "return" : "throw"](current);
772
- else listener.next(current);
773
- }
774
- },
775
- on(listener, temp = 0) {
776
- if (live > 1) throw new Error("Stream consumed");
777
- let subscribed = alive;
778
- if (alive) {
779
- for (temp = 0; temp < count; temp++) if (!listeners[temp]) break;
780
- if (temp === count) count++;
781
- listeners[temp] = listener;
782
- }
783
- internal.up(listener);
784
- if (live) {
785
- live = 2;
786
- buffer.length = 0;
787
- }
788
- return () => {
789
- if (alive && subscribed) {
790
- subscribed = false;
791
- listeners[temp] = void 0;
792
- while (count > 0 && !listeners[count - 1]) count--;
793
- listeners.length = count;
794
- }
795
- };
796
- }
797
- };
798
- return {
799
- __SEROVAL_STREAM__: true,
800
- on(listener) {
801
- return internal.on(listener);
802
- },
803
- next(value) {
804
- if (alive) internal.flush(value, "next");
805
- },
806
- throw(value) {
807
- if (alive) {
808
- internal.flush(value, "throw");
809
- alive = false;
810
- success = false;
811
- listeners.length = 0;
812
- }
813
- },
814
- return(value) {
815
- if (alive) {
816
- internal.flush(value, "return");
817
- alive = false;
818
- success = true;
819
- listeners.length = 0;
820
- }
821
- }
822
- };
823
- };
824
- const SERIALIZED_STREAM_CONSTRUCTOR = /* @__PURE__ */ STREAM_CONSTRUCTOR.toString();
825
- const ITERATOR_CONSTRUCTOR = (symbol) => (sequence) => () => {
826
- let index = 0;
827
- const instance = {
828
- [symbol]() {
829
- return instance;
830
- },
831
- next() {
832
- if (index > sequence.d) return {
833
- done: true,
834
- value: void 0
835
- };
836
- const currentIndex = index++;
837
- const data = sequence.v[currentIndex];
838
- if (currentIndex === sequence.t) throw data;
839
- return {
840
- done: currentIndex === sequence.d,
841
- value: data
842
- };
843
- }
844
- };
845
- return instance;
846
- };
847
- const SERIALIZED_ITERATOR_CONSTRUCTOR = /* @__PURE__ */ ITERATOR_CONSTRUCTOR.toString();
848
- const ASYNC_ITERATOR_CONSTRUCTOR = (symbol, createPromise) => (stream) => () => {
849
- let count = 0;
850
- let doneAt = -1;
851
- let isThrow = false;
852
- const buffer = [];
853
- const pending = [];
854
- const internal = { finalize(i = 0, len = pending.length) {
855
- for (; i < len; i++) pending[i].s({
856
- done: true,
857
- value: void 0
858
- });
859
- } };
860
- stream.on({
861
- next(value) {
862
- const temp = pending.shift();
863
- if (temp) temp.s({
864
- done: false,
865
- value
866
- });
867
- buffer.push(value);
868
- },
869
- throw(value) {
870
- const temp = pending.shift();
871
- if (temp) temp.f(value);
872
- internal.finalize();
873
- doneAt = buffer.length;
874
- isThrow = true;
875
- buffer.push(value);
876
- },
877
- return(value) {
878
- const temp = pending.shift();
879
- if (temp) temp.s({
880
- done: true,
881
- value
882
- });
883
- internal.finalize();
884
- doneAt = buffer.length;
885
- buffer.push(value);
886
- }
887
- });
888
- const instance = {
889
- [symbol]() {
890
- return instance;
891
- },
892
- next() {
893
- if (doneAt === -1) {
894
- const index = count++;
895
- if (index >= buffer.length) {
896
- const temp = createPromise();
897
- pending.push(temp);
898
- return temp.p;
899
- }
900
- return {
901
- done: false,
902
- value: buffer[index]
903
- };
904
- }
905
- if (count > doneAt) return {
906
- done: true,
907
- value: void 0
908
- };
909
- const index = count++;
910
- const value = buffer[index];
911
- if (index !== doneAt) return {
912
- done: false,
913
- value
914
- };
915
- if (isThrow) throw value;
916
- return {
917
- done: true,
918
- value
919
- };
920
- }
921
- };
922
- return instance;
923
- };
924
- const SERIALIZED_ASYNC_ITERATOR_CONSTRUCTOR = /* @__PURE__ */ ASYNC_ITERATOR_CONSTRUCTOR.toString();
925
- const ARRAY_BUFFER_CONSTRUCTOR = (b64) => {
926
- const decoded = atob(b64);
927
- const length = decoded.length;
928
- const arr = new Uint8Array(length);
929
- for (let i = 0; i < length; i++) arr[i] = decoded.charCodeAt(i);
930
- return arr.buffer;
931
- };
932
- const SERIALIZED_ARRAY_BUFFER_CONSTRUCTOR = /* @__PURE__ */ ARRAY_BUFFER_CONSTRUCTOR.toString();
933
- //#endregion
934
- //#region src/core/sequence.ts
935
- /**
936
- * An internal class rather than a tagged POJO: identity is checked with
937
- * `instanceof`, which untrusted input cannot forge. The class is exported
938
- * because bundlers cannot drop an unexported top-level class.
939
- * The eval-based `deserialize` path still rebuilds a `{__SEROVAL_SEQUENCE__…}`
940
- * POJO from embedded source - it has no access to this class - so a value read
941
- * back through `deserialize` is not an instance and, by design, is not treated
942
- * as a genuine Sequence on re-serialization.
943
- */
944
- var Sequence = class {
945
- constructor(values, throwAt, doneAt) {
946
- this.v = values;
947
- this.t = throwAt;
948
- this.d = doneAt;
949
- }
950
- };
951
- function isSequence(value) {
952
- return value instanceof Sequence;
953
- }
954
- function createSequence(values, throwAt, doneAt) {
955
- return new Sequence(values, throwAt, doneAt);
956
- }
957
- function createSequenceFromIterable(source) {
958
- const values = [];
959
- let throwsAt = -1;
960
- let doneAt = -1;
961
- const iterator = source[SYM_ITERATOR]();
962
- for (;;) try {
963
- const value = iterator.next();
964
- values.push(value.value);
965
- if (value.done) {
966
- doneAt = values.length - 1;
967
- break;
968
- }
969
- } catch (error) {
970
- throwsAt = values.length;
971
- doneAt = throwsAt;
972
- values.push(error);
973
- break;
974
- }
975
- return createSequence(values, throwsAt, doneAt);
976
- }
977
- const createIterator = /* @__PURE__ */ ITERATOR_CONSTRUCTOR(SYM_ITERATOR);
978
- function sequenceToIterator(sequence) {
979
- return createIterator(sequence);
980
- }
981
- //#endregion
982
- //#region src/core/special-reference.ts
983
- const ITERATOR = {};
984
- const ASYNC_ITERATOR = {};
985
- /**
986
- * Placeholder references
987
- */
988
- const SPECIAL_REFS = {
989
- [0]: {},
990
- [1]: {},
991
- [2]: {},
992
- [3]: {},
993
- [4]: {},
994
- [5]: {}
995
- };
996
- const SPECIAL_REF_STRING = {
997
- [0]: "[]",
998
- [1]: SERIALIZED_PROMISE_CONSTRUCTOR,
999
- [2]: SERIALIZED_PROMISE_SUCCESS,
1000
- [3]: SERIALIZED_PROMISE_FAILURE,
1001
- [4]: SERIALIZED_STREAM_CONSTRUCTOR,
1002
- [5]: SERIALIZED_ARRAY_BUFFER_CONSTRUCTOR
1003
- };
1004
- //#endregion
1005
- //#region src/core/stream.ts
1006
- /**
1007
- * An internal class rather than a tagged POJO: identity is checked with
1008
- * `instanceof`, which untrusted input cannot forge. The class is exported
1009
- * because bundlers cannot drop an unexported top-level class.
1010
- *
1011
- * The behavior is intentionally duplicated from `STREAM_CONSTRUCTOR`. That
1012
- * constructor's source is embedded verbatim into the eval-based `deserialize`
1013
- * output, which has no access to this class, so the two cannot be shared. A
1014
- * stream read back through `deserialize` is therefore a plain POJO and, by
1015
- * design, is not treated as a genuine Stream on re-serialization. Keep the two
1016
- * implementations in sync.
1017
- */
1018
- var Stream = class {
1019
- constructor(live) {
1020
- this.buffer = [];
1021
- this.listeners = [];
1022
- this.alive = true;
1023
- this.success = false;
1024
- this.count = 0;
1025
- this.live = live;
1026
- }
1027
- flush(value, mode) {
1028
- this.live > 1 || this.buffer.push(value);
1029
- for (let x = 0; x < this.count; x++) this.listeners[x]?.[mode](value);
1030
- }
1031
- replay(listener) {
1032
- for (let x = 0, z = this.buffer.length; x < z; x++) {
1033
- const current = this.buffer[x];
1034
- if (!this.alive && x === z - 1) listener[this.success ? "return" : "throw"](current);
1035
- else listener.next(current);
1036
- }
1037
- }
1038
- on(listener) {
1039
- if (this.live > 1) throw new Error("Stream consumed");
1040
- let subscribed = this.alive;
1041
- let temp = 0;
1042
- if (subscribed) {
1043
- for (; temp < this.count; temp++) if (!this.listeners[temp]) break;
1044
- if (temp === this.count) this.count++;
1045
- this.listeners[temp] = listener;
1046
- }
1047
- this.replay(listener);
1048
- if (this.live) {
1049
- this.live = 2;
1050
- this.buffer.length = 0;
1051
- }
1052
- return () => {
1053
- if (this.alive && subscribed) {
1054
- subscribed = false;
1055
- this.listeners[temp] = void 0;
1056
- while (this.count > 0 && !this.listeners[this.count - 1]) this.count--;
1057
- this.listeners.length = this.count;
1058
- }
1059
- };
1060
- }
1061
- /**
1062
- * Returns the events of a stream that has ended, without subscribing, so a
1063
- * live receiver is not consumed. The last value is the `return` or `throw`
1064
- * value. Returns `undefined` while the stream is open, or when a live
1065
- * receiver was already consumed and has no events left.
1066
- * @internal
1067
- */
1068
- endedEvents() {
1069
- if (this.alive || this.live > 1) return void 0;
1070
- return {
1071
- values: this.buffer.slice(),
1072
- success: this.success
1073
- };
1074
- }
1075
- next(value) {
1076
- if (this.alive) this.flush(value, "next");
1077
- }
1078
- throw(value) {
1079
- if (this.alive) {
1080
- this.flush(value, "throw");
1081
- this.alive = false;
1082
- this.success = false;
1083
- this.listeners.length = 0;
1084
- }
1085
- }
1086
- return(value) {
1087
- if (this.alive) {
1088
- this.flush(value, "return");
1089
- this.alive = false;
1090
- this.success = true;
1091
- this.listeners.length = 0;
1092
- }
1093
- }
1094
- };
1095
- function isStream(value) {
1096
- return value instanceof Stream || isLiveStream(value);
1097
- }
1098
- function createStream() {
1099
- return new Stream();
1100
- }
1101
- const createAsyncIterable = /* @__PURE__ */ ASYNC_ITERATOR_CONSTRUCTOR(SYM_ASYNC_ITERATOR, PROMISE_CONSTRUCTOR);
1102
- function streamToAsyncIterable(stream) {
1103
- return createAsyncIterable(stream);
1104
- }
1105
- //#endregion
1106
- //#region src/core/utils/promise-to-result.ts
1107
- async function promiseToResult(current) {
1108
- try {
1109
- return [1, await current];
1110
- } catch (e) {
1111
- return [0, e];
1112
- }
1113
- }
1114
- //#endregion
1115
- //#region src/core/binary-browser.ts
1116
- function encodeArrayBuffer$1(current) {
1117
- const bytes = new Uint8Array(current);
1118
- if (typeof bytes.toBase64 === "function") return bytes.toBase64();
1119
- let result = "";
1120
- for (let i = 0, len = bytes.length; i < len; i++) result += String.fromCharCode(bytes[i]);
1121
- return btoa(result);
1122
- }
1123
- //#endregion
1124
- //#region src/core/binary-neutral.ts
1125
- const MIN_NATIVE_BASE64_LENGTH = 512;
1126
- function encodeArrayBuffer(current) {
1127
- if (typeof Buffer !== "undefined") return Buffer.from(current).toString("base64");
1128
- return encodeArrayBuffer$1(current);
1129
- }
1130
- function decodeArrayBuffer(source) {
1131
- if (source.length < MIN_NATIVE_BASE64_LENGTH || typeof Buffer === "undefined") return ARRAY_BUFFER_CONSTRUCTOR(source);
1132
- const decoded = atob(source);
1133
- const buffer = new ArrayBuffer(decoded.length);
1134
- Buffer.from(buffer).write(decoded, "latin1");
1135
- return buffer;
1136
- }
1137
- //#endregion
1138
- //#region src/core/plugin.ts
1139
- let SerovalMode = /* @__PURE__ */ function(SerovalMode) {
1140
- SerovalMode[SerovalMode["Vanilla"] = 1] = "Vanilla";
1141
- SerovalMode[SerovalMode["Cross"] = 2] = "Cross";
1142
- return SerovalMode;
1143
- }({});
1144
- function createPlugin(plugin) {
1145
- return plugin;
1146
- }
1147
- function dedupePlugins(deduped, plugins) {
1148
- for (let i = 0, len = plugins.length; i < len; i++) {
1149
- const current = plugins[i];
1150
- if (!deduped.has(current)) {
1151
- deduped.add(current);
1152
- if (current.extends) dedupePlugins(deduped, current.extends);
1153
- }
1154
- }
1155
- }
1156
- const RESOLVED_PLUGINS = /* @__PURE__ */ new WeakMap();
1157
- function matchResolved(resolved, plugins, added) {
1158
- for (let i = 0, len = plugins.length; i < len; i++) {
1159
- const current = plugins[i];
1160
- if (current === resolved[added]) {
1161
- added++;
1162
- if (current.extends) {
1163
- added = matchResolved(resolved, current.extends, added);
1164
- if (added === -1) return -1;
1165
- }
1166
- } else {
1167
- const index = resolved.indexOf(current);
1168
- if (index === -1 || index >= added) return -1;
1169
- }
1170
- }
1171
- return added;
1172
- }
1173
- function resolvePlugins(plugins) {
1174
- if (plugins) {
1175
- const cached = RESOLVED_PLUGINS.get(plugins);
1176
- if (cached && matchResolved(cached, plugins, 0) === cached.length) return cached;
1177
- const deduped = /* @__PURE__ */ new Set();
1178
- dedupePlugins(deduped, plugins);
1179
- const resolved = [...deduped];
1180
- RESOLVED_PLUGINS.set(plugins, resolved);
1181
- return resolved;
1182
- }
1183
- }
1184
- /**
1185
- * Returns the plugins that are tested for plain objects. It is the same array
1186
- * when no plugin sets `skipPlainObjects`.
1187
- */
1188
- function getPlainObjectPlugins(plugins) {
1189
- if (plugins) {
1190
- for (let i = 0, len = plugins.length; i < len; i++) if (plugins[i].skipPlainObjects) {
1191
- const result = plugins.filter((plugin) => !plugin.skipPlainObjects);
1192
- return result.length ? result : void 0;
1193
- }
1194
- }
1195
- return plugins;
1196
- }
1197
- //#endregion
1198
- //#region src/core/keys.ts
1199
- const REFERENCES_KEY = "__SEROVAL_REFS__";
1200
- const GLOBAL_CONTEXT_R = `self.\$R`;
1201
- function getCrossReferenceHeader(id) {
1202
- if (id == null) return `${GLOBAL_CONTEXT_R}=${GLOBAL_CONTEXT_R}||[]`;
1203
- return `(${GLOBAL_CONTEXT_R}=${GLOBAL_CONTEXT_R}||{})["${serializeString(id)}"]=[]`;
1204
- }
1205
- //#endregion
1206
- //#region src/core/reference.ts
1207
- const REFERENCE = /* @__PURE__ */ new Map();
1208
- const INV_REFERENCE = /* @__PURE__ */ new Map();
1209
- let installed = false;
1210
- function getGlobalObject() {
1211
- if (typeof globalThis !== "undefined") return globalThis;
1212
- if (typeof window !== "undefined") return window;
1213
- if (typeof self !== "undefined") return self;
1214
- if (typeof global !== "undefined") return global;
1215
- }
1216
- function installReferenceStore() {
1217
- if (!installed) {
1218
- installed = true;
1219
- const globalObject = getGlobalObject();
1220
- if (globalObject) Object.defineProperty(globalObject, REFERENCES_KEY, {
1221
- value: INV_REFERENCE,
1222
- configurable: true,
1223
- writable: false,
1224
- enumerable: false
1225
- });
1226
- }
1227
- }
1228
- function createReference(id, value) {
1229
- installReferenceStore();
1230
- REFERENCE.set(value, id);
1231
- INV_REFERENCE.set(id, value);
1232
- return value;
1233
- }
1234
- function hasReference(id) {
1235
- return INV_REFERENCE.has(id);
1236
- }
1237
- function getReferenceID(value) {
1238
- return REFERENCE.get(value);
1239
- }
1240
- function getReference(id) {
1241
- if (hasReference(id)) return INV_REFERENCE.get(id);
1242
- throw new SerovalMissingReferenceForIdError(id);
1243
- }
1244
- //#endregion
1245
- //#region src/core/context/parser.ts
1246
- function createBaseParserContext(options) {
1247
- return {
1248
- plugins: options.plugins,
1249
- plainObjectPlugins: getPlainObjectPlugins(options.plugins),
1250
- marked: /* @__PURE__ */ new Set(),
1251
- features: 127 ^ (options.disabledFeatures ?? 0),
1252
- refs: options.refs ?? /* @__PURE__ */ new Map(),
1253
- depthLimit: options.depthLimit || 1e3,
1254
- compactArrayBufferViews: options.compactArrayBufferViews ?? false
1255
- };
1256
- }
1257
- /**
1258
- * Returns the plugins to test for an object. Plain objects, whose prototype is
1259
- * `Object.prototype`, skip the plugins that set `skipPlainObjects`. Checking
1260
- * the prototype as well as `constructor` keeps instances whose prototype has
1261
- * no own `constructor` property from skipping those plugins.
1262
- */
1263
- function getObjectPlugins(ctx, current, currentClass) {
1264
- return currentClass === Object && Object.getPrototypeOf(current) === Object.prototype ? ctx.plainObjectPlugins : ctx.plugins;
1265
- }
1266
- /**
1267
- * Ensures that the value (based on an identifier) has been visited by the parser.
1268
- * @param ctx
1269
- * @param id
1270
- */
1271
- function markParserRef(ctx, id) {
1272
- ctx.marked.add(id);
1273
- }
1274
- /**
1275
- * Creates an identifier for a value
1276
- * @param ctx
1277
- * @param current
1278
- */
1279
- function createIndexForValue(ctx, current) {
1280
- const id = ctx.refs.size;
1281
- ctx.refs.set(current, id);
1282
- return id;
1283
- }
1284
- /**
1285
- * Removes the ids registered from `size` on. A parse that fails emits none of
1286
- * them, so a caller-owned map must not keep them for later calls.
1287
- */
1288
- function rollbackRefs(refs, size) {
1289
- if (refs.size > size) {
1290
- for (const [value, id] of refs) if (id >= size) refs.delete(value);
1291
- }
1292
- }
1293
- function getNodeForIndexedValue(ctx, current) {
1294
- const registeredId = ctx.refs.get(current);
1295
- if (registeredId != null) {
1296
- markParserRef(ctx, registeredId);
1297
- return createIndexedValueNode(registeredId);
1298
- }
1299
- return createIndexForValue(ctx, current);
1300
- }
1301
- function getReferenceNode(ctx, current) {
1302
- const indexed = getNodeForIndexedValue(ctx, current);
1303
- if (typeof indexed !== "number") return indexed;
1304
- const referenceId = getReferenceID(current);
1305
- return referenceId === void 0 ? indexed : createReferenceNode(indexed, referenceId);
1306
- }
1307
- /**
1308
- * Parsing methods
1309
- */
1310
- function parseWellKnownSymbol(ctx, current) {
1311
- const ref = getReferenceNode(ctx, current);
1312
- if (typeof ref !== "number") return ref;
1313
- if (current in INV_SYMBOL_REF) return createWKSymbolNode(ref, current);
1314
- throw new SerovalUnsupportedTypeError(current);
1315
- }
1316
- function parseSpecialReference(ctx, ref) {
1317
- const result = getNodeForIndexedValue(ctx, SPECIAL_REFS[ref]);
1318
- if (typeof result !== "number") return result;
1319
- return createSerovalNode(26, result, ref);
1320
- }
1321
- function parseIteratorFactory(ctx) {
1322
- const result = getNodeForIndexedValue(ctx, ITERATOR);
1323
- if (typeof result !== "number") return result;
1324
- return createSerovalNode(27, result, void 0, void 0, void 0, void 0, void 0, void 0, parseWellKnownSymbol(ctx, SYM_ITERATOR));
1325
- }
1326
- function parseAsyncIteratorFactory(ctx) {
1327
- const result = getNodeForIndexedValue(ctx, ASYNC_ITERATOR);
1328
- if (typeof result !== "number") return result;
1329
- return createSerovalNode(29, result, void 0, void 0, void 0, void 0, void 0, [parseSpecialReference(ctx, 1), parseWellKnownSymbol(ctx, SYM_ASYNC_ITERATOR)]);
1330
- }
1331
- function getTemporalType(currentClass) {
1332
- switch (currentClass) {
1333
- case Temporal.Instant: return 0;
1334
- case Temporal.Duration: return 1;
1335
- case Temporal.PlainDate: return 2;
1336
- case Temporal.PlainDateTime: return 3;
1337
- case Temporal.PlainMonthDay: return 4;
1338
- case Temporal.PlainTime: return 5;
1339
- case Temporal.PlainYearMonth: return 6;
1340
- case Temporal.ZonedDateTime: return 7;
1341
- default: return;
1342
- }
1343
- }
1344
- function getObjectClass(current) {
1345
- const proto = Object.getPrototypeOf(current);
1346
- if (proto === null) return void 0;
1347
- if (proto === Object.prototype) return Object;
1348
- const currentClass = proto.constructor;
1349
- if (typeof currentClass !== "function" || currentClass === Object || currentClass.prototype === proto) return currentClass;
1350
- return proto;
1351
- }
1352
- /**
1353
- * Decides how an object is parsed. Shared by the sync, stream and async
1354
- * parsers so the class checks and feature gates live in one place.
1355
- */
1356
- function getObjectKind(current, currentClass, features) {
1357
- switch (currentClass) {
1358
- case Object: return 1;
1359
- case void 0: return 2;
1360
- case Date: return 3;
1361
- case Error:
1362
- case EvalError:
1363
- case RangeError:
1364
- case ReferenceError:
1365
- case SyntaxError:
1366
- case TypeError:
1367
- case URIError: return 4;
1368
- case Number:
1369
- case Boolean:
1370
- case String:
1371
- case BigInt: return 6;
1372
- case ArrayBuffer: return 7;
1373
- case Int8Array:
1374
- case Int16Array:
1375
- case Int32Array:
1376
- case Uint8Array:
1377
- case Uint16Array:
1378
- case Uint32Array:
1379
- case Uint8ClampedArray:
1380
- case Float32Array:
1381
- case Float64Array: return 8;
1382
- case DataView: return 10;
1383
- case Map: return 11;
1384
- case Set: return 12;
1385
- }
1386
- if (currentClass === Promise || current instanceof Promise) return 13;
1387
- if (features & 32 && currentClass === RegExp) return 14;
1388
- if (features & 16 && (currentClass === BigInt64Array || currentClass === BigUint64Array)) return 9;
1389
- if (features & 1 && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) return 5;
1390
- if (features & 64 && typeof Temporal !== "undefined" && getTemporalType(currentClass) != null) return 15;
1391
- if (ArrayBuffer.isView(current)) {
1392
- const name = getTypedArrayName(current);
1393
- if (name === void 0) return 10;
1394
- if (name !== "BigInt64Array" && name !== "BigUint64Array") return 8;
1395
- if (features & 16) return 9;
1396
- }
1397
- if (current instanceof Error) return 4;
1398
- if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) return 16;
1399
- return 0;
1400
- }
1401
- function createObjectNode(id, current, empty, record) {
1402
- return createSerovalNode(empty ? 11 : 10, id, void 0, void 0, void 0, record, void 0, void 0, void 0, void 0, getObjectFlag(current));
1403
- }
1404
- /**
1405
- * Gets the sentinel node for a Map. Call it before parsing the entries, so
1406
- * that an outer Map declares the sentinel before any Map inside it uses it.
1407
- */
1408
- function parseMapSentinel(ctx) {
1409
- return parseSpecialReference(ctx, 0);
1410
- }
1411
- function createMapNode(id, sentinel, k, v) {
1412
- return createSerovalNode(8, id, void 0, void 0, void 0, void 0, {
1413
- k,
1414
- v
1415
- }, void 0, sentinel);
1416
- }
1417
- function createPromiseConstructorNode(ctx, id, resolver) {
1418
- return createSerovalNode(22, id, resolver, void 0, void 0, void 0, void 0, void 0, parseSpecialReference(ctx, 1));
1419
- }
1420
- function getArrayBufferView(ctx, view) {
1421
- if (!ctx.compactArrayBufferViews) return view;
1422
- return {
1423
- buffer: new Uint8Array(view.buffer, view.byteOffset, view.byteLength).slice().buffer,
1424
- byteOffset: 0,
1425
- byteLength: view.byteLength,
1426
- length: view.length
1427
- };
1428
- }
1429
- function createArrayBufferNode(ctx, id, current) {
1430
- return createSerovalNode(19, id, encodeArrayBuffer(current), void 0, void 0, void 0, void 0, void 0, parseSpecialReference(ctx, 5));
1431
- }
1432
- //#endregion
1433
- //#region src/core/context/async-parser.ts
1434
- function createAsyncParserContext(options) {
1435
- return { base: createBaseParserContext(options) };
1436
- }
1437
- function ignoreRejection$1() {}
1438
- /**
1439
- * A promise gets its rejection handler only when the walk reaches it. While an
1440
- * earlier sibling is still pending, a later one that rejects would be an
1441
- * unhandled rejection, which ends a Node.js process by default. Mark the
1442
- * promises among the children as handled before walking them.
1443
- */
1444
- function handleChildPromises(values) {
1445
- for (const value of values) if (value instanceof Promise) Promise.prototype.then.call(value, void 0, ignoreRejection$1);
1446
- }
1447
- async function parseItems$1(ctx, depth, current) {
1448
- assertArrayHoles(current);
1449
- const len = current.length;
1450
- const nodes = new Array(len);
1451
- const values = new Array(len);
1452
- const present = new Array(len);
1453
- for (let i = 0; i < len; i++) {
1454
- present[i] = i in current;
1455
- if (present[i]) values[i] = current[i];
1456
- }
1457
- handleChildPromises(values);
1458
- for (let i = 0, node; i < len; i++) if (present[i]) {
1459
- node = parseValueAsync(ctx, depth, values[i]);
1460
- nodes[i] = node instanceof Promise ? await node : node;
1461
- } else nodes[i] = 0;
1462
- return nodes;
1463
- }
1464
- async function parseArray$1(ctx, depth, id, current) {
1465
- return createArrayNode(id, current, await parseItems$1(ctx, depth, current));
1466
- }
1467
- async function parseProperties$1(ctx, depth, properties) {
1468
- const keys = Object.keys(properties);
1469
- const len = keys.length;
1470
- const keyNodes = new Array(len);
1471
- const valueNodes = new Array(len);
1472
- const values = new Array(len);
1473
- for (let i = 0; i < len; i++) values[i] = properties[keys[i]];
1474
- handleChildPromises(values);
1475
- for (let i = 0, node; i < len; i++) {
1476
- keyNodes[i] = serializeString(keys[i]);
1477
- node = parseValueAsync(ctx, depth, values[i]);
1478
- valueNodes[i] = node instanceof Promise ? await node : node;
1479
- }
1480
- if (SYM_ITERATOR in properties) {
1481
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
1482
- valueNodes.push(createIteratorFactoryInstanceNode(28, parseIteratorFactory(ctx.base), await parseAsync(ctx, depth, createSequenceFromIterable(properties))));
1483
- }
1484
- if (SYM_ASYNC_ITERATOR in properties) {
1485
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
1486
- valueNodes.push(createIteratorFactoryInstanceNode(30, parseAsyncIteratorFactory(ctx.base), await parseAsyncIterable$1(ctx, depth, properties)));
1487
- }
1488
- if (SYM_TO_STRING_TAG in properties) {
1489
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
1490
- valueNodes.push(createStringNode(properties[SYM_TO_STRING_TAG]));
1491
- }
1492
- if (SYM_IS_CONCAT_SPREADABLE in properties) {
1493
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_IS_CONCAT_SPREADABLE));
1494
- valueNodes.push(properties[SYM_IS_CONCAT_SPREADABLE] ? TRUE_NODE : FALSE_NODE);
1495
- }
1496
- return {
1497
- k: keyNodes,
1498
- v: valueNodes
1499
- };
1500
- }
1501
- async function parsePlainObject$1(ctx, depth, id, current, empty) {
1502
- return createObjectNode(id, current, empty, await parseProperties$1(ctx, depth, current));
1503
- }
1504
- async function parseBoxed$1(ctx, depth, id, current) {
1505
- const node = parseValueAsync(ctx, depth, current.valueOf());
1506
- return createBoxedNode(id, node instanceof Promise ? await node : node);
1507
- }
1508
- async function parseView$1(ctx, depth, type, id, current) {
1509
- const view = getArrayBufferView(ctx.base, readArrayBufferView(current, type === 20));
1510
- return createViewNode(type, id, current, view, await parseAsync(ctx, depth, view.buffer));
1511
- }
1512
- async function parseError$1(ctx, depth, type, id, current) {
1513
- const options = getErrorOptions(current, ctx.base.features);
1514
- return createErrorNode(type, id, current, options ? await parseProperties$1(ctx, depth, options) : void 0);
1515
- }
1516
- async function parseMap$1(ctx, depth, id, current) {
1517
- const sentinel = parseMapSentinel(ctx.base);
1518
- const entries = [...current.entries()];
1519
- const keyNodes = new Array(entries.length);
1520
- const valueNodes = new Array(entries.length);
1521
- const keys = new Array(entries.length);
1522
- const values = new Array(entries.length);
1523
- for (let i = 0; i < entries.length; i++) {
1524
- keys[i] = entries[i][0];
1525
- values[i] = entries[i][1];
1526
- }
1527
- handleChildPromises(keys);
1528
- handleChildPromises(values);
1529
- for (let i = 0, node; i < entries.length; i++) {
1530
- node = parseValueAsync(ctx, depth, keys[i]);
1531
- keyNodes[i] = node instanceof Promise ? await node : node;
1532
- node = parseValueAsync(ctx, depth, values[i]);
1533
- valueNodes[i] = node instanceof Promise ? await node : node;
1534
- }
1535
- return createMapNode(id, sentinel, keyNodes, valueNodes);
1536
- }
1537
- async function parseSet$1(ctx, depth, id, current) {
1538
- const values = [...current.keys()];
1539
- const items = new Array(values.length);
1540
- handleChildPromises(values);
1541
- for (let i = 0, node; i < values.length; i++) {
1542
- node = parseValueAsync(ctx, depth, values[i]);
1543
- items[i] = node instanceof Promise ? await node : node;
1544
- }
1545
- return createSetNode(id, items);
1546
- }
1547
- async function parsePlugin$1(ctx, depth, id, current, currentPlugins) {
1548
- if (currentPlugins) for (let i = 0, len = currentPlugins.length; i < len; i++) {
1549
- const plugin = currentPlugins[i];
1550
- if (plugin.parse.async && plugin.test(current)) return createPluginNode(id, plugin.tag, await plugin.parse.async(current, {
1551
- parse: (value) => parseAsync(ctx, depth, value),
1552
- parseStreamSource(source) {
1553
- if (depth >= ctx.base.depthLimit) throw new SerovalDepthLimitError(ctx.base.depthLimit);
1554
- return parseAsyncIterable$1(ctx, depth + 1, source);
1555
- }
1556
- }, { id }));
1557
- }
1558
- }
1559
- async function parsePromise$1(ctx, depth, id, current) {
1560
- const [status, result] = await promiseToResult(current);
1561
- return createSerovalNode(12, id, status, void 0, void 0, void 0, void 0, void 0, await parseAsync(ctx, depth, result));
1562
- }
1563
- function parseStreamHandle(depth, id, current, resolve, reject) {
1564
- const sequence = [];
1565
- let unparsed = 0;
1566
- let ended = false;
1567
- let settled = false;
1568
- const fail = (error) => {
1569
- if (!settled) {
1570
- settled = true;
1571
- try {
1572
- cleanup(error);
1573
- } catch {}
1574
- reject(error);
1575
- }
1576
- };
1577
- const handle = (type) => (value, accept) => {
1578
- if (settled) return;
1579
- markParserRef(this.base, id);
1580
- const slot = sequence.push(void 0) - 1;
1581
- unparsed++;
1582
- if (type !== 32) ended = true;
1583
- parseAsync(this, depth, value).then((data) => {
1584
- if (!settled) {
1585
- sequence[slot] = createStreamEventNode(type, id, data);
1586
- unparsed--;
1587
- accept?.();
1588
- if (ended && unparsed === 0) {
1589
- settled = true;
1590
- try {
1591
- cleanup();
1592
- } catch (error) {
1593
- reject(error);
1594
- return;
1595
- }
1596
- resolve(sequence);
1597
- }
1598
- }
1599
- }, fail);
1600
- };
1601
- const listener = {
1602
- next: handle(32),
1603
- throw: handle(33),
1604
- return: handle(34)
1605
- };
1606
- const cleanup = isLiveStream(current) ? current.pump(listener) : current.on(listener);
1607
- }
1608
- async function parseStream$1(ctx, depth, id, current) {
1609
- return createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), await new Promise(parseStreamHandle.bind(ctx, depth, id, current)));
1610
- }
1611
- /**
1612
- * Collects an async iterable into a replay node, one value at a time.
1613
- */
1614
- async function parseAsyncIterable$1(ctx, depth, current) {
1615
- const id = createIndexForValue(ctx.base, {});
1616
- const reference = parseSpecialReference(ctx.base, 4);
1617
- const iterator = current[SYM_ASYNC_ITERATOR]();
1618
- const sequence = [];
1619
- for (;;) {
1620
- let result;
1621
- markParserRef(ctx.base, id);
1622
- try {
1623
- result = await iterator.next();
1624
- } catch (error) {
1625
- sequence.push(createStreamEventNode(33, id, await parseAsync(ctx, depth, error)));
1626
- break;
1627
- }
1628
- let parsed;
1629
- try {
1630
- parsed = await parseAsync(ctx, depth, result.value);
1631
- } catch (error) {
1632
- Promise.resolve().then(() => iterator.return?.()).catch(() => {});
1633
- throw error;
1634
- }
1635
- sequence.push(createStreamEventNode(result.done ? 34 : 32, id, parsed));
1636
- if (result.done) break;
1637
- }
1638
- return createStreamConstructorNode(id, reference, sequence);
1639
- }
1640
- async function parseSequence$1(ctx, depth, id, current) {
1641
- const len = current.v.length;
1642
- const nodes = new Array(len);
1643
- for (let i = 0, node; i < len; i++) {
1644
- node = parseValueAsync(ctx, depth, current.v[i]);
1645
- nodes[i] = node instanceof Promise ? await node : node;
1646
- }
1647
- return createSequenceNode(id, nodes, current.t, current.d);
1648
- }
1649
- async function parseObjectAsync(ctx, depth, id, current) {
1650
- if (Array.isArray(current)) return parseArray$1(ctx, depth, id, current);
1651
- if (isStream(current)) return parseStream$1(ctx, depth, id, current);
1652
- if (isSequence(current)) return parseSequence$1(ctx, depth, id, current);
1653
- const currentClass = getObjectClass(current);
1654
- if (currentClass === OpaqueReference) return parseAsync(ctx, depth, current.replacement);
1655
- const parsed = await parsePlugin$1(ctx, depth, id, current, getObjectPlugins(ctx.base, current, currentClass));
1656
- if (parsed) return parsed;
1657
- if (currentClass === Object) return parsePlainObject$1(ctx, depth, id, current, false);
1658
- switch (getObjectKind(current, currentClass, ctx.base.features)) {
1659
- case 2: return parsePlainObject$1(ctx, depth, id, current, true);
1660
- case 3: return createDateNode(id, current);
1661
- case 4: return parseError$1(ctx, depth, 13, id, current);
1662
- case 5: return parseError$1(ctx, depth, 14, id, current);
1663
- case 6: return parseBoxed$1(ctx, depth, id, current);
1664
- case 7: return createArrayBufferNode(ctx.base, id, current);
1665
- case 8: return parseView$1(ctx, depth, 15, id, current);
1666
- case 9: return parseView$1(ctx, depth, 16, id, current);
1667
- case 10: return parseView$1(ctx, depth, 20, id, current);
1668
- case 11: return parseMap$1(ctx, depth, id, current);
1669
- case 12: return parseSet$1(ctx, depth, id, current);
1670
- case 13: return parsePromise$1(ctx, depth, id, current);
1671
- case 14: return createRegExpNode(id, current);
1672
- case 15: return createTemporalNode(id, getTemporalType(currentClass), currentClass, current);
1673
- case 16: return parsePlainObject$1(ctx, depth, id, current, !!currentClass);
1674
- default: throw new SerovalUnsupportedTypeError(current);
1675
- }
1676
- }
1677
- async function parseFunctionAsync(ctx, depth, current) {
1678
- const ref = getReferenceNode(ctx.base, current);
1679
- if (typeof ref !== "number") return ref;
1680
- const plugin = await parsePlugin$1(ctx, depth, ref, current, ctx.base.plugins);
1681
- if (plugin) return plugin;
1682
- throw new SerovalUnsupportedTypeError(current);
1683
- }
1684
- /**
1685
- * Parses primitives and already-seen values synchronously; only objects and
1686
- * functions come back as a Promise. Errors are thrown synchronously, which
1687
- * an async caller turns into a rejection as before.
1688
- */
1689
- function parseValueAsync(ctx, depth, current) {
1690
- if (depth >= ctx.base.depthLimit) throw new SerovalDepthLimitError(ctx.base.depthLimit);
1691
- switch (typeof current) {
1692
- case "boolean": return current ? TRUE_NODE : FALSE_NODE;
1693
- case "undefined": return UNDEFINED_NODE;
1694
- case "string": return createStringNode(current);
1695
- case "number": return createNumberNode(current);
1696
- case "bigint": return createBigIntNode(current);
1697
- case "object":
1698
- if (current) {
1699
- const ref = getReferenceNode(ctx.base, current);
1700
- return typeof ref === "number" ? parseObjectAsync(ctx, depth + 1, ref, current) : ref;
1701
- }
1702
- return NULL_NODE;
1703
- case "symbol": return parseWellKnownSymbol(ctx.base, current);
1704
- case "function": return parseFunctionAsync(ctx, depth, current);
1705
- default: throw new SerovalUnsupportedTypeError(current);
1706
- }
1707
- }
1708
- async function parseAsync(ctx, depth, current) {
1709
- return await parseValueAsync(ctx, depth, current);
1710
- }
1711
- async function parseTopAsync(ctx, current) {
1712
- const refs = ctx.base.refs;
1713
- const size = refs.size;
1714
- try {
1715
- return await parseAsync(ctx, 0, current);
1716
- } catch (error) {
1717
- rollbackRefs(refs, size);
1718
- throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
1719
- }
1720
- }
1721
- //#endregion
1722
- //#region src/core/utils/valid-properties.ts
1723
- function isValidKey(key) {
1724
- switch (key) {
1725
- case "constructor":
1726
- case "__proto__":
1727
- case "prototype":
1728
- case "__defineGetter__":
1729
- case "__defineSetter__":
1730
- case "__lookupGetter__":
1731
- case "__lookupSetter__": return false;
1732
- default: return true;
1733
- }
1734
- }
1735
- function isValidSymbol(symbol) {
1736
- switch (symbol) {
1737
- case SYM_ASYNC_ITERATOR:
1738
- case SYM_IS_CONCAT_SPREADABLE:
1739
- case SYM_TO_STRING_TAG:
1740
- case SYM_ITERATOR: return true;
1741
- default: return false;
1742
- }
1743
- }
1744
- //#endregion
1745
- //#region src/core/context/deserializer.ts
1746
- const DEFAULT_MAX_BASE64_LENGTH = 1e6;
1747
- const MAX_BIGINT_LENGTH = 1e4;
1748
- const MAX_REGEXP_SOURCE_LENGTH = 2e4;
1749
- function applyObjectFlag(obj, flag) {
1750
- switch (flag) {
1751
- case 3: return Object.freeze(obj);
1752
- case 1: return Object.preventExtensions(obj);
1753
- case 2: return Object.seal(obj);
1754
- default: return obj;
1755
- }
1756
- }
1757
- const DEFAULT_DEPTH_LIMIT = 1e3;
1758
- const MAX_REGEXP_PROPERTY_ESCAPES = 32;
1759
- const REGEXP_PROPERTY_ESCAPE = /\\[pP]\{/g;
1760
- function createBaseDeserializerContext(options) {
1761
- const maxBase64Length = options.maxBase64Length ?? DEFAULT_MAX_BASE64_LENGTH;
1762
- if (!Number.isSafeInteger(maxBase64Length) || maxBase64Length < 0) throw new RangeError("maxBase64Length must be a non-negative safe integer");
1763
- const refs = options.refs ?? /* @__PURE__ */ new Map();
1764
- if (!("types" in refs)) Object.assign(refs, { types: /* @__PURE__ */ new Map() });
1765
- return {
1766
- plugins: options.plugins,
1767
- refs,
1768
- features: options.features ?? 127 ^ (options.disabledFeatures ?? 0),
1769
- depthLimit: options.depthLimit || DEFAULT_DEPTH_LIMIT,
1770
- maxBase64Length,
1771
- regexpPropertyEscapes: MAX_REGEXP_PROPERTY_ESCAPES
1772
- };
1773
- }
1774
- function createVanillaDeserializerContext(options) {
1775
- return {
1776
- base: createBaseDeserializerContext(options),
1777
- marked: new Set(options.markedRefs)
1778
- };
1779
- }
1780
- function createCrossDeserializerContext(options) {
1781
- return {
1782
- base: createBaseDeserializerContext(options),
1783
- marked: void 0
1784
- };
1785
- }
1786
- function guardIndexedValue(ctx, id) {
1787
- const node = {
1788
- t: 4,
1789
- i: id
1790
- };
1791
- if (id < 0 || !Number.isInteger(id)) throw new SerovalMalformedNodeError(node);
1792
- if (ctx.refs.has(id)) throw new SerovalConflictedNodeIdError(node);
1793
- }
1794
- function isThennable(value) {
1795
- return !!value && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function";
1796
- }
1797
- const ignoreRejection = () => {};
1798
- function assignIndexedValue$1(ctx, id, value) {
1799
- guardIndexedValue(ctx.base, id);
1800
- if (value instanceof Promise) value.catch(ignoreRejection);
1801
- const marked = ctx.marked;
1802
- if (!marked || marked.has(id)) ctx.base.refs.set(id, value);
1803
- return value;
1804
- }
1805
- function deserializeKnownValue(node, record, key) {
1806
- if (Object.hasOwn(record, key)) return record[key];
1807
- throw new SerovalMalformedNodeError(node);
1808
- }
1809
- function deserializeReference(ctx, node) {
1810
- return assignIndexedValue$1(ctx, node.i, getReference(deserializeString(node.s)));
1811
- }
1812
- function validateNodeList(node, list) {
1813
- if (!Array.isArray(list)) throw new SerovalMalformedNodeError(node);
1814
- }
1815
- function deserializeArray(ctx, depth, node) {
1816
- const items = node.a;
1817
- validateNodeList(node, items);
1818
- const len = items.length;
1819
- const result = assignIndexedValue$1(ctx, node.i, new Array(len));
1820
- for (let i = 0, item; i < len; i++) {
1821
- item = items[i];
1822
- if (item) result[i] = deserialize$1(ctx, depth, item);
1823
- }
1824
- applyObjectFlag(result, node.o);
1825
- return result;
1826
- }
1827
- function assignStringProperty(object, key, value) {
1828
- if (isValidKey(key)) object[key] = value;
1829
- else Object.defineProperty(object, key, {
1830
- value,
1831
- configurable: true,
1832
- enumerable: true,
1833
- writable: true
1834
- });
1835
- }
1836
- function assignProperty(ctx, depth, object, key, value) {
1837
- if (typeof key === "string") assignStringProperty(object, deserializeString(key), deserialize$1(ctx, depth, value));
1838
- else {
1839
- const actual = deserialize$1(ctx, depth, key);
1840
- switch (typeof actual) {
1841
- case "string":
1842
- assignStringProperty(object, actual, deserialize$1(ctx, depth, value));
1843
- break;
1844
- case "symbol":
1845
- if (isValidSymbol(actual)) object[actual] = deserialize$1(ctx, depth, value);
1846
- break;
1847
- default: throw new SerovalMalformedNodeError(key);
1848
- }
1849
- }
1850
- }
1851
- function assignNodeType(ctx, id, type) {
1852
- ctx.base.refs.types.set(id, type);
1853
- }
1854
- function validateNodeType(ctx, node, id, type) {
1855
- if (ctx.base.refs.types.get(id) !== type) throw new SerovalMalformedNodeError(node);
1856
- }
1857
- function deserializeProperties(ctx, depth, node, result) {
1858
- const keys = node.k;
1859
- validateNodeList(node, keys);
1860
- validateNodeList(node, node.v);
1861
- const len = keys.length;
1862
- if (len > 0) for (let i = 0, vals = node.v; i < len; i++) assignProperty(ctx, depth, result, keys[i], vals[i]);
1863
- return result;
1864
- }
1865
- function deserializeObject(ctx, depth, node) {
1866
- const result = assignIndexedValue$1(ctx, node.i, node.t === 10 ? {} : Object.create(null));
1867
- deserializeProperties(ctx, depth, node.p, result);
1868
- applyObjectFlag(result, node.o);
1869
- return result;
1870
- }
1871
- function deserializeDate(ctx, node) {
1872
- return assignIndexedValue$1(ctx, node.i, new Date(node.s));
1873
- }
1874
- function deserializeTemporal(ctx, node) {
1875
- if (!(ctx.base.features & 64)) throw new SerovalUnsupportedNodeError(node);
1876
- const construct = Temporal[deserializeKnownValue(node, TEMPORAL_TYPE_NAME, node.c)];
1877
- return assignIndexedValue$1(ctx, node.i, construct.from(node.s));
1878
- }
1879
- function deserializeRegExp(ctx, node) {
1880
- if (ctx.base.features & 32) {
1881
- const source = deserializeString(node.c);
1882
- if (source.length > MAX_REGEXP_SOURCE_LENGTH) throw new SerovalMalformedNodeError(node);
1883
- if (/[uv]/.test(String(node.m))) {
1884
- const escapes = source.match(REGEXP_PROPERTY_ESCAPE);
1885
- if (escapes) {
1886
- ctx.base.regexpPropertyEscapes -= escapes.length;
1887
- if (ctx.base.regexpPropertyEscapes < 0) throw new SerovalMalformedNodeError(node);
1888
- }
1889
- }
1890
- return assignIndexedValue$1(ctx, node.i, new RegExp(source, node.m));
1891
- }
1892
- throw new SerovalUnsupportedNodeError(node);
1893
- }
1894
- function deserializeSet(ctx, depth, node) {
1895
- const result = assignIndexedValue$1(ctx, node.i, /* @__PURE__ */ new Set());
1896
- validateNodeList(node, node.a);
1897
- for (let i = 0, items = node.a, len = items.length; i < len; i++) result.add(deserialize$1(ctx, depth, items[i]));
1898
- return result;
1899
- }
1900
- function deserializeMap(ctx, depth, node) {
1901
- const result = assignIndexedValue$1(ctx, node.i, /* @__PURE__ */ new Map());
1902
- validateNodeList(node, node.e.k);
1903
- validateNodeList(node, node.e.v);
1904
- for (let i = 0, keys = node.e.k, vals = node.e.v, len = keys.length; i < len; i++) result.set(deserialize$1(ctx, depth, keys[i]), deserialize$1(ctx, depth, vals[i]));
1905
- return result;
1906
- }
1907
- function deserializeArrayBuffer(ctx, node) {
1908
- if (typeof node.s !== "string") throw new SerovalMalformedNodeError(node);
1909
- if (node.s.length > ctx.base.maxBase64Length) throw new RangeError("ArrayBuffer exceeds maxBase64Length (" + ctx.base.maxBase64Length + ")");
1910
- const buffer = decodeArrayBuffer(deserializeString(node.s));
1911
- return assignIndexedValue$1(ctx, node.i, buffer);
1912
- }
1913
- function deserializeView(ctx, depth, node, construct) {
1914
- const source = deserialize$1(ctx, depth, node.f);
1915
- if (!(source instanceof ArrayBuffer)) throw new SerovalMalformedNodeError(node);
1916
- const offset = node.b ?? 0;
1917
- if (offset < 0 || offset > source.byteLength) throw new SerovalMalformedNodeError(node);
1918
- return assignIndexedValue$1(ctx, node.i, construct ? new construct(source, offset, node.l) : new DataView(source, offset, node.l));
1919
- }
1920
- function deserializeDictionary(ctx, depth, node, result) {
1921
- if (node.p) {
1922
- const fields = deserializeProperties(ctx, depth, node.p, {});
1923
- Object.defineProperties(result, Object.getOwnPropertyDescriptors(fields));
1924
- }
1925
- return result;
1926
- }
1927
- function deserializeAggregateError(ctx, depth, node) {
1928
- return deserializeDictionary(ctx, depth, node, assignIndexedValue$1(ctx, node.i, new AggregateError([], deserializeString(node.m))));
1929
- }
1930
- function deserializeError(ctx, depth, node) {
1931
- const construct = deserializeKnownValue(node, ERROR_CONSTRUCTOR, node.s);
1932
- return deserializeDictionary(ctx, depth, node, assignIndexedValue$1(ctx, node.i, new construct(deserializeString(node.m))));
1933
- }
1934
- function deserializePromise(ctx, depth, node) {
1935
- const deferred = PROMISE_CONSTRUCTOR();
1936
- const result = assignIndexedValue$1(ctx, node.i, deferred.p);
1937
- const deserialized = deserialize$1(ctx, depth, node.f);
1938
- if (isThennable(deserialized)) throw new SerovalMalformedNodeError(node.f);
1939
- if (node.s) deferred.s(deserialized);
1940
- else deferred.f(deserialized);
1941
- return result;
1942
- }
1943
- function deserializeBoxed(ctx, depth, node) {
1944
- return assignIndexedValue$1(ctx, node.i, Object(deserialize$1(ctx, depth, node.f)));
1945
- }
1946
- function deserializePlugin(ctx, depth, node) {
1947
- const currentPlugins = ctx.base.plugins;
1948
- if (currentPlugins) {
1949
- const tag = deserializeString(node.c);
1950
- for (let i = 0, len = currentPlugins.length; i < len; i++) {
1951
- const plugin = currentPlugins[i];
1952
- if (plugin.tag === tag) return assignIndexedValue$1(ctx, node.i, plugin.deserialize(node.s, { deserialize: (current) => deserialize$1(ctx, depth, current) }, { id: node.i }));
1953
- }
1954
- }
1955
- throw new SerovalMissingPluginError(node.c);
1956
- }
1957
- function deserializePromiseConstructor(ctx, node) {
1958
- const value = assignIndexedValue$1(ctx, node.i, assignIndexedValue$1(ctx, node.s, PROMISE_CONSTRUCTOR()).p);
1959
- assignNodeType(ctx, node.s, 22);
1960
- ctx.base.pending?.add(node.s);
1961
- return value;
1962
- }
1963
- function deserializePromiseFulfill(ctx, depth, node) {
1964
- const deferred = ctx.base.refs.get(node.i);
1965
- if (deferred) {
1966
- validateNodeType(ctx, node, node.i, 22);
1967
- const deserialized = deserialize$1(ctx, depth, node.a[1]);
1968
- if (isThennable(deserialized)) throw new SerovalMalformedNodeError(node.a[1]);
1969
- if (node.t === 23) deferred.s(deserialized);
1970
- else deferred.f(deserialized);
1971
- ctx.base.pending?.delete(node.i);
1972
- return;
1973
- }
1974
- throw new SerovalMissingInstanceError("Promise");
1975
- }
1976
- function deserializeIteratorFactoryInstance(ctx, depth, node) {
1977
- deserialize$1(ctx, depth, node.a[0]);
1978
- const source = deserialize$1(ctx, depth, node.a[1]);
1979
- if (!isSequence(source)) throw new SerovalMalformedNodeError(node.a[1]);
1980
- return sequenceToIterator(source);
1981
- }
1982
- function deserializeAsyncIteratorFactoryInstance(ctx, depth, node) {
1983
- deserialize$1(ctx, depth, node.a[0]);
1984
- const source = deserialize$1(ctx, depth, node.a[1]);
1985
- if (!isStream(source)) throw new SerovalMalformedNodeError(node.a[1]);
1986
- return streamToAsyncIterable(source);
1987
- }
1988
- function deserializeStreamConstructor(ctx, depth, node) {
1989
- const result = assignIndexedValue$1(ctx, node.i, new Stream(node.l === 1 ? 1 : void 0));
1990
- assignNodeType(ctx, node.i, 31);
1991
- ctx.base.pending?.add(node.i);
1992
- const items = node.a;
1993
- validateNodeList(node, items);
1994
- const len = items.length;
1995
- if (len) for (let i = 0; i < len; i++) deserialize$1(ctx, depth, items[i]);
1996
- return result;
1997
- }
1998
- function deserializeStreamCall(ctx, depth, node, method) {
1999
- const deferred = ctx.base.refs.get(node.i);
2000
- if (deferred) {
2001
- validateNodeType(ctx, node, node.i, 31);
2002
- deferred[method](deserialize$1(ctx, depth, node.f));
2003
- if (method !== "next") ctx.base.pending?.delete(node.i);
2004
- return;
2005
- }
2006
- throw new SerovalMissingInstanceError("Stream");
2007
- }
2008
- function deserializeIteratorFactory(ctx, depth, node) {
2009
- deserialize$1(ctx, depth, node.f);
2010
- }
2011
- function deserializeAsyncIteratorFactory(ctx, depth, node) {
2012
- deserialize$1(ctx, depth, node.a[1]);
2013
- }
2014
- function isSequenceIndex(value, size) {
2015
- return Number.isInteger(value) && value >= -1 && value < size;
2016
- }
2017
- function deserializeSequence(ctx, depth, node) {
2018
- validateNodeList(node, node.a);
2019
- const size = node.a.length;
2020
- if (!(isSequenceIndex(node.s, size) && isSequenceIndex(node.l, size))) throw new SerovalMalformedNodeError(node);
2021
- const result = assignIndexedValue$1(ctx, node.i, createSequence([], node.s, node.l));
2022
- assignNodeType(ctx, node.i, 35);
2023
- for (let i = 0; i < size; i++) result.v[i] = deserialize$1(ctx, depth, node.a[i]);
2024
- return result;
2025
- }
2026
- function deserialize$1(ctx, depth, node) {
2027
- if (depth > ctx.base.depthLimit) throw new SerovalDepthLimitError(ctx.base.depthLimit);
2028
- depth += 1;
2029
- switch (node.t) {
2030
- case 2: return deserializeKnownValue(node, CONSTANT_VAL, node.s);
2031
- case 0: return Number(node.s);
2032
- case 1: return deserializeString(String(node.s));
2033
- case 3:
2034
- if (String(node.s).length > MAX_BIGINT_LENGTH) throw new SerovalMalformedNodeError(node);
2035
- return BigInt(node.s);
2036
- case 4: return ctx.base.refs.get(node.i);
2037
- case 18: return deserializeReference(ctx, node);
2038
- case 9: return deserializeArray(ctx, depth, node);
2039
- case 10:
2040
- case 11: return deserializeObject(ctx, depth, node);
2041
- case 5: return deserializeDate(ctx, node);
2042
- case 6: return deserializeRegExp(ctx, node);
2043
- case 7: return deserializeSet(ctx, depth, node);
2044
- case 8: return deserializeMap(ctx, depth, node);
2045
- case 19: return deserializeArrayBuffer(ctx, node);
2046
- case 16:
2047
- case 15: return deserializeView(ctx, depth, node, getTypedArrayConstructor(node.c));
2048
- case 20: return deserializeView(ctx, depth, node);
2049
- case 14: return deserializeAggregateError(ctx, depth, node);
2050
- case 13: return deserializeError(ctx, depth, node);
2051
- case 12: return deserializePromise(ctx, depth, node);
2052
- case 17: return deserializeKnownValue(node, SYMBOL_REF, node.s);
2053
- case 21: return deserializeBoxed(ctx, depth, node);
2054
- case 25: return deserializePlugin(ctx, depth, node);
2055
- case 22: return deserializePromiseConstructor(ctx, node);
2056
- case 23:
2057
- case 24: return deserializePromiseFulfill(ctx, depth, node);
2058
- case 28: return deserializeIteratorFactoryInstance(ctx, depth, node);
2059
- case 30: return deserializeAsyncIteratorFactoryInstance(ctx, depth, node);
2060
- case 31: return deserializeStreamConstructor(ctx, depth, node);
2061
- case 32: return deserializeStreamCall(ctx, depth, node, "next");
2062
- case 33: return deserializeStreamCall(ctx, depth, node, "throw");
2063
- case 34: return deserializeStreamCall(ctx, depth, node, "return");
2064
- case 27: return deserializeIteratorFactory(ctx, depth, node);
2065
- case 29: return deserializeAsyncIteratorFactory(ctx, depth, node);
2066
- case 35: return deserializeSequence(ctx, depth, node);
2067
- case 36: return deserializeTemporal(ctx, node);
2068
- default: throw new SerovalUnsupportedNodeError(node);
2069
- }
2070
- }
2071
- function deserializeTop(ctx, node) {
2072
- ctx.base.regexpPropertyEscapes = MAX_REGEXP_PROPERTY_ESCAPES;
2073
- try {
2074
- return deserialize$1(ctx, 0, node);
2075
- } catch (error) {
2076
- throw new SerovalDeserializationError(error);
2077
- }
2078
- }
2079
- /**
2080
- * Rejects every pending promise and throws into every open stream tracked
2081
- * by `ctx.base.pending`, then drops the bookkeeping so the context no longer
2082
- * accepts deferred values. Does nothing once the bookkeeping is gone.
2083
- */
2084
- function abortDeferred(ctx, reason) {
2085
- const pending = ctx.base.pending;
2086
- if (pending) {
2087
- ctx.base.pending = void 0;
2088
- const refs = ctx.base.refs;
2089
- const errors = [];
2090
- for (const id of pending) try {
2091
- const value = refs.get(id);
2092
- if (refs.types.get(id) === 22) value.f(reason);
2093
- else value.throw(reason);
2094
- } catch (error) {
2095
- errors.push(error);
2096
- }
2097
- if (errors.length) throw errors[0];
2098
- }
2099
- }
2100
- //#endregion
2101
- //#region src/core/function-string.ts
2102
- const RETURN = () => T;
2103
- const IS_MODERN = /* @__PURE__ */ (/* @__PURE__ */ RETURN.toString()).includes("=>");
2104
- function createFunction(parameters, body) {
2105
- if (IS_MODERN) return (parameters.length === 1 ? parameters[0] : "(" + parameters.join(",") + ")") + "=>" + (body.startsWith("{") ? "(" + body + ")" : body);
2106
- return "function(" + parameters.join(",") + "){return " + body + "}";
2107
- }
2108
- function createEffectfulFunction(parameters, body) {
2109
- if (IS_MODERN) return (parameters.length === 1 ? parameters[0] : "(" + parameters.join(",") + ")") + "=>{" + body + "}";
2110
- return "function(" + parameters.join(",") + "){" + body + "}";
2111
- }
2112
- //#endregion
2113
- //#region src/core/utils/get-identifier.ts
2114
- const REF_START_CHARS = "hjkmoquxzABCDEFGHIJKLNPQRTUVWXYZ$_";
2115
- const REF_START_CHARS_LEN = 34;
2116
- const REF_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_";
2117
- const REF_CHARS_LEN = 64;
2118
- function getIdentifier(index) {
2119
- let mod = index % REF_START_CHARS_LEN;
2120
- let ref = REF_START_CHARS[mod];
2121
- index = (index - mod) / REF_START_CHARS_LEN;
2122
- while (index > 0) {
2123
- mod = index % REF_CHARS_LEN;
2124
- ref += REF_CHARS[mod];
2125
- index = (index - mod) / REF_CHARS_LEN;
2126
- }
2127
- return ref;
2128
- }
2129
- //#endregion
2130
- //#region src/core/utils/is-valid-identifier.ts
2131
- function isValidIdentifier(name) {
2132
- const len = name.length;
2133
- for (let i = 0; i < len; i++) {
2134
- const code = name.charCodeAt(i);
2135
- if (!(code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 && i > 0 || code === 95 || code === 36)) return false;
2136
- }
2137
- return len > 0;
2138
- }
2139
- //#endregion
2140
- //#region src/core/context/serializer.ts
2141
- function getAssignmentExpression(assignment) {
2142
- switch (assignment.t) {
2143
- case 0: return assignment.s + "=" + assignment.v;
2144
- case 2: return assignment.s + ".set(" + assignment.k + "," + assignment.v + ")";
2145
- case 1: return assignment.s + ".add(" + assignment.v + ")";
2146
- case 3: return assignment.s + ".delete(" + assignment.k + ")";
2147
- case 4: return "Object.defineProperty(" + assignment.s + ",\"__proto__\",{value:" + assignment.k + ",configurable:!0,enumerable:!0,writable:!0})";
2148
- }
2149
- }
2150
- const MAX_ASSIGNMENT_CHAIN_LENGTH = 100;
2151
- function resolveAssignments(assignments, chainValues = true) {
2152
- if (!assignments.length) return void 0;
2153
- let previous = assignments[0];
2154
- let expression = getAssignmentExpression(previous);
2155
- let result = "";
2156
- let chainLength = 1;
2157
- for (let index = 1, length = assignments.length; index < length; index++) {
2158
- const assignment = assignments[index];
2159
- if (chainLength === MAX_ASSIGNMENT_CHAIN_LENGTH) {
2160
- result += expression + ",";
2161
- expression = getAssignmentExpression(assignment);
2162
- chainLength = 0;
2163
- } else if (chainValues && assignment.t === 0 && previous.t === 0 && assignment.v === previous.v) expression = assignment.s + "=" + expression;
2164
- else if (assignment.t === 2 && previous.t === 2 && assignment.s === previous.s) expression += ".set(" + assignment.k + "," + assignment.v + ")";
2165
- else if (assignment.t === 1 && previous.t === 1 && assignment.s === previous.s) expression += ".add(" + assignment.v + ")";
2166
- else if (assignment.t === 3 && previous.t === 2 && assignment.s === previous.s) expression += ".delete(" + assignment.k + ")";
2167
- else {
2168
- result += expression + ",";
2169
- expression = getAssignmentExpression(assignment);
2170
- chainLength = 0;
2171
- }
2172
- chainLength++;
2173
- previous = assignment;
2174
- }
2175
- return result + expression + ",";
2176
- }
2177
- const NULL_CONSTRUCTOR = "Object.create(null)";
2178
- const SET_CONSTRUCTOR = "new Set";
2179
- const MAP_CONSTRUCTOR = "new Map";
2180
- const PROMISE_RESOLVE = "Promise.resolve";
2181
- const PROMISE_REJECT = "Promise.reject";
2182
- const OBJECT_FLAG_CONSTRUCTOR = {
2183
- [3]: "Object.freeze",
2184
- [2]: "Object.seal",
2185
- [1]: "Object.preventExtensions",
2186
- [0]: void 0
2187
- };
2188
- function createBaseSerializerContext(mode, options) {
2189
- return {
2190
- mode,
2191
- plugins: options.plugins,
2192
- features: options.features,
2193
- marked: Array.isArray(options.markedRefs) ? new Set(options.markedRefs) : options.markedRefs,
2194
- stack: [],
2195
- flags: [],
2196
- assignments: [],
2197
- assignAll: mode === 2 && !options.assignSharedRefsOnly
2198
- };
2199
- }
2200
- function createVanillaSerializerState() {
2201
- return {
2202
- valid: /* @__PURE__ */ new Map(),
2203
- vars: [],
2204
- sentinels: /* @__PURE__ */ new Set()
2205
- };
2206
- }
2207
- function createVanillaSerializerContext(options) {
2208
- return {
2209
- mode: 1,
2210
- base: createBaseSerializerContext(1, options),
2211
- state: createVanillaSerializerState()
2212
- };
2213
- }
2214
- function createCrossSerializerContext(options) {
2215
- return {
2216
- mode: 2,
2217
- base: createBaseSerializerContext(2, options),
2218
- state: options
2219
- };
2220
- }
2221
- /**
2222
- * Creates the reference param (identifier) from the given reference ID
2223
- * Calling this function means the value has been referenced somewhere
2224
- */
2225
- function getVanillaRefParam(state, index) {
2226
- /**
2227
- * Creates a new reference ID from a given reference ID
2228
- * This new reference ID means that the reference itself
2229
- * has been referenced at least once, and is used to generate
2230
- * the variables
2231
- */
2232
- let actualIndex = state.valid.get(index);
2233
- if (actualIndex == null) {
2234
- actualIndex = state.valid.size;
2235
- state.valid.set(index, actualIndex);
2236
- }
2237
- let identifier = state.vars[actualIndex];
2238
- if (identifier == null) {
2239
- identifier = getIdentifier(actualIndex);
2240
- state.vars[actualIndex] = identifier;
2241
- }
2242
- return identifier;
2243
- }
2244
- function getCrossRefParam(id) {
2245
- return "$R[" + id + "]";
2246
- }
2247
- /**
2248
- * Converts the ID of a reference into a identifier string
2249
- * that is used to refer to the object instance in the
2250
- * generated script.
2251
- */
2252
- function getRefParam(ctx, id) {
2253
- return ctx.mode === 1 ? getVanillaRefParam(ctx.state, id) : getCrossRefParam(id);
2254
- }
2255
- function markSerializerRef(ctx, id) {
2256
- ctx.marked.add(id);
2257
- }
2258
- function isSerializerRefMarked(ctx, id) {
2259
- return ctx.marked.has(id);
2260
- }
2261
- function pushObjectFlag(ctx, flag, id) {
2262
- if (flag !== 0) {
2263
- markSerializerRef(ctx.base, id);
2264
- ctx.base.flags.push({
2265
- type: flag,
2266
- value: getRefParam(ctx, id)
2267
- });
2268
- }
2269
- }
2270
- function resolveFlags(ctx) {
2271
- let result = "";
2272
- for (let i = 0, current = ctx.flags, len = current.length; i < len; i++) {
2273
- const flag = current[i];
2274
- result += OBJECT_FLAG_CONSTRUCTOR[flag.type] + "(" + flag.value + "),";
2275
- }
2276
- return result;
2277
- }
2278
- function resolvePatches(ctx) {
2279
- const assignments = resolveAssignments(ctx.assignments);
2280
- const flags = resolveFlags(ctx);
2281
- if (assignments) {
2282
- if (flags) return assignments + flags;
2283
- return assignments;
2284
- }
2285
- return flags;
2286
- }
2287
- /**
2288
- * Generates the inlined assignment for the reference
2289
- * This is different from the assignments array as this one
2290
- * signifies creation rather than mutation
2291
- */
2292
- function createAssignment(ctx, source, value) {
2293
- ctx.assignments.push({
2294
- t: 0,
2295
- s: source,
2296
- k: void 0,
2297
- v: value
2298
- });
2299
- }
2300
- function createAddAssignment(ctx, ref, value) {
2301
- ctx.base.assignments.push({
2302
- t: 1,
2303
- s: getRefParam(ctx, ref),
2304
- k: void 0,
2305
- v: value
2306
- });
2307
- }
2308
- function createSetAssignment(ctx, ref, key, value) {
2309
- ctx.base.assignments.push({
2310
- t: 2,
2311
- s: getRefParam(ctx, ref),
2312
- k: key,
2313
- v: value
2314
- });
2315
- }
2316
- function createDeleteAssignment(ctx, ref, key) {
2317
- ctx.base.assignments.push({
2318
- t: 3,
2319
- s: getRefParam(ctx, ref),
2320
- k: key,
2321
- v: void 0
2322
- });
2323
- }
2324
- function createArrayAssign(ctx, ref, index, value) {
2325
- createAssignment(ctx.base, getRefParam(ctx, ref) + "[" + index + "]", value);
2326
- }
2327
- function createObjectAssign(ctx, ref, key, value) {
2328
- if (key === "__proto__") {
2329
- ctx.base.assignments.push({
2330
- t: 4,
2331
- s: getRefParam(ctx, ref),
2332
- k: value,
2333
- v: void 0
2334
- });
2335
- return;
2336
- }
2337
- createAssignment(ctx.base, getRefParam(ctx, ref) + "." + key, value);
2338
- }
2339
- function createSequenceAssign(ctx, ref, index, value) {
2340
- createAssignment(ctx.base, getRefParam(ctx, ref) + ".v[" + index + "]", value);
2341
- }
2342
- function getKeyKind(key) {
2343
- const first = key.charCodeAt(0);
2344
- if (first >= 48 && first <= 57) {
2345
- const check = Number(key);
2346
- return check >= 0 && check.toString() === key ? 2 : 0;
2347
- }
2348
- if (key === "Infinity") return 2;
2349
- return isValidIdentifier(key) ? 1 : 0;
2350
- }
2351
- /**
2352
- * Checks if the value is in the stack. Stack here is a reference
2353
- * structure to know if a object is to be accessed in a TDZ.
2354
- */
2355
- function isIndexedValueInStack(ctx, node) {
2356
- return node.t === 4 && ctx.stack.includes(node.i);
2357
- }
2358
- /**
2359
- * Checks if the node, or any node inside it, is read from more than one
2360
- * place. Such a node must not be created inside a deferred assignment,
2361
- * because the places that read it may run before the assignment does.
2362
- */
2363
- function hasMarkedNode(ctx, node) {
2364
- if (Array.isArray(node)) {
2365
- for (let i = 0, len = node.length; i < len; i++) if (hasMarkedNode(ctx, node[i])) return true;
2366
- return false;
2367
- }
2368
- if (node == null || typeof node !== "object") return false;
2369
- const current = node;
2370
- if (current.t !== 4 && typeof current.i === "number" && isSerializerRefMarked(ctx, current.i)) return true;
2371
- for (const key in current) if (hasMarkedNode(ctx, current[key])) return true;
2372
- return false;
2373
- }
2374
- /**
2375
- * Produces an assignment expression. `id` generates a reference
2376
- * parameter (through `getRefParam`) and has the option to
2377
- * return the reference parameter directly or assign a value to
2378
- * it.
2379
- */
2380
- function assignIndexedValue(ctx, index, value) {
2381
- if (!ctx.base.assignAll && !isSerializerRefMarked(ctx.base, index)) return value;
2382
- /**
2383
- * In cross-reference, we have to assume that
2384
- * every reference are going to be referenced
2385
- * in the future, and so we need to store
2386
- * all of it into the reference array.
2387
- *
2388
- * otherwise in vanilla, we only do this if it
2389
- * is actually referenced. `assignSharedRefsOnly` gives cross-reference
2390
- * output the vanilla behavior.
2391
- */
2392
- return getRefParam(ctx, index) + "=" + value;
2393
- }
2394
- function serializeReference(node) {
2395
- return REFERENCES_KEY + ".get(\"" + node.s + "\")";
2396
- }
2397
- function serializeArrayItem(ctx, id, item, index) {
2398
- if (item) {
2399
- if (isIndexedValueInStack(ctx.base, item)) {
2400
- markSerializerRef(ctx.base, id);
2401
- createArrayAssign(ctx, id, index, getRefParam(ctx, item.i));
2402
- return "";
2403
- }
2404
- return serialize$1(ctx, item);
2405
- }
2406
- return "";
2407
- }
2408
- function serializeArray(ctx, node) {
2409
- const id = node.i;
2410
- const list = node.a;
2411
- const len = list.length;
2412
- if (len > 0) {
2413
- ctx.base.stack.push(id);
2414
- let values = serializeArrayItem(ctx, id, list[0], 0);
2415
- let isHoley = values === "";
2416
- for (let i = 1, item; i < len; i++) {
2417
- item = serializeArrayItem(ctx, id, list[i], i);
2418
- values += "," + item;
2419
- isHoley = item === "";
2420
- }
2421
- ctx.base.stack.pop();
2422
- pushObjectFlag(ctx, node.o, node.i);
2423
- return "[" + values + (isHoley ? ",]" : "]");
2424
- }
2425
- return "[]";
2426
- }
2427
- function serializeProperty(ctx, source, key, val) {
2428
- if (typeof key === "string") {
2429
- const kind = getKeyKind(key);
2430
- if (isIndexedValueInStack(ctx.base, val)) {
2431
- const refParam = getRefParam(ctx, val.i);
2432
- markSerializerRef(ctx.base, source.i);
2433
- createKeyAssign(ctx, source.i, kind, key, refParam);
2434
- return "";
2435
- }
2436
- if (key !== "__proto__") return (kind === 0 ? "\"" + key + "\"" : key) + ":" + serialize$1(ctx, val);
2437
- return "[\"" + key + "\"]:" + serialize$1(ctx, val);
2438
- }
2439
- return "[" + serialize$1(ctx, key) + "]:" + serialize$1(ctx, val);
2440
- }
2441
- function serializeProperties(ctx, source, record) {
2442
- const keys = record.k;
2443
- const len = keys.length;
2444
- if (len > 0) {
2445
- const values = record.v;
2446
- ctx.base.stack.push(source.i);
2447
- let result = serializeProperty(ctx, source, keys[0], values[0]);
2448
- for (let i = 1, item; i < len; i++) {
2449
- item = serializeProperty(ctx, source, keys[i], values[i]);
2450
- result += (item && result && ",") + item;
2451
- }
2452
- ctx.base.stack.pop();
2453
- return "{" + result + "}";
2454
- }
2455
- return "{}";
2456
- }
2457
- function serializeObject(ctx, node) {
2458
- pushObjectFlag(ctx, node.o, node.i);
2459
- return serializeProperties(ctx, node, node.p);
2460
- }
2461
- function serializeWithObjectAssign(ctx, source, value, serialized) {
2462
- const fields = serializeProperties(ctx, source, value);
2463
- if (fields !== "{}") return "Object.assign(" + serialized + "," + fields + ")";
2464
- return serialized;
2465
- }
2466
- function serializeStringKeyAssignment(ctx, source, mainAssignments, key, value) {
2467
- const base = ctx.base;
2468
- const serialized = serialize$1(ctx, value);
2469
- const parentAssignment = base.assignments;
2470
- if (!isIndexedValueInStack(base, value)) base.assignments = mainAssignments;
2471
- createKeyAssign(ctx, source.i, getKeyKind(key), key, serialized);
2472
- base.assignments = parentAssignment;
2473
- }
2474
- function createKeyAssign(ctx, ref, kind, key, value) {
2475
- if (kind === 1) createObjectAssign(ctx, ref, key, value);
2476
- else createArrayAssign(ctx, ref, kind === 2 ? key : "\"" + key + "\"", value);
2477
- }
2478
- function serializeAssignment(ctx, source, mainAssignments, key, value) {
2479
- if (typeof key === "string") serializeStringKeyAssignment(ctx, source, mainAssignments, key, value);
2480
- else {
2481
- const base = ctx.base;
2482
- const parent = base.stack;
2483
- base.stack = [];
2484
- const serialized = serialize$1(ctx, value);
2485
- base.stack = parent;
2486
- const parentAssignment = base.assignments;
2487
- base.assignments = mainAssignments;
2488
- createArrayAssign(ctx, source.i, serialize$1(ctx, key), serialized);
2489
- base.assignments = parentAssignment;
2490
- }
2491
- }
2492
- function serializeAssignments(ctx, source, node) {
2493
- const keys = node.k;
2494
- const len = keys.length;
2495
- if (len > 0) {
2496
- const mainAssignments = [];
2497
- const values = node.v;
2498
- ctx.base.stack.push(source.i);
2499
- for (let i = 0; i < len; i++) serializeAssignment(ctx, source, mainAssignments, keys[i], values[i]);
2500
- ctx.base.stack.pop();
2501
- return resolveAssignments(mainAssignments, false);
2502
- }
2503
- }
2504
- function serializeDictionary(ctx, node, init) {
2505
- if (node.p) {
2506
- const base = ctx.base;
2507
- if (base.features & 8 && !node.p.k.includes("__proto__")) init = serializeWithObjectAssign(ctx, node, node.p, init);
2508
- else {
2509
- markSerializerRef(base, node.i);
2510
- const assignments = serializeAssignments(ctx, node, node.p);
2511
- if (assignments) return "(" + assignIndexedValue(ctx, node.i, init) + "," + assignments + getRefParam(ctx, node.i) + ")";
2512
- }
2513
- }
2514
- return init;
2515
- }
2516
- function serializeNullConstructor(ctx, node) {
2517
- pushObjectFlag(ctx, node.o, node.i);
2518
- return serializeDictionary(ctx, node, NULL_CONSTRUCTOR);
2519
- }
2520
- function serializeDate(node) {
2521
- return "new Date(\"" + serializeString(node.s) + "\")";
2522
- }
2523
- function serializeTemporal(ctx, node) {
2524
- if (ctx.base.features & 64) return "Temporal." + TEMPORAL_TYPE_NAME[node.c] + ".from(\"" + serializeString(node.s) + "\")";
2525
- throw new SerovalUnsupportedNodeError(node);
2526
- }
2527
- function serializeRegExp(ctx, node) {
2528
- if (ctx.base.features & 32) {
2529
- if (node.c.includes("\\x3C")) return "new RegExp(\"" + node.c + "\",\"" + node.m + "\")";
2530
- return "/" + deserializeString(node.c) + "/" + node.m;
2531
- }
2532
- throw new SerovalUnsupportedNodeError(node);
2533
- }
2534
- function serializeSetItem(ctx, id, item) {
2535
- const base = ctx.base;
2536
- if (isIndexedValueInStack(base, item)) {
2537
- markSerializerRef(base, id);
2538
- createAddAssignment(ctx, id, getRefParam(ctx, item.i));
2539
- return "";
2540
- }
2541
- return serialize$1(ctx, item);
2542
- }
2543
- function serializeSet(ctx, node) {
2544
- let serialized = SET_CONSTRUCTOR;
2545
- const items = node.a;
2546
- const size = items.length;
2547
- const id = node.i;
2548
- if (size > 0) {
2549
- ctx.base.stack.push(id);
2550
- let result = serializeSetItem(ctx, id, items[0]);
2551
- for (let i = 1, item; i < size; i++) {
2552
- item = serializeSetItem(ctx, id, items[i]);
2553
- result += (item && result && ",") + item;
2554
- }
2555
- ctx.base.stack.pop();
2556
- if (result) serialized += "([" + result + "])";
2557
- }
2558
- return serialized;
2559
- }
2560
- function serializeMapEntry(ctx, id, key, val, getSentinel) {
2561
- const base = ctx.base;
2562
- if (isIndexedValueInStack(base, key)) {
2563
- const keyRef = getRefParam(ctx, key.i);
2564
- markSerializerRef(base, id);
2565
- if (isIndexedValueInStack(base, val)) {
2566
- createSetAssignment(ctx, id, keyRef, getRefParam(ctx, val.i));
2567
- return "";
2568
- }
2569
- if (val.t !== 4 && val.i != null && hasMarkedNode(base, val)) {
2570
- markSerializerRef(base, val.i);
2571
- const sentinel = getSentinel();
2572
- const serialized = "(" + serialize$1(ctx, val) + ",[" + sentinel + "," + sentinel + "])";
2573
- createSetAssignment(ctx, id, keyRef, getRefParam(ctx, val.i));
2574
- createDeleteAssignment(ctx, id, sentinel);
2575
- return serialized;
2576
- }
2577
- const parent = base.stack;
2578
- base.stack = [];
2579
- createSetAssignment(ctx, id, keyRef, serialize$1(ctx, val));
2580
- base.stack = parent;
2581
- return "";
2582
- }
2583
- if (isIndexedValueInStack(base, val)) {
2584
- const valueRef = getRefParam(ctx, val.i);
2585
- markSerializerRef(base, id);
2586
- if (key.t !== 4 && key.i != null && hasMarkedNode(base, key)) {
2587
- markSerializerRef(base, key.i);
2588
- const sentinel = getSentinel();
2589
- const serialized = "(" + serialize$1(ctx, key) + ",[" + sentinel + "," + sentinel + "])";
2590
- createSetAssignment(ctx, id, getRefParam(ctx, key.i), valueRef);
2591
- createDeleteAssignment(ctx, id, sentinel);
2592
- return serialized;
2593
- }
2594
- const parent = base.stack;
2595
- base.stack = [];
2596
- createSetAssignment(ctx, id, serialize$1(ctx, key), valueRef);
2597
- base.stack = parent;
2598
- return "";
2599
- }
2600
- return "[" + serialize$1(ctx, key) + "," + serialize$1(ctx, val) + "]";
2601
- }
2602
- function serializeMap(ctx, node) {
2603
- let serialized = MAP_CONSTRUCTOR;
2604
- const keys = node.e.k;
2605
- const size = keys.length;
2606
- const id = node.i;
2607
- const sentinel = node.f;
2608
- let sentinelRef;
2609
- const getSentinel = () => {
2610
- if (sentinelRef == null) {
2611
- sentinelRef = getRefParam(ctx, sentinel.i);
2612
- if (ctx.mode === 1) ctx.state.sentinels.add(ctx.state.valid.get(sentinel.i));
2613
- }
2614
- return sentinelRef;
2615
- };
2616
- const base = ctx.base;
2617
- if (size > 0) {
2618
- const vals = node.e.v;
2619
- base.stack.push(id);
2620
- let result = serializeMapEntry(ctx, id, keys[0], vals[0], getSentinel);
2621
- for (let i = 1, item; i < size; i++) {
2622
- item = serializeMapEntry(ctx, id, keys[i], vals[i], getSentinel);
2623
- result += (item && result && ",") + item;
2624
- }
2625
- base.stack.pop();
2626
- if (result) serialized += "([" + result + "])";
2627
- }
2628
- if (ctx.mode === 2 && sentinel.t === 26) {
2629
- markSerializerRef(base, sentinel.i);
2630
- serialized = "(" + serialize$1(ctx, sentinel) + "," + serialized + ")";
2631
- }
2632
- return serialized;
2633
- }
2634
- function serializeArrayBuffer(ctx, node) {
2635
- return getConstructor(ctx, node.f) + "(\"" + node.s + "\")";
2636
- }
2637
- function serializeView(ctx, node) {
2638
- return "new " + (node.t === 20 ? "DataView" : node.c) + "(" + serialize$1(ctx, node.f) + "," + +node.b + "," + +node.l + ")";
2639
- }
2640
- function serializeAggregateError(ctx, node) {
2641
- const id = node.i;
2642
- ctx.base.stack.push(id);
2643
- const serialized = serializeDictionary(ctx, node, "new AggregateError([],\"" + node.m + "\")");
2644
- ctx.base.stack.pop();
2645
- return serialized;
2646
- }
2647
- function serializeError(ctx, node) {
2648
- return serializeDictionary(ctx, node, "new " + ERROR_CONSTRUCTOR_STRING[node.s] + "(\"" + node.m + "\")");
2649
- }
2650
- function serializePromise(ctx, node) {
2651
- let serialized;
2652
- const fulfilled = node.f;
2653
- const id = node.i;
2654
- const promiseConstructor = node.s ? PROMISE_RESOLVE : PROMISE_REJECT;
2655
- const base = ctx.base;
2656
- if (isIndexedValueInStack(base, fulfilled)) {
2657
- const ref = getRefParam(ctx, fulfilled.i);
2658
- serialized = promiseConstructor + (node.s ? "().then(" + createFunction([], ref) + ")" : "().catch(" + createEffectfulFunction([], "throw " + ref) + ")");
2659
- } else {
2660
- base.stack.push(id);
2661
- const result = serialize$1(ctx, fulfilled);
2662
- base.stack.pop();
2663
- serialized = promiseConstructor + "(" + result + ")";
2664
- }
2665
- return serialized;
2666
- }
2667
- function serializeBoxed(ctx, node) {
2668
- return "Object(" + serialize$1(ctx, node.f) + ")";
2669
- }
2670
- function getConstructor(ctx, node) {
2671
- const current = serialize$1(ctx, node);
2672
- return node.t === 4 ? current : "(" + current + ")";
2673
- }
2674
- function serializePromiseConstructor(ctx, node) {
2675
- if (ctx.mode === 1) throw new SerovalUnsupportedNodeError(node);
2676
- return "(" + assignIndexedValue(ctx, node.s, getConstructor(ctx, node.f) + "()") + ").p";
2677
- }
2678
- function serializePromiseResult(ctx, node) {
2679
- if (ctx.mode === 1) throw new SerovalUnsupportedNodeError(node);
2680
- return getConstructor(ctx, node.a[0]) + "(" + getRefParam(ctx, node.i) + "," + serialize$1(ctx, node.a[1]) + ")";
2681
- }
2682
- function serializePlugin(ctx, node) {
2683
- const currentPlugins = ctx.base.plugins;
2684
- if (currentPlugins) for (let i = 0, len = currentPlugins.length; i < len; i++) {
2685
- const plugin = currentPlugins[i];
2686
- if (plugin.tag === node.c) return plugin.serialize(node.s, { serialize: (current) => serialize$1(ctx, current) }, { id: node.i });
2687
- }
2688
- throw new SerovalMissingPluginError(node.c);
2689
- }
2690
- function serializeIteratorFactory(ctx, node) {
2691
- let result = "";
2692
- let initialized = false;
2693
- if (node.f.t !== 4) {
2694
- markSerializerRef(ctx.base, node.f.i);
2695
- result = "(" + serialize$1(ctx, node.f) + ",";
2696
- initialized = true;
2697
- }
2698
- result += assignIndexedValue(ctx, node.i, "(" + SERIALIZED_ITERATOR_CONSTRUCTOR + ")(" + getRefParam(ctx, node.f.i) + ")");
2699
- if (initialized) result += ")";
2700
- return result;
2701
- }
2702
- function serializeIteratorFactoryInstance(ctx, node) {
2703
- return getConstructor(ctx, node.a[0]) + "(" + serialize$1(ctx, node.a[1]) + ")";
2704
- }
2705
- function serializeAsyncIteratorFactory(ctx, node) {
2706
- const promise = node.a[0];
2707
- const symbol = node.a[1];
2708
- const base = ctx.base;
2709
- let result = "";
2710
- if (promise.t !== 4) {
2711
- markSerializerRef(base, promise.i);
2712
- result += "(" + serialize$1(ctx, promise);
2713
- }
2714
- if (symbol.t !== 4) {
2715
- markSerializerRef(base, symbol.i);
2716
- result += (result ? "," : "(") + serialize$1(ctx, symbol);
2717
- }
2718
- if (result) result += ",";
2719
- const iterator = assignIndexedValue(ctx, node.i, "(" + SERIALIZED_ASYNC_ITERATOR_CONSTRUCTOR + ")(" + getRefParam(ctx, symbol.i) + "," + getRefParam(ctx, promise.i) + ")");
2720
- if (result) return result + iterator + ")";
2721
- return iterator;
2722
- }
2723
- function serializeStreamConstructor(ctx, node) {
2724
- const result = assignIndexedValue(ctx, node.i, getConstructor(ctx, node.f) + (node.l === 1 ? "(1)" : "()"));
2725
- const len = node.a.length;
2726
- if (len) {
2727
- let values = serialize$1(ctx, node.a[0]);
2728
- for (let i = 1; i < len; i++) values += "," + serialize$1(ctx, node.a[i]);
2729
- return "(" + result + "," + values + "," + getRefParam(ctx, node.i) + ")";
2730
- }
2731
- return result;
2732
- }
2733
- function serializeStreamCall(ctx, node, method) {
2734
- return getRefParam(ctx, node.i) + "." + method + "(" + serialize$1(ctx, node.f) + ")";
2735
- }
2736
- function serializeSequenceItem(ctx, id, index, item) {
2737
- const base = ctx.base;
2738
- if (isIndexedValueInStack(base, item)) {
2739
- markSerializerRef(base, id);
2740
- createSequenceAssign(ctx, id, index, getRefParam(ctx, item.i));
2741
- return "";
2742
- }
2743
- return serialize$1(ctx, item);
2744
- }
2745
- function serializeSequence(ctx, node) {
2746
- const items = node.a;
2747
- const size = items.length;
2748
- const id = node.i;
2749
- if (size > 0) {
2750
- ctx.base.stack.push(id);
2751
- let result = serializeSequenceItem(ctx, id, 0, items[0]);
2752
- for (let i = 1, item; i < size; i++) {
2753
- item = serializeSequenceItem(ctx, id, i, items[i]);
2754
- result += (item && result && ",") + item;
2755
- }
2756
- ctx.base.stack.pop();
2757
- if (result) return "{__SEROVAL_SEQUENCE__:!0,v:[" + result + "],t:" + +node.s + ",d:" + +node.l + "}";
2758
- }
2759
- return "{__SEROVAL_SEQUENCE__:!0,v:[],t:-1,d:0}";
2760
- }
2761
- function serializeAssignable(ctx, node) {
2762
- switch (node.t) {
2763
- case 17: return SYMBOL_STRING[node.s];
2764
- case 18: return serializeReference(node);
2765
- case 9: return serializeArray(ctx, node);
2766
- case 10: return serializeObject(ctx, node);
2767
- case 11: return serializeNullConstructor(ctx, node);
2768
- case 5: return serializeDate(node);
2769
- case 6: return serializeRegExp(ctx, node);
2770
- case 7: return serializeSet(ctx, node);
2771
- case 8: return serializeMap(ctx, node);
2772
- case 19: return serializeArrayBuffer(ctx, node);
2773
- case 16:
2774
- case 15:
2775
- case 20: return serializeView(ctx, node);
2776
- case 14: return serializeAggregateError(ctx, node);
2777
- case 13: return serializeError(ctx, node);
2778
- case 12: return serializePromise(ctx, node);
2779
- case 21: return serializeBoxed(ctx, node);
2780
- case 22: return serializePromiseConstructor(ctx, node);
2781
- case 25: return serializePlugin(ctx, node);
2782
- case 26: return SPECIAL_REF_STRING[node.s];
2783
- case 35: return serializeSequence(ctx, node);
2784
- case 36: return serializeTemporal(ctx, node);
2785
- default: throw new SerovalUnsupportedNodeError(node);
2786
- }
2787
- }
2788
- function serialize$1(ctx, node) {
2789
- switch (node.t) {
2790
- case 2: return CONSTANT_STRING[node.s];
2791
- case 0: return "" + node.s;
2792
- case 1: return "\"" + node.s + "\"";
2793
- case 3: return node.s + "n";
2794
- case 4: return getRefParam(ctx, node.i);
2795
- case 23:
2796
- case 24: return serializePromiseResult(ctx, node);
2797
- case 27: return serializeIteratorFactory(ctx, node);
2798
- case 28:
2799
- case 30: return serializeIteratorFactoryInstance(ctx, node);
2800
- case 29: return serializeAsyncIteratorFactory(ctx, node);
2801
- case 31: return serializeStreamConstructor(ctx, node);
2802
- case 32: return serializeStreamCall(ctx, node, "next");
2803
- case 33: return serializeStreamCall(ctx, node, "throw");
2804
- case 34: return serializeStreamCall(ctx, node, "return");
2805
- default: return assignIndexedValue(ctx, node.i, serializeAssignable(ctx, node));
2806
- }
2807
- }
2808
- function serializeVanilla(ctx, tree) {
2809
- const result = serialize$1(ctx, tree);
2810
- if (tree.i != null && ctx.state.vars.length) {
2811
- const patches = resolvePatches(ctx.base);
2812
- let body = result;
2813
- if (patches) {
2814
- const index = getRefParam(ctx, tree.i);
2815
- body = result + "," + patches + index;
2816
- if (!result.startsWith(index + "=")) body = index + "=" + body;
2817
- body = "(" + body + ")";
2818
- }
2819
- const sentinels = ctx.state.sentinels;
2820
- if (sentinels.size) {
2821
- let declarations = "";
2822
- for (const index of sentinels) declarations += ctx.state.vars[index] + "=[],";
2823
- body = "(" + declarations + body + ")";
2824
- }
2825
- return "(" + createFunction(ctx.state.vars, body) + ")()";
2826
- }
2827
- if (tree.t === 10) return "(" + result + ")";
2828
- return result;
2829
- }
2830
- function serializeCross(ctx, tree) {
2831
- const result = serialize$1(ctx, tree);
2832
- const id = tree.i;
2833
- if (id == null) return result;
2834
- const patches = resolvePatches(ctx.base);
2835
- const ref = getRefParam(ctx, id);
2836
- let body = result;
2837
- if (patches) {
2838
- if (!ctx.base.assignAll && !result.startsWith(ref + "=")) body = ref + "=" + result;
2839
- body = "(" + body + "," + patches + ref + ")";
2840
- }
2841
- const scopeId = ctx.state.scopeId;
2842
- if (scopeId == null) {
2843
- if (tree.t === 10 && !patches) return "(" + body + ")";
2844
- return body;
2845
- }
2846
- return "(" + createFunction(["$R"], body) + ")($R[\"" + serializeString(scopeId) + "\"])";
2847
- }
2848
- function wrapSerializationError(error) {
2849
- return error instanceof SerovalSerializationError ? error : new SerovalSerializationError(error);
2850
- }
2851
- function serializeTopVanilla(ctx, tree) {
2852
- try {
2853
- return serializeVanilla(ctx, tree);
2854
- } catch (error) {
2855
- throw wrapSerializationError(error);
2856
- }
2857
- }
2858
- function serializeTopCross(ctx, tree) {
2859
- try {
2860
- return serializeCross(ctx, tree);
2861
- } catch (error) {
2862
- throw wrapSerializationError(error);
2863
- }
2864
- }
2865
- //#endregion
2866
- //#region src/core/context/sync-parser.ts
2867
- function createSyncParserContext(options) {
2868
- return {
2869
- type: 1,
2870
- base: createBaseParserContext(options)
2871
- };
2872
- }
2873
- function parseItems(ctx, depth, current) {
2874
- assertArrayHoles(current);
2875
- const len = current.length;
2876
- const nodes = new Array(len);
2877
- for (let i = 0; i < len; i++) if (i in current) nodes[i] = parseSOS(ctx, depth, current[i]);
2878
- else nodes[i] = 0;
2879
- return nodes;
2880
- }
2881
- function parseArray(ctx, depth, id, current) {
2882
- return createArrayNode(id, current, parseItems(ctx, depth, current));
2883
- }
2884
- function parseProperties(ctx, depth, properties) {
2885
- const keys = Object.keys(properties);
2886
- const len = keys.length;
2887
- const keyNodes = new Array(len);
2888
- const valueNodes = new Array(len);
2889
- for (let i = 0, key; i < len; i++) {
2890
- key = keys[i];
2891
- keyNodes[i] = serializeString(key);
2892
- valueNodes[i] = parseSOS(ctx, depth, properties[key]);
2893
- }
2894
- if (SYM_ITERATOR in properties) {
2895
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
2896
- valueNodes.push(createIteratorFactoryInstanceNode(28, parseIteratorFactory(ctx.base), parseSOS(ctx, depth, createSequenceFromIterable(properties))));
2897
- }
2898
- if (SYM_ASYNC_ITERATOR in properties) {
2899
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
2900
- valueNodes.push(createIteratorFactoryInstanceNode(30, parseAsyncIteratorFactory(ctx.base), parseAsyncIterable(ctx, depth, properties)));
2901
- }
2902
- if (SYM_TO_STRING_TAG in properties) {
2903
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
2904
- valueNodes.push(createStringNode(properties[SYM_TO_STRING_TAG]));
2905
- }
2906
- if (SYM_IS_CONCAT_SPREADABLE in properties) {
2907
- keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_IS_CONCAT_SPREADABLE));
2908
- valueNodes.push(properties[SYM_IS_CONCAT_SPREADABLE] ? TRUE_NODE : FALSE_NODE);
2909
- }
2910
- return {
2911
- k: keyNodes,
2912
- v: valueNodes
2913
- };
2914
- }
2915
- function parseAsyncIterable(ctx, depth, current) {
2916
- if (ctx.type !== 2) throw new SerovalUnsupportedTypeError(current);
2917
- const id = createIndexForValue(ctx.base, {});
2918
- const result = createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), []);
2919
- ctx.state.iterable(ctx, depth, id, current);
2920
- return result;
2921
- }
2922
- function parsePlainObject(ctx, depth, id, current, empty) {
2923
- return createObjectNode(id, current, empty, parseProperties(ctx, depth, current));
2924
- }
2925
- function parseBoxed(ctx, depth, id, current) {
2926
- return createBoxedNode(id, parseSOS(ctx, depth, current.valueOf()));
2927
- }
2928
- function parseView(ctx, depth, type, id, current) {
2929
- const view = getArrayBufferView(ctx.base, readArrayBufferView(current, type === 20));
2930
- return createViewNode(type, id, current, view, parseSOS(ctx, depth, view.buffer));
2931
- }
2932
- function parseError(ctx, depth, type, id, current) {
2933
- const options = getErrorOptions(current, ctx.base.features);
2934
- return createErrorNode(type, id, current, options ? parseProperties(ctx, depth, options) : void 0);
2935
- }
2936
- function parseMap(ctx, depth, id, current) {
2937
- const sentinel = parseMapSentinel(ctx.base);
2938
- const keyNodes = new Array(current.size);
2939
- const valueNodes = new Array(current.size);
2940
- let i = 0;
2941
- for (const [key, value] of current.entries()) {
2942
- keyNodes[i] = parseSOS(ctx, depth, key);
2943
- valueNodes[i] = parseSOS(ctx, depth, value);
2944
- i++;
2945
- }
2946
- return createMapNode(id, sentinel, keyNodes, valueNodes);
2947
- }
2948
- function parseSet(ctx, depth, id, current) {
2949
- const items = new Array(current.size);
2950
- let i = 0;
2951
- for (const item of current.keys()) items[i++] = parseSOS(ctx, depth, item);
2952
- return createSetNode(id, items);
2953
- }
2954
- /**
2955
- * Sends the events of a stream that has ended, so the copy gets all of them.
2956
- * A stream that is still open throws, because the other sync modes cannot
2957
- * send its later events.
2958
- */
2959
- function parseEndedStream(ctx, depth, id, current) {
2960
- const events = current.endedEvents();
2961
- if (!events) throw new SerovalUnsupportedTypeError(current);
2962
- const values = events.values;
2963
- const last = values.length - 1;
2964
- const sequence = new Array(values.length);
2965
- if (last >= 0) markParserRef(ctx.base, id);
2966
- for (let i = 0; i <= last; i++) sequence[i] = createStreamEventNode(i < last ? 32 : events.success ? 34 : 33, id, parseSOS(ctx, depth, values[i]));
2967
- return sequence;
2968
- }
2969
- function parseStream(ctx, depth, id, current) {
2970
- const reference = parseSpecialReference(ctx.base, 4);
2971
- if (ctx.type === 2) {
2972
- const result = createStreamConstructorNode(id, reference, []);
2973
- ctx.state.stream(ctx, depth, id, current);
2974
- return result;
2975
- }
2976
- return createStreamConstructorNode(id, reference, parseEndedStream(ctx, depth, id, current));
2977
- }
2978
- function parseLiveStream(ctx, depth, id, current) {
2979
- if (ctx.type !== 2) throw new SerovalUnsupportedTypeError(current);
2980
- const result = createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), [], 1);
2981
- ctx.state.live(ctx, depth, id, current);
2982
- return result;
2983
- }
2984
- function parsePromise(ctx, depth, id, current) {
2985
- if (ctx.type !== 2) throw new SerovalUnsupportedTypeError(current);
2986
- const resolver = createIndexForValue(ctx.base, {});
2987
- ctx.state.promise(ctx, resolver, depth, current);
2988
- return createPromiseConstructorNode(ctx.base, id, resolver);
2989
- }
2990
- function parsePluginSync(ctx, depth, id, current, currentPlugins) {
2991
- for (let i = 0, len = currentPlugins.length; i < len; i++) {
2992
- const plugin = currentPlugins[i];
2993
- if (plugin.parse.sync && plugin.test(current)) return createPluginNode(id, plugin.tag, plugin.parse.sync(current, { parse: (value) => parseSOS(ctx, depth, value) }, { id }));
2994
- }
2995
- }
2996
- function parsePlugin(ctx, depth, id, current, currentPlugins) {
2997
- if (currentPlugins) return ctx.type === 1 ? parsePluginSync(ctx, depth, id, current, currentPlugins) : ctx.state.plugin(ctx, depth, id, current, currentPlugins);
2998
- }
2999
- function parseSequence(ctx, depth, id, current) {
3000
- const len = current.v.length;
3001
- const nodes = new Array(len);
3002
- for (let i = 0; i < len; i++) nodes[i] = parseSOS(ctx, depth, current.v[i]);
3003
- return createSequenceNode(id, nodes, current.t, current.d);
3004
- }
3005
- function parseObjectPhase2(ctx, depth, id, current, currentClass) {
3006
- if (currentClass === Object) return parsePlainObject(ctx, depth, id, current, false);
3007
- switch (getObjectKind(current, currentClass, ctx.base.features)) {
3008
- case 2: return parsePlainObject(ctx, depth, id, current, true);
3009
- case 3: return createDateNode(id, current);
3010
- case 4: return parseError(ctx, depth, 13, id, current);
3011
- case 5: return parseError(ctx, depth, 14, id, current);
3012
- case 6: return parseBoxed(ctx, depth, id, current);
3013
- case 7: return createArrayBufferNode(ctx.base, id, current);
3014
- case 8: return parseView(ctx, depth, 15, id, current);
3015
- case 9: return parseView(ctx, depth, 16, id, current);
3016
- case 10: return parseView(ctx, depth, 20, id, current);
3017
- case 11: return parseMap(ctx, depth, id, current);
3018
- case 12: return parseSet(ctx, depth, id, current);
3019
- case 13: return parsePromise(ctx, depth, id, current);
3020
- case 14: return createRegExpNode(id, current);
3021
- case 15: return createTemporalNode(id, getTemporalType(currentClass), currentClass, current);
3022
- case 16: return parsePlainObject(ctx, depth, id, current, !!currentClass);
3023
- default: throw new SerovalUnsupportedTypeError(current);
3024
- }
3025
- }
3026
- function parseObject(ctx, depth, id, current) {
3027
- if (Array.isArray(current)) return parseArray(ctx, depth, id, current);
3028
- if (isLiveStream(current)) return parseLiveStream(ctx, depth, id, current);
3029
- if (current instanceof Stream) return parseStream(ctx, depth, id, current);
3030
- if (isSequence(current)) return parseSequence(ctx, depth, id, current);
3031
- const currentClass = getObjectClass(current);
3032
- if (currentClass === OpaqueReference) return parseSOS(ctx, depth, current.replacement);
3033
- const parsed = parsePlugin(ctx, depth, id, current, getObjectPlugins(ctx.base, current, currentClass));
3034
- if (parsed) return parsed;
3035
- return parseObjectPhase2(ctx, depth, id, current, currentClass);
3036
- }
3037
- function parseFunction(ctx, depth, current) {
3038
- const ref = getReferenceNode(ctx.base, current);
3039
- if (typeof ref !== "number") return ref;
3040
- const plugin = parsePlugin(ctx, depth, ref, current, ctx.base.plugins);
3041
- if (plugin) return plugin;
3042
- throw new SerovalUnsupportedTypeError(current);
3043
- }
3044
- function parseSOS(ctx, depth, current) {
3045
- if (depth >= ctx.base.depthLimit) throw new SerovalDepthLimitError(ctx.base.depthLimit);
3046
- switch (typeof current) {
3047
- case "boolean": return current ? TRUE_NODE : FALSE_NODE;
3048
- case "undefined": return UNDEFINED_NODE;
3049
- case "string": return createStringNode(current);
3050
- case "number": return createNumberNode(current);
3051
- case "bigint": return createBigIntNode(current);
3052
- case "object":
3053
- if (current) {
3054
- const ref = getReferenceNode(ctx.base, current);
3055
- return typeof ref === "number" ? parseObject(ctx, depth + 1, ref, current) : ref;
3056
- }
3057
- return NULL_NODE;
3058
- case "symbol": return parseWellKnownSymbol(ctx.base, current);
3059
- case "function": return parseFunction(ctx, depth, current);
3060
- default: throw new SerovalUnsupportedTypeError(current);
3061
- }
3062
- }
3063
- function parseTop(ctx, current) {
3064
- const refs = ctx.base.refs;
3065
- const size = refs.size;
3066
- try {
3067
- return parseSOS(ctx, 0, current);
3068
- } catch (error) {
3069
- rollbackRefs(refs, size);
3070
- throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
3071
- }
3072
- }
3073
- //#endregion
3074
- //#region src/core/context/stream-parser.ts
3075
- /**
3076
- * Streaming parse mode. Everything here is reached through the function
3077
- * fields of the stream parser state, which only `createStreamParserContext`
3078
- * sets, so synchronous consumers (`serialize`, `toJSON`) never bundle it.
3079
- */
3080
- function createStreamParsePluginContext(ctx, depth) {
3081
- const state = ctx.state;
3082
- function parse(current) {
3083
- state.parsing++;
3084
- try {
3085
- return parseSOS(ctx, depth, current);
3086
- } finally {
3087
- state.parsing--;
3088
- if (!state.alive) releaseParserValues(ctx);
3089
- }
3090
- }
3091
- return {
3092
- parse,
3093
- parseStreamSource(current) {
3094
- state.parsing++;
3095
- try {
3096
- if (depth >= ctx.base.depthLimit) throw new SerovalDepthLimitError(ctx.base.depthLimit);
3097
- const id = createIndexForValue(ctx.base, {});
3098
- const node = createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), [], 1);
3099
- iterateAsync(ctx, depth + 1, id, current, true);
3100
- return node;
3101
- } finally {
3102
- state.parsing--;
3103
- if (!state.alive) releaseParserValues(ctx);
3104
- }
3105
- },
3106
- parseWithError(current) {
3107
- try {
3108
- return parse(current);
3109
- } catch (error) {
3110
- stopStreamParse(ctx, 1, error);
3111
- return;
3112
- }
3113
- },
3114
- isAlive: () => state.alive,
3115
- pushPendingState: () => {
3116
- pushPendingState(ctx);
3117
- },
3118
- popPendingState: () => {
3119
- popPendingState(ctx);
3120
- },
3121
- onParse(node) {
3122
- if (state.alive) {
3123
- state.queue.push({
3124
- node,
3125
- initial: false,
3126
- accept: void 0,
3127
- refs: ctx.base.refs.size
3128
- });
3129
- drainOutput(ctx);
3130
- }
3131
- },
3132
- onError(error) {
3133
- stopStreamParse(ctx, 1, error);
3134
- },
3135
- addCleanup(callback) {
3136
- addCleanup(ctx, callback);
3137
- }
3138
- };
3139
- }
3140
- function getStreamParsePluginContext(ctx, depth) {
3141
- const contexts = ctx.state.pluginContexts;
3142
- return contexts[depth] ?? (contexts[depth] = createStreamParsePluginContext(ctx, depth));
3143
- }
3144
- function addCleanup(ctx, callback) {
3145
- if (ctx.state.alive) ctx.state.cleanups.push(callback);
3146
- else callback();
3147
- }
3148
- function parsePluginStream(ctx, depth, id, current, currentPlugins) {
3149
- for (let i = 0, len = currentPlugins.length; i < len; i++) {
3150
- const plugin = currentPlugins[i];
3151
- if (plugin.parse.stream && plugin.test(current)) return createPluginNode(id, plugin.tag, plugin.parse.stream(current, getStreamParsePluginContext(ctx, depth), { id }));
3152
- }
3153
- }
3154
- /**
3155
- * One listener shape serves both `Stream.on` (no accept) and
3156
- * `LiveStream.pump` (accept tied to record acceptance). Handlers return the
3157
- * parse error so the pump can stop the source.
3158
- */
3159
- function streamListener(ctx, depth, id, subscription) {
3160
- const handle = (type, terminal) => (value, accept) => {
3161
- let failure = void 0;
3162
- if (ctx.state.alive) try {
3163
- failure = parseEvent(ctx, depth, value, createStreamEventNode.bind(null, type, id), accept);
3164
- } catch (error) {
3165
- if (!subscription?.active) throw error;
3166
- subscription.failure ?? (subscription.failure = { value: error });
3167
- failure = error;
3168
- }
3169
- if (terminal && !accept) popPendingState(ctx);
3170
- return failure;
3171
- };
3172
- return {
3173
- next: handle(32, false),
3174
- throw: handle(33, true),
3175
- return: handle(34, true),
3176
- done() {
3177
- popPendingState(ctx);
3178
- },
3179
- error(reason) {
3180
- if (ctx.state.alive) stopStreamParse(ctx, 1, reason);
3181
- }
3182
- };
3183
- }
3184
- function subscribeStream(ctx, depth, id, current) {
3185
- pushPendingState(ctx);
3186
- const subscription = {
3187
- active: true,
3188
- failure: void 0
3189
- };
3190
- let cleanup;
3191
- try {
3192
- cleanup = current.on(streamListener(ctx, depth, id, subscription));
3193
- } finally {
3194
- subscription.active = false;
3195
- }
3196
- try {
3197
- addCleanup(ctx, cleanup);
3198
- } catch (error) {
3199
- subscription.failure ?? (subscription.failure = { value: error });
3200
- }
3201
- const failure = subscription.failure;
3202
- subscription.failure = void 0;
3203
- if (failure) throw failure.value;
3204
- }
3205
- function consumeLiveStream(ctx, depth, id, current) {
3206
- const cancel = current.pump(streamListener(ctx, depth, id));
3207
- pushPendingState(ctx);
3208
- addCleanup(ctx, () => {
3209
- cancel(ctx.state.reason);
3210
- });
3211
- }
3212
- function wrapPromiseResult(ctx, type, id, node) {
3213
- return createSerovalNode(type, id, void 0, void 0, void 0, void 0, void 0, [parseSpecialReference(ctx.base, type === 23 ? 2 : 3), node]);
3214
- }
3215
- function handlePromise(type, id, depth, data) {
3216
- if (this.state.alive) parseEvent(this, depth, data, wrapPromiseResult.bind(null, this, type, id), void 0);
3217
- popPendingState(this);
3218
- }
3219
- function watchPromise(ctx, resolver, depth, current) {
3220
- pushPendingState(ctx);
3221
- let settled = false;
3222
- current.then((data) => {
3223
- if (!settled) {
3224
- settled = true;
3225
- handlePromise.call(ctx, 23, resolver, depth, data);
3226
- }
3227
- }, (data) => {
3228
- if (!settled) {
3229
- settled = true;
3230
- handlePromise.call(ctx, 24, resolver, depth, data);
3231
- }
3232
- });
3233
- }
3234
- function returnIterator(iterator) {
3235
- Promise.resolve().then(() => iterator.return?.()).catch(() => {});
3236
- }
3237
- /**
3238
- * Drives an async iterator directly. The next value is pulled only after the
3239
- * record for the previous one has been accepted, and cancellation returns
3240
- * the iterator once.
3241
- */
3242
- function iterateAsync(ctx, depth, id, current, forwardReason) {
3243
- const iterator = current[SYM_ASYNC_ITERATOR]();
3244
- const listener = streamListener(ctx, depth, id);
3245
- let active = true;
3246
- function stop() {
3247
- if (active) {
3248
- active = false;
3249
- if (forwardReason) try {
3250
- Promise.resolve(iterator.return?.(ctx.state.reason)).catch(() => {});
3251
- } catch {}
3252
- else returnIterator(iterator);
3253
- }
3254
- }
3255
- function pull() {
3256
- if (active) iterator.next().then((result) => {
3257
- if (active) {
3258
- if (result.done) {
3259
- active = false;
3260
- listener.return(result.value, void 0);
3261
- } else if (listener.next(result.value, pull) !== void 0) {
3262
- stop();
3263
- listener.done();
3264
- }
3265
- }
3266
- }, (error) => {
3267
- if (active) {
3268
- active = false;
3269
- listener.throw(error, void 0);
3270
- }
3271
- });
3272
- }
3273
- pushPendingState(ctx);
3274
- addCleanup(ctx, stop);
3275
- pull();
3276
- }
3277
- function createStreamParserState(options) {
3278
- return {
3279
- alive: true,
3280
- pending: 0,
3281
- parsing: 0,
3282
- queue: [],
3283
- head: 0,
3284
- writing: false,
3285
- inFlight: void 0,
3286
- reason: void 0,
3287
- starting: false,
3288
- onParse: options.onParse,
3289
- onError: options.onError,
3290
- onDone: options.onDone,
3291
- cleanups: [],
3292
- pluginContexts: [],
3293
- stream: subscribeStream,
3294
- live: consumeLiveStream,
3295
- promise: watchPromise,
3296
- iterable: iterateAsync,
3297
- plugin: parsePluginStream
3298
- };
3299
- }
3300
- function createStreamParserContext(options) {
3301
- return {
3302
- type: 2,
3303
- base: createBaseParserContext(options),
3304
- state: createStreamParserState(options)
3305
- };
3306
- }
3307
- function pushPendingState(ctx) {
3308
- if (ctx.state.alive) ctx.state.pending++;
3309
- }
3310
- function popPendingState(ctx) {
3311
- if (ctx.state.alive) {
3312
- ctx.state.pending--;
3313
- checkStreamParse(ctx);
3314
- }
3315
- }
3316
- /**
3317
- * Parses a value that arrived after the root. Its record is queued before
3318
- * parsing starts so that records discovered inside it follow it, and it is
3319
- * dropped again if parsing fails. Returns the parse error after reporting
3320
- * it, or `undefined`.
3321
- */
3322
- function parseEvent(ctx, depth, value, wrap, accept) {
3323
- const state = ctx.state;
3324
- const record = {
3325
- node: void 0,
3326
- initial: false,
3327
- accept,
3328
- refs: ctx.base.refs.size
3329
- };
3330
- let failure;
3331
- state.queue.push(record);
3332
- state.parsing++;
3333
- try {
3334
- record.node = wrap(parseSOS(ctx, depth, value));
3335
- } catch (error) {
3336
- failure = { value: error };
3337
- } finally {
3338
- state.parsing--;
3339
- if (!state.alive) releaseParserValues(ctx);
3340
- }
3341
- if (failure) stopStreamParse(ctx, 1, failure.value);
3342
- else drainOutput(ctx);
3343
- return failure?.value;
3344
- }
3345
- function takeRecord(state) {
3346
- const record = state.queue[state.head];
3347
- state.queue[state.head++] = void 0;
3348
- if (state.head === state.queue.length) {
3349
- state.queue.length = 0;
3350
- state.head = 0;
3351
- } else if (state.head > 1024 && state.head * 2 > state.queue.length) {
3352
- state.queue.splice(0, state.head);
3353
- state.head = 0;
3354
- }
3355
- return record;
3356
- }
3357
- /**
3358
- * Emits queued records one at a time. A callback that returns a promise
3359
- * pauses emission until it settles; the source event behind the record is
3360
- * accepted only after that.
3361
- */
3362
- function drainOutput(ctx) {
3363
- const state = ctx.state;
3364
- if (state.writing || state.parsing > 0) return;
3365
- while (state.alive && state.head < state.queue.length) {
3366
- const record = takeRecord(state);
3367
- if (!record.node) continue;
3368
- let pending;
3369
- state.writing = true;
3370
- state.inFlight = record;
3371
- state.parsing++;
3372
- try {
3373
- if (!state.onParse) throw new Error("Stream output callback is unavailable");
3374
- const result = state.onParse(record.node, record.initial);
3375
- if (result !== null && (typeof result === "object" || typeof result === "function")) {
3376
- const then = Reflect.get(result, "then");
3377
- if (typeof then === "function") pending = new Promise((resolve, reject) => {
3378
- Reflect.apply(then, result, [resolve, reject]);
3379
- });
3380
- }
3381
- } catch (error) {
3382
- releaseRecord(record);
3383
- stopStreamParse(ctx, 1, error);
3384
- return;
3385
- } finally {
3386
- state.parsing--;
3387
- if (!state.alive) releaseParserValues(ctx);
3388
- }
3389
- record.node = void 0;
3390
- if (pending) {
3391
- if (!state.alive) releaseRecord(record);
3392
- pending.then(() => {
3393
- state.writing = false;
3394
- state.inFlight = void 0;
3395
- if (state.alive) {
3396
- const accept = record.accept;
3397
- releaseRecord(record);
3398
- accept?.();
3399
- drainOutput(ctx);
3400
- }
3401
- }, (error) => {
3402
- state.writing = false;
3403
- state.inFlight = void 0;
3404
- releaseRecord(record);
3405
- stopStreamParse(ctx, 1, error);
3406
- });
3407
- return;
3408
- }
3409
- if (!state.alive) {
3410
- releaseRecord(record);
3411
- return;
3412
- }
3413
- state.writing = false;
3414
- state.inFlight = void 0;
3415
- const accept = record.accept;
3416
- releaseRecord(record);
3417
- accept?.();
3418
- }
3419
- checkStreamParse(ctx);
3420
- }
3421
- function checkStreamParse(ctx) {
3422
- const state = ctx.state;
3423
- if (state.alive && state.parsing === 0 && state.pending <= 0 && state.head === state.queue.length && !state.writing) stopStreamParse(ctx, 0);
3424
- }
3425
- function startStreamParse(ctx, current) {
3426
- const state = ctx.state;
3427
- let parsed;
3428
- let failure;
3429
- const refs = ctx.base.refs;
3430
- const size = refs.size;
3431
- state.starting = true;
3432
- try {
3433
- state.parsing++;
3434
- try {
3435
- parsed = parseSOS(ctx, 0, current);
3436
- } catch (error) {
3437
- failure = { value: error };
3438
- } finally {
3439
- state.parsing--;
3440
- if (!state.alive) releaseParserValues(ctx);
3441
- }
3442
- if (failure) {
3443
- rollbackRefs(refs, size);
3444
- if (state.alive) stopStreamParse(ctx, 1, failure.value);
3445
- else throw failure.value;
3446
- } else if (parsed && state.alive) {
3447
- state.queue.unshift({
3448
- node: parsed,
3449
- initial: true,
3450
- accept: void 0,
3451
- refs: size
3452
- });
3453
- drainOutput(ctx);
3454
- }
3455
- } finally {
3456
- state.starting = false;
3457
- }
3458
- }
3459
- function runCleanups(state) {
3460
- const cleanups = state.cleanups;
3461
- let failure;
3462
- state.cleanups = [];
3463
- for (const record of state.queue) if (record) releaseRecord(record);
3464
- state.queue.length = 0;
3465
- state.head = 0;
3466
- if (state.inFlight) releaseRecord(state.inFlight);
3467
- state.inFlight = void 0;
3468
- for (let i = 0, len = cleanups.length; i < len; i++) try {
3469
- cleanups[i]();
3470
- } catch (error) {
3471
- failure ?? (failure = { value: error });
3472
- }
3473
- if (failure) throw failure.value;
3474
- }
3475
- function releaseRecord(record) {
3476
- record.node = void 0;
3477
- record.accept = void 0;
3478
- }
3479
- function releaseParserValues(ctx) {
3480
- ctx.base.refs = /* @__PURE__ */ new Map();
3481
- ctx.base.marked.clear();
3482
- ctx.base.plugins = void 0;
3483
- ctx.base.plainObjectPlugins = void 0;
3484
- ctx.state.pluginContexts = [];
3485
- if (ctx.state.parsing === 0) ctx.state.reason = void 0;
3486
- }
3487
- /**
3488
- * Ends the parse once: `onDone` on success, `onError` on failure, and every
3489
- * cleanup either way.
3490
- */
3491
- function stopStreamParse(ctx, mode, reason) {
3492
- const state = ctx.state;
3493
- if (state.alive) {
3494
- state.alive = false;
3495
- const unsent = state.queue[state.head];
3496
- if (mode !== 0 && unsent) rollbackRefs(ctx.base.refs, unsent.refs);
3497
- const onError = state.onError;
3498
- const onDone = state.onDone;
3499
- if (mode === 1 && !onError && !(reason instanceof SerovalParserError)) reason = new SerovalParserError(reason);
3500
- state.reason = reason;
3501
- state.onParse = void 0;
3502
- state.onError = void 0;
3503
- state.onDone = void 0;
3504
- state.writing = false;
3505
- state.parsing++;
3506
- let failure;
3507
- try {
3508
- if (mode === 1) {
3509
- if (onError) onError(reason);
3510
- else if (state.starting) throw reason;
3511
- } else if (mode === 0) onDone?.();
3512
- } catch (error) {
3513
- failure = { value: error };
3514
- }
3515
- try {
3516
- runCleanups(state);
3517
- } catch (error) {
3518
- failure ?? (failure = { value: error });
3519
- } finally {
3520
- state.parsing--;
3521
- releaseParserValues(ctx);
3522
- state.pending = 0;
3523
- }
3524
- if (failure) throw failure.value;
3525
- }
3526
- }
3527
- function destroyStreamParse(ctx, reason) {
3528
- stopStreamParse(ctx, 2, reason);
3529
- }
3530
- //#endregion
3531
- //#region src/core/cross/index.ts
3532
- function crossSerialize(source, options = {}) {
3533
- const plugins = resolvePlugins(options.plugins);
3534
- const ctx = createSyncParserContext({
3535
- compactArrayBufferViews: options.compactArrayBufferViews,
3536
- depthLimit: options.depthLimit,
3537
- plugins,
3538
- disabledFeatures: options.disabledFeatures,
3539
- refs: options.refs
3540
- });
3541
- const tree = parseTop(ctx, source);
3542
- return serializeTopCross(createCrossSerializerContext({
3543
- plugins,
3544
- features: ctx.base.features,
3545
- scopeId: options.scopeId,
3546
- markedRefs: ctx.base.marked,
3547
- assignSharedRefsOnly: options.assignSharedRefsOnly
3548
- }), tree);
3549
- }
3550
- async function crossSerializeAsync(source, options = {}) {
3551
- const plugins = resolvePlugins(options.plugins);
3552
- const ctx = createAsyncParserContext({
3553
- compactArrayBufferViews: options.compactArrayBufferViews,
3554
- depthLimit: options.depthLimit,
3555
- plugins,
3556
- disabledFeatures: options.disabledFeatures,
3557
- refs: options.refs
3558
- });
3559
- const tree = await parseTopAsync(ctx, source);
3560
- return serializeTopCross(createCrossSerializerContext({
3561
- plugins,
3562
- features: ctx.base.features,
3563
- scopeId: options.scopeId,
3564
- markedRefs: ctx.base.marked,
3565
- assignSharedRefsOnly: options.assignSharedRefsOnly
3566
- }), tree);
3567
- }
3568
- function toCrossJSON(source, options = {}) {
3569
- const plugins = resolvePlugins(options.plugins);
3570
- return parseTop(createSyncParserContext({
3571
- compactArrayBufferViews: options.compactArrayBufferViews,
3572
- depthLimit: options.depthLimit,
3573
- plugins,
3574
- disabledFeatures: options.disabledFeatures,
3575
- refs: options.refs
3576
- }), source);
3577
- }
3578
- async function toCrossJSONAsync(source, options = {}) {
3579
- const plugins = resolvePlugins(options.plugins);
3580
- return await parseTopAsync(createAsyncParserContext({
3581
- compactArrayBufferViews: options.compactArrayBufferViews,
3582
- depthLimit: options.depthLimit,
3583
- plugins,
3584
- disabledFeatures: options.disabledFeatures,
3585
- refs: options.refs
3586
- }), source);
3587
- }
3588
- function crossSerializeStream(source, options) {
3589
- const plugins = resolvePlugins(options.plugins);
3590
- const onSerialize = options.onSerialize;
3591
- const scopeId = options.scopeId;
3592
- const ctx = createStreamParserContext({
3593
- compactArrayBufferViews: options.compactArrayBufferViews,
3594
- depthLimit: options.depthLimit,
3595
- plugins,
3596
- refs: options.refs,
3597
- disabledFeatures: options.disabledFeatures,
3598
- onParse(node, initial) {
3599
- const serial = createCrossSerializerContext({
3600
- plugins,
3601
- features: ctx.base.features,
3602
- scopeId,
3603
- markedRefs: ctx.base.marked
3604
- });
3605
- return onSerialize(serializeTopCross(serial, node), initial);
3606
- },
3607
- onError: options.onError,
3608
- onDone: options.onDone
3609
- });
3610
- startStreamParse(ctx, source);
3611
- return destroyStreamParse.bind(null, ctx);
3612
- }
3613
- function toCrossJSONStream(source, options) {
3614
- const plugins = resolvePlugins(options.plugins);
3615
- const ctx = createStreamParserContext({
3616
- compactArrayBufferViews: options.compactArrayBufferViews,
3617
- plugins,
3618
- refs: options.refs,
3619
- disabledFeatures: options.disabledFeatures,
3620
- depthLimit: options.depthLimit,
3621
- onParse: options.onParse,
3622
- onError: options.onError,
3623
- onDone: options.onDone
3624
- });
3625
- startStreamParse(ctx, source);
3626
- return destroyStreamParse.bind(null, ctx);
3627
- }
3628
- function createFromCrossJSONContext(options) {
3629
- return createCrossDeserializerContext({
3630
- maxBase64Length: options.maxBase64Length,
3631
- plugins: resolvePlugins(options.plugins),
3632
- refs: options.refs,
3633
- features: options.features,
3634
- disabledFeatures: options.disabledFeatures,
3635
- depthLimit: options.depthLimit
3636
- });
3637
- }
3638
- function fromCrossJSON(source, options) {
3639
- return deserializeTop(createFromCrossJSONContext(options), source);
3640
- }
3641
- function createCrossDeserializer(options) {
3642
- const ctx = createFromCrossJSONContext(options);
3643
- ctx.base.pending = /* @__PURE__ */ new Set();
3644
- return {
3645
- deserialize(node) {
3646
- if (!ctx.base.pending) throw new SerovalAbortedError();
3647
- return deserializeTop(ctx, node);
3648
- },
3649
- get pending() {
3650
- return ctx.base.pending?.size ?? 0;
3651
- },
3652
- abort(reason) {
3653
- abortDeferred(ctx, reason);
3654
- }
3655
- };
3656
- }
3657
- //#endregion
3658
- //#region src/core/Serializer.ts
3659
- var Serializer = class {
3660
- constructor(options) {
3661
- this.alive = true;
3662
- this.flushed = false;
3663
- this.done = false;
3664
- this.pending = 0;
3665
- this.cleanups = [];
3666
- this.refs = /* @__PURE__ */ new Map();
3667
- this.keys = /* @__PURE__ */ new Set();
3668
- this.ids = 0;
3669
- this.options = options;
3670
- this.plugins = resolvePlugins(options.plugins);
3671
- }
3672
- write(key, value) {
3673
- const options = this.options;
3674
- if (this.alive && !this.flushed && options) {
3675
- this.pending++;
3676
- this.keys.add(key);
3677
- let starting = true;
3678
- const cleanup = crossSerializeStream(value, {
3679
- plugins: this.plugins,
3680
- scopeId: options.scopeId,
3681
- refs: this.refs,
3682
- disabledFeatures: options.disabledFeatures,
3683
- compactArrayBufferViews: options.compactArrayBufferViews,
3684
- depthLimit: options.depthLimit,
3685
- onError: (error) => {
3686
- let failure;
3687
- try {
3688
- if (options.onError) options.onError(error);
3689
- else if (starting) throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
3690
- } catch (handlerError) {
3691
- failure = { value: handlerError };
3692
- }
3693
- try {
3694
- this.finishWrite();
3695
- } catch (finishError) {
3696
- failure ?? (failure = { value: finishError });
3697
- }
3698
- if (failure) throw failure.value;
3699
- },
3700
- onSerialize: (data, initial) => {
3701
- const current = this.options;
3702
- if (this.alive && current) current.onData(initial ? current.globalIdentifier + "[\"" + serializeString(key) + "\"]=" + data : data);
3703
- },
3704
- onDone: () => {
3705
- this.finishWrite();
3706
- }
3707
- });
3708
- starting = false;
3709
- if (this.alive) this.cleanups.push(cleanup);
3710
- else cleanup();
3711
- }
3712
- }
3713
- finishWrite() {
3714
- if (this.alive) {
3715
- this.pending--;
3716
- if (this.pending <= 0 && this.flushed && !this.done) this.close();
3717
- }
3718
- }
3719
- getNextID() {
3720
- while (this.keys.has("" + this.ids)) this.ids++;
3721
- return "" + this.ids;
3722
- }
3723
- push(value) {
3724
- const newID = this.getNextID();
3725
- this.write(newID, value);
3726
- return newID;
3727
- }
3728
- flush() {
3729
- if (this.alive) {
3730
- this.flushed = true;
3731
- if (this.pending <= 0 && !this.done) this.close();
3732
- }
3733
- }
3734
- close() {
3735
- this.finish();
3736
- }
3737
- finish() {
3738
- if (this.alive) {
3739
- this.alive = false;
3740
- const options = this.options;
3741
- this.options = void 0;
3742
- this.plugins = void 0;
3743
- const cleanups = this.cleanups;
3744
- this.cleanups = [];
3745
- let failure;
3746
- for (let index = 0, length = cleanups.length; index < length; index++) try {
3747
- cleanups[index]();
3748
- } catch (error) {
3749
- failure ?? (failure = { value: error });
3750
- }
3751
- this.refs.clear();
3752
- if (!this.done) {
3753
- this.done = true;
3754
- try {
3755
- options?.onDone?.();
3756
- } catch (error) {
3757
- failure ?? (failure = { value: error });
3758
- }
3759
- }
3760
- if (failure) throw failure.value;
3761
- }
3762
- }
3763
- };
3764
- //#endregion
3765
- //#region src/core/tree/index.ts
3766
- function serialize(source, options = {}) {
3767
- const plugins = resolvePlugins(options.plugins);
3768
- const ctx = createSyncParserContext({
3769
- compactArrayBufferViews: options.compactArrayBufferViews,
3770
- depthLimit: options.depthLimit,
3771
- plugins,
3772
- disabledFeatures: options.disabledFeatures
3773
- });
3774
- const tree = parseTop(ctx, source);
3775
- return serializeTopVanilla(createVanillaSerializerContext({
3776
- plugins,
3777
- features: ctx.base.features,
3778
- markedRefs: ctx.base.marked
3779
- }), tree);
3780
- }
3781
- async function serializeAsync(source, options = {}) {
3782
- const plugins = resolvePlugins(options.plugins);
3783
- const ctx = createAsyncParserContext({
3784
- compactArrayBufferViews: options.compactArrayBufferViews,
3785
- depthLimit: options.depthLimit,
3786
- plugins,
3787
- disabledFeatures: options.disabledFeatures
3788
- });
3789
- const tree = await parseTopAsync(ctx, source);
3790
- return serializeTopVanilla(createVanillaSerializerContext({
3791
- plugins,
3792
- features: ctx.base.features,
3793
- markedRefs: ctx.base.marked
3794
- }), tree);
3795
- }
3796
- function deserialize(source) {
3797
- return (0, eval)(source);
3798
- }
3799
- function toJSON(source, options = {}) {
3800
- const plugins = resolvePlugins(options.plugins);
3801
- const ctx = createSyncParserContext({
3802
- compactArrayBufferViews: options.compactArrayBufferViews,
3803
- depthLimit: options.depthLimit,
3804
- plugins,
3805
- disabledFeatures: options.disabledFeatures
3806
- });
3807
- return {
3808
- t: parseTop(ctx, source),
3809
- f: ctx.base.features,
3810
- m: Array.from(ctx.base.marked)
3811
- };
3812
- }
3813
- async function toJSONAsync(source, options = {}) {
3814
- const plugins = resolvePlugins(options.plugins);
3815
- const ctx = createAsyncParserContext({
3816
- compactArrayBufferViews: options.compactArrayBufferViews,
3817
- depthLimit: options.depthLimit,
3818
- plugins,
3819
- disabledFeatures: options.disabledFeatures
3820
- });
3821
- return {
3822
- t: await parseTopAsync(ctx, source),
3823
- f: ctx.base.features,
3824
- m: Array.from(ctx.base.marked)
3825
- };
3826
- }
3827
- function compileJSON(source, options = {}) {
3828
- return serializeTopVanilla(createVanillaSerializerContext({
3829
- plugins: resolvePlugins(options.plugins),
3830
- features: source.f,
3831
- markedRefs: source.m
3832
- }), source.t);
3833
- }
3834
- function fromJSON(source, options = {}) {
3835
- const plugins = resolvePlugins(options.plugins);
3836
- const disabledFeatures = options.disabledFeatures ?? 0;
3837
- const sourceFeatures = source.f ?? 127;
3838
- return deserializeTop(createVanillaDeserializerContext({
3839
- depthLimit: options.depthLimit,
3840
- maxBase64Length: options.maxBase64Length,
3841
- plugins,
3842
- markedRefs: source.m,
3843
- features: sourceFeatures & ~disabledFeatures,
3844
- disabledFeatures
3845
- }), source.t);
3846
- }
3847
- //#endregion
3848
- exports.Feature = Feature;
3849
- exports.LiveStream = LiveStream;
3850
- exports.OpaqueReference = OpaqueReference;
3851
- exports.Sequence = Sequence;
3852
- exports.Serializer = Serializer;
3853
- exports.SerovalAbortedError = SerovalAbortedError;
3854
- exports.SerovalConflictedNodeIdError = SerovalConflictedNodeIdError;
3855
- exports.SerovalDepthLimitError = SerovalDepthLimitError;
3856
- exports.SerovalDeserializationError = SerovalDeserializationError;
3857
- exports.SerovalError = SerovalError;
3858
- exports.SerovalLiveStreamError = SerovalLiveStreamError;
3859
- exports.SerovalMalformedNodeError = SerovalMalformedNodeError;
3860
- exports.SerovalMissingInstanceError = SerovalMissingInstanceError;
3861
- exports.SerovalMissingPluginError = SerovalMissingPluginError;
3862
- exports.SerovalMissingReferenceError = SerovalMissingReferenceError;
3863
- exports.SerovalMissingReferenceForIdError = SerovalMissingReferenceForIdError;
3864
- exports.SerovalMode = SerovalMode;
3865
- exports.SerovalParserError = SerovalParserError;
3866
- exports.SerovalSerializationError = SerovalSerializationError;
3867
- exports.SerovalUnknownTypedArrayError = SerovalUnknownTypedArrayError;
3868
- exports.SerovalUnsupportedNodeError = SerovalUnsupportedNodeError;
3869
- exports.SerovalUnsupportedTypeError = SerovalUnsupportedTypeError;
3870
- exports.Stream = Stream;
3871
- exports.compileJSON = compileJSON;
3872
- exports.createCrossDeserializer = createCrossDeserializer;
3873
- exports.createLiveStream = createLiveStream;
3874
- exports.createPlugin = createPlugin;
3875
- exports.createReference = createReference;
3876
- exports.createStream = createStream;
3877
- exports.crossSerialize = crossSerialize;
3878
- exports.crossSerializeAsync = crossSerializeAsync;
3879
- exports.crossSerializeStream = crossSerializeStream;
3880
- exports.deserialize = deserialize;
3881
- exports.fromCrossJSON = fromCrossJSON;
3882
- exports.fromJSON = fromJSON;
3883
- exports.getCrossReferenceHeader = getCrossReferenceHeader;
3884
- exports.getPlainObjectPlugins = getPlainObjectPlugins;
3885
- exports.isLiveStream = isLiveStream;
3886
- exports.isStream = isStream;
3887
- exports.resolvePlugins = resolvePlugins;
3888
- exports.serialize = serialize;
3889
- exports.serializeAsync = serializeAsync;
3890
- exports.toCrossJSON = toCrossJSON;
3891
- exports.toCrossJSONAsync = toCrossJSONAsync;
3892
- exports.toCrossJSONStream = toCrossJSONStream;
3893
- exports.toJSON = toJSON;
3894
- exports.toJSONAsync = toJSONAsync;
2
+ const require_shared = require("./shared-DWx3Bwb6.cjs");
3
+ const require_read = require("./read-DvIuZ2yx.cjs");
4
+ const require_write = require("./write-DGOp2jqo.cjs");
5
+ let src_core_validator = require("./validator.cjs");
6
+ exports.Feature = require_shared.Feature;
7
+ exports.LiveStream = require_shared.LiveStream;
8
+ exports.OpaqueReference = require_shared.OpaqueReference;
9
+ exports.Sequence = require_shared.Sequence;
10
+ exports.Serializer = require_write.Serializer;
11
+ exports.SerovalAbortedError = require_shared.SerovalAbortedError;
12
+ exports.SerovalConflictedNodeIdError = require_shared.SerovalConflictedNodeIdError;
13
+ exports.SerovalDepthLimitError = require_shared.SerovalDepthLimitError;
14
+ exports.SerovalDeserializationError = require_shared.SerovalDeserializationError;
15
+ exports.SerovalError = require_shared.SerovalError;
16
+ exports.SerovalLiveStreamError = require_shared.SerovalLiveStreamError;
17
+ exports.SerovalMalformedNodeError = require_shared.SerovalMalformedNodeError;
18
+ exports.SerovalMissingInstanceError = require_shared.SerovalMissingInstanceError;
19
+ exports.SerovalMissingPluginError = require_shared.SerovalMissingPluginError;
20
+ exports.SerovalMissingReferenceError = require_shared.SerovalMissingReferenceError;
21
+ exports.SerovalMissingReferenceForIdError = require_shared.SerovalMissingReferenceForIdError;
22
+ exports.SerovalMode = require_shared.SerovalMode;
23
+ exports.SerovalParserError = require_shared.SerovalParserError;
24
+ exports.SerovalPluginValidationError = require_shared.SerovalPluginValidationError;
25
+ exports.SerovalSerializationError = require_shared.SerovalSerializationError;
26
+ exports.SerovalUnknownTypedArrayError = require_shared.SerovalUnknownTypedArrayError;
27
+ exports.SerovalUnsupportedNodeError = require_shared.SerovalUnsupportedNodeError;
28
+ exports.SerovalUnsupportedTypeError = require_shared.SerovalUnsupportedTypeError;
29
+ exports.Stream = require_shared.Stream;
30
+ exports.compileJSON = require_write.compileJSON;
31
+ exports.createCrossDeserializer = require_read.createCrossDeserializer;
32
+ exports.createLiveStream = require_shared.createLiveStream;
33
+ exports.createPlugin = require_shared.createPlugin;
34
+ exports.createReference = require_shared.createReference;
35
+ exports.createStream = require_shared.createStream;
36
+ exports.crossSerialize = require_write.crossSerialize;
37
+ exports.crossSerializeAsync = require_write.crossSerializeAsync;
38
+ exports.crossSerializeStream = require_write.crossSerializeStream;
39
+ exports.deserialize = require_read.deserialize;
40
+ exports.fromCrossJSON = require_read.fromCrossJSON;
41
+ exports.fromJSON = require_read.fromJSON;
42
+ exports.getCrossReferenceHeader = require_shared.getCrossReferenceHeader;
43
+ exports.getPlainObjectPlugins = require_shared.getPlainObjectPlugins;
44
+ exports.isLiveStream = require_shared.isLiveStream;
45
+ exports.isStream = require_shared.isStream;
46
+ exports.resolvePlugins = require_shared.resolvePlugins;
47
+ exports.serialize = require_write.serialize;
48
+ exports.serializeAsync = require_write.serializeAsync;
49
+ exports.toCrossJSON = require_write.toCrossJSON;
50
+ exports.toCrossJSONAsync = require_write.toCrossJSONAsync;
51
+ exports.toCrossJSONStream = require_write.toCrossJSONStream;
52
+ exports.toJSON = require_write.toJSON;
53
+ exports.toJSONAsync = require_write.toJSONAsync;
54
+ Object.defineProperty(exports, "v", {
55
+ enumerable: true,
56
+ get: function() {
57
+ return src_core_validator;
58
+ }
59
+ });