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