UNPKG

awesome-im

Version:

Lightweight, extensible, JavaScript Instant Messaging.

1,324 lines (1,305 loc) 87.7 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.im = factory()); })(this, (function () { 'use strict'; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } class EventEmitter { constructor() { this._map = {}; } on(eventType, listener, target) { var arr = this._map[eventType] || (this._map[eventType] = []); if (arr.some(item => item.listener === listener && item.target === target)) { return; } arr.push({ listener, target }); } once(eventType, listener, target) { var arr = this._map[eventType] || (this._map[eventType] = []); if (arr.some(item => item.listener === listener && item.target === target)) { return; } arr.push({ listener, target, once: true }); } off(eventType, listener, target) { var arr = this._map[eventType]; if (!arr) { return; } arr = arr.filter(item => item.listener !== listener || item.target !== target); if (arr.length) { this._map[eventType] = arr; } else { delete this._map[eventType]; } } emit(eventType) { var arr = this._map[eventType]; if (!arr) { return; } for (var _len = arguments.length, attrs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { attrs[_key - 1] = arguments[_key]; } for (var i = arr.length - 1; i >= 0; i -= 1) { var { target, once, listener } = arr[i]; if (once) arr.splice(i, 1); try { listener.call(target, ...attrs); } catch (error) {} } } removeAll(eventType) { delete this._map[eventType]; } clear() { Object.keys(this._map).forEach(this.removeAll, this); } } var eventEmitter = new EventEmitter(); var event = { STATUS: "STATUS", MESSAGE: "MESSAGE", TEST: "TEST" }; var ConnectionStatus = { TIMEOUT: -1, CONNECTED: 0, CONNECTING: 1, DISCONNECTED: 2, NETWORK_UNAVAILABLE: 3, CONNECTION_CLOSED: 4, KICKED_OFFLINE_BY_OTHER_CLIENT: 6, WEBSOCKET_UNAVAILABLE: 7, WEBSOCKET_ERROR: 8 }; var ErrorCode = { TIMEOUT: { code: -1, msg: 'Network timeout' }, SUCCESS: { code: 0, errMsg: "success" }, NOT_CONNECTED: { code: 10001, errMsg: "not connect" }, SERVER_SEND_DATA_NOT_RIGHT: { code: 10002, errMsg: "SERVER SEND DATA NOT RIGHT" }, CONNECTION_EXIST: { code: 10003, errMsg: "Connection already exists" } }; var MessageType = { TEXT: "TxtMsg", IMAGE: "ImgMsg", FILE: "FileMsg", PING: "PingMsg", SIGNAL: "SignalMsg" }; var ConversationType = { SERVER: 0, PRIVATE: 1, DISCUSSION: 2, GROUP: 3, CHATROOM: 4, SYSTEM: 5 }; var MessageDirection = { SEND: 1, RECEIVE: 2 }; class MessageModel { constructor(messageData) { var { messageType, conversationType, message, extra, from, to, messageUId, messageId } = messageData; var Message = { "messageDirection": MessageDirection.SEND, "messageType": messageType || MessageType.TEXT, "sentTime": new Date().getTime(), "messageUId": messageUId, "messageId": messageId, "conversationType": conversationType || ConversationType.SERVER }; if (message) { Message.content = { message, extra: extra || null }; } from && (Message.from = from); to && (Message.to = to); return Message; } } class TextMessage extends MessageModel { constructor(messageData) { var Message = super(messageData); Message.messageType = MessageType.TEXT; return Message; } } class ImageMessage extends MessageModel { constructor(messageData) { var Message = super(messageData); Message.messageType = MessageType.IMAGE; return Message; } } class PingMessage extends MessageModel { constructor(messageData) { var Message = super(messageData); Message.messageType = MessageType.PING; Message.conversationType = ConversationType.SERVER; return Message; } } class SignalMessage extends MessageModel { constructor(messageData) { var Message = super(messageData); Message.messageType = MessageType.SIGNAL; Message.signalName = messageData.signalName; Message.conversationType = ConversationType.SERVER; return Message; } } var Message = /*#__PURE__*/Object.freeze({ __proto__: null, ConversationType: ConversationType, ImageMessage: ImageMessage, MessageDirection: MessageDirection, MessageType: MessageType, PingMessage: PingMessage, SignalMessage: SignalMessage, TextMessage: TextMessage, default: MessageModel }); function utf8Count(str) { var strLength = str.length; var byteLength = 0; var pos = 0; while (pos < strLength) { var value = str.charCodeAt(pos++); if ((value & 0xffffff80) === 0) { // 1-byte byteLength++; continue; } else if ((value & 0xfffff800) === 0) { // 2-bytes byteLength += 2; } else { // handle surrogate pair if (value >= 0xd800 && value <= 0xdbff) { // high surrogate if (pos < strLength) { var extra = str.charCodeAt(pos); if ((extra & 0xfc00) === 0xdc00) { ++pos; value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000; } } } if ((value & 0xffff0000) === 0) { // 3-byte byteLength += 3; } else { // 4-byte byteLength += 4; } } } return byteLength; } function utf8EncodeJs(str, output, outputOffset) { var strLength = str.length; var offset = outputOffset; var pos = 0; while (pos < strLength) { var value = str.charCodeAt(pos++); if ((value & 0xffffff80) === 0) { // 1-byte output[offset++] = value; continue; } else if ((value & 0xfffff800) === 0) { // 2-bytes output[offset++] = ((value >> 6) & 0x1f) | 0xc0; } else { // handle surrogate pair if (value >= 0xd800 && value <= 0xdbff) { // high surrogate if (pos < strLength) { var extra = str.charCodeAt(pos); if ((extra & 0xfc00) === 0xdc00) { ++pos; value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000; } } } if ((value & 0xffff0000) === 0) { // 3-byte output[offset++] = ((value >> 12) & 0x0f) | 0xe0; output[offset++] = ((value >> 6) & 0x3f) | 0x80; } else { // 4-byte output[offset++] = ((value >> 18) & 0x07) | 0xf0; output[offset++] = ((value >> 12) & 0x3f) | 0x80; output[offset++] = ((value >> 6) & 0x3f) | 0x80; } } output[offset++] = (value & 0x3f) | 0x80; } } // TextEncoder and TextDecoder are standardized in whatwg encoding: // https://encoding.spec.whatwg.org/ // and available in all the modern browsers: // https://caniuse.com/textencoder // They are available in Node.js since v12 LTS as well: // https://nodejs.org/api/globals.html#textencoder var sharedTextEncoder = new TextEncoder(); // This threshold should be determined by benchmarking, which might vary in engines and input data. // Run `npx ts-node benchmark/encode-string.ts` for details. var TEXT_ENCODER_THRESHOLD = 50; function utf8EncodeTE(str, output, outputOffset) { sharedTextEncoder.encodeInto(str, output.subarray(outputOffset)); } function utf8Encode(str, output, outputOffset) { if (str.length > TEXT_ENCODER_THRESHOLD) { utf8EncodeTE(str, output, outputOffset); } else { utf8EncodeJs(str, output, outputOffset); } } var CHUNK_SIZE = 4096; function utf8DecodeJs(bytes, inputOffset, byteLength) { var offset = inputOffset; var end = offset + byteLength; var units = []; var result = ""; while (offset < end) { var byte1 = bytes[offset++]; if ((byte1 & 0x80) === 0) { // 1 byte units.push(byte1); } else if ((byte1 & 0xe0) === 0xc0) { // 2 bytes var byte2 = bytes[offset++] & 0x3f; units.push(((byte1 & 0x1f) << 6) | byte2); } else if ((byte1 & 0xf0) === 0xe0) { // 3 bytes var byte2 = bytes[offset++] & 0x3f; var byte3 = bytes[offset++] & 0x3f; units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3); } else if ((byte1 & 0xf8) === 0xf0) { // 4 bytes var byte2 = bytes[offset++] & 0x3f; var byte3 = bytes[offset++] & 0x3f; var byte4 = bytes[offset++] & 0x3f; var unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4; if (unit > 0xffff) { unit -= 0x10000; units.push(((unit >>> 10) & 0x3ff) | 0xd800); unit = 0xdc00 | (unit & 0x3ff); } units.push(unit); } else { units.push(byte1); } if (units.length >= CHUNK_SIZE) { result += String.fromCharCode.apply(String, units); units.length = 0; } } if (units.length > 0) { result += String.fromCharCode.apply(String, units); } return result; } var sharedTextDecoder = new TextDecoder(); // This threshold should be determined by benchmarking, which might vary in engines and input data. // Run `npx ts-node benchmark/decode-string.ts` for details. var TEXT_DECODER_THRESHOLD = 200; function utf8DecodeTD(bytes, inputOffset, byteLength) { var stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength); return sharedTextDecoder.decode(stringBytes); } function utf8Decode(bytes, inputOffset, byteLength) { if (byteLength > TEXT_DECODER_THRESHOLD) { return utf8DecodeTD(bytes, inputOffset, byteLength); } else { return utf8DecodeJs(bytes, inputOffset, byteLength); } } /** * ExtData is used to handle Extension Types that are not registered to ExtensionCodec. */ var ExtData = /** @class */ (function () { function ExtData(type, data) { this.type = type; this.data = data; } return ExtData; }()); var __extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var DecodeError = /** @class */ (function (_super) { __extends(DecodeError, _super); function DecodeError(message) { var _this = _super.call(this, message) || this; // fix the prototype chain in a cross-platform way var proto = Object.create(DecodeError.prototype); Object.setPrototypeOf(_this, proto); Object.defineProperty(_this, "name", { configurable: true, enumerable: false, value: DecodeError.name, }); return _this; } return DecodeError; }(Error)); // Integer Utility var UINT32_MAX = 4294967295; // DataView extension to handle int64 / uint64, // where the actual range is 53-bits integer (a.k.a. safe integer) function setUint64(view, offset, value) { var high = value / 4294967296; var low = value; // high bits are truncated by DataView view.setUint32(offset, high); view.setUint32(offset + 4, low); } function setInt64(view, offset, value) { var high = Math.floor(value / 4294967296); var low = value; // high bits are truncated by DataView view.setUint32(offset, high); view.setUint32(offset + 4, low); } function getInt64(view, offset) { var high = view.getInt32(offset); var low = view.getUint32(offset + 4); return high * 4294967296 + low; } function getUint64(view, offset) { var high = view.getUint32(offset); var low = view.getUint32(offset + 4); return high * 4294967296 + low; } // https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type var EXT_TIMESTAMP = -1; var TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int var TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int function encodeTimeSpecToTimestamp(_a) { var sec = _a.sec, nsec = _a.nsec; if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) { // Here sec >= 0 && nsec >= 0 if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) { // timestamp 32 = { sec32 (unsigned) } var rv = new Uint8Array(4); var view = new DataView(rv.buffer); view.setUint32(0, sec); return rv; } else { // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) } var secHigh = sec / 0x100000000; var secLow = sec & 0xffffffff; var rv = new Uint8Array(8); var view = new DataView(rv.buffer); // nsec30 | secHigh2 view.setUint32(0, (nsec << 2) | (secHigh & 0x3)); // secLow32 view.setUint32(4, secLow); return rv; } } else { // timestamp 96 = { nsec32 (unsigned), sec64 (signed) } var rv = new Uint8Array(12); var view = new DataView(rv.buffer); view.setUint32(0, nsec); setInt64(view, 4, sec); return rv; } } function encodeDateToTimeSpec(date) { var msec = date.getTime(); var sec = Math.floor(msec / 1e3); var nsec = (msec - sec * 1e3) * 1e6; // Normalizes { sec, nsec } to ensure nsec is unsigned. var nsecInSec = Math.floor(nsec / 1e9); return { sec: sec + nsecInSec, nsec: nsec - nsecInSec * 1e9, }; } function encodeTimestampExtension(object) { if (object instanceof Date) { var timeSpec = encodeDateToTimeSpec(object); return encodeTimeSpecToTimestamp(timeSpec); } else { return null; } } function decodeTimestampToTimeSpec(data) { var view = new DataView(data.buffer, data.byteOffset, data.byteLength); // data may be 32, 64, or 96 bits switch (data.byteLength) { case 4: { // timestamp 32 = { sec32 } var sec = view.getUint32(0); var nsec = 0; return { sec: sec, nsec: nsec }; } case 8: { // timestamp 64 = { nsec30, sec34 } var nsec30AndSecHigh2 = view.getUint32(0); var secLow32 = view.getUint32(4); var sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32; var nsec = nsec30AndSecHigh2 >>> 2; return { sec: sec, nsec: nsec }; } case 12: { // timestamp 96 = { nsec32 (unsigned), sec64 (signed) } var sec = getInt64(view, 4); var nsec = view.getUint32(0); return { sec: sec, nsec: nsec }; } default: throw new DecodeError("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(data.length)); } } function decodeTimestampExtension(data) { var timeSpec = decodeTimestampToTimeSpec(data); return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6); } var timestampExtension = { type: EXT_TIMESTAMP, encode: encodeTimestampExtension, decode: decodeTimestampExtension, }; // ExtensionCodec to handle MessagePack extensions var ExtensionCodec = /** @class */ (function () { function ExtensionCodec() { // built-in extensions this.builtInEncoders = []; this.builtInDecoders = []; // custom extensions this.encoders = []; this.decoders = []; this.register(timestampExtension); } ExtensionCodec.prototype.register = function (_a) { var type = _a.type, encode = _a.encode, decode = _a.decode; if (type >= 0) { // custom extensions this.encoders[type] = encode; this.decoders[type] = decode; } else { // built-in extensions var index = 1 + type; this.builtInEncoders[index] = encode; this.builtInDecoders[index] = decode; } }; ExtensionCodec.prototype.tryToEncode = function (object, context) { // built-in extensions for (var i = 0; i < this.builtInEncoders.length; i++) { var encodeExt = this.builtInEncoders[i]; if (encodeExt != null) { var data = encodeExt(object, context); if (data != null) { var type = -1 - i; return new ExtData(type, data); } } } // custom extensions for (var i = 0; i < this.encoders.length; i++) { var encodeExt = this.encoders[i]; if (encodeExt != null) { var data = encodeExt(object, context); if (data != null) { var type = i; return new ExtData(type, data); } } } if (object instanceof ExtData) { // to keep ExtData as is return object; } return null; }; ExtensionCodec.prototype.decode = function (data, type, context) { var decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type]; if (decodeExt) { return decodeExt(data, type, context); } else { // decode() does not fail, returns ExtData instead. return new ExtData(type, data); } }; ExtensionCodec.defaultCodec = new ExtensionCodec(); return ExtensionCodec; }()); function ensureUint8Array(buffer) { if (buffer instanceof Uint8Array) { return buffer; } else if (ArrayBuffer.isView(buffer)) { return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); } else if (buffer instanceof ArrayBuffer) { return new Uint8Array(buffer); } else { // ArrayLike<number> return Uint8Array.from(buffer); } } function createDataView(buffer) { if (buffer instanceof ArrayBuffer) { return new DataView(buffer); } var bufferView = ensureUint8Array(buffer); return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength); } var DEFAULT_MAX_DEPTH = 100; var DEFAULT_INITIAL_BUFFER_SIZE = 2048; var Encoder = /** @class */ (function () { function Encoder(options) { var _a, _b, _c, _d, _e, _f, _g, _h; this.extensionCodec = (_a = options === null || options === void 0 ? void 0 : options.extensionCodec) !== null && _a !== void 0 ? _a : ExtensionCodec.defaultCodec; this.context = options === null || options === void 0 ? void 0 : options.context; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined this.useBigInt64 = (_b = options === null || options === void 0 ? void 0 : options.useBigInt64) !== null && _b !== void 0 ? _b : false; this.maxDepth = (_c = options === null || options === void 0 ? void 0 : options.maxDepth) !== null && _c !== void 0 ? _c : DEFAULT_MAX_DEPTH; this.initialBufferSize = (_d = options === null || options === void 0 ? void 0 : options.initialBufferSize) !== null && _d !== void 0 ? _d : DEFAULT_INITIAL_BUFFER_SIZE; this.sortKeys = (_e = options === null || options === void 0 ? void 0 : options.sortKeys) !== null && _e !== void 0 ? _e : false; this.forceFloat32 = (_f = options === null || options === void 0 ? void 0 : options.forceFloat32) !== null && _f !== void 0 ? _f : false; this.ignoreUndefined = (_g = options === null || options === void 0 ? void 0 : options.ignoreUndefined) !== null && _g !== void 0 ? _g : false; this.forceIntegerToFloat = (_h = options === null || options === void 0 ? void 0 : options.forceIntegerToFloat) !== null && _h !== void 0 ? _h : false; this.pos = 0; this.view = new DataView(new ArrayBuffer(this.initialBufferSize)); this.bytes = new Uint8Array(this.view.buffer); } Encoder.prototype.reinitializeState = function () { this.pos = 0; }; /** * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}. * * @returns Encodes the object and returns a shared reference the encoder's internal buffer. */ Encoder.prototype.encodeSharedRef = function (object) { this.reinitializeState(); this.doEncode(object, 1); return this.bytes.subarray(0, this.pos); }; /** * @returns Encodes the object and returns a copy of the encoder's internal buffer. */ Encoder.prototype.encode = function (object) { this.reinitializeState(); this.doEncode(object, 1); return this.bytes.slice(0, this.pos); }; Encoder.prototype.doEncode = function (object, depth) { if (depth > this.maxDepth) { throw new Error("Too deep objects in depth ".concat(depth)); } if (object == null) { this.encodeNil(); } else if (typeof object === "boolean") { this.encodeBoolean(object); } else if (typeof object === "number") { if (!this.forceIntegerToFloat) { this.encodeNumber(object); } else { this.encodeNumberAsFloat(object); } } else if (typeof object === "string") { this.encodeString(object); } else if (this.useBigInt64 && typeof object === "bigint") { this.encodeBigInt64(object); } else { this.encodeObject(object, depth); } }; Encoder.prototype.ensureBufferSizeToWrite = function (sizeToWrite) { var requiredSize = this.pos + sizeToWrite; if (this.view.byteLength < requiredSize) { this.resizeBuffer(requiredSize * 2); } }; Encoder.prototype.resizeBuffer = function (newSize) { var newBuffer = new ArrayBuffer(newSize); var newBytes = new Uint8Array(newBuffer); var newView = new DataView(newBuffer); newBytes.set(this.bytes); this.view = newView; this.bytes = newBytes; }; Encoder.prototype.encodeNil = function () { this.writeU8(0xc0); }; Encoder.prototype.encodeBoolean = function (object) { if (object === false) { this.writeU8(0xc2); } else { this.writeU8(0xc3); } }; Encoder.prototype.encodeNumber = function (object) { if (!this.forceIntegerToFloat && Number.isSafeInteger(object)) { if (object >= 0) { if (object < 0x80) { // positive fixint this.writeU8(object); } else if (object < 0x100) { // uint 8 this.writeU8(0xcc); this.writeU8(object); } else if (object < 0x10000) { // uint 16 this.writeU8(0xcd); this.writeU16(object); } else if (object < 0x100000000) { // uint 32 this.writeU8(0xce); this.writeU32(object); } else if (!this.useBigInt64) { // uint 64 this.writeU8(0xcf); this.writeU64(object); } else { this.encodeNumberAsFloat(object); } } else { if (object >= -0x20) { // negative fixint this.writeU8(0xe0 | (object + 0x20)); } else if (object >= -0x80) { // int 8 this.writeU8(0xd0); this.writeI8(object); } else if (object >= -0x8000) { // int 16 this.writeU8(0xd1); this.writeI16(object); } else if (object >= -0x80000000) { // int 32 this.writeU8(0xd2); this.writeI32(object); } else if (!this.useBigInt64) { // int 64 this.writeU8(0xd3); this.writeI64(object); } else { this.encodeNumberAsFloat(object); } } } else { this.encodeNumberAsFloat(object); } }; Encoder.prototype.encodeNumberAsFloat = function (object) { if (this.forceFloat32) { // float 32 this.writeU8(0xca); this.writeF32(object); } else { // float 64 this.writeU8(0xcb); this.writeF64(object); } }; Encoder.prototype.encodeBigInt64 = function (object) { if (object >= BigInt(0)) { // uint 64 this.writeU8(0xcf); this.writeBigUint64(object); } else { // int 64 this.writeU8(0xd3); this.writeBigInt64(object); } }; Encoder.prototype.writeStringHeader = function (byteLength) { if (byteLength < 32) { // fixstr this.writeU8(0xa0 + byteLength); } else if (byteLength < 0x100) { // str 8 this.writeU8(0xd9); this.writeU8(byteLength); } else if (byteLength < 0x10000) { // str 16 this.writeU8(0xda); this.writeU16(byteLength); } else if (byteLength < 0x100000000) { // str 32 this.writeU8(0xdb); this.writeU32(byteLength); } else { throw new Error("Too long string: ".concat(byteLength, " bytes in UTF-8")); } }; Encoder.prototype.encodeString = function (object) { var maxHeaderSize = 1 + 4; var byteLength = utf8Count(object); this.ensureBufferSizeToWrite(maxHeaderSize + byteLength); this.writeStringHeader(byteLength); utf8Encode(object, this.bytes, this.pos); this.pos += byteLength; }; Encoder.prototype.encodeObject = function (object, depth) { // try to encode objects with custom codec first of non-primitives var ext = this.extensionCodec.tryToEncode(object, this.context); if (ext != null) { this.encodeExtension(ext); } else if (Array.isArray(object)) { this.encodeArray(object, depth); } else if (ArrayBuffer.isView(object)) { this.encodeBinary(object); } else if (typeof object === "object") { this.encodeMap(object, depth); } else { // symbol, function and other special object come here unless extensionCodec handles them. throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(object))); } }; Encoder.prototype.encodeBinary = function (object) { var size = object.byteLength; if (size < 0x100) { // bin 8 this.writeU8(0xc4); this.writeU8(size); } else if (size < 0x10000) { // bin 16 this.writeU8(0xc5); this.writeU16(size); } else if (size < 0x100000000) { // bin 32 this.writeU8(0xc6); this.writeU32(size); } else { throw new Error("Too large binary: ".concat(size)); } var bytes = ensureUint8Array(object); this.writeU8a(bytes); }; Encoder.prototype.encodeArray = function (object, depth) { var size = object.length; if (size < 16) { // fixarray this.writeU8(0x90 + size); } else if (size < 0x10000) { // array 16 this.writeU8(0xdc); this.writeU16(size); } else if (size < 0x100000000) { // array 32 this.writeU8(0xdd); this.writeU32(size); } else { throw new Error("Too large array: ".concat(size)); } for (var _i = 0, object_1 = object; _i < object_1.length; _i++) { var item = object_1[_i]; this.doEncode(item, depth + 1); } }; Encoder.prototype.countWithoutUndefined = function (object, keys) { var count = 0; for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { var key = keys_1[_i]; if (object[key] !== undefined) { count++; } } return count; }; Encoder.prototype.encodeMap = function (object, depth) { var keys = Object.keys(object); if (this.sortKeys) { keys.sort(); } var size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length; if (size < 16) { // fixmap this.writeU8(0x80 + size); } else if (size < 0x10000) { // map 16 this.writeU8(0xde); this.writeU16(size); } else if (size < 0x100000000) { // map 32 this.writeU8(0xdf); this.writeU32(size); } else { throw new Error("Too large map object: ".concat(size)); } for (var _i = 0, keys_2 = keys; _i < keys_2.length; _i++) { var key = keys_2[_i]; var value = object[key]; if (!(this.ignoreUndefined && value === undefined)) { this.encodeString(key); this.doEncode(value, depth + 1); } } }; Encoder.prototype.encodeExtension = function (ext) { var size = ext.data.length; if (size === 1) { // fixext 1 this.writeU8(0xd4); } else if (size === 2) { // fixext 2 this.writeU8(0xd5); } else if (size === 4) { // fixext 4 this.writeU8(0xd6); } else if (size === 8) { // fixext 8 this.writeU8(0xd7); } else if (size === 16) { // fixext 16 this.writeU8(0xd8); } else if (size < 0x100) { // ext 8 this.writeU8(0xc7); this.writeU8(size); } else if (size < 0x10000) { // ext 16 this.writeU8(0xc8); this.writeU16(size); } else if (size < 0x100000000) { // ext 32 this.writeU8(0xc9); this.writeU32(size); } else { throw new Error("Too large extension object: ".concat(size)); } this.writeI8(ext.type); this.writeU8a(ext.data); }; Encoder.prototype.writeU8 = function (value) { this.ensureBufferSizeToWrite(1); this.view.setUint8(this.pos, value); this.pos++; }; Encoder.prototype.writeU8a = function (values) { var size = values.length; this.ensureBufferSizeToWrite(size); this.bytes.set(values, this.pos); this.pos += size; }; Encoder.prototype.writeI8 = function (value) { this.ensureBufferSizeToWrite(1); this.view.setInt8(this.pos, value); this.pos++; }; Encoder.prototype.writeU16 = function (value) { this.ensureBufferSizeToWrite(2); this.view.setUint16(this.pos, value); this.pos += 2; }; Encoder.prototype.writeI16 = function (value) { this.ensureBufferSizeToWrite(2); this.view.setInt16(this.pos, value); this.pos += 2; }; Encoder.prototype.writeU32 = function (value) { this.ensureBufferSizeToWrite(4); this.view.setUint32(this.pos, value); this.pos += 4; }; Encoder.prototype.writeI32 = function (value) { this.ensureBufferSizeToWrite(4); this.view.setInt32(this.pos, value); this.pos += 4; }; Encoder.prototype.writeF32 = function (value) { this.ensureBufferSizeToWrite(4); this.view.setFloat32(this.pos, value); this.pos += 4; }; Encoder.prototype.writeF64 = function (value) { this.ensureBufferSizeToWrite(8); this.view.setFloat64(this.pos, value); this.pos += 8; }; Encoder.prototype.writeU64 = function (value) { this.ensureBufferSizeToWrite(8); setUint64(this.view, this.pos, value); this.pos += 8; }; Encoder.prototype.writeI64 = function (value) { this.ensureBufferSizeToWrite(8); setInt64(this.view, this.pos, value); this.pos += 8; }; Encoder.prototype.writeBigUint64 = function (value) { this.ensureBufferSizeToWrite(8); this.view.setBigUint64(this.pos, value); this.pos += 8; }; Encoder.prototype.writeBigInt64 = function (value) { this.ensureBufferSizeToWrite(8); this.view.setBigInt64(this.pos, value); this.pos += 8; }; return Encoder; }()); /** * It encodes `value` in the MessagePack format and * returns a byte buffer. * * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`. */ function encode(value, options) { var encoder = new Encoder(options); return encoder.encodeSharedRef(value); } function prettyByte(byte) { return "".concat(byte < 0 ? "-" : "", "0x").concat(Math.abs(byte).toString(16).padStart(2, "0")); } var DEFAULT_MAX_KEY_LENGTH = 16; var DEFAULT_MAX_LENGTH_PER_KEY = 16; var CachedKeyDecoder = /** @class */ (function () { function CachedKeyDecoder(maxKeyLength, maxLengthPerKey) { if (maxKeyLength === void 0) { maxKeyLength = DEFAULT_MAX_KEY_LENGTH; } if (maxLengthPerKey === void 0) { maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY; } this.maxKeyLength = maxKeyLength; this.maxLengthPerKey = maxLengthPerKey; this.hit = 0; this.miss = 0; // avoid `new Array(N)`, which makes a sparse array, // because a sparse array is typically slower than a non-sparse array. this.caches = []; for (var i = 0; i < this.maxKeyLength; i++) { this.caches.push([]); } } CachedKeyDecoder.prototype.canBeCached = function (byteLength) { return byteLength > 0 && byteLength <= this.maxKeyLength; }; CachedKeyDecoder.prototype.find = function (bytes, inputOffset, byteLength) { var records = this.caches[byteLength - 1]; FIND_CHUNK: for (var _i = 0, records_1 = records; _i < records_1.length; _i++) { var record = records_1[_i]; var recordBytes = record.bytes; for (var j = 0; j < byteLength; j++) { if (recordBytes[j] !== bytes[inputOffset + j]) { continue FIND_CHUNK; } } return record.str; } return null; }; CachedKeyDecoder.prototype.store = function (bytes, value) { var records = this.caches[bytes.length - 1]; var record = { bytes: bytes, str: value }; if (records.length >= this.maxLengthPerKey) { // `records` are full! // Set `record` to an arbitrary position. records[(Math.random() * records.length) | 0] = record; } else { records.push(record); } }; CachedKeyDecoder.prototype.decode = function (bytes, inputOffset, byteLength) { var cachedValue = this.find(bytes, inputOffset, byteLength); if (cachedValue != null) { this.hit++; return cachedValue; } this.miss++; var str = utf8DecodeJs(bytes, inputOffset, byteLength); // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer. var slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength); this.store(slicedCopyOfBytes, str); return str; }; return CachedKeyDecoder; }()); var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (undefined && undefined.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __asyncValues = (undefined && undefined.__asyncValues) || function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } }; var __await = (undefined && undefined.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }; var __asyncGenerator = (undefined && undefined.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var STATE_ARRAY = "array"; var STATE_MAP_KEY = "map_key"; var STATE_MAP_VALUE = "map_value"; var isValidMapKeyType = function (key) { return typeof key === "string" || typeof key === "number"; }; var HEAD_BYTE_REQUIRED = -1; var EMPTY_VIEW = new DataView(new ArrayBuffer(0)); var EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer); try { // IE11: The spec says it should throw RangeError, // IE11: but in IE11 it throws TypeError. EMPTY_VIEW.getInt8(0); } catch (e) { if (!(e instanceof RangeError)) { throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access"); } } var DataViewIndexOutOfBoundsError = RangeError; var MORE_DATA = new DataViewIndexOutOfBoundsError("Insufficient data"); var sharedCachedKeyDecoder = new CachedKeyDecoder(); var Decoder = /** @class */ (function () { function Decoder(options) { var _a, _b, _c, _d, _e, _f, _g; this.totalPos = 0; this.pos = 0; this.view = EMPTY_VIEW; this.bytes = EMPTY_BYTES; this.headByte = HEAD_BYTE_REQUIRED; this.stack = []; this.extensionCodec = (_a = options === null || options === void 0 ? void 0 : options.extensionCodec) !== null && _a !== void 0 ? _a : ExtensionCodec.defaultCodec; this.context = options === null || options === void 0 ? void 0 : options.context; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined this.useBigInt64 = (_b = options === null || options === void 0 ? void 0 : options.useBigInt64) !== null && _b !== void 0 ? _b : false; this.maxStrLength = (_c = options === null || options === void 0 ? void 0 : options.maxStrLength) !== null && _c !== void 0 ? _c : UINT32_MAX; this.maxBinLength = (_d = options === null || options === void 0 ? void 0 : options.maxBinLength) !== null && _d !== void 0 ? _d : UINT32_MAX; this.maxArrayLength = (_e = options === null || options === void 0 ? void 0 : options.maxArrayLength) !== null && _e !== void 0 ? _e : UINT32_MAX; this.maxMapLength = (_f = options === null || options === void 0 ? void 0 : options.maxMapLength) !== null && _f !== void 0 ? _f : UINT32_MAX; this.maxExtLength = (_g = options === null || options === void 0 ? void 0 : options.maxExtLength) !== null && _g !== void 0 ? _g : UINT32_MAX; this.keyDecoder = ((options === null || options === void 0 ? void 0 : options.keyDecoder) !== undefined) ? options.keyDecoder : sharedCachedKeyDecoder; } Decoder.prototype.reinitializeState = function () { this.totalPos = 0; this.headByte = HEAD_BYTE_REQUIRED; this.stack.length = 0; // view, bytes, and pos will be re-initialized in setBuffer() };