seroval 1.6.12 → 1.7.0

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