UNPKG

seroval

Version:
4 lines 236 kB
{ "version": 3, "sources": ["../../../src/core/compat.ts", "../../../src/core/string.ts", "../../../src/core/keys.ts", "../../../src/core/utils/assert.ts", "../../../src/core/reference.ts", "../../../src/core/plugin.ts", "../../../src/core/abort-signal.ts", "../../../src/core/constants.ts", "../../../src/core/node.ts", "../../../src/core/literals.ts", "../../../src/core/utils/error.ts", "../../../src/core/utils/get-object-flag.ts", "../../../src/core/base-primitives.ts", "../../../src/core/errors.ts", "../../../src/core/opaque-reference.ts", "../../../src/core/special-reference.ts", "../../../src/core/utils/deferred.ts", "../../../src/core/stream.ts", "../../../src/core/utils/iterator-to-sequence.ts", "../../../src/core/utils/promise-to-result.ts", "../../../src/core/context/parser.ts", "../../../src/core/context/parser/async.ts", "../../../src/core/cross/async.ts", "../../../src/core/utils/typed-array.ts", "../../../src/core/context/deserializer.ts", "../../../src/core/cross/deserializer.ts", "../../../src/core/utils/is-valid-identifier.ts", "../../../src/core/context/serializer.ts", "../../../src/core/cross/serializer.ts", "../../../src/core/context/parser/sync.ts", "../../../src/core/context/parser/stream.ts", "../../../src/core/cross/stream.ts", "../../../src/core/cross/sync.ts", "../../../src/core/cross/index.ts", "../../../src/core/tree/async.ts", "../../../src/core/tree/deserializer.ts", "../../../src/core/utils/get-identifier.ts", "../../../src/core/tree/serializer.ts", "../../../src/core/tree/sync.ts", "../../../src/core/tree/index.ts", "../../../src/core/Serializer.ts"], "sourcesContent": ["/**\n * References\n * - https://compat-table.github.io/compat-table/es6/\n * - MDN\n */\n\nexport const enum Feature {\n AggregateError = 0x01,\n ArrowFunction = 0x02,\n ErrorPrototypeStack = 0x04,\n ObjectAssign = 0x08,\n BigIntTypedArray = 0x10,\n AbortSignal = 0x20,\n}\n\nexport const ALL_ENABLED = 0x2f;\n", "export function serializeChar(str: string): string | undefined {\n switch (str) {\n case '\"':\n return '\\\\\"';\n case '\\\\':\n return '\\\\\\\\';\n case '\\n':\n return '\\\\n';\n case '\\r':\n return '\\\\r';\n case '\\b':\n return '\\\\b';\n case '\\t':\n return '\\\\t';\n case '\\f':\n return '\\\\f';\n case '<':\n return '\\\\x3C';\n case '\\u2028':\n return '\\\\u2028';\n case '\\u2029':\n return '\\\\u2029';\n default:\n return undefined;\n }\n}\n\n// Written by https://github.com/DylanPiercey and is distributed under the MIT license.\n// Creates a JavaScript double quoted string and escapes all characters\n// not listed as DoubleStringCharacters on\n// Also includes \"<\" to escape \"</script>\" and \"\\\" to avoid invalid escapes in the output.\n// http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4\nexport function serializeString(str: string): string {\n let result = '';\n let lastPos = 0;\n let replacement: string | undefined;\n for (let i = 0, len = str.length; i < len; i++) {\n replacement = serializeChar(str[i]);\n if (replacement) {\n result += str.slice(lastPos, i) + replacement;\n lastPos = i + 1;\n }\n }\n if (lastPos === 0) {\n result = str;\n } else {\n result += str.slice(lastPos);\n }\n return result;\n}\n\nfunction deserializeReplacer(str: string): string {\n switch (str) {\n case '\\\\\\\\':\n return '\\\\';\n case '\\\\\"':\n return '\"';\n case '\\\\n':\n return '\\n';\n case '\\\\r':\n return '\\r';\n case '\\\\b':\n return '\\b';\n case '\\\\t':\n return '\\t';\n case '\\\\f':\n return '\\f';\n case '\\\\x3C':\n return '\\x3C';\n case '\\\\u2028':\n return '\\u2028';\n case '\\\\u2029':\n return '\\u2029';\n default:\n return str;\n }\n}\n\nexport function deserializeString(str: string): string {\n return str.replace(\n /(\\\\\\\\|\\\\\"|\\\\n|\\\\r|\\\\b|\\\\t|\\\\f|\\\\u2028|\\\\u2029|\\\\x3C)/g,\n deserializeReplacer,\n );\n}\n", "import { serializeString } from './string';\n\n// Used for mapping isomorphic references\nexport const REFERENCES_KEY = '__SEROVAL_REFS__';\n\nexport const GLOBAL_CONTEXT_REFERENCES = '$R';\n\nconst GLOBAL_CONTEXT_R = `self.${GLOBAL_CONTEXT_REFERENCES}`;\n\nexport function getCrossReferenceHeader(id?: string): string {\n if (id == null) {\n return `${GLOBAL_CONTEXT_R}=${GLOBAL_CONTEXT_R}||[]`;\n }\n return `(${GLOBAL_CONTEXT_R}=${GLOBAL_CONTEXT_R}||{})[\"${serializeString(\n id,\n )}\"]=[]`;\n}\n", "export default function assert(cond: unknown, error: Error): asserts cond {\n if (!cond) {\n throw error;\n }\n}\n", "import {\n SerovalMissingReferenceError,\n SerovalMissingReferenceForIdError,\n} from '..';\nimport { REFERENCES_KEY } from './keys';\nimport assert from './utils/assert';\n\nconst REFERENCE = new Map<unknown, string>();\nconst INV_REFERENCE = new Map<string, unknown>();\n\nexport function createReference<T>(id: string, value: T): T {\n REFERENCE.set(value, id);\n INV_REFERENCE.set(id, value);\n return value;\n}\n\nexport function hasReferenceID<T>(value: T): boolean {\n return REFERENCE.has(value);\n}\n\nexport function hasReference(id: string): boolean {\n return INV_REFERENCE.has(id);\n}\n\nexport function getReferenceID<T>(value: T): string {\n assert(hasReferenceID(value), new SerovalMissingReferenceError(value));\n return REFERENCE.get(value)!;\n}\n\nexport function getReference<T>(id: string): T {\n assert(hasReference(id), new SerovalMissingReferenceForIdError(id));\n return INV_REFERENCE.get(id) as T;\n}\n\nif (typeof globalThis !== 'undefined') {\n Object.defineProperty(globalThis, REFERENCES_KEY, {\n value: INV_REFERENCE,\n configurable: true,\n writable: false,\n enumerable: false,\n });\n} else if (typeof window !== 'undefined') {\n Object.defineProperty(window, REFERENCES_KEY, {\n value: INV_REFERENCE,\n configurable: true,\n writable: false,\n enumerable: false,\n });\n} else if (typeof self !== 'undefined') {\n Object.defineProperty(self, REFERENCES_KEY, {\n value: INV_REFERENCE,\n configurable: true,\n writable: false,\n enumerable: false,\n });\n} else if (typeof global !== 'undefined') {\n Object.defineProperty(global, REFERENCES_KEY, {\n value: INV_REFERENCE,\n configurable: true,\n writable: false,\n enumerable: false,\n });\n}\n", "import type BaseDeserializerContext from './context/deserializer';\nimport type BaseAsyncParserContext from './context/parser/async';\nimport type BaseStreamParserContext from './context/parser/stream';\nimport type BaseSyncParserContext from './context/parser/sync';\nimport type BaseSerializerContext from './context/serializer';\n\nexport type SerovalMode = 'vanilla' | 'cross';\n\nexport interface PluginData {\n id: number;\n}\n\nexport interface Plugin<Value, Node> {\n /**\n * A unique string that helps idenfity the plugin\n */\n tag: string;\n /**\n * List of dependency plugins\n */\n extends?: Plugin<any, any>[];\n /**\n * Method to test if a value is an expected value of the plugin\n * @param value\n */\n test(value: unknown): boolean;\n /**\n * Parsing modes\n */\n parse: {\n sync?: (value: Value, ctx: BaseSyncParserContext, data: PluginData) => Node;\n async?: (\n value: Value,\n ctx: BaseAsyncParserContext,\n data: PluginData,\n ) => Promise<Node>;\n stream?: (\n value: Value,\n ctx: BaseStreamParserContext,\n data: PluginData,\n ) => Node;\n };\n /**\n * Convert the parsed node into a JS string\n */\n serialize(node: Node, ctx: BaseSerializerContext, data: PluginData): string;\n /**\n * Convert the parsed node into its runtime equivalent.\n */\n deserialize(\n node: Node,\n ctx: BaseDeserializerContext,\n data: PluginData,\n ): Value;\n}\n\nexport function createPlugin<Value, Node>(\n plugin: Plugin<Value, Node>,\n): Plugin<Value, Node> {\n return plugin;\n}\n\nexport interface PluginAccessOptions {\n plugins?: Plugin<any, any>[];\n}\n\nfunction dedupePlugins(\n deduped: Set<Plugin<any, any>>,\n plugins: Plugin<any, any>[],\n): void {\n for (let i = 0, len = plugins.length; i < len; i++) {\n const current = plugins[i];\n if (!deduped.has(current)) {\n deduped.add(current);\n if (current.extends) {\n dedupePlugins(deduped, current.extends);\n }\n }\n }\n}\n\nexport function resolvePlugins(\n plugins?: Plugin<any, any>[],\n): Plugin<any, any>[] | undefined {\n if (plugins) {\n const deduped = new Set<Plugin<any, any>>();\n dedupePlugins(deduped, plugins);\n return [...deduped];\n }\n return undefined;\n}\n", "function resolveAbortSignalResult(\n this: AbortSignal,\n resolve: (value: any) => void,\n): void {\n resolve(this.reason);\n}\n\nfunction resolveAbortSignal(\n this: AbortSignal,\n resolve: (value: any) => void,\n): void {\n this.addEventListener('abort', resolveAbortSignalResult.bind(this, resolve), {\n once: true,\n });\n}\n\nexport function abortSignalToPromise(signal: AbortSignal): Promise<any> {\n return new Promise(resolveAbortSignal.bind(signal));\n}\n", "export const enum SerovalConstant {\n Null = 0,\n Undefined = 1,\n True = 2,\n False = 3,\n NegZero = 4,\n Inf = 5,\n NegInf = 6,\n Nan = 7,\n}\n\nexport const enum SerovalNodeType {\n Number = 0,\n String = 1,\n Constant = 2,\n BigInt = 3,\n IndexedValue = 4,\n Date = 5,\n RegExp = 6,\n Set = 7,\n Map = 8,\n Array = 9,\n Object = 10,\n NullConstructor = 11,\n Promise = 12,\n Error = 13,\n AggregateError = 14,\n TypedArray = 15,\n BigIntTypedArray = 16,\n WKSymbol = 17,\n Reference = 18,\n ArrayBuffer = 19,\n DataView = 20,\n Boxed = 21,\n PromiseConstructor = 22,\n PromiseResolve = 23,\n PromiseReject = 24,\n Plugin = 25,\n SpecialReference = 26,\n IteratorFactory = 27,\n IteratorFactoryInstance = 28,\n AsyncIteratorFactory = 29,\n AsyncIteratorFactoryInstance = 30,\n StreamConstructor = 31,\n StreamNext = 32,\n StreamThrow = 33,\n StreamReturn = 34,\n AbortSignalConstructor = 35,\n AbortSignalAbort = 36,\n AbortSignalSync = 37,\n}\n\nexport const enum SerovalObjectFlags {\n None = 0,\n NonExtensible = 1,\n Sealed = 2,\n Frozen = 3,\n}\n\nexport const enum Symbols {\n AsyncIterator = 0,\n HasInstance = 1,\n IsConcatSpreadable = 2,\n Iterator = 3,\n Match = 4,\n MatchAll = 5,\n Replace = 6,\n Search = 7,\n Species = 8,\n Split = 9,\n ToPrimitive = 10,\n ToStringTag = 11,\n Unscopables = 12,\n}\n\nexport const SYMBOL_STRING: Record<Symbols, string> = {\n [Symbols.AsyncIterator]: 'Symbol.asyncIterator',\n [Symbols.HasInstance]: 'Symbol.hasInstance',\n [Symbols.IsConcatSpreadable]: 'Symbol.isConcatSpreadable',\n [Symbols.Iterator]: 'Symbol.iterator',\n [Symbols.Match]: 'Symbol.match',\n [Symbols.MatchAll]: 'Symbol.matchAll',\n [Symbols.Replace]: 'Symbol.replace',\n [Symbols.Search]: 'Symbol.search',\n [Symbols.Species]: 'Symbol.species',\n [Symbols.Split]: 'Symbol.split',\n [Symbols.ToPrimitive]: 'Symbol.toPrimitive',\n [Symbols.ToStringTag]: 'Symbol.toStringTag',\n [Symbols.Unscopables]: 'Symbol.unscopables',\n};\n\nexport const INV_SYMBOL_REF = /* @__PURE__ */ {\n [Symbol.asyncIterator]: Symbols.AsyncIterator,\n [Symbol.hasInstance]: Symbols.HasInstance,\n [Symbol.isConcatSpreadable]: Symbols.IsConcatSpreadable,\n [Symbol.iterator]: Symbols.Iterator,\n [Symbol.match]: Symbols.Match,\n [Symbol.matchAll]: Symbols.MatchAll,\n [Symbol.replace]: Symbols.Replace,\n [Symbol.search]: Symbols.Search,\n [Symbol.species]: Symbols.Species,\n [Symbol.split]: Symbols.Split,\n [Symbol.toPrimitive]: Symbols.ToPrimitive,\n [Symbol.toStringTag]: Symbols.ToStringTag,\n [Symbol.unscopables]: Symbols.Unscopables,\n};\n\nexport type WellKnownSymbols = keyof typeof INV_SYMBOL_REF;\n\nexport const SYMBOL_REF: Record<Symbols, WellKnownSymbols> = {\n [Symbols.AsyncIterator]: Symbol.asyncIterator,\n [Symbols.HasInstance]: Symbol.hasInstance,\n [Symbols.IsConcatSpreadable]: Symbol.isConcatSpreadable,\n [Symbols.Iterator]: Symbol.iterator,\n [Symbols.Match]: Symbol.match,\n [Symbols.MatchAll]: Symbol.matchAll,\n [Symbols.Replace]: Symbol.replace,\n [Symbols.Search]: Symbol.search,\n [Symbols.Species]: Symbol.species,\n [Symbols.Split]: Symbol.split,\n [Symbols.ToPrimitive]: Symbol.toPrimitive,\n [Symbols.ToStringTag]: Symbol.toStringTag,\n [Symbols.Unscopables]: Symbol.unscopables,\n};\n\nexport const CONSTANT_STRING: Record<SerovalConstant, string> = {\n [SerovalConstant.True]: '!0',\n [SerovalConstant.False]: '!1',\n [SerovalConstant.Undefined]: 'void 0',\n [SerovalConstant.Null]: 'null',\n [SerovalConstant.NegZero]: '-0',\n [SerovalConstant.Inf]: '1/0',\n [SerovalConstant.NegInf]: '-1/0',\n [SerovalConstant.Nan]: '0/0',\n};\n\nexport const CONSTANT_VAL: Record<SerovalConstant, unknown> = {\n [SerovalConstant.True]: true,\n [SerovalConstant.False]: false,\n [SerovalConstant.Undefined]: undefined,\n [SerovalConstant.Null]: null,\n [SerovalConstant.NegZero]: -0,\n [SerovalConstant.Inf]: Number.POSITIVE_INFINITY,\n [SerovalConstant.NegInf]: Number.NEGATIVE_INFINITY,\n [SerovalConstant.Nan]: Number.NaN,\n};\n\nexport const enum ErrorConstructorTag {\n Error = 0,\n EvalError = 1,\n RangeError = 2,\n ReferenceError = 3,\n SyntaxError = 4,\n TypeError = 5,\n URIError = 6,\n}\n\nexport const ERROR_CONSTRUCTOR_STRING: Record<ErrorConstructorTag, string> = {\n [ErrorConstructorTag.Error]: 'Error',\n [ErrorConstructorTag.EvalError]: 'EvalError',\n [ErrorConstructorTag.RangeError]: 'RangeError',\n [ErrorConstructorTag.ReferenceError]: 'ReferenceError',\n [ErrorConstructorTag.SyntaxError]: 'SyntaxError',\n [ErrorConstructorTag.TypeError]: 'TypeError',\n [ErrorConstructorTag.URIError]: 'URIError',\n};\n\ntype ErrorConstructors =\n | ErrorConstructor\n | EvalErrorConstructor\n | RangeErrorConstructor\n | ReferenceErrorConstructor\n | SyntaxErrorConstructor\n | TypeErrorConstructor\n | URIErrorConstructor;\n\nexport const ERROR_CONSTRUCTOR: Record<ErrorConstructorTag, ErrorConstructors> =\n {\n [ErrorConstructorTag.Error]: Error,\n [ErrorConstructorTag.EvalError]: EvalError,\n [ErrorConstructorTag.RangeError]: RangeError,\n [ErrorConstructorTag.ReferenceError]: ReferenceError,\n [ErrorConstructorTag.SyntaxError]: SyntaxError,\n [ErrorConstructorTag.TypeError]: TypeError,\n [ErrorConstructorTag.URIError]: URIError,\n };\n\nexport const NIL = undefined;\n", "import type { SerovalNodeType } from './constants';\nimport type { SerovalNode } from './types';\n\ntype ExtractedNodeType<T extends SerovalNodeType> = Extract<\n SerovalNode,\n { t: T }\n>;\n\nexport function createSerovalNode<\n T extends SerovalNodeType,\n N extends ExtractedNodeType<T>,\n>(\n t: T,\n i: N['i'],\n s: N['s'],\n l: N['l'],\n c: N['c'],\n m: N['m'],\n p: N['p'],\n e: N['e'],\n a: N['a'],\n f: N['f'],\n b: N['b'],\n o: N['o'],\n): N {\n return {\n t,\n i,\n s,\n l,\n c,\n m,\n p,\n e,\n a,\n f,\n b,\n o,\n } as N;\n}\n", "import { NIL, SerovalConstant, SerovalNodeType } from './constants';\nimport { createSerovalNode } from './node';\nimport type { SerovalConstantNode } from './types';\n\nfunction createConstantNode(value: SerovalConstant): SerovalConstantNode {\n return createSerovalNode(\n SerovalNodeType.Constant,\n NIL,\n value,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport const TRUE_NODE = /* @__PURE__ */ createConstantNode(\n SerovalConstant.True,\n);\nexport const FALSE_NODE = /* @__PURE__ */ createConstantNode(\n SerovalConstant.False,\n);\nexport const UNDEFINED_NODE = /* @__PURE__ */ createConstantNode(\n SerovalConstant.Undefined,\n);\nexport const NULL_NODE = /* @__PURE__ */ createConstantNode(\n SerovalConstant.Null,\n);\nexport const NEG_ZERO_NODE = /* @__PURE__ */ createConstantNode(\n SerovalConstant.NegZero,\n);\nexport const INFINITY_NODE = /* @__PURE__ */ createConstantNode(\n SerovalConstant.Inf,\n);\nexport const NEG_INFINITY_NODE = /* @__PURE__ */ createConstantNode(\n SerovalConstant.NegInf,\n);\nexport const NAN_NODE = /* @__PURE__ */ createConstantNode(SerovalConstant.Nan);\n", "import { Feature } from '../compat';\nimport { ERROR_CONSTRUCTOR_STRING, ErrorConstructorTag } from '../constants';\n\ntype ErrorValue =\n | Error\n | AggregateError\n | EvalError\n | RangeError\n | ReferenceError\n | TypeError\n | SyntaxError\n | URIError;\n\nexport function getErrorConstructor(error: ErrorValue): ErrorConstructorTag {\n if (error instanceof EvalError) {\n return ErrorConstructorTag.EvalError;\n }\n if (error instanceof RangeError) {\n return ErrorConstructorTag.RangeError;\n }\n if (error instanceof ReferenceError) {\n return ErrorConstructorTag.ReferenceError;\n }\n if (error instanceof SyntaxError) {\n return ErrorConstructorTag.SyntaxError;\n }\n if (error instanceof TypeError) {\n return ErrorConstructorTag.TypeError;\n }\n if (error instanceof URIError) {\n return ErrorConstructorTag.URIError;\n }\n return ErrorConstructorTag.Error;\n}\n\nfunction getInitialErrorOptions(\n error: Error,\n): Record<string, unknown> | undefined {\n const construct = ERROR_CONSTRUCTOR_STRING[getErrorConstructor(error)];\n // Name has been modified\n if (error.name !== construct) {\n return { name: error.name };\n }\n if (error.constructor.name !== construct) {\n // Otherwise, name is overriden because\n // the Error class is extended\n return { name: error.constructor.name };\n }\n return {};\n}\n\nexport function getErrorOptions(\n error: Error,\n features: number,\n): Record<string, unknown> | undefined {\n let options = getInitialErrorOptions(error);\n const names = Object.getOwnPropertyNames(error);\n for (let i = 0, len = names.length, name: string; i < len; i++) {\n name = names[i];\n if (name !== 'name' && name !== 'message') {\n if (name === 'stack') {\n if (features & Feature.ErrorPrototypeStack) {\n options = options || {};\n options[name] = error[name as keyof Error];\n }\n } else {\n options = options || {};\n options[name] = error[name as keyof Error];\n }\n }\n }\n return options;\n}\n", "import { SerovalObjectFlags } from '../constants';\n\nexport function getObjectFlag(obj: unknown): SerovalObjectFlags {\n if (Object.isFrozen(obj)) {\n return SerovalObjectFlags.Frozen;\n }\n if (Object.isSealed(obj)) {\n return SerovalObjectFlags.Sealed;\n }\n if (Object.isExtensible(obj)) {\n return SerovalObjectFlags.None;\n }\n return SerovalObjectFlags.NonExtensible;\n}\n", "import type { WellKnownSymbols } from './constants';\nimport { INV_SYMBOL_REF, NIL, SerovalNodeType } from './constants';\nimport {\n INFINITY_NODE,\n NAN_NODE,\n NEG_INFINITY_NODE,\n NEG_ZERO_NODE,\n} from './literals';\nimport { createSerovalNode } from './node';\nimport { getReferenceID } from './reference';\nimport { serializeString } from './string';\nimport type {\n SerovalAbortSignalSyncNode,\n SerovalAggregateErrorNode,\n SerovalArrayBufferNode,\n SerovalArrayNode,\n SerovalAsyncIteratorFactoryInstanceNode,\n SerovalBigIntNode,\n SerovalBigIntTypedArrayNode,\n SerovalBoxedNode,\n SerovalConstantNode,\n SerovalDataViewNode,\n SerovalDateNode,\n SerovalErrorNode,\n SerovalIndexedValueNode,\n SerovalIteratorFactoryInstanceNode,\n SerovalNode,\n SerovalNodeWithID,\n SerovalNumberNode,\n SerovalObjectRecordNode,\n SerovalPluginNode,\n SerovalReferenceNode,\n SerovalRegExpNode,\n SerovalSetNode,\n SerovalStreamConstructorNode,\n SerovalStreamNextNode,\n SerovalStreamReturnNode,\n SerovalStreamThrowNode,\n SerovalStringNode,\n SerovalTypedArrayNode,\n SerovalWKSymbolNode,\n} from './types';\nimport { getErrorConstructor } from './utils/error';\nimport { getObjectFlag } from './utils/get-object-flag';\nimport type {\n BigIntTypedArrayValue,\n TypedArrayValue,\n} from './utils/typed-array';\n\nexport function createNumberNode(\n value: number,\n): SerovalConstantNode | SerovalNumberNode {\n switch (value) {\n case Number.POSITIVE_INFINITY:\n return INFINITY_NODE;\n case Number.NEGATIVE_INFINITY:\n return NEG_INFINITY_NODE;\n }\n if (value !== value) {\n return NAN_NODE;\n }\n if (Object.is(value, -0)) {\n return NEG_ZERO_NODE;\n }\n return createSerovalNode(\n SerovalNodeType.Number,\n NIL,\n value,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createStringNode(value: string): SerovalStringNode {\n return createSerovalNode(\n SerovalNodeType.String,\n NIL,\n serializeString(value),\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createBigIntNode(current: bigint): SerovalBigIntNode {\n return createSerovalNode(\n SerovalNodeType.BigInt,\n NIL,\n '' + current,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createIndexedValueNode(id: number): SerovalIndexedValueNode {\n return createSerovalNode(\n SerovalNodeType.IndexedValue,\n id,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createDateNode(id: number, current: Date): SerovalDateNode {\n return createSerovalNode(\n SerovalNodeType.Date,\n id,\n current.toISOString(),\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createRegExpNode(\n id: number,\n current: RegExp,\n): SerovalRegExpNode {\n return createSerovalNode(\n SerovalNodeType.RegExp,\n id,\n NIL,\n NIL,\n serializeString(current.source),\n current.flags,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createArrayBufferNode(\n id: number,\n current: ArrayBuffer,\n): SerovalArrayBufferNode {\n const bytes = new Uint8Array(current);\n const len = bytes.length;\n const values = new Array<number>(len);\n for (let i = 0; i < len; i++) {\n values[i] = bytes[i];\n }\n return createSerovalNode(\n SerovalNodeType.ArrayBuffer,\n id,\n values,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createWKSymbolNode(\n id: number,\n current: WellKnownSymbols,\n): SerovalWKSymbolNode {\n return createSerovalNode(\n SerovalNodeType.WKSymbol,\n id,\n INV_SYMBOL_REF[current],\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createReferenceNode<T>(\n id: number,\n ref: T,\n): SerovalReferenceNode {\n return createSerovalNode(\n SerovalNodeType.Reference,\n id,\n serializeString(getReferenceID(ref)),\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createPluginNode(\n id: number,\n tag: string,\n value: unknown,\n): SerovalPluginNode {\n return createSerovalNode(\n SerovalNodeType.Plugin,\n id,\n value,\n NIL,\n serializeString(tag),\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createArrayNode(\n id: number,\n current: unknown[],\n parsedItems: SerovalNode[],\n): SerovalArrayNode {\n return createSerovalNode(\n SerovalNodeType.Array,\n id,\n NIL,\n current.length,\n NIL,\n NIL,\n NIL,\n NIL,\n parsedItems,\n NIL,\n NIL,\n getObjectFlag(current),\n );\n}\n\nexport function createBoxedNode(\n id: number,\n boxed: SerovalNode,\n): SerovalBoxedNode {\n return createSerovalNode(\n SerovalNodeType.Boxed,\n id,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n boxed,\n NIL,\n NIL,\n );\n}\n\nexport function createTypedArrayNode(\n id: number,\n current: TypedArrayValue,\n buffer: SerovalNode,\n): SerovalTypedArrayNode {\n return createSerovalNode(\n SerovalNodeType.TypedArray,\n id,\n NIL,\n current.length,\n current.constructor.name,\n NIL,\n NIL,\n NIL,\n NIL,\n buffer,\n current.byteOffset,\n NIL,\n );\n}\n\nexport function createBigIntTypedArrayNode(\n id: number,\n current: BigIntTypedArrayValue,\n buffer: SerovalNode,\n): SerovalBigIntTypedArrayNode {\n return createSerovalNode(\n SerovalNodeType.BigIntTypedArray,\n id,\n NIL,\n current.length,\n current.constructor.name,\n NIL,\n NIL,\n NIL,\n NIL,\n buffer,\n current.byteOffset,\n NIL,\n );\n}\n\nexport function createDataViewNode(\n id: number,\n current: DataView,\n buffer: SerovalNode,\n): SerovalDataViewNode {\n return createSerovalNode(\n SerovalNodeType.DataView,\n id,\n NIL,\n current.byteLength,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n buffer,\n current.byteOffset,\n NIL,\n );\n}\n\nexport function createErrorNode(\n id: number,\n current: Error,\n options: SerovalObjectRecordNode | undefined,\n): SerovalErrorNode {\n return createSerovalNode(\n SerovalNodeType.Error,\n id,\n getErrorConstructor(current),\n NIL,\n NIL,\n serializeString(current.message),\n options,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createAggregateErrorNode(\n id: number,\n current: AggregateError,\n options: SerovalObjectRecordNode | undefined,\n): SerovalAggregateErrorNode {\n return createSerovalNode(\n SerovalNodeType.AggregateError,\n id,\n getErrorConstructor(current),\n NIL,\n NIL,\n serializeString(current.message),\n options,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createSetNode(\n id: number,\n size: number,\n items: SerovalNode[],\n): SerovalSetNode {\n return createSerovalNode(\n SerovalNodeType.Set,\n id,\n NIL,\n size,\n NIL,\n NIL,\n NIL,\n NIL,\n items,\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createIteratorFactoryInstanceNode(\n factory: SerovalNodeWithID,\n items: SerovalNode,\n): SerovalIteratorFactoryInstanceNode {\n return createSerovalNode(\n SerovalNodeType.IteratorFactoryInstance,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n [factory, items],\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createAsyncIteratorFactoryInstanceNode(\n factory: SerovalNodeWithID,\n items: SerovalNode,\n): SerovalAsyncIteratorFactoryInstanceNode {\n return createSerovalNode(\n SerovalNodeType.AsyncIteratorFactoryInstance,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n [factory, items],\n NIL,\n NIL,\n NIL,\n );\n}\n\nexport function createStreamConstructorNode(\n id: number,\n factory: SerovalNodeWithID,\n sequence: SerovalNode[],\n): SerovalStreamConstructorNode {\n return createSerovalNode(\n SerovalNodeType.StreamConstructor,\n id,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n sequence,\n factory,\n NIL,\n NIL,\n );\n}\n\nexport function createStreamNextNode(\n id: number,\n parsed: SerovalNode,\n): SerovalStreamNextNode {\n return createSerovalNode(\n SerovalNodeType.StreamNext,\n id,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n parsed,\n NIL,\n NIL,\n );\n}\n\nexport function createStreamThrowNode(\n id: number,\n parsed: SerovalNode,\n): SerovalStreamThrowNode {\n return createSerovalNode(\n SerovalNodeType.StreamThrow,\n id,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n parsed,\n NIL,\n NIL,\n );\n}\n\nexport function createStreamReturnNode(\n id: number,\n parsed: SerovalNode,\n): SerovalStreamReturnNode {\n return createSerovalNode(\n SerovalNodeType.StreamReturn,\n id,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n parsed,\n NIL,\n NIL,\n );\n}\n\nexport function createAbortSignalSyncNode(\n id: number,\n parsed: SerovalNode,\n): SerovalAbortSignalSyncNode {\n return createSerovalNode(\n SerovalNodeType.AbortSignalSync,\n id,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n parsed,\n NIL,\n NIL,\n );\n}\n", "import { serializeString } from './string';\nimport type { SerovalNode } from './types';\n\nconst { toString: objectToString } = /* @__PURE__ */ Object.prototype;\n\nfunction getErrorMessage(type: string, cause: any): string {\n if (cause instanceof Error) {\n return `Seroval caught an error during the ${type} process.\n \n${cause.name}\n${cause.message}\n\n- For more information, please check the \"cause\" property of this error.\n- If you believe this is an error in Seroval, please submit an issue at https://github.com/lxsmnsyc/seroval/issues/new`;\n }\n return `Seroval caught an error during the ${type} process.\n\n\"${objectToString.call(cause)}\"\n\nFor more information, please check the \"cause\" property of this error.`;\n}\n\nexport class SerovalError extends Error {\n constructor(\n type: string,\n public cause: any,\n ) {\n super(getErrorMessage(type, cause));\n }\n}\n\nexport class SerovalParserError extends SerovalError {\n constructor(cause: any) {\n super('parsing', cause);\n }\n}\n\nexport class SerovalSerializationError extends SerovalError {\n constructor(cause: any) {\n super('serialization', cause);\n }\n}\n\nexport class SerovalDeserializationError extends SerovalError {\n constructor(cause: any) {\n super('deserialization', cause);\n }\n}\n\nexport class SerovalUnsupportedTypeError extends Error {\n constructor(public value: unknown) {\n super(\n `The value ${objectToString.call(value)} of type \"${typeof value}\" cannot be parsed/serialized.\n \nThere are few workarounds for this problem:\n- Transform the value in a way that it can be serialized.\n- If the reference is present on multiple runtimes (isomorphic), you can use the Reference API to map the references.`,\n );\n }\n}\n\nexport class SerovalUnsupportedNodeError extends Error {\n constructor(node: SerovalNode) {\n super('Unsupported node type \"' + node.t + '\".');\n }\n}\n\nexport class SerovalMissingPluginError extends Error {\n constructor(tag: string) {\n super('Missing plugin for tag \"' + tag + '\".');\n }\n}\n\nexport class SerovalMissingInstanceError extends Error {\n constructor(tag: string) {\n super('Missing \"' + tag + '\" instance.');\n }\n}\n\nexport class SerovalMissingReferenceError extends Error {\n constructor(public value: unknown) {\n super(\n 'Missing reference for the value \"' +\n objectToString.call(value) +\n '\" of type \"' +\n typeof value +\n '\"',\n );\n }\n}\n\nexport class SerovalMissingReferenceForIdError extends Error {\n constructor(id: string) {\n super('Missing reference for id \"' + serializeString(id) + '\"');\n }\n}\n\nexport class SerovalUnknownTypedArrayError extends Error {\n constructor(name: string) {\n super('Unknown TypedArray \"' + name + '\"');\n }\n}\n", "/**\n * An opaque reference allows hiding values from the serializer.\n */\nexport class OpaqueReference<V, R = undefined> {\n constructor(\n public readonly value: V,\n public readonly replacement?: R,\n ) {}\n}\n", "export const ITERATOR = {};\n\nexport const ASYNC_ITERATOR = {};\n\nexport const enum SpecialReference {\n MapSentinel = 0,\n PromiseConstructor = 1,\n PromiseResolve = 2,\n PromiseReject = 3,\n StreamConstructor = 4,\n AbortSignalConstructor = 5,\n AbortSignalAbort = 6,\n}\n\n/**\n * Placeholder references\n */\nexport const SPECIAL_REFS: Record<SpecialReference, unknown> = {\n [SpecialReference.MapSentinel]: {},\n [SpecialReference.PromiseConstructor]: {},\n [SpecialReference.PromiseResolve]: {},\n [SpecialReference.PromiseReject]: {},\n [SpecialReference.StreamConstructor]: {},\n [SpecialReference.AbortSignalConstructor]: {},\n [SpecialReference.AbortSignalAbort]: {},\n};\n", "export interface Deferred {\n promise: Promise<unknown>;\n resolve(value: unknown): void;\n reject(value: unknown): void;\n}\n\nexport function createDeferred(): Deferred {\n let resolve: Deferred['resolve'];\n let reject: Deferred['reject'];\n return {\n promise: new Promise<unknown>((res, rej) => {\n resolve = res;\n reject = rej;\n }),\n resolve(value): void {\n resolve(value);\n },\n reject(value): void {\n reject(value);\n },\n };\n}\n", "import type { Deferred } from './utils/deferred';\nimport { createDeferred } from './utils/deferred';\n\ninterface StreamListener<T> {\n next(value: T): void;\n throw(value: unknown): void;\n return(value: T): void;\n}\n\nexport interface Stream<T> {\n __SEROVAL_STREAM__: true;\n\n on(listener: StreamListener<T>): () => void;\n\n next(value: T): void;\n throw(value: unknown): void;\n return(value: T): void;\n}\n\nexport function isStream<T>(value: object): value is Stream<T> {\n return '__SEROVAL_STREAM__' in value;\n}\n\nexport function createStream<T>(): Stream<T> {\n const listeners = new Set<StreamListener<T>>();\n const buffer: unknown[] = [];\n let alive = true;\n let success = true;\n\n function flushNext(value: T): void {\n for (const listener of listeners.keys()) {\n listener.next(value);\n }\n }\n\n function flushThrow(value: unknown): void {\n for (const listener of listeners.keys()) {\n listener.throw(value);\n }\n }\n\n function flushReturn(value: T): void {\n for (const listener of listeners.keys()) {\n listener.return(value);\n }\n }\n\n return {\n __SEROVAL_STREAM__: true,\n on(listener: StreamListener<T>): () => void {\n if (alive) {\n listeners.add(listener);\n }\n for (let i = 0, len = buffer.length; i < len; i++) {\n const value = buffer[i];\n if (i === len - 1 && !alive) {\n if (success) {\n listener.return(value as T);\n } else {\n listener.throw(value);\n }\n } else {\n listener.next(value as T);\n }\n }\n return () => {\n if (alive) {\n listeners.delete(listener);\n }\n };\n },\n next(value): void {\n if (alive) {\n buffer.push(value);\n flushNext(value);\n }\n },\n throw(value): void {\n if (alive) {\n buffer.push(value);\n flushThrow(value);\n alive = false;\n success = false;\n listeners.clear();\n }\n },\n return(value): void {\n if (alive) {\n buffer.push(value);\n flushReturn(value);\n alive = false;\n success = true;\n listeners.clear();\n }\n },\n };\n}\n\nexport function createStreamFromAsyncIterable<T>(\n iterable: AsyncIterable<T>,\n): Stream<T> {\n const stream = createStream<T>();\n\n const iterator = iterable[Symbol.asyncIterator]();\n\n async function push(): Promise<void> {\n try {\n const value = await iterator.next();\n if (value.done) {\n stream.return(value.value as T);\n } else {\n stream.next(value.value);\n await push();\n }\n } catch (error) {\n stream.throw(error);\n }\n }\n\n push().catch(() => {\n // no-op\n });\n\n return stream;\n}\n\nexport function streamToAsyncIterable<T>(\n stream: Stream<T>,\n): () => AsyncIterableIterator<T> {\n return (): AsyncIterableIterator<T> => {\n const buffer: T[] = [];\n const pending: Deferred[] = [];\n let count = 0;\n let doneAt = -1;\n let isThrow = false;\n\n function resolveAll(): void {\n for (let i = 0, len = pending.length; i < len; i++) {\n pending[i].resolve({ done: true, value: undefined });\n }\n }\n\n stream.on({\n next(value) {\n const current = pending.shift();\n if (current) {\n current.resolve({ done: false, value });\n }\n buffer.push(value);\n },\n throw(value) {\n const current = pending.shift();\n if (current) {\n current.reject(value);\n }\n resolveAll();\n doneAt = buffer.length;\n buffer.push(value as T);\n isThrow = true;\n },\n return(value) {\n const current = pending.shift();\n if (current) {\n current.resolve({ done: true, value });\n }\n resolveAll();\n doneAt = buffer.length;\n buffer.push(value);\n },\n });\n\n function finalize() {\n const current = count++;\n const value = buffer[current];\n if (current !== doneAt) {\n return { done: false, value };\n }\n if (isThrow) {\n throw value;\n }\n return { done: true, value };\n }\n\n return {\n [Symbol.asyncIterator](): AsyncIterableIterator<T> {\n return this;\n },\n async next(): Promise<IteratorResult<T>> {\n if (doneAt === -1) {\n const current = count++;\n if (current >= buffer.length) {\n const deferred = createDeferred();\n pending.push(deferred);\n return (await deferred.promise) as Promise<IteratorResult<T>>;\n }\n return { done: false, value: buffer[current] };\n }\n if (count > doneAt) {\n return { done: true, value: undefined };\n }\n return finalize();\n },\n };\n };\n}\n", "import { NIL } from \"../constants\";\n\nexport interface Sequence {\n v: unknown[];\n t: number;\n d: number;\n}\n\nexport function iteratorToSequence<T>(source: Iterable<T>): Sequence {\n const values: unknown[] = [];\n let throwsAt = -1;\n let doneAt = -1;\n\n const iterator = source[Symbol.iterator]();\n\n while (true) {\n try {\n const value = iterator.next();\n values.push(value.value);\n if (value.done) {\n doneAt = values.length - 1;\n break;\n }\n } catch (error) {\n throwsAt = values.length;\n values.push(error);\n }\n }\n\n return {\n v: values,\n t: throwsAt,\n d: doneAt,\n };\n}\n\nexport function sequenceToIterator<T>(\n sequence: Sequence,\n): () => IterableIterator<T> {\n return (): IterableIterator<T> => {\n let index = 0;\n\n return {\n [Symbol.iterator](): IterableIterator<T> {\n return this;\n },\n next(): IteratorResult<T> {\n if (index > sequence.d) {\n return {\n done: true,\n value: NIL,\n };\n }\n const currentIndex = index++;\n const currentItem = sequence.v[currentIndex];\n if (currentIndex === sequence.t) {\n throw currentItem;\n }\n return {\n done: currentIndex === sequence.d,\n value: currentItem as T,\n };\n },\n };\n };\n}\n", "export default async function promiseToResult(\n current: Promise<unknown>,\n): Promise<[0 | 1, unknown]> {\n try {\n return [1, await current];\n } catch (e) {\n return [0, e];\n }\n}\n", "import {\n createIndexedValueNode,\n createReferenceNode,\n createWKSymbolNode,\n} from '../base-primitives';\nimport { ALL_ENABLED } from '../compat';\nimport type { WellKnownSymbols } from '../constants';\nimport { INV_SYMBOL_REF, NIL, SerovalNodeType } from '../constants';\nimport { SerovalUnsupportedTypeError } from '../errors';\nimport { createSerovalNode } from '../node';\nimport type { Plugin, PluginAccessOptions, SerovalMode } from '../plugin';\nimport { hasReferenceID } from '../reference';\nimport {\n ASYNC_ITERATOR,\n ITERATOR,\n SPECIAL_REFS,\n SpecialReference,\n} from '../special-reference';\nimport type {\n SerovalAbortSignalConstructorNode,\n SerovalAsyncIteratorFactoryNode,\n SerovalIndexedValueNode,\n SerovalIteratorFactoryNode,\n SerovalMapNode,\n SerovalNode,\n SerovalNullConstructorNode,\n SerovalObjectNode,\n SerovalObjectRecordNode,\n SerovalPromiseConstructorNode,\n SerovalReferenceNode,\n SerovalSpecialReferenceNode,\n SerovalWKSymbolNode,\n} from '../types';\nimport assert from '../utils/assert';\nimport { getObjectFlag } from '../utils/get-object-flag';\n\nexport interface BaseParserContextOptions extends PluginAccessOptions {\n disabledFeatures?: number;\n refs?: Map<unknown, number>;\n}\n\nexport const enum ParserNodeType {\n Fresh = 0,\n Indexed = 1,\n Referenced = 2,\n}\n\nexport interface FreshNode {\n type: ParserNodeType.Fresh;\n value: number;\n}\n\nexport interface IndexedNode {\n type: ParserNodeType.Indexed;\n value: SerovalIndexedValueNode;\n}\n\nexport interface ReferencedNode {\n type: ParserNodeType.Referenced;\n value: SerovalReferenceNode;\n}\n\ntype ObjectNode = FreshNode | IndexedNode | ReferencedNode;\n\nexport abstract class BaseParserContext implements PluginAccessOptions {\n abstract readonly mode: SerovalMode;\n\n features: number;\n\n marked = new Set<number>();\n\n refs: Map<unknown, number>;\n\n plugins?: Plugin<any, any>[] | undefined;\n\n constructor(options: BaseParserContextOptions) {\n this.plugins = options.plugins;\n this.features = ALL_ENABLED ^ (options.disabledFeatures || 0);\n this.refs = options.refs || new Map<unknown, number>();\n }\n\n protected markRef(id: number): void {\n this.marked.add(id);\n }\n\n protected isMarked(id: number): boolean {\n return this.marked.has(id);\n }\n\n protected getIndexedValue<T>(current: T): FreshNode | IndexedNode {\n const registeredId = this.refs.get(current);\n if (registeredId != null) {\n this.markRef(registeredId);\n return {\n type: ParserNodeType.Indexed,\n value: createIndexedValueNode(registeredId),\n };\n }\n const id = this.refs.size;\n this.refs.set(current, id);\n return {\n type: ParserNodeType.Fresh,\n value: id,\n };\n }\n\n protected getReference<T>(current: T): ObjectNode {\n const indexed = this.getIndexedValue(current);\n if (indexed.type === ParserNodeType.Indexed) {\n return indexed;\n }\n if (hasReferenceID(current)) {\n return {\n type: ParserNodeType.Referenced,\n value: createReferenceNode(indexed.value, current),\n };\n }\n return indexed;\n }\n\n protected parseWellKnownSymbol(\n current: symbol,\n ): SerovalIndexedValueNode | SerovalWKSymbolNode | SerovalReferenceNode {\n const ref = this.getReference(current);\n if (ref.type !== ParserNodeType.Fresh) {\n return ref.value;\n }\n assert(current in INV_SYMBOL_REF, new SerovalUnsupportedTypeError(current));\n return createWKSymbolNode(ref.value, current as WellKnownSymbols);\n }\n\n protected parseSpecialReference(\n ref: SpecialReference,\n ): SerovalIndexedValueNode | SerovalSpecialReferenceNode {\n const result = this.getIndexedValue(SPECIAL_REFS[ref]);\n if (result.type === ParserNodeType.Indexed) {\n return result.value;\n }\n return createSerovalNode(\n SerovalNodeType.SpecialReference,\n result.value,\n ref,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n );\n }\n\n protected parseIteratorFactory():\n | SerovalIndexedValueNode\n | SerovalIteratorFactoryNode {\n const result = this.getIndexedValue(ITERATOR);\n if (result.type === ParserNodeType.Indexed) {\n return result.value;\n }\n return createSerovalNode(\n SerovalNodeType.IteratorFactory,\n result.value,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n this.parseWellKnownSymbol(Symbol.iterator),\n NIL,\n NIL,\n );\n }\n\n protected parseAsyncIteratorFactory():\n | SerovalIndexedValueNode\n | SerovalAsyncIteratorFactoryNode {\n const result = this.getIndexedValue(ASYNC_ITERATOR);\n if (result.type === ParserNodeType.Indexed) {\n return result.value;\n }\n return createSerovalNode(\n SerovalNodeType.AsyncIteratorFactory,\n result.value,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n [\n this.parseSpecialReference(SpecialReference.PromiseConstructor),\n this.parseWellKnownSymbol(Symbol.asyncIterator),\n ],\n NIL,\n NIL,\n NIL,\n );\n }\n\n protected createObjectNode(\n id: number,\n current: Record<string, unknown>,\n empty: boolean,\n record: SerovalObjectRecordNode,\n ): SerovalObjectNode | SerovalNullConstructorNode {\n return createSerovalNode(\n empty ? SerovalNodeType.NullConstructor : SerovalNodeType.Object,\n id,\n NIL,\n NIL,\n NIL,\n NIL,\n record,\n NIL,\n NIL,\n NIL,\n NIL,\n getObjectFlag(current),\n );\n }\n\n protected createMapNode(\n id: number,\n k: SerovalNode[],\n v: SerovalNode[],\n s: number,\n ): SerovalMapNode {\n return createSerovalNode(\n SerovalNodeType.Map,\n id,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n { k, v, s },\n NIL,\n this.parseSpecialReference(SpecialReference.MapSentinel),\n NIL,\n NIL,\n );\n }\n\n protected createPromiseConstructorNode(\n id: number,\n ): SerovalPromiseConstructorNode {\n return createSerovalNode(\n SerovalNodeType.PromiseConstructor,\n id,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n this.parseSpecialReference(SpecialReference.PromiseConstructor),\n NIL,\n NIL,\n );\n }\n\n protected createAbortSignalConstructorNode(\n id: number,\n ): SerovalAbortSignalConstructorNode {\n return createSerovalNode(\n SerovalNodeType.AbortSignalConstructor,\n id,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n NIL,\n this.parseSpecialReference(SpecialReference.AbortSignalConstructor),\n NIL,\n NIL,\n );\n }\n}\n", "import { abortSignalToPromise } from '../../abort-signal';\nimport {\n createAggregateErrorNode,\n createArrayBufferNode,\n createArrayNode,\n createAsyncIteratorFactoryInstanceNode,\n createBigIntNode,\n createBigIntTypedArrayNode,\n createBoxedNode,\n createDataViewNode,\n createDateNode,\n createErrorNode,\n createIteratorFactoryInstanceNode,\n createNumberNode,\n createPluginNode,\n createRegExpNode,\n createSetNode,\n createStreamConstructorNode,\n createStreamNextNode,\n createStreamReturnNode,\n createStreamThrowNode,\n createStringNode,\n createTypedArrayNode,\n} from '../../base-primitives';\nimport { Feature } from '../../compat';\nimport { NIL, SerovalNodeType } from '../../constants';\nimport { SerovalParserError, SerovalUnsupportedTypeError } from '../../errors';\nimport {\n FALSE_NODE,\n NULL_NODE,\n TRUE_NODE,\n UNDEFINED_NODE,\n} from '../../literals';\nimport { createSerovalNode } from '../../node';\nimport { OpaqueReference } from '../../opaque-reference';\nimport { SpecialReference } from '../../special-reference';\nimport type { Stream } from '../../stream';\nimport { createStreamFromAsyncIterable, isStream } from '../../stream';\nimport { serializeString } from '../../string';\nimport type {\n SerovalAbortSignalSyncNode,\n SerovalAggregateErrorNode,\n SerovalArrayNode,\n SerovalBigIntTypedArrayNode,\n SerovalBoxedNode,\n SerovalDataViewNode,\n SerovalErrorNode,\n SerovalMapNode,\n SerovalNode,\n SerovalNullConstructorNode,\n SerovalObjectNode,\n SerovalObjectRecordKey,\n SerovalObjectRecordNode,\n SerovalPluginNode,\n SerovalPromiseNode,\n SerovalSetNode,\n SerovalStreamConstructorNode,\n SerovalTypedArrayNode,\n} from '../../types';\nimport { getErrorOptions } from '../../utils/error';\nimport { iteratorToSequence } from '../../utils/iterator-to-sequence';\nimport promiseToResult from '../../utils/promise-to-result';\nimport type {\n BigIntTypedArrayValue,\n TypedArrayValue,\n} from '../../utils/typed-array';\nimport { BaseParserContext, ParserNodeType } from '../parser';\n\ntype ObjectLikeNode =\n | SerovalObjectNode\n | SerovalNullConstructorNode\n | SerovalPromiseNode;\n\nexport default abstract class BaseAsyncParserContext extends BaseParserContext {\n private async parseItems(current: unknown[]): Promise<SerovalNode[]> {\n const nodes = [];\n for (let i = 0, len = current.length; i < len; i++) {\n // For consistency in holes\n if (i in current) {\n nodes[i] = await this.parse(current[i]);\n }\n }\n return nodes;\n }\n\n private async parseArray(\n id: number,\n current: unknown[],\n ): Promise<SerovalArrayNode> {\n return createArrayNode(id, current, await this.parseItems(current));\n }\n\n private async parseProperties(\n properties: Record<string | symbol, unknown>,\n ): Promise<SerovalObjectRecordNode> {\n const entries = Object.entries(properties);\n const keyNodes: SerovalObjectRecordKey[] = [];\n const valueNodes: SerovalNode[] = [];\n for (let i = 0, len = entries.length; i < len; i++) {\n keyNodes.push(serializeString(entries[i][0]));\n valueNodes.push(await this.parse(entries[i][1]));\n }\n // Check special properties\n let symbol = Symbol.iterator;\n if (symbol in properties) {\n keyNodes.push(this.parseWellKnownSymbol(symbol));\n valueNodes.push(\n createIteratorFactoryInstanceNode(\n this.parseIteratorFactory(),\n await this.parse(\n iteratorToSequence(properties as unknown as Iterable<unknown>),\n ),\n ),\n );\n }\n symbol = Symbol.asyncIterat