UNPKG

netflux

Version:

Peer to peer isomorphic transport API based on WebRTC and WebSocket. Allows to create/join full mesh network

1,387 lines (1,369 loc) 212 kB
import * as crypto from 'crypto'; import { TextDecoder, TextEncoder } from 'text-encoding'; import * as WebSocket from 'uws'; import { Server } from 'uws'; import { merge, Subject, BehaviorSubject, ReplaySubject } from 'rxjs'; import { filter, map } from 'rxjs/operators'; import { parse } from 'url'; var env = {}; env.WebSocket = WebSocket; env.TextEncoder = TextEncoder; env.TextDecoder = TextDecoder; env.cryptoNode = crypto; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ 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 (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __awaiter(thisArg, _arguments, P, generator) { 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(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 (_) 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 }; } } function __values(o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } var netfluxCSS = 'background-color: #FFCA28; padding: 0 3px'; var debugCSS = 'background-color: #b3ba2e; padding: 0 3px'; var webrtcCSS = 'background-color: #CE93D8; padding: 0 3px'; var channelCSS = 'background-color: #90CAF9; padding: 0 3px'; var topologyCSS = 'background-color: #26A69A; padding: 0 3px'; var signalingCSS = 'background-color: #66BB6A; padding: 0 3px'; var channelBuilderCSS = 'background-color: #F57C00; padding: 0 3px'; var signalingStateCSS = 'background-color: #9FA8DA; padding: 0 2px'; var webGroupStateCSS = 'background-color: #EF9A9A; padding: 0 2px'; var warningeCSS = 'background-color: #FF5252; padding: 0 2px'; var log = { webgroup: function () { }, signalingState: function () { }, webGroupState: function () { }, webrtc: function () { }, channel: function () { }, topology: function () { }, signaling: function () { }, channelBuilder: function () { }, debug: function () { }, warn: function () { }, }; var LogLevel; (function (LogLevel) { LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; LogLevel[LogLevel["WEB_GROUP"] = 1] = "WEB_GROUP"; LogLevel[LogLevel["WEBRTC"] = 2] = "WEBRTC"; LogLevel[LogLevel["CHANNEL"] = 3] = "CHANNEL"; LogLevel[LogLevel["TOPOLOGY"] = 4] = "TOPOLOGY"; LogLevel[LogLevel["SIGNALING"] = 5] = "SIGNALING"; LogLevel[LogLevel["CHANNEL_BUILDER"] = 6] = "CHANNEL_BUILDER"; })(LogLevel || (LogLevel = {})); var logLevels = []; function setLogLevel() { var levels = []; for (var _i = 0; _i < arguments.length; _i++) { levels[_i] = arguments[_i]; } logLevels = levels; if (logLevels.includes(LogLevel.WEB_GROUP)) { log.webgroup = function (msg) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } if (rest.length === 0) { console.info("%cNETFLUX WebGroup%c: " + msg, netfluxCSS, ''); } else { console.info.apply(console, __spread(["%cNETFLUX WebGroup%c: " + msg, netfluxCSS, ''], rest)); } }; log.signalingState = function (msg, id) { console.info("%cNETFLUX " + id + " WebGroup%c: Signaling: %c" + msg + "%c", netfluxCSS, '', signalingStateCSS, ''); }; log.webGroupState = function (msg, id) { console.info("%cNETFLUX " + id + " WebGroup%c: WebGroup: %c" + msg + "%c", netfluxCSS, '', webGroupStateCSS, ''); }; } else { log.webgroup = function () { }; log.signalingState = function () { }; log.webGroupState = function () { }; } if (logLevels.includes(LogLevel.WEBRTC)) { log.webrtc = function (msg) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } if (rest.length === 0) { console.info("%cNETFLUX WebRTC%c: " + msg, webrtcCSS, ''); } else { console.info.apply(console, __spread(["%cNETFLUX WebRTC%c: " + msg, webrtcCSS, ''], rest)); } }; } else { log.webrtc = function () { }; } if (logLevels.includes(LogLevel.CHANNEL)) { log.channel = function (msg) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } if (rest.length === 0) { console.info("%cNETFLUX Channel%c: " + msg, channelCSS, ''); } else { console.info.apply(console, __spread(["%cNETFLUX Channel%c: " + msg, channelCSS, ''], rest)); } }; } else { log.channel = function () { }; } if (logLevels.includes(LogLevel.TOPOLOGY)) { log.topology = function (msg) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } if (rest.length === 0) { console.info("%cNETFLUX Topology%c: " + msg, topologyCSS, ''); } else { console.info.apply(console, __spread(["%cNETFLUX Topology%c: " + msg, topologyCSS, ''], rest)); } }; } else { log.topology = function () { }; } if (logLevels.includes(LogLevel.SIGNALING)) { log.signaling = function (msg) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } if (rest.length === 0) { console.info("%cNETFLUX Signaling%c: " + msg, signalingCSS, ''); } else { console.info.apply(console, __spread(["%cNETFLUX Signaling%c: " + msg, signalingCSS, ''], rest)); } }; } else { log.signaling = function () { }; } if (logLevels.includes(LogLevel.CHANNEL_BUILDER)) { log.channelBuilder = function (msg) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } if (rest.length === 0) { console.info("%cNETFLUX ChannelBuilder%c: " + msg, channelBuilderCSS, ''); } else { console.info.apply(console, __spread(["%cNETFLUX ChannelBuilder%c: " + msg, channelBuilderCSS, ''], rest)); } }; } else { log.channelBuilder = function () { }; } if (logLevels.includes(LogLevel.DEBUG)) { log.debug = function (msg) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } if (rest.length === 0) { console.info("%cNETFLUX Debug%c: " + msg, debugCSS, ''); } else { console.info.apply(console, __spread(["%cNETFLUX Debug%c: " + msg, debugCSS, ''], rest)); } }; } else { log.debug = function () { }; } log.warn = function (msg) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } if (rest.length === 0) { console.info("%cNETFLUX WARNING%c: " + msg, warningeCSS, ''); } else { console.info.apply(console, __spread(["%cNETFLUX WARNING%c: " + msg, warningeCSS, ''], rest)); } }; } var MIN_ID = 2147483648; var isBrowser = typeof window === 'undefined' ? false : true; function isOnline() { return isBrowser ? navigator.onLine : true; } function isVisible() { return isBrowser ? document.visibilityState === 'visible' : true; } function validateWebSocketURL(url) { var regex = /^(wss|ws):\/\/((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9]))(:[0-9]{1,5})?(\/.*)?$/; if (!new RegExp(regex, 'i').test(url)) { throw new Error("Invalid URL: " + url); } } function generateKey() { var mask = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; var length = 42; var values = randNumbers(length); var result = ''; for (var i = 0; i < length; i++) { result += mask[values[i] % mask.length]; } return result; } function generateId(exclude) { if (exclude === void 0) { exclude = []; } var id = randNumbers()[0]; if (id < MIN_ID) { id += MIN_ID; } if (exclude.includes(id)) { return generateId(exclude); } return id; } var MAX_KEY_LENGTH = 512; function validateKey(key) { if (typeof key !== 'string') { throw new Error("The key type \"" + typeof key + "\" is not a \"string\""); } else if (key === '') { throw new Error('The key is an empty string'); } else if (key.length > MAX_KEY_LENGTH) { throw new Error("The key length of " + key.length + " exceeds the maximum of " + MAX_KEY_LENGTH + " characters"); } return true; } function extractHostnameAndPort(url) { return url.split('/')[2]; } function randNumbers(length) { if (length === void 0) { length = 1; } var res; if (isBrowser) { res = new Uint32Array(length); env.crypto.getRandomValues(res); } else { res = []; var bytes = env.cryptoNode.randomBytes(4 * length); for (var i = 0; i < bytes.length; i += 4) { res[res.length] = bytes.readUInt32BE(i, true); } } return res; } function isWebSocketSupported() { return !!env.WebSocket; } function isWebRTCSupported() { return !!env.RTCPeerConnection && 'createDataChannel' in env.RTCPeerConnection.prototype; } var Service = (function () { function Service(serviceId, proto) { this.serviceId = serviceId; this.proto = proto; } Service.prototype.useWebChannelStream = function (wc) { var _this = this; return { id: wc.STREAM_ID, message: wc.messageFromStream.pipe(filter(function (_a) { var serviceId = _a.serviceId; return serviceId === _this.serviceId; }), map(function (_a) { var channel = _a.channel, senderId = _a.senderId, recipientId = _a.recipientId, content = _a.content; return ({ channel: channel, senderId: senderId, recipientId: recipientId, msg: _this.decode(content), }); }), filter(function (_a) { var msg = _a.msg; return msg && msg.type; })), send: function (content, recipientId) { wc.sendOverStream({ senderId: wc.myId, recipientId: recipientId, serviceId: _this.serviceId, content: content instanceof Uint8Array ? content : _this.encode(content), }); }, }; }; Service.prototype.useSignalingStream = function (sig) { var _this = this; return { id: sig.STREAM_ID, message: sig.messageFromStream.pipe(filter(function (_a) { var serviceId = _a.serviceId; return serviceId === _this.serviceId; }), map(function (_a) { var senderId = _a.senderId, recipientId = _a.recipientId, content = _a.content; return ({ senderId: senderId, recipientId: recipientId, msg: _this.decode(content), }); }), filter(function (_a) { var msg = _a.msg; return msg && msg.type; })), send: function (content, recipientId, senderId) { sig.sendOverStream({ senderId: senderId, recipientId: recipientId, serviceId: _this.serviceId, content: content instanceof Uint8Array ? content : _this.encode(content), }); }, }; }; Service.prototype.useAllStreams = function (wc, sig) { var wcStream = this.useWebChannelStream(wc); var sigStream = this.useSignalingStream(sig); return { message: merge(wcStream.message.pipe(map(function (_a) { var senderId = _a.senderId, recipientId = _a.recipientId, msg = _a.msg; return ({ streamId: wcStream.id, senderId: senderId, recipientId: recipientId, msg: msg, }); })), sigStream.message.pipe(map(function (_a) { var senderId = _a.senderId, recipientId = _a.recipientId, msg = _a.msg; return ({ streamId: sigStream.id, senderId: senderId, recipientId: recipientId, msg: msg, }); }))), sendOver: function (streamId, msg, recipientId, senderId) { if (streamId === wcStream.id) { wcStream.send(msg, recipientId); } else { sigStream.send(msg, recipientId, senderId); } }, }; }; Service.prototype.encode = function (msg) { return this.proto.encode(this.proto.create(msg)).finish(); }; Service.prototype.decode = function (bytes) { try { return this.proto.decode(bytes); } catch (err) { log.warn('Decode service message error: ', err); } return { type: undefined }; }; return Service; }()); var TopologyEnum; (function (TopologyEnum) { TopologyEnum[TopologyEnum["FULL_MESH"] = 0] = "FULL_MESH"; })(TopologyEnum || (TopologyEnum = {})); var TopologyState; (function (TopologyState) { TopologyState[TopologyState["CONSTRUCTING"] = 0] = "CONSTRUCTING"; TopologyState[TopologyState["CONSTRUCTED"] = 1] = "CONSTRUCTED"; TopologyState[TopologyState["IDLE"] = 2] = "IDLE"; })(TopologyState || (TopologyState = {})); var Topology = (function (_super) { __extends(Topology, _super); function Topology(wc, serviceId, proto) { var _this = _super.call(this, serviceId, proto) || this; _this.wc = wc; _this.wcStream = _super.prototype.useWebChannelStream.call(_this, wc); _this.stateSubject = new Subject(); _this._state = TopologyState.IDLE; return _this; } Object.defineProperty(Topology.prototype, "onState", { get: function () { return this.stateSubject.asObservable(); }, enumerable: true, configurable: true }); Object.defineProperty(Topology.prototype, "state", { get: function () { return this._state; }, enumerable: true, configurable: true }); Topology.prototype.setJoinedState = function () { this.setState(TopologyState.CONSTRUCTED); }; Topology.prototype.setState = function (state) { if (this.state !== state) { log.topology("Topology state = " + TopologyState[state]); this._state = state; this.stateSubject.next(state); } }; return Topology; }(Service)); var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var aspromise = asPromise; function asPromise(fn, ctx ) { var params = new Array(arguments.length - 1), offset = 0, index = 2, pending = true; while (index < arguments.length) params[offset++] = arguments[index++]; return new Promise(function executor(resolve, reject) { params[offset] = function callback(err ) { if (pending) { pending = false; if (err) reject(err); else { var params = new Array(arguments.length - 1), offset = 0; while (offset < params.length) params[offset++] = arguments[offset]; resolve.apply(null, params); } } }; try { fn.apply(ctx || null, params); } catch (err) { if (pending) { pending = false; reject(err); } } }); } var base64_1 = createCommonjsModule(function (module, exports) { var base64 = exports; base64.length = function length(string) { var p = string.length; if (!p) return 0; var n = 0; while (--p % 4 > 1 && string.charAt(p) === "=") ++n; return Math.ceil(string.length * 3) / 4 - n; }; var b64 = new Array(64); var s64 = new Array(123); for (var i = 0; i < 64;) s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; base64.encode = function encode(buffer, start, end) { var parts = null, chunk = []; var i = 0, j = 0, t; while (start < end) { var b = buffer[start++]; switch (j) { case 0: chunk[i++] = b64[b >> 2]; t = (b & 3) << 4; j = 1; break; case 1: chunk[i++] = b64[t | b >> 4]; t = (b & 15) << 2; j = 2; break; case 2: chunk[i++] = b64[t | b >> 6]; chunk[i++] = b64[b & 63]; j = 0; break; } if (i > 8191) { (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); i = 0; } } if (j) { chunk[i++] = b64[t]; chunk[i++] = 61; if (j === 1) chunk[i++] = 61; } if (parts) { if (i) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); return parts.join(""); } return String.fromCharCode.apply(String, chunk.slice(0, i)); }; var invalidEncoding = "invalid encoding"; base64.decode = function decode(string, buffer, offset) { var start = offset; var j = 0, t; for (var i = 0; i < string.length;) { var c = string.charCodeAt(i++); if (c === 61 && j > 1) break; if ((c = s64[c]) === undefined) throw Error(invalidEncoding); switch (j) { case 0: t = c; j = 1; break; case 1: buffer[offset++] = t << 2 | (c & 48) >> 4; t = c; j = 2; break; case 2: buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; t = c; j = 3; break; case 3: buffer[offset++] = (t & 3) << 6 | c; j = 0; break; } } if (j === 1) throw Error(invalidEncoding); return offset - start; }; base64.test = function test(string) { return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); }; }); var eventemitter = EventEmitter; function EventEmitter() { this._listeners = {}; } EventEmitter.prototype.on = function on(evt, fn, ctx) { (this._listeners[evt] || (this._listeners[evt] = [])).push({ fn : fn, ctx : ctx || this }); return this; }; EventEmitter.prototype.off = function off(evt, fn) { if (evt === undefined) this._listeners = {}; else { if (fn === undefined) this._listeners[evt] = []; else { var listeners = this._listeners[evt]; for (var i = 0; i < listeners.length;) if (listeners[i].fn === fn) listeners.splice(i, 1); else ++i; } } return this; }; EventEmitter.prototype.emit = function emit(evt) { var listeners = this._listeners[evt]; if (listeners) { var args = [], i = 1; for (; i < arguments.length;) args.push(arguments[i++]); for (i = 0; i < listeners.length;) listeners[i].fn.apply(listeners[i++].ctx, args); } return this; }; var float_1 = factory(factory); function factory(exports) { if (typeof Float32Array !== "undefined") (function() { var f32 = new Float32Array([ -0 ]), f8b = new Uint8Array(f32.buffer), le = f8b[3] === 128; function writeFloat_f32_cpy(val, buf, pos) { f32[0] = val; buf[pos ] = f8b[0]; buf[pos + 1] = f8b[1]; buf[pos + 2] = f8b[2]; buf[pos + 3] = f8b[3]; } function writeFloat_f32_rev(val, buf, pos) { f32[0] = val; buf[pos ] = f8b[3]; buf[pos + 1] = f8b[2]; buf[pos + 2] = f8b[1]; buf[pos + 3] = f8b[0]; } exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; function readFloat_f32_cpy(buf, pos) { f8b[0] = buf[pos ]; f8b[1] = buf[pos + 1]; f8b[2] = buf[pos + 2]; f8b[3] = buf[pos + 3]; return f32[0]; } function readFloat_f32_rev(buf, pos) { f8b[3] = buf[pos ]; f8b[2] = buf[pos + 1]; f8b[1] = buf[pos + 2]; f8b[0] = buf[pos + 3]; return f32[0]; } exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; })(); else (function() { function writeFloat_ieee754(writeUint, val, buf, pos) { var sign = val < 0 ? 1 : 0; if (sign) val = -val; if (val === 0) writeUint(1 / val > 0 ? 0 : 2147483648, buf, pos); else if (isNaN(val)) writeUint(2143289344, buf, pos); else if (val > 3.4028234663852886e+38) writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); else if (val < 1.1754943508222875e-38) writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); else { var exponent = Math.floor(Math.log(val) / Math.LN2), mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); } } exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); function readFloat_ieee754(readUint, buf, pos) { var uint = readUint(buf, pos), sign = (uint >> 31) * 2 + 1, exponent = uint >>> 23 & 255, mantissa = uint & 8388607; return exponent === 255 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 1.401298464324817e-45 * mantissa : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); } exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); })(); if (typeof Float64Array !== "undefined") (function() { var f64 = new Float64Array([-0]), f8b = new Uint8Array(f64.buffer), le = f8b[7] === 128; function writeDouble_f64_cpy(val, buf, pos) { f64[0] = val; buf[pos ] = f8b[0]; buf[pos + 1] = f8b[1]; buf[pos + 2] = f8b[2]; buf[pos + 3] = f8b[3]; buf[pos + 4] = f8b[4]; buf[pos + 5] = f8b[5]; buf[pos + 6] = f8b[6]; buf[pos + 7] = f8b[7]; } function writeDouble_f64_rev(val, buf, pos) { f64[0] = val; buf[pos ] = f8b[7]; buf[pos + 1] = f8b[6]; buf[pos + 2] = f8b[5]; buf[pos + 3] = f8b[4]; buf[pos + 4] = f8b[3]; buf[pos + 5] = f8b[2]; buf[pos + 6] = f8b[1]; buf[pos + 7] = f8b[0]; } exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; function readDouble_f64_cpy(buf, pos) { f8b[0] = buf[pos ]; f8b[1] = buf[pos + 1]; f8b[2] = buf[pos + 2]; f8b[3] = buf[pos + 3]; f8b[4] = buf[pos + 4]; f8b[5] = buf[pos + 5]; f8b[6] = buf[pos + 6]; f8b[7] = buf[pos + 7]; return f64[0]; } function readDouble_f64_rev(buf, pos) { f8b[7] = buf[pos ]; f8b[6] = buf[pos + 1]; f8b[5] = buf[pos + 2]; f8b[4] = buf[pos + 3]; f8b[3] = buf[pos + 4]; f8b[2] = buf[pos + 5]; f8b[1] = buf[pos + 6]; f8b[0] = buf[pos + 7]; return f64[0]; } exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; })(); else (function() { function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { var sign = val < 0 ? 1 : 0; if (sign) val = -val; if (val === 0) { writeUint(0, buf, pos + off0); writeUint(1 / val > 0 ? 0 : 2147483648, buf, pos + off1); } else if (isNaN(val)) { writeUint(0, buf, pos + off0); writeUint(2146959360, buf, pos + off1); } else if (val > 1.7976931348623157e+308) { writeUint(0, buf, pos + off0); writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); } else { var mantissa; if (val < 2.2250738585072014e-308) { mantissa = val / 5e-324; writeUint(mantissa >>> 0, buf, pos + off0); writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); } else { var exponent = Math.floor(Math.log(val) / Math.LN2); if (exponent === 1024) exponent = 1023; mantissa = val * Math.pow(2, -exponent); writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); } } } exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); function readDouble_ieee754(readUint, off0, off1, buf, pos) { var lo = readUint(buf, pos + off0), hi = readUint(buf, pos + off1); var sign = (hi >> 31) * 2 + 1, exponent = hi >>> 20 & 2047, mantissa = 4294967296 * (hi & 1048575) + lo; return exponent === 2047 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 5e-324 * mantissa : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); } exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); })(); return exports; } function writeUintLE(val, buf, pos) { buf[pos ] = val & 255; buf[pos + 1] = val >>> 8 & 255; buf[pos + 2] = val >>> 16 & 255; buf[pos + 3] = val >>> 24; } function writeUintBE(val, buf, pos) { buf[pos ] = val >>> 24; buf[pos + 1] = val >>> 16 & 255; buf[pos + 2] = val >>> 8 & 255; buf[pos + 3] = val & 255; } function readUintLE(buf, pos) { return (buf[pos ] | buf[pos + 1] << 8 | buf[pos + 2] << 16 | buf[pos + 3] << 24) >>> 0; } function readUintBE(buf, pos) { return (buf[pos ] << 24 | buf[pos + 1] << 16 | buf[pos + 2] << 8 | buf[pos + 3]) >>> 0; } var inquire_1 = inquire; function inquire(moduleName) { return null; } var utf8_1 = createCommonjsModule(function (module, exports) { var utf8 = exports; utf8.length = function utf8_length(string) { var len = 0, c = 0; for (var i = 0; i < string.length; ++i) { c = string.charCodeAt(i); if (c < 128) len += 1; else if (c < 2048) len += 2; else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { ++i; len += 4; } else len += 3; } return len; }; utf8.read = function utf8_read(buffer, start, end) { var len = end - start; if (len < 1) return ""; var parts = null, chunk = [], i = 0, t; while (start < end) { t = buffer[start++]; if (t < 128) chunk[i++] = t; else if (t > 191 && t < 224) chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; else if (t > 239 && t < 365) { t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; chunk[i++] = 0xD800 + (t >> 10); chunk[i++] = 0xDC00 + (t & 1023); } else chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; if (i > 8191) { (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); i = 0; } } if (parts) { if (i) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); return parts.join(""); } return String.fromCharCode.apply(String, chunk.slice(0, i)); }; utf8.write = function utf8_write(string, buffer, offset) { var start = offset, c1, c2; for (var i = 0; i < string.length; ++i) { c1 = string.charCodeAt(i); if (c1 < 128) { buffer[offset++] = c1; } else if (c1 < 2048) { buffer[offset++] = c1 >> 6 | 192; buffer[offset++] = c1 & 63 | 128; } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); ++i; buffer[offset++] = c1 >> 18 | 240; buffer[offset++] = c1 >> 12 & 63 | 128; buffer[offset++] = c1 >> 6 & 63 | 128; buffer[offset++] = c1 & 63 | 128; } else { buffer[offset++] = c1 >> 12 | 224; buffer[offset++] = c1 >> 6 & 63 | 128; buffer[offset++] = c1 & 63 | 128; } } return offset - start; }; }); var pool_1 = pool; function pool(alloc, slice, size) { var SIZE = size || 8192; var MAX = SIZE >>> 1; var slab = null; var offset = SIZE; return function pool_alloc(size) { if (size < 1 || size > MAX) return alloc(size); if (offset + size > SIZE) { slab = alloc(SIZE); offset = 0; } var buf = slice.call(slab, offset, offset += size); if (offset & 7) offset = (offset | 7) + 1; return buf; }; } var longbits = LongBits; function LongBits(lo, hi) { this.lo = lo >>> 0; this.hi = hi >>> 0; } var zero = LongBits.zero = new LongBits(0, 0); zero.toNumber = function() { return 0; }; zero.zzEncode = zero.zzDecode = function() { return this; }; zero.length = function() { return 1; }; var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; LongBits.fromNumber = function fromNumber(value) { if (value === 0) return zero; var sign = value < 0; if (sign) value = -value; var lo = value >>> 0, hi = (value - lo) / 4294967296 >>> 0; if (sign) { hi = ~hi >>> 0; lo = ~lo >>> 0; if (++lo > 4294967295) { lo = 0; if (++hi > 4294967295) hi = 0; } } return new LongBits(lo, hi); }; LongBits.from = function from(value) { if (typeof value === "number") return LongBits.fromNumber(value); if (minimal.isString(value)) { if (minimal.Long) value = minimal.Long.fromString(value); else return LongBits.fromNumber(parseInt(value, 10)); } return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; }; LongBits.prototype.toNumber = function toNumber(unsigned) { if (!unsigned && this.hi >>> 31) { var lo = ~this.lo + 1 >>> 0, hi = ~this.hi >>> 0; if (!lo) hi = hi + 1 >>> 0; return -(lo + hi * 4294967296); } return this.lo + this.hi * 4294967296; }; LongBits.prototype.toLong = function toLong(unsigned) { return minimal.Long ? new minimal.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; }; var charCodeAt = String.prototype.charCodeAt; LongBits.fromHash = function fromHash(hash) { if (hash === zeroHash) return zero; return new LongBits( ( charCodeAt.call(hash, 0) | charCodeAt.call(hash, 1) << 8 | charCodeAt.call(hash, 2) << 16 | charCodeAt.call(hash, 3) << 24) >>> 0 , ( charCodeAt.call(hash, 4) | charCodeAt.call(hash, 5) << 8 | charCodeAt.call(hash, 6) << 16 | charCodeAt.call(hash, 7) << 24) >>> 0 ); }; LongBits.prototype.toHash = function toHash() { return String.fromCharCode( this.lo & 255, this.lo >>> 8 & 255, this.lo >>> 16 & 255, this.lo >>> 24 , this.hi & 255, this.hi >>> 8 & 255, this.hi >>> 16 & 255, this.hi >>> 24 ); }; LongBits.prototype.zzEncode = function zzEncode() { var mask = this.hi >> 31; this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; this.lo = ( this.lo << 1 ^ mask) >>> 0; return this; }; LongBits.prototype.zzDecode = function zzDecode() { var mask = -(this.lo & 1); this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; this.hi = ( this.hi >>> 1 ^ mask) >>> 0; return this; }; LongBits.prototype.length = function length() { var part0 = this.lo, part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, part2 = this.hi >>> 24; return part2 === 0 ? part1 === 0 ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 : part2 < 128 ? 9 : 10; }; var minimal = createCommonjsModule(function (module, exports) { var util = exports; util.asPromise = aspromise; util.base64 = base64_1; util.EventEmitter = eventemitter; util.float = float_1; util.inquire = inquire_1; util.utf8 = utf8_1; util.pool = pool_1; util.LongBits = longbits; util.global = typeof window !== "undefined" && window || typeof commonjsGlobal !== "undefined" && commonjsGlobal || typeof self !== "undefined" && self || commonjsGlobal; util.emptyArray = Object.freeze ? Object.freeze([]) : []; util.emptyObject = Object.freeze ? Object.freeze({}) : {}; util.isNode = Boolean(util.global.process && util.global.process.versions && util.global.process.versions.node); util.isInteger = Number.isInteger || function isInteger(value) { return typeof value === "number" && isFinite(value) && Math.floor(value) === value; }; util.isString = function isString(value) { return typeof value === "string" || value instanceof String; }; util.isObject = function isObject(value) { return value && typeof value === "object"; }; util.isset = util.isSet = function isSet(obj, prop) { var value = obj[prop]; if (value != null && obj.hasOwnProperty(prop)) return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; return false; }; util.Buffer = (function() { try { var Buffer = util.inquire("buffer").Buffer; return Buffer.prototype.utf8Write ? Buffer : null; } catch (e) { return null; } })(); util._Buffer_from = null; util._Buffer_allocUnsafe = null; util.newBuffer = function newBuffer(sizeOrArray) { return typeof sizeOrArray === "number" ? util.Buffer ? util._Buffer_allocUnsafe(sizeOrArray) : new util.Array(sizeOrArray) : util.Buffer ? util._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray); }; util.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array; util.Long = util.global.dcodeIO && util.global.dcodeIO.Long || util.global.Long || util.inquire("long"); util.key2Re = /^true|false|0|1$/; util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; util.longToHash = function longToHash(value) { return value ? util.LongBits.from(value).toHash() : util.LongBits.zeroHash; }; util.longFromHash = function longFromHash(hash, unsigned) { var bits = util.LongBits.fromHash(hash); if (util.Long) return util.Long.fromBits(bits.lo, bits.hi, unsigned); return bits.toNumber(Boolean(unsigned)); }; function merge$$1(dst, src, ifNotSet) { for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) if (dst[keys[i]] === undefined || !ifNotSet) dst[keys[i]] = src[keys[i]]; return dst; } util.merge = merge$$1; util.lcFirst = function lcFirst(str) { return str.charAt(0).toLowerCase() + str.substring(1); }; function newError(name) { function CustomError(message, properties) { if (!(this instanceof CustomError)) return new CustomError(message, properties); Object.defineProperty(this, "message", { get: function() { return message; } }); if (Error.captureStackTrace) Error.captureStackTrace(this, CustomError); else Object.defineProperty(this, "stack", { value: (new Error()).stack || "" }); if (properties) merge$$1(this, properties); } (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError; Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } }); CustomError.prototype.toString = function toString() { return this.name + ": " + this.message; }; return CustomError; } util.newError = newError; util.ProtocolError = newError("ProtocolError"); util.oneOfGetter = function getOneOf(fieldNames) { var fieldMap = {}; for (var i = 0; i < fieldNames.length; ++i) fieldMap[fieldNames[i]] = 1; return function() { for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) return keys[i]; }; }; util.oneOfSetter = function setOneOf(fieldNames) { return function(name) { for (var i = 0; i < fieldNames.length; ++i) if (fieldNames[i] !== name) delete this[fieldNames[i]]; }; }; util.toJSONOptions = { longs: String, enums: String, bytes: String, json: true }; util._configure = function() { var Buffer = util.Buffer; if (!Buffer) { util._Buffer_from = util._Buffer_allocUnsafe = null; return; } util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || function Buffer_from(value, encoding) { return new Buffer(value, encoding); }; util._Buffer_allocUnsafe = Buffer.allocUnsafe || function Buffer_allocUnsafe(size) { return new Buffer(size); }; }; }); var writer = Writer; var BufferWriter; var LongBits$1 = minimal.LongBits, base64 = minimal.base64, utf8 = minimal.utf8; function Op(fn, len, val) { this.fn = fn; this.len = len; this.next = undefined; this.val = val; } function noop() {} function State(writer) { this.head = writer.head; this.tail = writer.tail; this.len = writer.len; this.next = writer.states; } function Writer() { this.len = 0; this.head = new Op(noop, 0, 0); this.tail = this.head; this.states = null; } Writer.create = minimal.Buffer ? function create_buffer_setup() { return (Writer.create = function create_buffer() { return new BufferWriter(); })(); } : function create_array() { return new Writer(); }; Writer.alloc = function alloc(size) { return new minimal.Array(size); }; if (minimal.Array !== Array) Writer.alloc = minimal.pool(Writer.alloc, minimal.Array.prototype.subarray); Writer.prototype._push = function push(fn, len, val) { this.tail = this.tail.next = new Op(fn, len, val); this.len += len; return this; }; function writeByte(val, buf, pos) { buf[pos] = val & 255; } function writeVarint32(val, buf, pos) { while (val > 127) { buf[pos++] = val & 127 | 128; val >>>= 7; } buf[pos] = val; } function VarintOp(len, val) { this.len = len; this.next = undefined; this.val = val; } VarintOp.prototype = Object.create(Op.prototype); VarintOp.prototype.fn = writeVarint32; Writer.prototype.uint32 = function write_uint32(value) { this.len += (this.tail = this.tail.next = new VarintOp( (value = value >>> 0) < 128 ? 1 : value < 16384 ? 2 : value < 2097152 ? 3 : value < 268435456 ? 4 : 5, value)).len; return this; }; Writer.prototype.int32 = function write_int32(value) { return value < 0 ? this._push(writeVarint64, 10, LongBits$1.fromNumber(value)) : this.uint32(value); }; Writer.prototype.sint32 = function write_sint32(value) { return this.uint32((value << 1 ^ value >> 31) >>> 0); }; function writeVarint64(val, buf, pos) { while (val.hi) { buf[pos++] = val.lo & 127 | 128; val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; val.hi >>>= 7; } while (val.lo > 127) { buf[pos++] = val.lo & 127 | 128; val.lo = val.lo >>> 7; } buf[pos++] = val.lo; } Writer.prototype.uint64 = function write_uint64(value) { var bits = LongBits$1.from(value); return this._push(writeVarint64, bits.length(), bits); }; Writer.prototype.int64 = Writer.prototype.uint64; Writer.prototype.sint64 = function write_sint64(value) { var bits = LongBits$1.from(value).zzEncode(); return this._push(writeVarint64, bits.length(), bits); }; Writer.prototype.bool = function write_bool(value) { return this._push(writeByte, 1, value ? 1 : 0); }; function writeFixed32(val, buf, pos) { buf[pos ] = val & 255; buf[pos + 1] = val >>> 8 & 255; buf[pos + 2] = val >>> 16 & 255; buf[pos + 3] = val >>> 24; } Writer.prototype.fixed32 = function write_fixed32(value) { return this._push(writeFixed32, 4, value >>> 0); }; Writer.prototype.sfixed32 = Writer.prototype.fixed32; Writer.prototype.fixed64 = function write_fixed64(value) { var bits = LongBits$1.from(value); return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); }; Writer.prototype.sfixed64 = Writer.prototype.fixed64; Writer.prototype.float = function write_float(value) { return this._push(minimal.float.writeFloatLE, 4, value); }; Writer.prototype.double = function write_double(value) { return this._push(minimal.float