#!/usr/bin/env node /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 7413: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; /** * @author Toru Nagashima * See LICENSE file in root directory for full license. */ Object.defineProperty(exports, "__esModule", ({ value: true })); var eventTargetShim = __nccwpck_require__(6577); /** * The signal class. * @see https://dom.spec.whatwg.org/#abortsignal */ class AbortSignal extends eventTargetShim.EventTarget { /** * AbortSignal cannot be constructed directly. */ constructor() { super(); throw new TypeError("AbortSignal cannot be constructed directly"); } /** * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. */ get aborted() { const aborted = abortedFlags.get(this); if (typeof aborted !== "boolean") { throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); } return aborted; } } eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort"); /** * Create an AbortSignal object. */ function createAbortSignal() { const signal = Object.create(AbortSignal.prototype); eventTargetShim.EventTarget.call(signal); abortedFlags.set(signal, false); return signal; } /** * Abort a given signal. */ function abortSignal(signal) { if (abortedFlags.get(signal) !== false) { return; } abortedFlags.set(signal, true); signal.dispatchEvent({ type: "abort" }); } /** * Aborted flag for each instances. */ const abortedFlags = new WeakMap(); // Properties should be enumerable. Object.defineProperties(AbortSignal.prototype, { aborted: { enumerable: true }, }); // `toString()` should return `"[object AbortSignal]"` if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { configurable: true, value: "AbortSignal", }); } /** * The AbortController. * @see https://dom.spec.whatwg.org/#abortcontroller */ class AbortController { /** * Initialize this controller. */ constructor() { signals.set(this, createAbortSignal()); } /** * Returns the `AbortSignal` object associated with this object. */ get signal() { return getSignal(this); } /** * Abort and signal to any observers that the associated activity is to be aborted. */ abort() { abortSignal(getSignal(this)); } } /** * Associated signals. */ const signals = new WeakMap(); /** * Get the associated signal of a given controller. */ function getSignal(controller) { const signal = signals.get(controller); if (signal == null) { throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); } return signal; } // Properties should be enumerable. Object.defineProperties(AbortController.prototype, { signal: { enumerable: true }, abort: { enumerable: true }, }); if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { configurable: true, value: "AbortController", }); } exports.AbortController = AbortController; exports.AbortSignal = AbortSignal; exports["default"] = AbortController; module.exports = AbortController module.exports.AbortController = module.exports["default"] = AbortController module.exports.AbortSignal = AbortSignal //# sourceMappingURL=abort-controller.js.map /***/ }), /***/ 3716: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); // 阿里云LinkPlatform平台功能topic方法参数模块 var ALIYUN_BROKER_METHODS_TEMPLATE = exports.ALIYUN_BROKER_METHODS_TEMPLATE = { /* device methods */ POST_PROPERY: 'thing.event.property.post', POST_EVENT: 'thing.event.%s.post', POST_TAGS: 'thing.deviceinfo.update', DELETE_TAGS: 'thing.deviceinfo.delete', GET_CONFIG: 'thing.config.get', /* gateway methods */ ADD_TOPO: 'thing.topo.add', DELETE_TOPO: 'thing.topo.delete', GET_TOPO: 'thing.topo.get', SUBDEVICE_REGISTER: 'thing.sub.register' }; var ALIYUN_BROKER_TOPICS = exports.ALIYUN_BROKER_TOPICS = { /* device topic */ SERVICE_TOPIC: '/sys/%s/%s/thing/service/%s', SERVICE_RESP_TOPIC: '/sys/%s/%s/thing/service/%s_reply', PROPERTY_POST_TOPIC: '/sys/%s/%s/thing/event/property/post', PROPERTY_POST_REPLY_TOPIC: '/sys/%s/%s/thing/event/property/post_reply', EVENT_POST_TOPIC: '/sys/%s/%s/thing/event/%s/post', EVENT_POST_REPLY_TOPIC: '/sys/%s/%s/thing/event/%s/post_reply', REPORT_SDK_INFO_TOPIC: '/sys/%s/%s/thing/deviceinfo/update', //设备标签上报topic。参数:{productKey}/{deviceName} TAG_TOPIC: '/sys/%s/%s/thing/deviceinfo/update', //设备标签上报reply的topic。参数:{productKey}/{deviceName} TAG_REPLY_TOPIC: '/sys/%s/%s/thing/deviceinfo/update_reply', //删除设备标签topic。参数:{productKey}/{deviceName} TAG_DELETE_TOPIC: '/sys/%s/%s/thing/deviceinfo/delete', //删除设备标签reply的topic。参数:{productKey}/{deviceName} TAG_DELETE_REPLY_TOPIC: '/sys/%s/%s/thing/deviceinfo/delete_reply', // 远程配置topic 参数:{productKey}/{deviceName} CONFIG_TOPIC: '/sys/%s/%s/thing/config/get', // 远程配置reply topic 参数:{productKey}/{deviceName} CONFIG_REPLY_TOPIC: '/sys/%s/%s/thing/config/get_reply', // 远程配置订阅变化topic 参数:{productKey}/{deviceName} CONFIG_SUBSCRIBE_TOPIC: '/sys/%s/%s/thing/config/push', // 远程配置reply topic 参数:{productKey}/{deviceName} CONFIG_SUBSCRIBE_RESP_TOPIC: '/sys/%s/%s/thing/config/push_reply', // 设备影子订阅topic SHADOW_SUBSCRIBE_TOPIC: '/shadow/get/%s/%s', // 设备影子获取topic SHADOW_GET_TOPIC: '/shadow/update/%s/%s', // 设备影子更新topic SHADOW_POST_TOPIC: '/shadow/update/%s/%s', /* gateway topic */ ADD_TOPO_TOPIC: '/sys/%s/%s/thing/topo/add', ADD_TOPO_REPLY_TOPIC: '/sys/%s/%s/thing/topo/add_reply', DELETE_TOPO_TOPIC: '/sys/%s/%s/thing/topo/delete', DELETE_TOPO_REPLY_TOPIC: '/sys/%s/%s/thing/topo/delete_reply', GET_TOPO_TOPIC: '/sys/%s/%s/thing/topo/get', GET_TOPO_REPLY_TOPIC: '/sys/%s/%s/thing/topo/get_reply', LOGIN_TOPIC: '/ext/session/%s/%s/combine/login', LOGIN_REPLY_TOPIC: '/ext/session/%s/%s/combine/login_reply', LOGOUT_TOPIC: '/ext/session/%s/%s/combine/logout', LOGOUT_REPLY_TOPIC: '/ext/session/%s/%s/combine/logout_reply', SUBDEVICE_REGISTER_TOPIC: '/sys/%s/%s/thing/sub/register', SUBDEVICE_REGISTER_REPLY_TOPIC: '/sys/%s/%s/thing/sub/register_reply' }; /***/ }), /***/ 4601: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var mqtt = __nccwpck_require__(4879); var EventEmitter = __nccwpck_require__(4434); var util = __nccwpck_require__(9023); var _require = __nccwpck_require__(8074), createGuid = _require.createGuid, createDebug = _require.createDebug, getIP = _require.getIP, isJsonString = _require.isJsonString; var debug = createDebug('device'); var guid = createGuid(); var packagejson = __nccwpck_require__(5055); var Model = __nccwpck_require__(6458); var Device = function (_EventEmitter) { _inherits(Device, _EventEmitter); function Device() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Device); //init var _this = _possibleConstructorReturn(this, (Device.__proto__ || Object.getPrototypeOf(Device)).call(this)); _this.model = new Model(config); _this._createClient(_this.model); //订阅topic _this._subscribePresetTopic(); //上报客户端sdk信息 _this._reportSDKInfo(); _this.serveCB = []; _this._onShadowCB; //兼容旧版本 _this._compatibleoverdue(); return _this; } // 发布消息到topic _createClass(Device, [{ key: 'publish', value: function publish() { var _mqttClient; (_mqttClient = this._mqttClient).publish.apply(_mqttClient, arguments); } // 订阅消息 }, { key: 'subscribe', value: function subscribe() { var _mqttClient2; (_mqttClient2 = this._mqttClient).subscribe.apply(_mqttClient2, arguments); } // 取消订阅消息 }, { key: 'unsubscribe', value: function unsubscribe() { var _mqttClient3; (_mqttClient3 = this._mqttClient).unsubscribe.apply(_mqttClient3, arguments); } }, { key: 'end', value: function end() { var _mqttClient4; (_mqttClient4 = this._mqttClient).end.apply(_mqttClient4, arguments); } // 属性快捷获取 }, { key: 'postProps', /* 高级版设备属性上报:详细文档地址:https://help.aliyun.com/document_detail/89301.html?spm=a2c4g.11186623.6.660.3ad223dcF1jjSU "params": {"key": "key","value": "value"} */ value: function postProps() { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var cb = arguments[1]; this._publishAlinkMessage({ method: this.model.POST_PROPERY_METHOD, pubTopic: this.model.POST_PROPS_TOPIC, params: props }, cb); } /* 高级版设备事件上报:详细文档地址:https://help.aliyun.com/document_detail/89301.html?spm=a2c4g.11186623.6.660.3ad223dcF1jjSU "params": {"key": "key","value": "value"} */ }, { key: 'postEvent', value: function postEvent(eventName) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var cb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {}; //event需要动态订阅topic返回值 if (this._addEventListenerFn == undefined) { this._addEventListenerFn = this._wrapEventSubscribe(eventName); } this._addEventListenerFn(); this._publishAlinkMessage({ method: this.model.getPostEventMethod(eventName), pubTopic: this.model.getPostEvenTopic(eventName), params: params }, cb); } //修改onService方法 }, { key: 'onService', value: function onService(serviceName, cb) { if (this._addServiceListenerFn == undefined) { this._addServiceListenerFn = this._wrapServiceSubscribe(serviceName, cb); } this._addServiceListenerFn(); this._pushReceiveServiceCallback(serviceName, cb); } /* 设备标签上报:详细文档地址:https://help.aliyun.com/document_detail/89304.html?spm=a2c4g.11174283.6.662.7e9d16685aIS1k "params": [{"attrKey": "key","attrValue": "value"},{},{}] 每次上报不会清除上一次的tag */ }, { key: 'postTags', value: function postTags() { var tags = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var cb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {}; this._publishAlinkMessage({ method: this.model.POST_TAGS_METHOD, pubTopic: this.model.TAG_TOPIC, params: tags }, cb); } // 删除设备标签 }, { key: 'deleteTags', value: function deleteTags() { var tags = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var cb = arguments[1]; var params = tags.map(function (tag) { return { attrKey: tag }; }); this._publishAlinkMessage({ method: this.model.DELETE_TAGS_METHOD, pubTopic: this.model.TAG_DELETE_TOPIC, params: params }, cb); } /* * 获取远程配置 * 技术文档地址:https://help.aliyun.com/document_detail/89308.html?spm=a2c4g.11186623.6.666.53e168d0joDPCn * 返回数据格式 example { code: 200, data: { configId: '3cfda5091d5b4f53b51621cf4bbf86ec', configSize: 16, getType: 'file', sign: '0e89816213d1e462482311a16310424a2cbc5aeea79f7213934d087d97f8b763', signMethod: 'Sha256', url: 'https://otx-devicecenter-thing-config-cn-shanghai-online.oss-cn-shanghai.aliyuncs.com/a1aq9sQk2JE/1548394288572_h6z5LVjh?Expires=1548396135&OSSAccessKeyId=LTAIRY3rx5dg2JBm&Signature=27SgWTHTGRZ6k8UYk5uIELopJFk%3D' }, id: '3', method: 'thing.config.get', version: '1.0' } */ }, { key: 'getConfig', value: function getConfig() { var cb = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {}; // 目前只支持产品维度和文件类型 var params = { "configScope": "product", "getType": "file" }; this._publishAlinkMessage({ method: this.model.GET_CONFIG_METHOD, pubTopic: this.model.CONFIG_TOPIC, params: params }, cb); } //当远程配置下发到设备触发 todo // onConfig(cb = () => {}) { // this._onConfig = cb; // // console.log(this.model.CONFIG_SUBSCRIBE_TOPIC); // this.subscribe(this.model.CONFIG_SUBSCRIBE_TOPIC, (error, res) => { // console.log('onConfig,sub error:', error, res); // }); // } // 获取设备影子数据 }, { key: 'getShadow', value: function getShadow() { var msg = { "method": "get" }; this._publishMessage(this.model.SHADOW_GET_TOPIC, msg); } // 设备上报实际值 }, { key: 'postShadow', value: function postShadow(reported) { var msg = { "method": "update", "state": { "reported": reported }, "version": Date.now() }; this._publishMessage(this.model.SHADOW_POST_TOPIC, msg); } // 删除影子设备 }, { key: 'deleteShadow', value: function deleteShadow(keys) { var reported = {}; if (typeof keys == 'string') { var key = keys; reported[key] = "null"; } if ((typeof keys === 'undefined' ? 'undefined' : _typeof(keys)) == "object") { keys.forEach(function (key) { reported[key] = "null"; }); } if (keys == undefined) { reported = "null"; } var msg = { "method": "delete", "state": { reported: reported }, "version": Date.now() }; this._publishMessage(this.model.SHADOW_POST_TOPIC, msg); } // 注册影子设备监听 }, { key: 'onShadow', value: function onShadow(cb) { this._onShadowCB = cb; } // responseService(serviceName,msg){ // const payload = JSON.stringify(msg); // this._mqttClient.publish(this.model.getServiceRespTopic(serviceName), payload) // } // 发送普通消息 }, { key: '_publishMessage', value: function _publishMessage(pubTopic) { var msg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var qos = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var payload = JSON.stringify(msg); this.publish(pubTopic, payload, { qos: qos }, function (err, res) { if (err) { // console.log('publish error', pubTopic, msg.id, err, res) } }); } // 发送alink协议消息 }, { key: '_publishAlinkMessage', value: function _publishAlinkMessage(_ref, cb) { var _ref$method = _ref.method, method = _ref$method === undefined ? "" : _ref$method, pubTopic = _ref.pubTopic, params = _ref.params, timeout = _ref.timeout; var id = guid(); //暂存回调函数 this._pushCallback(id, cb); var msg = this.model.genAlinkContent(method, params, id); var payload = JSON.stringify(msg); // console.log("_publishAlinkMessage:",payload); this.publish(pubTopic, payload, function (err, res) { debug('pub callback', pubTopic, msg.id, err, res); // console.log('pub callback', pubTopic, msg.id, err, res); if (err) { debug('publish error', pubTopic, msg.id, err, res); } }); } }, { key: '_createClient', value: function _createClient() { var client = mqtt.connect(this.model.brokerUrl, this.model.genConnectPrarms()); this._mqttClient = client; } }, { key: '_subscribePresetTopic', value: function _subscribePresetTopic() { var _this2 = this; ['connect', 'error', 'close', 'reconnect', 'offline', 'message'].forEach(function (evtName) { _this2._mqttClient.on(evtName, function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } debug('mqtt client ' + evtName); if (evtName === 'connect') { debug('mqtt connected'); //初始化只需要订阅 属性返回的topic和标签删除返回的topic,事件topic需要跟进event动态订阅,所以初始化不需要订阅 [ // devices _this2.model.POST_PROPS_REPLY_TOPIC, _this2.model.TAG_REPLY_TOPIC, _this2.model.TAG_DELETE_REPLY_TOPIC, _this2.model.CONFIG_REPLY_TOPIC, _this2.model.SHADOW_SUBSCRIBE_TOPIC, // gateway _this2.model.ADD_TOPO_REPLY_TOPIC, _this2.model.DELETE_TOPO_REPLY_TOPIC, _this2.model.GET_TOPO_REPLY_TOPIC, _this2.model.LOGIN_REPLY_TOPIC, _this2.model.LOGOUT_REPLY_TOPIC, _this2.model.SUBDEVICE_REGISTER_REPLY_TOPIC].forEach(function (replyTopic) { _this2.subscribe(replyTopic, { "qos": 1 }, function (error, res) { if (error) { debug('sub error:', error.toString); } }); }); } // 事件流到设备端开发者lib中的方式有2中,通过subscribe和通过callback if (evtName === 'message') { // 1:处理subscribe通知 _this2.emit.apply(_this2, [evtName].concat(args)); // 2:处理callback通知 _this2._mqttCallbackHandler.apply(_this2, args); return; } // 其他事件 'connect', 'error', 'close', 'reconnect', 'offline'处理 _this2.emit(evtName, args); }); }); } // 处理内部message以及各种方法的回调 }, { key: '_mqttCallbackHandler', value: function _mqttCallbackHandler(topic, message) { // 几种不处理的情况 // 情况1:回调函数为空 if (this._cb == [] && this._serviceCB == [] && this._onShadowCB == []) { return; } // 情况2:返回值为非结构化数据(非结构化可能是:基础版产品或是用户自定义topic) if (isJsonString(message.toString()) == false) { return; } // 开始处理返回值 var res = void 0; try { res = JSON.parse(message.toString()); var _res = res, method = _res.method; //处理物模型服务订阅返回数据 if (method.indexOf("thing.service") != -1) { this._onReceiveService(res); return; } // 影子设备reply和云端或应用下发影子配置通知,很久之前cmp定义的方法名称,所以格式与其他名称不太相同 if (method == "reply" || method == "control") { this._onShadowCB(res); return; } } catch (e) {} // 其他rrpc方法 finally { var _res2 = res, cbID = _res2.id; var callback = this._popCallback(cbID); if (callback) { callback(res); } } } // 查找回调函数,找到后使 }, { key: '_popCallback', value: function _popCallback(cbID) { var cb = this._cb[cbID] || function () {}; delete this._cb[cbID]; return cb; } }, { key: '_wrapEventSubscribe', value: function _wrapEventSubscribe(eventName) { var _this3 = this; var subscription = void 0; var fn = function fn() { //初始化 if (subscription == undefined) { subscription = {}; }; // 查找是否存在 if (subscription.eventName == undefined) { _this3.subscribe(_this3.model.getPostEvenReplyTopic(eventName), function (error, res) { if (error) { debug('sub error:', subTopic); } }); subscription.eventName = true; } }; return fn; } }, { key: '_wrapServiceSubscribe', value: function _wrapServiceSubscribe(serviceName, cb) { var _this4 = this; var subscription = void 0; var fn = function fn() { //初始化 if (subscription == undefined) { subscription = {}; }; // 查找是否存在 if (subscription.serviceName == undefined) { _this4.subscribe(_this4.model.getServiceTopic(serviceName), function (error, res) { if (error) { debug('sub error:', res); } }); subscription.serviceName = true; } }; return fn; } //处理接收云端下发服务调用 }, { key: '_onReceiveService', value: function _onReceiveService(res) { var method = res.method; var serviceName = method.split('.').pop(); var cb = this._serviceCB[serviceName] || function () {}; cb(res); } }, { key: '_pushCallback', value: function _pushCallback(msgid, fn) { // 初始化回调函数数组 if (this._cb == undefined) { this._cb = []; }; this._cb[msgid] = fn; } }, { key: '_pushReceiveServiceCallback', value: function _pushReceiveServiceCallback(serviceName, fn) { // 初始化回调函数数组 if (this._serviceCB == undefined) { this._serviceCB = []; }; this._serviceCB[serviceName] = fn; } }, { key: '_reportSDKInfo', value: function _reportSDKInfo() { //上报sdk版本信息 var networkInfo = 'WiFi|' + getIP(); var sdkInfo = []; var KVS = { 'SYS_SDK_LANGUAGE': 'NodeJS', 'SYS_LP_SDK_VERSION': packagejson.version, 'SYS_SDK_IF_INFO': networkInfo }; Object.keys(KVS).forEach(function (key) { sdkInfo.push({ "attrKey": key, "attrValue": KVS[key], "domain": "SYSTEM" }); }); this.postTags(sdkInfo); // console.log('publish sdk info',sdkInfo); } }, { key: '_compatibleoverdue', value: function _compatibleoverdue() { //兼容老版本serve 方法 0.5版本去掉 // this.serve = this.onService; } }, { key: 'connected', get: function get() { return this._mqttClient.connected; } }, { key: 'mqttClient', get: function get() { return this._mqttClient; } }]); return Device; }(EventEmitter); module.exports = Device; /***/ }), /***/ 3109: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var util = __nccwpck_require__(9023); // const Device = require('./device'); var Device = __nccwpck_require__(4601); var _require = __nccwpck_require__(8074), createDebug = _require.createDebug, signUtil = _require.signUtil; var debug = createDebug('gateway'); var Gateway = function (_Device) { _inherits(Gateway, _Device); function Gateway() { var _ref; _classCallCheck(this, Gateway); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } // 调试模式标识 var _this = _possibleConstructorReturn(this, (_ref = Gateway.__proto__ || Object.getPrototypeOf(Gateway)).call.apply(_ref, [this].concat(args))); debug('debugger mode'); return _this; } // 入参,设备三元组组成的数组 _createClass(Gateway, [{ key: 'addTopo', value: function addTopo(devices, cb) { var signed = devices.map(function (device) { return signUtil(device); }); this._publishAlinkMessage({ method: this.model.ADD_TOPO_METHOD, pubTopic: this.model.ADD_TOPO_TOPIC, params: signed }, cb); } }, { key: 'getTopo', value: function getTopo(cb) { this._publishAlinkMessage({ method: this.model.GET_TOPO_METHOD, pubTopic: this.model.GET_TOPO_TOPIC, params: {} }, cb); } /* {"id" : "123", "version":"1.0", "params" : [{ "deviceName" : "deviceName1234", "productKey" : "1234556554" }], "method":"thing.topo.delete" } */ }, { key: 'removeTopo', value: function removeTopo(devices, cb) { this._publishAlinkMessage({ method: this.model.DELETE_TOPO_METHOD, pubTopic: this.model.DELETE_TOPO_TOPIC, params: devices }, cb); } }, { key: 'login', value: function login(device, cb) { this._publishAlinkMessage({ params: signUtil(device), pubTopic: this.model.LOGIN_TOPIC }, cb); return this._careteSubDevice(device); // const sub = this.careteSubDevice(device); // return sub; } }, { key: 'logout', value: function logout(params, cb) { this._publishAlinkMessage({ params: params, pubTopic: this.model.LOGOUT_TOPIC }, cb); } /* * 网关动态注册子设备 "params": [ { "deviceName": "deviceName1234", "productKey": "1234556554" } ] */ }, { key: 'regiestSubDevice', value: function regiestSubDevice(data, cb) { var params = void 0; if (data instanceof Array) { params = data; } else if (data instanceof Object) { params = [data]; } this._publishAlinkMessage({ method: this.model.SUBDEVICE_REGISTER_METHOD, params: params, pubTopic: this.model.SUBDEVICE_REGISTER_TOPIC }, cb); } // 内部方法,创建一个子设备 }, { key: '_careteSubDevice', value: function _careteSubDevice(device) { var subDevice = new Device(device); subDevice._type = "subdevice"; subDevice._parent = this; //子设备标识 subDevice._isSubdevice = true; var subArrayKey = device.productKey + '&' + device.deviceName; // 初始化subdevices数组 if (this._subDevices == undefined) { this._subDevices = {}; } //保存子设备 if (this._getSubDevice(device) == undefined) { this._subDevices.subArrayKey = subDevice; } return subDevice; } // 找到子设备 }, { key: '_getSubDevice', value: function _getSubDevice(device) { var subArrayKey = device.productKey + '&' + device.deviceName; if (this._subDevices == undefined) return; return this._subDevices.subArrayKey; } }]); return Gateway; }(Device); module.exports = Gateway; /***/ }), /***/ 9871: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var mqtt = __nccwpck_require__(4879); var _require = __nccwpck_require__(8074), register = _require.register; var aliyunIot = { device: function device(config) { var Device = __nccwpck_require__(4601);; return new Device(config); }, gateway: function gateway(config) { var Gateway = __nccwpck_require__(3109); return new Gateway(config); }, register: register }; if (typeof window !== 'undefined' && typeof location !== 'undefined') { window.aliyunIot = aliyunIot; } module.exports = aliyunIot; /***/ }), /***/ 6458: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _const = __nccwpck_require__(3716); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _require = __nccwpck_require__(8074), hmacSign = _require.hmacSign; var util = __nccwpck_require__(9023); var isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined' || typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope; var DEFAULT_REGION = 'cn-shanghai'; var BROKER_URL = '%s%s.iot-as-mqtt.%s.aliyuncs.com:%s/'; var tlsPrefix = ['tls://', 'mqtts://', 'wss://']; var Model = function () { function Model(config) { _classCallCheck(this, Model); //初始化参数 this.init(config); //参数校验合法 this.configchecking(); } // 获取通配订阅topic _createClass(Model, [{ key: 'getWildcardTopic', value: function getWildcardTopic() { return util.format("/sys/%s/%s/thing", this.productKey, this.deviceName); } // 获取三元组 }, { key: 'triple', value: function triple() { var productKey = this.productKey, deviceName = this.deviceName, deviceSecret = this.deviceSecret; return { productKey: productKey, deviceName: deviceName, deviceSecret: deviceSecret }; } }, { key: 'getPostEventMethod', value: function getPostEventMethod(eventName) { return util.format(_const.ALIYUN_BROKER_METHODS_TEMPLATE.POST_EVENT, eventName); } }, { key: 'getPostEvenTopic', value: function getPostEvenTopic(eventName) { return util.format(_const.ALIYUN_BROKER_TOPICS.EVENT_POST_TOPIC, this.productKey, this.deviceName, eventName); } }, { key: 'getPostEvenReplyTopic', value: function getPostEvenReplyTopic(eventName) { return util.format(_const.ALIYUN_BROKER_TOPICS.EVENT_POST_REPLY_TOPIC, this.productKey, this.deviceName, eventName); } }, { key: 'getServiceTopic', value: function getServiceTopic(serviceName) { var serviceNameReplace = serviceName; if (serviceName.indexOf('/') != -1) { serviceNameReplace = serviceName.replace('.', '/'); } return util.format(_const.ALIYUN_BROKER_TOPICS.SERVICE_TOPIC, this.productKey, this.deviceName, serviceNameReplace); } // getServiceRespTopic(serviceName) { // let serviceNameReplace = serviceName; // if (serviceName.indexOf('/') != -1) { // serviceNameReplace = serviceName.replace('.', '/') // } // return util.format(BROKER_TOPICS.SERVICE_RESP_TOPIC, this.productKey, this.deviceName, serviceNameReplace) // } //生成alink协议内容 }, { key: 'genAlinkContent', value: function genAlinkContent(method, params) { var id = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ""; var version = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '1.0'; var msg = { id: id, version: version, params: params, method: method }; return msg; } /** * 连接参数生成规则 * broker:${YourProductKey}.iot-as-mqtt.${Region}.aliyuncs.com:1883 * Region:https://help.aliyun.com/document_detail/40654.html?spm=a2c4g.11186623.2.14.6cba65fekp352N * ClientId: 表示客户端ID,建议使用设备的MAC地址或SN码,64字符内 ,clientId+"|securemode=3,signmethod=hmacsha1,timestamp=132323232|" * Username: deviceName+"&"+productKey * Password: sign_hmac(deviceSecret,content) * securemode:表示目前安全模式,可选值有2 (TLS直连模式)和3(TCP直连模式) * signmethod:签名算法,支持hmacmd5,hmacsha1,hmacsha256和 sha256,默认为hmacmd5。 * timestamp: 可选 */ }, { key: 'genConnectPrarms', value: function genConnectPrarms() { return { clientId: this.clientId + '|securemode=' + this.securemode + ',\n signmethod=hmac' + this.signAlgorithm + ',\n timestamp=' + this.timestamp + '|', username: this.deviceName + '&' + this.productKey, password: hmacSign(this.signAlgorithm, this.deviceSecret, 'clientId' + this.clientId + 'deviceName' + this.deviceName + 'productKey' + this.productKey + 'timestamp' + this.timestamp), keepalive: this.keepalive, clean: this.clean }; } }, { key: 'init', value: function init(config) { var _this = this; // 初始化连接参数 if (config.brokerUrl && tlsPrefix.some(function (prefix) { return config.brokerUrl.startsWith(prefix); }) || config.tls) { this.securemode = 2; this.tls = true; } else { this.securemode = 3; } if (isBrowser) { if (this.tls) { this.brokerProtocol = 'wss://'; } else { this.brokerProtocol = 'ws://'; } this.brokerPort = 443; } else { if (this.tls) { this.brokerProtocol = 'mqtts://'; } else { this.brokerProtocol = 'mqtt://'; } this.brokerPort = 1883; } if (config.brokerUrl && tlsPrefix.some(function (prefix) { return config.brokerUrl.startsWith(prefix); }) || config.tls) { this.securemode = 2; this.tls = true; } else { this.securemode = 3; } if (isBrowser) { if (this.tls) { this.brokerProtocol = 'wss://'; } else { this.brokerProtocol = 'ws://'; } this.brokerPort = 443; } else { if (this.tls) { this.brokerProtocol = 'mqtts://'; } else { this.brokerProtocol = 'mqtt://'; } this.brokerPort = 1883; } //三元组忽略大小写 Object.keys(config).forEach(function (originKey) { var key = originKey.toLowerCase(); switch (key) { case "productkey": _this.productKey = config[originKey]; break; case "devicename": _this.deviceName = config[originKey]; break; case "devicesecret": _this.deviceSecret = config[originKey]; break; } }); this.region = config.region || config.regionId; this.keepalive = config.keepalive || 60; //keepalive,默认60 this.clean = config.clean || false; //cleanSession配置选项 this.signAlgorithm = config.signAlgorithm || 'sha1'; this.config = config || {}; if (config.brokerUrl) { this.brokerUrl = config.brokerUrl; } else { this.brokerUrl = util.format(BROKER_URL, this.brokerProtocol, this.productKey, this.region || DEFAULT_REGION, this.brokerPort); } this.timestamp = Date.now(); this.clientId = config.clientId ? config.clientId + '_aliyun-iot-device-sdk-js' : this.productKey + '&' + this.deviceName + '_aliyun-iot-device-sdk-js'; /* 初始化topic */ //methods this.POST_PROPERY_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.POST_PROPERY; // this.POST_EVENT = util.format(METHODS_TEMPLATE.POST_EVENT, eventName); this.POST_TAGS_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.POST_TAGS; this.DELETE_TAGS_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.DELETE_TAGS; this.GET_CONFIG_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.GET_CONFIG; this.ADD_TOPO_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.ADD_TOPO; this.DELETE_TOPO_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.DELETE_TOPO; this.GET_TOPO_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.GET_TOPO; this.SUBDEVICE_REGISTER_METHOD = _const.ALIYUN_BROKER_METHODS_TEMPLATE.SUBDEVICE_REGISTER; //topic var _formatWithPKDN = function _formatWithPKDN(template) { return util.format(template, _this.productKey, _this.deviceName); }; this.POST_PROPS_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.PROPERTY_POST_TOPIC); this.POST_PROPS_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.PROPERTY_POST_REPLY_TOPIC); // this.POST_EVENT_TOPIC = _formatWithPKDN(BROKER_TOPICS.EVENT_POST_TOPIC) // this.POST_EVENT_REPLY_TOPIC = _formatWithPKDN(BROKER_TOPICS.EVENT_POST_REPLY_TOPIC) this.SERVICE_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.SERVICE_TOPIC); this.TAG_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.TAG_TOPIC); this.TAG_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.TAG_REPLY_TOPIC); this.TAG_DELETE_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.TAG_DELETE_TOPIC); this.TAG_DELETE_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.TAG_DELETE_REPLY_TOPIC); this.CONFIG_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.CONFIG_TOPIC); this.CONFIG_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.CONFIG_REPLY_TOPIC); this.CONFIG_SUBSCRIBE_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.CONFIG_SUBSCRIBE_TOPIC); this.CONFIG_SUBSCRIBE_RESP_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.CONFIG_SUBSCRIBE_RESP_TOPIC); this.SHADOW_SUBSCRIBE_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.SHADOW_SUBSCRIBE_TOPIC); this.SHADOW_GET_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.SHADOW_GET_TOPIC); this.SHADOW_POST_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.SHADOW_POST_TOPIC); // gateway this.ADD_TOPO_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.ADD_TOPO_TOPIC); this.ADD_TOPO_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.ADD_TOPO_REPLY_TOPIC); this.DELETE_TOPO_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.DELETE_TOPO_TOPIC); this.DELETE_TOPO_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.DELETE_TOPO_REPLY_TOPIC); this.GET_TOPO_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.GET_TOPO_TOPIC); this.GET_TOPO_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.GET_TOPO_REPLY_TOPIC); this.LOGIN_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.LOGIN_TOPIC); this.LOGIN_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.LOGIN_REPLY_TOPIC); this.LOGOUT_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.LOGOUT_TOPIC); this.LOGOUT_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.LOGOUT_REPLY_TOPIC); this.SUBDEVICE_REGISTER_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.SUBDEVICE_REGISTER_TOPIC); this.SUBDEVICE_REGISTER_REPLY_TOPIC = _formatWithPKDN(_const.ALIYUN_BROKER_TOPICS.SUBDEVICE_REGISTER_REPLY_TOPIC); } }, { key: 'configchecking', value: function configchecking() { if (typeof this.productKey === 'undefined') { throw new Error('productKey should not be empty'); } if (typeof this.deviceName === 'undefined') { throw new Error('deviceName should not be empty'); } if (typeof this.deviceSecret === 'undefined') { throw new Error('deviceSecret should not be empty'); } } }]); return Model; }(); exports["default"] = Model; module.exports = Model; /***/ }), /***/ 8074: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var crypto = __nccwpck_require__(6982); var os = __nccwpck_require__(857); var axios = __nccwpck_require__(4922); var qs = __nccwpck_require__(240); function hmacSign(type, secret, content) { return crypto.createHmac(type, secret).update(content).digest('hex'); } // function mqttMatch(filter, topic) { // const filterArray = filter.split('/'); // const length = filterArray.length; // const topicArray = topic.split('/'); // for (var i = 0; i < length; ++i) { // var left = filterArray[i]; // var right = topicArray[i]; // if (left === '#') return true; // if (left !== '+' && left !== right) return false; // } // return length === topicArray.length; // } function createGuid() { var id = 1; return function () { return String(id++); }; } function isJsonString(str) { try { if (_typeof(JSON.parse(str)) == "object") { return true; } } catch (e) {} return false; } function signUtil(deviceConfig) { var signMethod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'sha1'; var timestamp = Date.now(); var device = { productKey: deviceConfig.productKey, deviceName: deviceConfig.deviceName, clientId: deviceConfig.productKey + '&' + deviceConfig.deviceName, timestamp: timestamp }; device.signMethod = 'hmac' + signMethod; var signcontent = 'clientId' + device.clientId + 'deviceName' + device.deviceName + 'productKey' + device.productKey + 'timestamp' + timestamp; device.sign = hmacSign(signMethod, deviceConfig.deviceSecret, signcontent); return device; } function deviceRegisterSign(productKey, productSecret, deviceName, random) { var signMethod = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'sha1'; // signMethod = `hmac${signMethod}`; var signcontent = 'deviceName' + deviceName + 'productKey' + productKey + 'random' + random; // console.log("deviceRegisterSign",signMethod,signcontent) var sign = hmacSign("sha1", productSecret, signcontent); return sign; } function createDebug(mod) { return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var debugMod = process.env.DEBUG; if (debugMod && (debugMod === '*' || mod.indexOf(debugMod) > -1)) { var _console; var _args = [mod + ':'].concat(args); (_console = console).log.apply(_console, _toConsumableArray(_args)); } }; } function getIP() { var ifaces = os.networkInterfaces(); var ip = ""; for (var dev in ifaces) { ifaces[dev].forEach(function (details) { if (details.family == 'IPv4' && dev === 'en0') { ip = details.address; } }); } return ip; } /* * 设备动态注册 * 子设备注册+直连设备使用一型一密动态注册 */ function register(_ref, cb) { var productKey = _ref.productKey, productSecret = _ref.productSecret, deviceName = _ref.deviceName, random = _ref.random, signMethod = _ref.signMethod, registerURL = _ref.registerURL; var rd = random || Math.random().toString(36).substr(2); var sm = signMethod || "hmacsha1"; var url = registerURL || "https://iot-auth.cn-shanghai.aliyuncs.com/auth/register/device"; var sign = deviceRegisterSign(productKey, productSecret, deviceName, rd, sm); var data = qs.stringify({ productKey: productKey, deviceName: deviceName, random: rd, sign: sign, signMethod: sm }); axios.post(url, data).then(function (res) { var data = res.data; if (data.code != 200) { throw data; } cb(data); }).catch(function (error) { cb(error); }); } exports.getIP = getIP; exports.hmacSign = hmacSign; // exports.mqttMatch = mqttMatch; exports.createGuid = createGuid; exports.signUtil = signUtil; exports.createDebug = createDebug; exports.register = register; exports.isJsonString = isJsonString; /***/ }), /***/ 2723: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var DuplexStream = __nccwpck_require__(8522) , util = __nccwpck_require__(9023) , Buffer = (__nccwpck_require__(3058).Buffer) function BufferList (callback) { if (!(this instanceof BufferList)) return new BufferList(callback) this._bufs = [] this.length = 0 if (typeof callback == 'function') { this._callback = callback var piper = function piper (err) { if (this._callback) { this._callback(err) this._callback = null } }.bind(this) this.on('pipe', function onPipe (src) { src.on('error', piper) }) this.on('unpipe', function onUnpipe (src) { src.removeListener('error', piper) }) } else { this.append(callback) } DuplexStream.call(this) } util.inherits(BufferList, DuplexStream) BufferList.prototype._offset = function _offset (offset) { var tot = 0, i = 0, _t if (offset === 0) return [ 0, 0 ] for (; i < this._bufs.length; i++) { _t = tot + this._bufs[i].length if (offset < _t || i == this._bufs.length - 1) return [ i, offset - tot ] tot = _t } } BufferList.prototype.append = function append (buf) { var i = 0 if (Buffer.isBuffer(buf)) { this._appendBuffer(buf); } else if (Array.isArray(buf)) { for (; i < buf.length; i++) this.append(buf[i]) } else if (buf instanceof BufferList) { // unwrap argument into individual BufferLists for (; i < buf._bufs.length; i++) this.append(buf._bufs[i]) } else if (buf != null) { // coerce number arguments to strings, since Buffer(number) does // uninitialized memory allocation if (typeof buf == 'number') buf = buf.toString() this._appendBuffer(Buffer.from(buf)); } return this } BufferList.prototype._appendBuffer = function appendBuffer (buf) { this._bufs.push(buf) this.length += buf.length } BufferList.prototype._write = function _write (buf, encoding, callback) { this._appendBuffer(buf) if (typeof callback == 'function') callback() } BufferList.prototype._read = function _read (size) { if (!this.length) return this.push(null) size = Math.min(size, this.length) this.push(this.slice(0, size)) this.consume(size) } BufferList.prototype.end = function end (chunk) { DuplexStream.prototype.end.call(this, chunk) if (this._callback) { this._callback(null, this.slice()) this._callback = null } } BufferList.prototype.get = function get (index) { return this.slice(index, index + 1)[0] } BufferList.prototype.slice = function slice (start, end) { if (typeof start == 'number' && start < 0) start += this.length if (typeof end == 'number' && end < 0) end += this.length return this.copy(null, 0, start, end) } BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { if (typeof srcStart != 'number' || srcStart < 0) srcStart = 0 if (typeof srcEnd != 'number' || srcEnd > this.length) srcEnd = this.length if (srcStart >= this.length) return dst || Buffer.alloc(0) if (srcEnd <= 0) return dst || Buffer.alloc(0) var copy = !!dst , off = this._offset(srcStart) , len = srcEnd - srcStart , bytes = len , bufoff = (copy && dstStart) || 0 , start = off[1] , l , i // copy/slice everything if (srcStart === 0 && srcEnd == this.length) { if (!copy) { // slice, but full concat if multiple buffers return this._bufs.length === 1 ? this._bufs[0] : Buffer.concat(this._bufs, this.length) } // copy, need to copy individual buffers for (i = 0; i < this._bufs.length; i++) { this._bufs[i].copy(dst, bufoff) bufoff += this._bufs[i].length } return dst } // easy, cheap case where it's a subset of one of the buffers if (bytes <= this._bufs[off[0]].length - start) { return copy ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) : this._bufs[off[0]].slice(start, start + bytes) } if (!copy) // a slice, we need something to copy in to dst = Buffer.allocUnsafe(len) for (i = off[0]; i < this._bufs.length; i++) { l = this._bufs[i].length - start if (bytes > l) { this._bufs[i].copy(dst, bufoff, start) bufoff += l } else { this._bufs[i].copy(dst, bufoff, start, start + bytes) bufoff += l break } bytes -= l if (start) start = 0 } // safeguard so that we don't return uninitialized memory if (dst.length > bufoff) return dst.slice(0, bufoff) return dst } BufferList.prototype.shallowSlice = function shallowSlice (start, end) { start = start || 0 end = end || this.length if (start < 0) start += this.length if (end < 0) end += this.length var startOffset = this._offset(start) , endOffset = this._offset(end) , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) if (endOffset[1] == 0) buffers.pop() else buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1]) if (startOffset[1] != 0) buffers[0] = buffers[0].slice(startOffset[1]) return new BufferList(buffers) } BufferList.prototype.toString = function toString (encoding, start, end) { return this.slice(start, end).toString(encoding) } BufferList.prototype.consume = function consume (bytes) { // first, normalize the argument, in accordance with how Buffer does it bytes = Math.trunc(bytes) // do nothing if not a positive number if (Number.isNaN(bytes) || bytes <= 0) return this while (this._bufs.length) { if (bytes >= this._bufs[0].length) { bytes -= this._bufs[0].length this.length -= this._bufs[0].length this._bufs.shift() } else { this._bufs[0] = this._bufs[0].slice(bytes) this.length -= bytes break } } return this } BufferList.prototype.duplicate = function duplicate () { var i = 0 , copy = new BufferList() for (; i < this._bufs.length; i++) copy.append(this._bufs[i]) return copy } BufferList.prototype.destroy = function destroy () { this._bufs.length = 0 this.length = 0 this.push(null) } ;(function () { var methods = { 'readDoubleBE' : 8 , 'readDoubleLE' : 8 , 'readFloatBE' : 4 , 'readFloatLE' : 4 , 'readInt32BE' : 4 , 'readInt32LE' : 4 , 'readUInt32BE' : 4 , 'readUInt32LE' : 4 , 'readInt16BE' : 2 , 'readInt16LE' : 2 , 'readUInt16BE' : 2 , 'readUInt16LE' : 2 , 'readInt8' : 1 , 'readUInt8' : 1 } for (var m in methods) { (function (m) { BufferList.prototype[m] = function (offset) { return this.slice(offset, offset + methods[m])[m](0) } }(m)) } }()) module.exports = BufferList /***/ }), /***/ 2273: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* The MIT License (MIT) Copyright (c) 2014 Matteo Collina Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var leven = __nccwpck_require__(1444) function commist () { var commands = [] function lookup (array) { if (typeof array === 'string') { array = array.split(' ') } return commands.map(function (cmd) { return cmd.match(array) }).filter(function (match) { return match.partsNotMatched === 0 }).sort(function (a, b) { if (a.inputNotMatched > b.inputNotMatched) { return 1 } if (a.inputNotMatched === b.inputNotMatched && a.totalDistance > b.totalDistance) { return 1 } return -1 }).map(function (match) { return match.cmd }) } function parse (args) { var matching = lookup(args) if (matching.length > 0) { matching[0].call(args) // return null if there is nothing left to do return null } return args } function register (inputCommand, func) { var commandOptions = { command: inputCommand, strict: false, func: func } if (typeof inputCommand === 'object') { commandOptions = Object.assign(commandOptions, inputCommand) } var matching = lookup(commandOptions.command) matching.forEach(function (match) { if (match.string === commandOptions.command) { throw new Error('command already registered: ' + commandOptions.command) } }) commands.push(new Command(commandOptions)) return this } return { register: register, parse: parse, lookup: lookup } } function Command (options) { this.string = options.command this.strict = options.strict this.parts = this.string.split(' ') this.length = this.parts.length this.func = options.func this.parts.forEach(function (part) { if (part.length < 3) { throw new Error('command words must be at least 3 chars: ' + options.command) } }) } Command.prototype.call = function call (argv) { this.func(argv.slice(this.length)) } Command.prototype.match = function match (string) { return new CommandMatch(this, string) } function CommandMatch (cmd, array) { this.cmd = cmd this.distances = cmd.parts.map(function (elem, i) { if (array[i] !== undefined) { if (cmd.strict) { return elem === array[i] ? 0 : undefined } else { return leven(elem, array[i]) } } else { return undefined } }).filter(function (distance, i) { return distance !== undefined && distance < cmd.parts[i].length - 2 }) this.partsNotMatched = cmd.length - this.distances.length this.inputNotMatched = array.length - this.distances.length this.totalDistance = this.distances.reduce(function (acc, i) { return acc + i }, 0) } module.exports = commist /***/ }), /***/ 6298: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var Writable = (__nccwpck_require__(6131).Writable) var inherits = __nccwpck_require__(9598) var bufferFrom = __nccwpck_require__(4718) if (typeof Uint8Array === 'undefined') { var U8 = (__nccwpck_require__(2317)/* .Uint8Array */ .SE) } else { var U8 = Uint8Array } function ConcatStream(opts, cb) { if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb) if (typeof opts === 'function') { cb = opts opts = {} } if (!opts) opts = {} var encoding = opts.encoding var shouldInferEncoding = false if (!encoding) { shouldInferEncoding = true } else { encoding = String(encoding).toLowerCase() if (encoding === 'u8' || encoding === 'uint8') { encoding = 'uint8array' } } Writable.call(this, { objectMode: true }) this.encoding = encoding this.shouldInferEncoding = shouldInferEncoding if (cb) this.on('finish', function () { cb(this.getBody()) }) this.body = [] } module.exports = ConcatStream inherits(ConcatStream, Writable) ConcatStream.prototype._write = function(chunk, enc, next) { this.body.push(chunk) next() } ConcatStream.prototype.inferEncoding = function (buff) { var firstBuffer = buff === undefined ? this.body[0] : buff; if (Buffer.isBuffer(firstBuffer)) return 'buffer' if (typeof Uint8Array !== 'undefined' && firstBuffer instanceof Uint8Array) return 'uint8array' if (Array.isArray(firstBuffer)) return 'array' if (typeof firstBuffer === 'string') return 'string' if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object' return 'buffer' } ConcatStream.prototype.getBody = function () { if (!this.encoding && this.body.length === 0) return [] if (this.shouldInferEncoding) this.encoding = this.inferEncoding() if (this.encoding === 'array') return arrayConcat(this.body) if (this.encoding === 'string') return stringConcat(this.body) if (this.encoding === 'buffer') return bufferConcat(this.body) if (this.encoding === 'uint8array') return u8Concat(this.body) return this.body } var isArray = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]' } function isArrayish (arr) { return /Array\]$/.test(Object.prototype.toString.call(arr)) } function isBufferish (p) { return typeof p === 'string' || isArrayish(p) || (p && typeof p.subarray === 'function') } function stringConcat (parts) { var strings = [] var needsToString = false for (var i = 0; i < parts.length; i++) { var p = parts[i] if (typeof p === 'string') { strings.push(p) } else if (Buffer.isBuffer(p)) { strings.push(p) } else if (isBufferish(p)) { strings.push(bufferFrom(p)) } else { strings.push(bufferFrom(String(p))) } } if (Buffer.isBuffer(parts[0])) { strings = Buffer.concat(strings) strings = strings.toString('utf8') } else { strings = strings.join('') } return strings } function bufferConcat (parts) { var bufs = [] for (var i = 0; i < parts.length; i++) { var p = parts[i] if (Buffer.isBuffer(p)) { bufs.push(p) } else if (isBufferish(p)) { bufs.push(bufferFrom(p)) } else { bufs.push(bufferFrom(String(p))) } } return Buffer.concat(bufs) } function arrayConcat (parts) { var res = [] for (var i = 0; i < parts.length; i++) { res.push.apply(res, parts[i]) } return res } function u8Concat (parts) { var len = 0 for (var i = 0; i < parts.length; i++) { if (typeof parts[i] === 'string') { parts[i] = bufferFrom(parts[i]) } len += parts[i].length } var u8 = new U8(len) for (var i = 0, offset = 0; i < parts.length; i++) { var part = parts[i] for (var j = 0; j < part.length; j++) { u8[offset++] = part[j] } } return u8 } /***/ }), /***/ 6197: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var fs = __nccwpck_require__(9896) var path = __nccwpck_require__(6928) var through = __nccwpck_require__(4612) var globStream = __nccwpck_require__(8625) var concat = __nccwpck_require__(8626) var xtend = __nccwpck_require__(869) var defaults = { dir: path.join(path.dirname(__nccwpck_require__.c[__nccwpck_require__.s].filename), 'doc'), ext: '.txt', help: 'help' } function helpMe (opts) { opts = xtend(defaults, opts) if (!opts.dir) { throw new Error('missing directory') } return { createStream: createStream, toStdout: toStdout } function createStream (args) { if (typeof args === 'string') { args = args.split(' ') } else if (!args || args.length === 0) { args = [opts.help] } var out = through() var gs = globStream([opts.dir + '/**/*' + opts.ext]) var re = new RegExp(args.map(function (arg) { return arg + '[a-zA-Z0-9]*' }).join('[ /]+')) gs.pipe(concat({ objectMode: true }, function (err, files) { if (err) return out.emit('error', err) files = files.map(function (file) { file.relative = file.path.replace(file.base, '').replace(/^\//, '') return file }).filter(function (file) { return file.relative.match(re) }) if (files.length === 0) { return out.emit('error', new Error('no such help file')) } else if (files.length > 1) { out.write('There are ' + files.length + ' help pages ') out.write('that matches the given request, please disambiguate:\n') files.forEach(function (file) { out.write(' * ') out.write(file.relative.replace(opts.ext, '')) out.write('\n') }) out.end() return } fs.createReadStream(files[0].path) .on('error', function (err) { out.emit('error', err) }) .pipe(out) })) return out } function toStdout (args) { createStream(args) .on('error', function () { console.log('no such help file\n') toStdout() }) .pipe(process.stdout) } } module.exports = helpMe /***/ }), /***/ 2933: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Buffer = (__nccwpck_require__(3058).Buffer) /* Protocol - protocol constants */ var protocol = module.exports /* Command code => mnemonic */ protocol.types = { 0: 'reserved', 1: 'connect', 2: 'connack', 3: 'publish', 4: 'puback', 5: 'pubrec', 6: 'pubrel', 7: 'pubcomp', 8: 'subscribe', 9: 'suback', 10: 'unsubscribe', 11: 'unsuback', 12: 'pingreq', 13: 'pingresp', 14: 'disconnect', 15: 'reserved' } /* Mnemonic => Command code */ protocol.codes = {} for (var k in protocol.types) { var v = protocol.types[k] protocol.codes[v] = k } /* Header */ protocol.CMD_SHIFT = 4 protocol.CMD_MASK = 0xF0 protocol.DUP_MASK = 0x08 protocol.QOS_MASK = 0x03 protocol.QOS_SHIFT = 1 protocol.RETAIN_MASK = 0x01 /* Length */ protocol.LENGTH_MASK = 0x7F protocol.LENGTH_FIN_MASK = 0x80 /* Connack */ protocol.SESSIONPRESENT_MASK = 0x01 protocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK]) protocol.CONNACK_HEADER = Buffer.from([protocol.codes['connack'] << protocol.CMD_SHIFT]) /* Connect */ protocol.USERNAME_MASK = 0x80 protocol.PASSWORD_MASK = 0x40 protocol.WILL_RETAIN_MASK = 0x20 protocol.WILL_QOS_MASK = 0x18 protocol.WILL_QOS_SHIFT = 3 protocol.WILL_FLAG_MASK = 0x04 protocol.CLEAN_SESSION_MASK = 0x02 protocol.CONNECT_HEADER = Buffer.from([protocol.codes['connect'] << protocol.CMD_SHIFT]) function genHeader (type) { return [0, 1, 2].map(function (qos) { return [0, 1].map(function (dup) { return [0, 1].map(function (retain) { var buf = new Buffer(1) buf.writeUInt8( protocol.codes[type] << protocol.CMD_SHIFT | (dup ? protocol.DUP_MASK : 0) | qos << protocol.QOS_SHIFT | retain, 0, true) return buf }) }) }) } /* Publish */ protocol.PUBLISH_HEADER = genHeader('publish') /* Subscribe */ protocol.SUBSCRIBE_HEADER = genHeader('subscribe') /* Unsubscribe */ protocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe') /* Confirmations */ protocol.ACKS = { unsuback: genHeader('unsuback'), puback: genHeader('puback'), pubcomp: genHeader('pubcomp'), pubrel: genHeader('pubrel'), pubrec: genHeader('pubrec') } protocol.SUBACK_HEADER = Buffer.from([protocol.codes['suback'] << protocol.CMD_SHIFT]) /* Protocol versions */ protocol.VERSION3 = Buffer.from([3]) protocol.VERSION4 = Buffer.from([4]) /* QoS */ protocol.QOS = [0, 1, 2].map(function (qos) { return Buffer.from([qos]) }) /* Empty packets */ protocol.EMPTY = { pingreq: Buffer.from([protocol.codes['pingreq'] << 4, 0]), pingresp: Buffer.from([protocol.codes['pingresp'] << 4, 0]), disconnect: Buffer.from([protocol.codes['disconnect'] << 4, 0]) } /***/ }), /***/ 6549: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Buffer = (__nccwpck_require__(3058).Buffer) var writeToStream = __nccwpck_require__(318) var EE = (__nccwpck_require__(4434).EventEmitter) var inherits = __nccwpck_require__(9598) function generate (packet) { var stream = new Accumulator() writeToStream(packet, stream) return stream.concat() } function Accumulator () { this._array = new Array(20) this._i = 0 } inherits(Accumulator, EE) Accumulator.prototype.write = function (chunk) { this._array[this._i++] = chunk return true } Accumulator.prototype.concat = function () { var length = 0 var lengths = new Array(this._array.length) var list = this._array var pos = 0 var i var result for (i = 0; i < list.length && list[i] !== undefined; i++) { if (typeof list[i] !== 'string') lengths[i] = list[i].length else lengths[i] = Buffer.byteLength(list[i]) length += lengths[i] } result = Buffer.allocUnsafe(length) for (i = 0; i < list.length && list[i] !== undefined; i++) { if (typeof list[i] !== 'string') { list[i].copy(result, pos) pos += lengths[i] } else { result.write(list[i], pos) pos += lengths[i] } } return result } module.exports = generate /***/ }), /***/ 8971: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; exports.parser = __nccwpck_require__(9157) exports.generate = __nccwpck_require__(6549) exports.writeToStream = __nccwpck_require__(318) /***/ }), /***/ 810: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Buffer = (__nccwpck_require__(3058).Buffer) var max = 65536 var cache = {} function generateBuffer (i) { var buffer = Buffer.allocUnsafe(2) buffer.writeUInt8(i >> 8, 0) buffer.writeUInt8(i & 0x00FF, 0 + 1) return buffer } function generateCache () { for (var i = 0; i < max; i++) { cache[i] = generateBuffer(i) } } module.exports = { cache: cache, generateCache: generateCache, generateNumber: generateBuffer } /***/ }), /***/ 7914: /***/ ((module) => { function Packet () { this.cmd = null this.retain = false this.qos = 0 this.dup = false this.length = -1 this.topic = null this.payload = null } module.exports = Packet /***/ }), /***/ 9157: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var bl = __nccwpck_require__(2723) var inherits = __nccwpck_require__(9598) var EE = (__nccwpck_require__(4434).EventEmitter) var Packet = __nccwpck_require__(7914) var constants = __nccwpck_require__(2933) function Parser () { if (!(this instanceof Parser)) return new Parser() this._states = [ '_parseHeader', '_parseLength', '_parsePayload', '_newPacket' ] this._resetState() } inherits(Parser, EE) Parser.prototype._resetState = function () { this.packet = new Packet() this.error = null this._list = bl() this._stateCounter = 0 } Parser.prototype.parse = function (buf) { if (this.error) this._resetState() this._list.append(buf) while ((this.packet.length !== -1 || this._list.length > 0) && this[this._states[this._stateCounter]]() && !this.error) { this._stateCounter++ if (this._stateCounter >= this._states.length) this._stateCounter = 0 } return this._list.length } Parser.prototype._parseHeader = function () { // There is at least one byte in the buffer var zero = this._list.readUInt8(0) this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT] this.packet.retain = (zero & constants.RETAIN_MASK) !== 0 this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK this.packet.dup = (zero & constants.DUP_MASK) !== 0 this._list.consume(1) return true } Parser.prototype._parseLength = function () { // There is at least one byte in the list var bytes = 0 var mul = 1 var length = 0 var result = true var current while (bytes < 5) { current = this._list.readUInt8(bytes++) length += mul * (current & constants.LENGTH_MASK) mul *= 0x80 if ((current & constants.LENGTH_FIN_MASK) === 0) break if (this._list.length <= bytes) { result = false break } } if (result) { this.packet.length = length this._list.consume(bytes) } return result } Parser.prototype._parsePayload = function () { var result = false // Do we have a payload? Do we have enough data to complete the payload? // PINGs have no payload if (this.packet.length === 0 || this._list.length >= this.packet.length) { this._pos = 0 switch (this.packet.cmd) { case 'connect': this._parseConnect() break case 'connack': this._parseConnack() break case 'publish': this._parsePublish() break case 'puback': case 'pubrec': case 'pubrel': case 'pubcomp': this._parseMessageId() break case 'subscribe': this._parseSubscribe() break case 'suback': this._parseSuback() break case 'unsubscribe': this._parseUnsubscribe() break case 'unsuback': this._parseUnsuback() break case 'pingreq': case 'pingresp': case 'disconnect': // These are empty, nothing to do break default: this._emitError(new Error('Not supported')) } result = true } return result } Parser.prototype._parseConnect = function () { var protocolId // Protocol ID var clientId // Client ID var topic // Will topic var payload // Will payload var password // Password var username // Username var flags = {} var packet = this.packet // Parse protocolId protocolId = this._parseString() if (protocolId === null) return this._emitError(new Error('Cannot parse protocolId')) if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') { return this._emitError(new Error('Invalid protocolId')) } packet.protocolId = protocolId // Parse constants version number if (this._pos >= this._list.length) return this._emitError(new Error('Packet too short')) packet.protocolVersion = this._list.readUInt8(this._pos) if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4) { return this._emitError(new Error('Invalid protocol version')) } this._pos++ if (this._pos >= this._list.length) { return this._emitError(new Error('Packet too short')) } // Parse connect flags flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK) flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK) flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK) if (flags.will) { packet.will = {} packet.will.retain = (this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) !== 0 packet.will.qos = (this._list.readUInt8(this._pos) & constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT } packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0 this._pos++ // Parse keepalive packet.keepalive = this._parseNum() if (packet.keepalive === -1) return this._emitError(new Error('Packet too short')) // Parse clientId clientId = this._parseString() if (clientId === null) return this._emitError(new Error('Packet too short')) packet.clientId = clientId if (flags.will) { // Parse will topic topic = this._parseString() if (topic === null) return this._emitError(new Error('Cannot parse will topic')) packet.will.topic = topic // Parse will payload payload = this._parseBuffer() if (payload === null) return this._emitError(new Error('Cannot parse will payload')) packet.will.payload = payload } // Parse username if (flags.username) { username = this._parseString() if (username === null) return this._emitError(new Error('Cannot parse username')) packet.username = username } // Parse password if (flags.password) { password = this._parseBuffer() if (password === null) return this._emitError(new Error('Cannot parse password')) packet.password = password } return packet } Parser.prototype._parseConnack = function () { var packet = this.packet if (this._list.length < 2) return null packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants.SESSIONPRESENT_MASK) packet.returnCode = this._list.readUInt8(this._pos) if (packet.returnCode === -1) return this._emitError(new Error('Cannot parse return code')) } Parser.prototype._parsePublish = function () { var packet = this.packet packet.topic = this._parseString() if (packet.topic === null) return this._emitError(new Error('Cannot parse topic')) // Parse messageId if (packet.qos > 0) if (!this._parseMessageId()) { return } packet.payload = this._list.slice(this._pos, packet.length) } Parser.prototype._parseSubscribe = function () { var packet = this.packet var topic var qos if (packet.qos !== 1) { return this._emitError(new Error('Wrong subscribe header')) } packet.subscriptions = [] if (!this._parseMessageId()) { return } while (this._pos < packet.length) { // Parse topic topic = this._parseString() if (topic === null) return this._emitError(new Error('Cannot parse topic')) if (this._pos >= packet.length) return this._emitError(new Error('Malformed Subscribe Payload')) qos = this._list.readUInt8(this._pos++) // Push pair to subscriptions packet.subscriptions.push({ topic: topic, qos: qos }) } } Parser.prototype._parseSuback = function () { this.packet.granted = [] if (!this._parseMessageId()) { return } // Parse granted QoSes while (this._pos < this.packet.length) { this.packet.granted.push(this._list.readUInt8(this._pos++)) } } Parser.prototype._parseUnsubscribe = function () { var packet = this.packet packet.unsubscriptions = [] // Parse messageId if (!this._parseMessageId()) { return } while (this._pos < packet.length) { var topic // Parse topic topic = this._parseString() if (topic === null) return this._emitError(new Error('Cannot parse topic')) // Push topic to unsubscriptions packet.unsubscriptions.push(topic) } } Parser.prototype._parseUnsuback = function () { if (!this._parseMessageId()) return this._emitError(new Error('Cannot parse messageId')) } Parser.prototype._parseMessageId = function () { var packet = this.packet packet.messageId = this._parseNum() if (packet.messageId === null) { this._emitError(new Error('Cannot parse messageId')) return false } return true } Parser.prototype._parseString = function (maybeBuffer) { var length = this._parseNum() var result var end = length + this._pos if (length === -1 || end > this._list.length || end > this.packet.length) return null result = this._list.toString('utf8', this._pos, end) this._pos += length return result } Parser.prototype._parseBuffer = function () { var length = this._parseNum() var result var end = length + this._pos if (length === -1 || end > this._list.length || end > this.packet.length) return null result = this._list.slice(this._pos, end) this._pos += length return result } Parser.prototype._parseNum = function () { if (this._list.length - this._pos < 2) return -1 var result = this._list.readUInt16BE(this._pos) this._pos += 2 return result } Parser.prototype._newPacket = function () { if (this.packet) { this._list.consume(this.packet.length) this.emit('packet', this.packet) } this.packet = new Packet() return true } Parser.prototype._emitError = function (err) { this.error = err this.emit('error', err) } module.exports = Parser /***/ }), /***/ 318: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var protocol = __nccwpck_require__(2933) var Buffer = (__nccwpck_require__(3058).Buffer) var empty = Buffer.allocUnsafe(0) var zeroBuf = Buffer.from([0]) var numbers = __nccwpck_require__(810) var nextTick = (__nccwpck_require__(1564).nextTick) var numCache = numbers.cache var generateNumber = numbers.generateNumber var generateCache = numbers.generateCache var writeNumber = writeNumberCached var toGenerate = true function generate (packet, stream) { if (stream.cork) { stream.cork() nextTick(uncork, stream) } if (toGenerate) { toGenerate = false generateCache() } switch (packet.cmd) { case 'connect': return connect(packet, stream) case 'connack': return connack(packet, stream) case 'publish': return publish(packet, stream) case 'puback': case 'pubrec': case 'pubrel': case 'pubcomp': case 'unsuback': return confirmation(packet, stream) case 'subscribe': return subscribe(packet, stream) case 'suback': return suback(packet, stream) case 'unsubscribe': return unsubscribe(packet, stream) case 'pingreq': case 'pingresp': case 'disconnect': return emptyPacket(packet, stream) default: stream.emit('error', new Error('Unknown command')) return false } } /** * Controls numbers cache. * Set to "false" to allocate buffers on-the-flight instead of pre-generated cache */ Object.defineProperty(generate, 'cacheNumbers', { get: function () { return writeNumber === writeNumberCached }, set: function (value) { if (value) { if (!numCache || Object.keys(numCache).length === 0) toGenerate = true writeNumber = writeNumberCached } else { toGenerate = false writeNumber = writeNumberGenerated } } }) function uncork (stream) { stream.uncork() } function connect (opts, stream) { var settings = opts || {} var protocolId = settings.protocolId || 'MQTT' var protocolVersion = settings.protocolVersion || 4 var will = settings.will var clean = settings.clean var keepalive = settings.keepalive || 0 var clientId = settings.clientId || '' var username = settings.username var password = settings.password if (clean === undefined) clean = true var length = 0 // Must be a string and non-falsy if (!protocolId || (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) { stream.emit('error', new Error('Invalid protocolId')) return false } else length += protocolId.length + 2 // Must be 3 or 4 if (protocolVersion !== 3 && protocolVersion !== 4) { stream.emit('error', new Error('Invalid protocol version')) return false } else length += 1 // ClientId might be omitted in 3.1.1, but only if cleanSession is set to 1 if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) && (clientId || protocolVersion === 4) && (clientId || clean)) { length += clientId.length + 2 } else { if (protocolVersion < 4) { stream.emit('error', new Error('clientId must be supplied before 3.1.1')) return false } if ((clean * 1) === 0) { stream.emit('error', new Error('clientId must be given if cleanSession set to 0')) return false } } // Must be a two byte number if (typeof keepalive !== 'number' || keepalive < 0 || keepalive > 65535 || keepalive % 1 !== 0) { stream.emit('error', new Error('Invalid keepalive')) return false } else length += 2 // Connect flags length += 1 // If will exists... if (will) { // It must be an object if (typeof will !== 'object') { stream.emit('error', new Error('Invalid will')) return false } // It must have topic typeof string if (!will.topic || typeof will.topic !== 'string') { stream.emit('error', new Error('Invalid will topic')) return false } else { length += Buffer.byteLength(will.topic) + 2 } // Payload if (will.payload && will.payload) { if (will.payload.length >= 0) { if (typeof will.payload === 'string') { length += Buffer.byteLength(will.payload) + 2 } else { length += will.payload.length + 2 } } else { stream.emit('error', new Error('Invalid will payload')) return false } } else { length += 2 } } // Username var providedUsername = false if (username != null) { if (isStringOrBuffer(username)) { providedUsername = true length += Buffer.byteLength(username) + 2 } else { stream.emit('error', new Error('Invalid username')) return false } } // Password if (password != null) { if (!providedUsername) { stream.emit('error', new Error('Username is required to use password')) return false } if (isStringOrBuffer(password)) { length += byteLength(password) + 2 } else { stream.emit('error', new Error('Invalid password')) return false } } // Generate header stream.write(protocol.CONNECT_HEADER) // Generate length writeLength(stream, length) // Generate protocol ID writeStringOrBuffer(stream, protocolId) stream.write( protocolVersion === 4 ? protocol.VERSION4 : protocol.VERSION3 ) // Connect flags var flags = 0 flags |= (username != null) ? protocol.USERNAME_MASK : 0 flags |= (password != null) ? protocol.PASSWORD_MASK : 0 flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0 flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0 flags |= will ? protocol.WILL_FLAG_MASK : 0 flags |= clean ? protocol.CLEAN_SESSION_MASK : 0 stream.write(Buffer.from([flags])) // Keepalive writeNumber(stream, keepalive) // Client ID writeStringOrBuffer(stream, clientId) // Will if (will) { writeString(stream, will.topic) writeStringOrBuffer(stream, will.payload) } // Username and password if (username != null) { writeStringOrBuffer(stream, username) } if (password != null) { writeStringOrBuffer(stream, password) } // This is a small packet that happens only once on a stream // We assume the stream is always free to receive more data after this return true } function connack (opts, stream) { var settings = opts || {} var rc = settings.returnCode // Check return code if (typeof rc !== 'number') { stream.emit('error', new Error('Invalid return code')) return false } stream.write(protocol.CONNACK_HEADER) writeLength(stream, 2) stream.write(opts.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf) return stream.write(Buffer.from([rc])) } function publish (opts, stream) { var settings = opts || {} var qos = settings.qos || 0 var retain = settings.retain ? protocol.RETAIN_MASK : 0 var topic = settings.topic var payload = settings.payload || empty var id = settings.messageId var length = 0 // Topic must be a non-empty string or Buffer if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2 else if (Buffer.isBuffer(topic)) length += topic.length + 2 else { stream.emit('error', new Error('Invalid topic')) return false } // Get the payload length if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload) else length += payload.length // Message ID must a number if qos > 0 if (qos && typeof id !== 'number') { stream.emit('error', new Error('Invalid messageId')) return false } else if (qos) length += 2 // Header stream.write(protocol.PUBLISH_HEADER[qos][opts.dup ? 1 : 0][retain ? 1 : 0]) // Remaining length writeLength(stream, length) // Topic writeNumber(stream, byteLength(topic)) stream.write(topic) // Message ID if (qos > 0) writeNumber(stream, id) // Payload return stream.write(payload) } /* Puback, pubrec, pubrel and pubcomp */ function confirmation (opts, stream) { var settings = opts || {} var type = settings.cmd || 'puback' var id = settings.messageId var dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0 var qos = 0 if (type === 'pubrel') qos = 1 // Check message ID if (typeof id !== 'number') { stream.emit('error', new Error('Invalid messageId')) return false } // Header stream.write(protocol.ACKS[type][qos][dup][0]) // Length writeLength(stream, 2) // Message ID return writeNumber(stream, id) } function subscribe (opts, stream) { var settings = opts || {} var dup = settings.dup ? protocol.DUP_MASK : 0 var id = settings.messageId var subs = settings.subscriptions var length = 0 // Check message ID if (typeof id !== 'number') { stream.emit('error', new Error('Invalid messageId')) return false } else length += 2 // Check subscriptions if (typeof subs === 'object' && subs.length) { for (var i = 0; i < subs.length; i += 1) { var itopic = subs[i].topic var iqos = subs[i].qos if (typeof itopic !== 'string') { stream.emit('error', new Error('Invalid subscriptions - invalid topic')) return false } if (typeof iqos !== 'number') { stream.emit('error', new Error('Invalid subscriptions - invalid qos')) return false } length += Buffer.byteLength(itopic) + 2 + 1 } } else { stream.emit('error', new Error('Invalid subscriptions')) return false } // Generate header stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0]) // Generate length writeLength(stream, length) // Generate message ID writeNumber(stream, id) var result = true // Generate subs for (var j = 0; j < subs.length; j++) { var sub = subs[j] var jtopic = sub.topic var jqos = sub.qos // Write topic string writeString(stream, jtopic) // Write qos result = stream.write(protocol.QOS[jqos]) } return result } function suback (opts, stream) { var settings = opts || {} var id = settings.messageId var granted = settings.granted var length = 0 // Check message ID if (typeof id !== 'number') { stream.emit('error', new Error('Invalid messageId')) return false } else length += 2 // Check granted qos vector if (typeof granted === 'object' && granted.length) { for (var i = 0; i < granted.length; i += 1) { if (typeof granted[i] !== 'number') { stream.emit('error', new Error('Invalid qos vector')) return false } length += 1 } } else { stream.emit('error', new Error('Invalid qos vector')) return false } // header stream.write(protocol.SUBACK_HEADER) // Length writeLength(stream, length) // Message ID writeNumber(stream, id) return stream.write(Buffer.from(granted)) } function unsubscribe (opts, stream) { var settings = opts || {} var id = settings.messageId var dup = settings.dup ? protocol.DUP_MASK : 0 var unsubs = settings.unsubscriptions var length = 0 // Check message ID if (typeof id !== 'number') { stream.emit('error', new Error('Invalid messageId')) return false } else { length += 2 } // Check unsubs if (typeof unsubs === 'object' && unsubs.length) { for (var i = 0; i < unsubs.length; i += 1) { if (typeof unsubs[i] !== 'string') { stream.emit('error', new Error('Invalid unsubscriptions')) return false } length += Buffer.byteLength(unsubs[i]) + 2 } } else { stream.emit('error', new Error('Invalid unsubscriptions')) return false } // Header stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0]) // Length writeLength(stream, length) // Message ID writeNumber(stream, id) // Unsubs var result = true for (var j = 0; j < unsubs.length; j++) { result = writeString(stream, unsubs[j]) } return result } function emptyPacket (opts, stream) { return stream.write(protocol.EMPTY[opts.cmd]) } /** * calcLengthLength - calculate the length of the remaining * length field * * @api private */ function calcLengthLength (length) { if (length >= 0 && length < 128) return 1 else if (length >= 128 && length < 16384) return 2 else if (length >= 16384 && length < 2097152) return 3 else if (length >= 2097152 && length < 268435456) return 4 else return 0 } function genBufLength (length) { var digit = 0 var pos = 0 var buffer = Buffer.allocUnsafe(calcLengthLength(length)) do { digit = length % 128 | 0 length = length / 128 | 0 if (length > 0) digit = digit | 0x80 buffer.writeUInt8(digit, pos++) } while (length > 0) return buffer } /** * writeLength - write an MQTT style length field to the buffer * * @param buffer - destination * @param pos - offset * @param length - length (>0) * @returns number of bytes written * * @api private */ var lengthCache = {} function writeLength (stream, length) { var buffer = lengthCache[length] if (!buffer) { buffer = genBufLength(length) if (length < 16384) lengthCache[length] = buffer } stream.write(buffer) } /** * writeString - write a utf8 string to the buffer * * @param buffer - destination * @param pos - offset * @param string - string to write * @return number of bytes written * * @api private */ function writeString (stream, string) { var strlen = Buffer.byteLength(string) writeNumber(stream, strlen) stream.write(string, 'utf8') } /** * writeNumber - write a two byte number to the buffer * * @param buffer - destination * @param pos - offset * @param number - number to write * @return number of bytes written * * @api private */ function writeNumberCached (stream, number) { return stream.write(numCache[number]) } function writeNumberGenerated (stream, number) { return stream.write(generateNumber(number)) } /** * writeStringOrBuffer - write a String or Buffer with the its length prefix * * @param buffer - destination * @param pos - offset * @param toWrite - String or Buffer * @return number of bytes written */ function writeStringOrBuffer (stream, toWrite) { if (typeof toWrite === 'string') { writeString(stream, toWrite) } else if (toWrite) { writeNumber(stream, toWrite.length) stream.write(toWrite) } else writeNumber(stream, 0) } function byteLength (bufOrString) { if (!bufOrString) return 0 else if (bufOrString instanceof Buffer) return bufOrString.length else return Buffer.byteLength(bufOrString) } function isStringOrBuffer (field) { return typeof field === 'string' || field instanceof Buffer } module.exports = generate /***/ }), /***/ 4768: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var mqtt = __nccwpck_require__(4879) var pump = __nccwpck_require__(7898) var path = __nccwpck_require__(6928) var fs = __nccwpck_require__(9896) var concat = __nccwpck_require__(6298) var Writable = (__nccwpck_require__(6131).Writable) var helpMe = __nccwpck_require__(6197)({ dir: __nccwpck_require__.ab + "doc" }) var minimist = __nccwpck_require__(994) var split2 = __nccwpck_require__(2077) function send (args) { var client = mqtt.connect(args) client.on('connect', function () { client.publish(args.topic, args.message, args, function (err) { if (err) { console.warn(err) } client.end() }) }) client.on('error', function (err) { console.warn(err) client.end() }) } function multisend (args) { var client = mqtt.connect(args) var sender = new Writable({ objectMode: true }) sender._write = function (line, enc, cb) { client.publish(args.topic, line.trim(), args, cb) } client.on('connect', function () { pump(process.stdin, split2(), sender, function (err) { client.end() if (err) { throw err } }) }) } function start (args) { args = minimist(args, { string: ['hostname', 'username', 'password', 'key', 'cert', 'ca', 'message', 'clientId', 'i', 'id'], boolean: ['stdin', 'retain', 'help', 'insecure', 'multiline'], alias: { port: 'p', hostname: ['h', 'host'], topic: 't', message: 'm', qos: 'q', clientId: ['i', 'id'], retain: 'r', username: 'u', password: 'P', stdin: 's', multiline: 'M', protocol: ['C', 'l'], help: 'H', ca: 'cafile' }, default: { host: 'localhost', qos: 0, retain: false, topic: '', message: '' } }) if (args.help) { return helpMe.toStdout('publish') } if (args.key) { args.key = fs.readFileSync(args.key) } if (args.cert) { args.cert = fs.readFileSync(args.cert) } if (args.ca) { args.ca = fs.readFileSync(args.ca) } if (args.key && args.cert && !args.protocol) { args.protocol = 'mqtts' } if (args.port) { if (typeof args.port !== 'number') { console.warn('# Port: number expected, \'%s\' was given.', typeof args.port) return } } if (args['will-topic']) { args.will = {} args.will.topic = args['will-topic'] args.will.payload = args['will-message'] args.will.qos = args['will-qos'] args.will.retain = args['will-retain'] } if (args.insecure) { args.rejectUnauthorized = false } args.topic = (args.topic || args._.shift()).toString() args.message = (args.message || args._.shift()).toString() if (!args.topic) { console.error('missing topic\n') return helpMe.toStdout('publish') } if (args.stdin) { if (args.multiline) { multisend(args) } else { process.stdin.pipe(concat(function (data) { args.message = data send(args) })) } } else { send(args) } } module.exports = start if (false) {} /***/ }), /***/ 881: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var mqtt = __nccwpck_require__(4879) var path = __nccwpck_require__(6928) var fs = __nccwpck_require__(9896) var helpMe = __nccwpck_require__(6197)({ dir: __nccwpck_require__.ab + "doc" }) var minimist = __nccwpck_require__(994) function start (args) { args = minimist(args, { string: ['hostname', 'username', 'password', 'key', 'cert', 'ca', 'clientId', 'i', 'id'], boolean: ['stdin', 'help', 'clean', 'insecure'], alias: { port: 'p', hostname: ['h', 'host'], topic: 't', qos: 'q', clean: 'c', keepalive: 'k', clientId: ['i', 'id'], username: 'u', password: 'P', protocol: ['C', 'l'], verbose: 'v', help: '-H', ca: 'cafile' }, default: { host: 'localhost', qos: 0, retain: false, clean: true, keepAlive: 30 // 30 sec } }) if (args.help) { return helpMe.toStdout('subscribe') } args.topic = args.topic || args._.shift() if (!args.topic) { console.error('missing topic\n') return helpMe.toStdout('subscribe') } if (args.key) { args.key = fs.readFileSync(args.key) } if (args.cert) { args.cert = fs.readFileSync(args.cert) } if (args.ca) { args.ca = fs.readFileSync(args.ca) } if (args.key && args.cert && !args.protocol) { args.protocol = 'mqtts' } if (args.insecure) { args.rejectUnauthorized = false } if (args.port) { if (typeof args.port !== 'number') { console.warn('# Port: number expected, \'%s\' was given.', typeof args.port) return } } if (args['will-topic']) { args.will = {} args.will.topic = args['will-topic'] args.will.payload = args['will-message'] args.will.qos = args['will-qos'] args.will.retain = args['will-retain'] } args.keepAlive = args['keep-alive'] var client = mqtt.connect(args) client.on('connect', function () { client.subscribe(args.topic, { qos: args.qos }, function (err, result) { if (err) { console.error(err) process.exit(1) } result.forEach(function (sub) { if (sub.qos > 2) { console.error('subscription negated to', sub.topic, 'with code', sub.qos) process.exit(1) } }) }) }) client.on('message', function (topic, payload) { if (args.verbose) { console.log(topic, payload.toString()) } else { console.log(payload.toString()) } }) client.on('error', function (err) { console.warn(err) client.end() }) } module.exports = start if (false) {} /***/ }), /***/ 3246: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /** * Module dependencies */ var events = __nccwpck_require__(4434) var Store = __nccwpck_require__(2764) var eos = __nccwpck_require__(1424) var mqttPacket = __nccwpck_require__(8971) var Writable = (__nccwpck_require__(6131).Writable) var inherits = __nccwpck_require__(9598) var reInterval = __nccwpck_require__(902) var validations = __nccwpck_require__(2581) var xtend = __nccwpck_require__(869) var setImmediate = global.setImmediate || function (callback) { // works in node v0.8 process.nextTick(callback) } var defaultConnectOptions = { keepalive: 60, reschedulePings: true, protocolId: 'MQTT', protocolVersion: 4, reconnectPeriod: 1000, connectTimeout: 30 * 1000, clean: true, resubscribe: true } function defaultId () { return 'mqttjs_' + Math.random().toString(16).substr(2, 8) } function sendPacket (client, packet, cb) { client.emit('packetsend', packet) var result = mqttPacket.writeToStream(packet, client.stream) if (!result && cb) { client.stream.once('drain', cb) } else if (cb) { cb() } } function flush (queue) { if (queue) { Object.keys(queue).forEach(function (messageId) { if (typeof queue[messageId] === 'function') { queue[messageId](new Error('Connection closed')) delete queue[messageId] } }) } } function storeAndSend (client, packet, cb) { client.outgoingStore.put(packet, function storedPacket (err) { if (err) { return cb && cb(err) } sendPacket(client, packet, cb) }) } function nop () {} /** * MqttClient constructor * * @param {Stream} stream - stream * @param {Object} [options] - connection options * (see Connection#connect) */ function MqttClient (streamBuilder, options) { var k var that = this if (!(this instanceof MqttClient)) { return new MqttClient(streamBuilder, options) } this.options = options || {} // Defaults for (k in defaultConnectOptions) { if (typeof this.options[k] === 'undefined') { this.options[k] = defaultConnectOptions[k] } else { this.options[k] = options[k] } } this.options.clientId = (typeof this.options.clientId === 'string') ? this.options.clientId : defaultId() this.streamBuilder = streamBuilder // Inflight message storages this.outgoingStore = this.options.outgoingStore || new Store() this.incomingStore = this.options.incomingStore || new Store() // Should QoS zero messages be queued when the connection is broken? this.queueQoSZero = this.options.queueQoSZero === undefined ? true : this.options.queueQoSZero // map of subscribed topics to support reconnection this._resubscribeTopics = {} // map of a subscribe messageId and a topic this.messageIdToTopic = {} // Ping timer, setup in _setupPingTimer this.pingTimer = null // Is the client connected? this.connected = false // Are we disconnecting? this.disconnecting = false // Packet queue this.queue = [] // connack timer this.connackTimer = null // Reconnect timer this.reconnectTimer = null /** * MessageIDs starting with 1 * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810 */ this.nextId = Math.max(1, Math.floor(Math.random() * 65535)) // Inflight callbacks this.outgoing = {} // Mark connected on connect this.on('connect', function () { if (this.disconnected) { return } this.connected = true var outStore = this.outgoingStore.createStream() this.once('close', remove) outStore.on('end', function () { that.removeListener('close', remove) }) outStore.on('error', function (err) { that.removeListener('close', remove) that.emit('error', err) }) function remove () { outStore.destroy() outStore = null } function storeDeliver () { // edge case, we wrapped this twice if (!outStore) { return } var packet = outStore.read(1) var cb if (!packet) { // read when data is available in the future outStore.once('readable', storeDeliver) return } // Avoid unnecessary stream read operations when disconnected if (!that.disconnecting && !that.reconnectTimer) { cb = that.outgoing[packet.messageId] that.outgoing[packet.messageId] = function (err, status) { // Ensure that the original callback passed in to publish gets invoked if (cb) { cb(err, status) } storeDeliver() } that._sendPacket(packet) } else if (outStore.destroy) { outStore.destroy() } } // start flowing storeDeliver() }) // Mark disconnected on stream close this.on('close', function () { this.connected = false clearTimeout(this.connackTimer) }) // Setup ping timer this.on('connect', this._setupPingTimer) // Send queued packets this.on('connect', function () { var queue = this.queue function deliver () { var entry = queue.shift() var packet = null if (!entry) { return } packet = entry.packet that._sendPacket( packet, function (err) { if (entry.cb) { entry.cb(err) } deliver() } ) } deliver() }) var firstConnection = true // resubscribe this.on('connect', function () { if (!firstConnection && this.options.clean && Object.keys(this._resubscribeTopics).length > 0) { if (this.options.resubscribe) { this._resubscribeTopics.resubscribe = true this.subscribe(this._resubscribeTopics) } else { this._resubscribeTopics = {} } } firstConnection = false }) // Clear ping timer this.on('close', function () { if (that.pingTimer !== null) { that.pingTimer.clear() that.pingTimer = null } }) // Setup reconnect timer on disconnect this.on('close', this._setupReconnect) events.EventEmitter.call(this) this._setupStream() } inherits(MqttClient, events.EventEmitter) /** * setup the event handlers in the inner stream. * * @api private */ MqttClient.prototype._setupStream = function () { var connectPacket var that = this var writable = new Writable() var parser = mqttPacket.parser(this.options) var completeParse = null var packets = [] this._clearReconnect() this.stream = this.streamBuilder(this) parser.on('packet', function (packet) { packets.push(packet) }) function nextTickWork () { process.nextTick(work) } function work () { var packet = packets.shift() var done = completeParse if (packet) { that._handlePacket(packet, nextTickWork) } else { completeParse = null done() } } writable._write = function (buf, enc, done) { completeParse = done parser.parse(buf) work() } this.stream.pipe(writable) // Suppress connection errors this.stream.on('error', nop) // Echo stream close eos(this.stream, this.emit.bind(this, 'close')) // Send a connect packet connectPacket = Object.create(this.options) connectPacket.cmd = 'connect' // avoid message queue sendPacket(this, connectPacket) // Echo connection errors parser.on('error', this.emit.bind(this, 'error')) // many drain listeners are needed for qos 1 callbacks if the connection is intermittent this.stream.setMaxListeners(1000) clearTimeout(this.connackTimer) this.connackTimer = setTimeout(function () { that._cleanUp(true) }, this.options.connectTimeout) } MqttClient.prototype._handlePacket = function (packet, done) { this.emit('packetreceive', packet) switch (packet.cmd) { case 'publish': this._handlePublish(packet, done) break case 'puback': case 'pubrec': case 'pubcomp': case 'suback': case 'unsuback': this._handleAck(packet) done() break case 'pubrel': this._handlePubrel(packet, done) break case 'connack': this._handleConnack(packet) done() break case 'pingresp': this._handlePingresp(packet) done() break default: // do nothing // maybe we should do an error handling // or just log it break } } MqttClient.prototype._checkDisconnecting = function (callback) { if (this.disconnecting) { if (callback) { callback(new Error('client disconnecting')) } else { this.emit('error', new Error('client disconnecting')) } } return this.disconnecting } /** * publish - publish to * * @param {String} topic - topic to publish to * @param {String, Buffer} message - message to publish * @param {Object} [opts] - publish options, includes: * {Number} qos - qos level to publish on * {Boolean} retain - whether or not to retain the message * {Boolean} dup - whether or not mark a message as duplicate * @param {Function} [callback] - function(err){} * called when publish succeeds or fails * @returns {MqttClient} this - for chaining * @api public * * @example client.publish('topic', 'message'); * @example * client.publish('topic', 'message', {qos: 1, retain: true, dup: true}); * @example client.publish('topic', 'message', console.log); */ MqttClient.prototype.publish = function (topic, message, opts, callback) { var packet // .publish(topic, payload, cb); if (typeof opts === 'function') { callback = opts opts = null } // default opts var defaultOpts = {qos: 0, retain: false, dup: false} opts = xtend(defaultOpts, opts) if (this._checkDisconnecting(callback)) { return this } packet = { cmd: 'publish', topic: topic, payload: message, qos: opts.qos, retain: opts.retain, messageId: this._nextId(), dup: opts.dup } switch (opts.qos) { case 1: case 2: // Add to callbacks this.outgoing[packet.messageId] = callback || nop this._sendPacket(packet) break default: this._sendPacket(packet, callback) break } return this } /** * subscribe - subscribe to * * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos} * @param {Object} [opts] - optional subscription options, includes: * {Number} qos - subscribe qos level * @param {Function} [callback] - function(err, granted){} where: * {Error} err - subscription error (none at the moment!) * {Array} granted - array of {topic: 't', qos: 0} * @returns {MqttClient} this - for chaining * @api public * @example client.subscribe('topic'); * @example client.subscribe('topic', {qos: 1}); * @example client.subscribe({'topic': 0, 'topic2': 1}, console.log); * @example client.subscribe('topic', console.log); */ MqttClient.prototype.subscribe = function () { var packet var args = Array.prototype.slice.call(arguments) var subs = [] var obj = args.shift() var resubscribe = obj.resubscribe var callback = args.pop() || nop var opts = args.pop() var invalidTopic var that = this delete obj.resubscribe if (typeof obj === 'string') { obj = [obj] } if (typeof callback !== 'function') { opts = callback callback = nop } invalidTopic = validations.validateTopics(obj) if (invalidTopic !== null) { setImmediate(callback, new Error('Invalid topic ' + invalidTopic)) return this } if (this._checkDisconnecting(callback)) { return this } var defaultOpts = { qos: 0 } opts = xtend(defaultOpts, opts) if (Array.isArray(obj)) { obj.forEach(function (topic) { if (that._resubscribeTopics[topic] < opts.qos || !that._resubscribeTopics.hasOwnProperty(topic) || resubscribe) { subs.push({ topic: topic, qos: opts.qos }) } }) } else { Object .keys(obj) .forEach(function (k) { if (that._resubscribeTopics[k] < obj[k] || !that._resubscribeTopics.hasOwnProperty(k) || resubscribe) { subs.push({ topic: k, qos: obj[k] }) } }) } packet = { cmd: 'subscribe', subscriptions: subs, qos: 1, retain: false, dup: false, messageId: this._nextId() } if (!subs.length) { callback(null, []) return } // subscriptions to resubscribe to in case of disconnect if (this.options.resubscribe) { var topics = [] subs.forEach(function (sub) { if (that.options.reconnectPeriod > 0) { that._resubscribeTopics[sub.topic] = sub.qos topics.push(sub.topic) } }) that.messageIdToTopic[packet.messageId] = topics } this.outgoing[packet.messageId] = function (err, packet) { if (!err) { var granted = packet.granted for (var i = 0; i < granted.length; i += 1) { subs[i].qos = granted[i] } } callback(err, subs) } this._sendPacket(packet) return this } /** * unsubscribe - unsubscribe from topic(s) * * @param {String, Array} topic - topics to unsubscribe from * @param {Function} [callback] - callback fired on unsuback * @returns {MqttClient} this - for chaining * @api public * @example client.unsubscribe('topic'); * @example client.unsubscribe('topic', console.log); */ MqttClient.prototype.unsubscribe = function (topic, callback) { var packet = { cmd: 'unsubscribe', qos: 1, messageId: this._nextId() } var that = this callback = callback || nop if (this._checkDisconnecting(callback)) { return this } if (typeof topic === 'string') { packet.unsubscriptions = [topic] } else if (typeof topic === 'object' && topic.length) { packet.unsubscriptions = topic } if (this.options.resubscribe) { packet.unsubscriptions.forEach(function (topic) { delete that._resubscribeTopics[topic] }) } this.outgoing[packet.messageId] = callback this._sendPacket(packet) return this } /** * end - close connection * * @returns {MqttClient} this - for chaining * @param {Boolean} force - do not wait for all in-flight messages to be acked * @param {Function} cb - called when the client has been closed * * @api public */ MqttClient.prototype.end = function (force, cb) { var that = this if (typeof force === 'function') { cb = force force = false } function closeStores () { that.disconnected = true that.incomingStore.close(function () { that.outgoingStore.close(function () { if (cb) { cb.apply(null, arguments) } that.emit('end') }) }) if (that._deferredReconnect) { that._deferredReconnect() } } function finish () { // defer closesStores of an I/O cycle, // just to make sure things are // ok for websockets that._cleanUp(force, setImmediate.bind(null, closeStores)) } if (this.disconnecting) { return this } this._clearReconnect() this.disconnecting = true if (!force && Object.keys(this.outgoing).length > 0) { // wait 10ms, just to be sure we received all of it this.once('outgoingEmpty', setTimeout.bind(null, finish, 10)) } else { finish() } return this } /** * removeOutgoingMessage - remove a message in outgoing store * the outgoing callback will be called withe Error('Message removed') if the message is removed * * @param {Number} mid - messageId to remove message * @returns {MqttClient} this - for chaining * @api public * * @example client.removeOutgoingMessage(client.getLastMessageId()); */ MqttClient.prototype.removeOutgoingMessage = function (mid) { var cb = this.outgoing[mid] delete this.outgoing[mid] this.outgoingStore.del({messageId: mid}, function () { cb(new Error('Message removed')) }) return this } /** * reconnect - connect again using the same options as connect() * * @param {Object} [opts] - optional reconnect options, includes: * {Store} incomingStore - a store for the incoming packets * {Store} outgoingStore - a store for the outgoing packets * if opts is not given, current stores are used * @returns {MqttClient} this - for chaining * * @api public */ MqttClient.prototype.reconnect = function (opts) { var that = this var f = function () { if (opts) { that.options.incomingStore = opts.incomingStore that.options.outgoingStore = opts.outgoingStore } else { that.options.incomingStore = null that.options.outgoingStore = null } that.incomingStore = that.options.incomingStore || new Store() that.outgoingStore = that.options.outgoingStore || new Store() that.disconnecting = false that.disconnected = false that._deferredReconnect = null that._reconnect() } if (this.disconnecting && !this.disconnected) { this._deferredReconnect = f } else { f() } return this } /** * _reconnect - implement reconnection * @api privateish */ MqttClient.prototype._reconnect = function () { this.emit('reconnect') this._setupStream() } /** * _setupReconnect - setup reconnect timer */ MqttClient.prototype._setupReconnect = function () { var that = this if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) { if (!this.reconnecting) { this.emit('offline') this.reconnecting = true } that.reconnectTimer = setInterval(function () { that._reconnect() }, that.options.reconnectPeriod) } } /** * _clearReconnect - clear the reconnect timer */ MqttClient.prototype._clearReconnect = function () { if (this.reconnectTimer) { clearInterval(this.reconnectTimer) this.reconnectTimer = null } } /** * _cleanUp - clean up on connection end * @api private */ MqttClient.prototype._cleanUp = function (forced, done) { if (done) { this.stream.on('close', done) } if (forced) { if ((this.options.reconnectPeriod === 0) && this.options.clean) { flush(this.outgoing) } this.stream.destroy() } else { this._sendPacket( { cmd: 'disconnect' }, setImmediate.bind( null, this.stream.end.bind(this.stream) ) ) } if (!this.disconnecting) { this._clearReconnect() this._setupReconnect() } if (this.pingTimer !== null) { this.pingTimer.clear() this.pingTimer = null } if (done && !this.connected) { this.stream.removeListener('close', done) done() } } /** * _sendPacket - send or queue a packet * @param {String} type - packet type (see `protocol`) * @param {Object} packet - packet options * @param {Function} cb - callback when the packet is sent * @api private */ MqttClient.prototype._sendPacket = function (packet, cb) { if (!this.connected) { if (((packet.qos || 0) === 0 && this.queueQoSZero) || packet.cmd !== 'publish') { this.queue.push({ packet: packet, cb: cb }) } else if (packet.qos > 0) { cb = this.outgoing[packet.messageId] this.outgoingStore.put(packet, function (err) { if (err) { return cb && cb(err) } }) } else if (cb) { cb(new Error('No connection to broker')) } return } // When sending a packet, reschedule the ping timer this._shiftPingInterval() switch (packet.cmd) { case 'publish': break case 'pubrel': storeAndSend(this, packet, cb) return default: sendPacket(this, packet, cb) return } switch (packet.qos) { case 2: case 1: storeAndSend(this, packet, cb) break /** * no need of case here since it will be caught by default * and jshint comply that before default it must be a break * anyway it will result in -1 evaluation */ case 0: /* falls through */ default: sendPacket(this, packet, cb) break } } /** * _setupPingTimer - setup the ping timer * * @api private */ MqttClient.prototype._setupPingTimer = function () { var that = this if (!this.pingTimer && this.options.keepalive) { this.pingResp = true this.pingTimer = reInterval(function () { that._checkPing() }, this.options.keepalive * 1000) } } /** * _shiftPingInterval - reschedule the ping interval * * @api private */ MqttClient.prototype._shiftPingInterval = function () { if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) { this.pingTimer.reschedule(this.options.keepalive * 1000) } } /** * _checkPing - check if a pingresp has come back, and ping the server again * * @api private */ MqttClient.prototype._checkPing = function () { if (this.pingResp) { this.pingResp = false this._sendPacket({ cmd: 'pingreq' }) } else { // do a forced cleanup since socket will be in bad shape this._cleanUp(true) } } /** * _handlePingresp - handle a pingresp * * @api private */ MqttClient.prototype._handlePingresp = function () { this.pingResp = true } /** * _handleConnack * * @param {Object} packet * @api private */ MqttClient.prototype._handleConnack = function (packet) { var rc = packet.returnCode var errors = [ '', 'Unacceptable protocol version', 'Identifier rejected', 'Server unavailable', 'Bad username or password', 'Not authorized' ] clearTimeout(this.connackTimer) if (rc === 0) { this.reconnecting = false this.emit('connect', packet) } else if (rc > 0) { var err = new Error('Connection refused: ' + errors[rc]) err.code = rc this.emit('error', err) } } /** * _handlePublish * * @param {Object} packet * @api private */ /* those late 2 case should be rewrite to comply with coding style: case 1: case 0: // do not wait sending a puback // no callback passed if (1 === qos) { this._sendPacket({ cmd: 'puback', messageId: mid }); } // emit the message event for both qos 1 and 0 this.emit('message', topic, message, packet); this.handleMessage(packet, done); break; default: // do nothing but every switch mus have a default // log or throw an error about unknown qos break; for now i just suppressed the warnings */ MqttClient.prototype._handlePublish = function (packet, done) { done = typeof done !== 'undefined' ? done : nop var topic = packet.topic.toString() var message = packet.payload var qos = packet.qos var mid = packet.messageId var that = this switch (qos) { case 2: this.incomingStore.put(packet, function (err) { if (err) { return done(err) } that._sendPacket({cmd: 'pubrec', messageId: mid}, done) }) break case 1: // emit the message event this.emit('message', topic, message, packet) this.handleMessage(packet, function (err) { if (err) { return done(err) } // send 'puback' if the above 'handleMessage' method executed // successfully. that._sendPacket({cmd: 'puback', messageId: mid}, done) }) break case 0: // emit the message event this.emit('message', topic, message, packet) this.handleMessage(packet, done) break default: // do nothing // log or throw an error about unknown qos break } } /** * Handle messages with backpressure support, one at a time. * Override at will. * * @param Packet packet the packet * @param Function callback call when finished * @api public */ MqttClient.prototype.handleMessage = function (packet, callback) { callback() } /** * _handleAck * * @param {Object} packet * @api private */ MqttClient.prototype._handleAck = function (packet) { /* eslint no-fallthrough: "off" */ var mid = packet.messageId var type = packet.cmd var response = null var cb = this.outgoing[mid] var that = this if (!cb) { // Server sent an ack in error, ignore it. return } // Process switch (type) { case 'pubcomp': // same thing as puback for QoS 2 case 'puback': // Callback - we're done delete this.outgoing[mid] this.outgoingStore.del(packet, cb) break case 'pubrec': response = { cmd: 'pubrel', qos: 2, messageId: mid } this._sendPacket(response) break case 'suback': delete this.outgoing[mid] if (packet.granted.length === 1 && (packet.granted[0] & 0x80) !== 0) { // suback with Failure status var topics = this.messageIdToTopic[mid] if (topics) { topics.forEach(function (topic) { delete that._resubscribeTopics[topic] }) } } cb(null, packet) break case 'unsuback': delete this.outgoing[mid] cb(null) break default: that.emit('error', new Error('unrecognized packet type')) } if (this.disconnecting && Object.keys(this.outgoing).length === 0) { this.emit('outgoingEmpty') } } /** * _handlePubrel * * @param {Object} packet * @api private */ MqttClient.prototype._handlePubrel = function (packet, callback) { callback = typeof callback !== 'undefined' ? callback : nop var mid = packet.messageId var that = this var comp = {cmd: 'pubcomp', messageId: mid} that.incomingStore.get(packet, function (err, pub) { if (!err && pub.cmd !== 'pubrel') { that.emit('message', pub.topic, pub.payload, pub) that.incomingStore.put(packet, function (err) { if (err) { return callback(err) } that.handleMessage(pub, function (err) { if (err) { return callback(err) } that._sendPacket(comp, callback) }) }) } else { that._sendPacket(comp, callback) } }) } /** * _nextId * @return unsigned int */ MqttClient.prototype._nextId = function () { // id becomes current state of this.nextId and increments afterwards var id = this.nextId++ // Ensure 16 bit unsigned int (max 65535, nextId got one higher) if (this.nextId === 65536) { this.nextId = 1 } return id } /** * getLastMessageId * @return unsigned int */ MqttClient.prototype.getLastMessageId = function () { return (this.nextId === 1) ? 65535 : (this.nextId - 1) } module.exports = MqttClient /***/ }), /***/ 1260: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var MqttClient = __nccwpck_require__(3246) var Store = __nccwpck_require__(2764) var url = __nccwpck_require__(7016) var xtend = __nccwpck_require__(869) var protocols = {} if (process.title !== 'browser') { protocols.mqtt = __nccwpck_require__(1243) protocols.tcp = __nccwpck_require__(1243) protocols.ssl = __nccwpck_require__(7033) protocols.tls = __nccwpck_require__(7033) protocols.mqtts = __nccwpck_require__(7033) } else { protocols.wx = __nccwpck_require__(1577) protocols.wxs = __nccwpck_require__(1577) } protocols.ws = __nccwpck_require__(5400) protocols.wss = __nccwpck_require__(5400) /** * Parse the auth attribute and merge username and password in the options object. * * @param {Object} [opts] option object */ function parseAuthOptions (opts) { var matches if (opts.auth) { matches = opts.auth.match(/^(.+):(.+)$/) if (matches) { opts.username = matches[1] opts.password = matches[2] } else { opts.username = opts.auth } } } /** * connect - connect to an MQTT broker. * * @param {String} [brokerUrl] - url of the broker, optional * @param {Object} opts - see MqttClient#constructor */ function connect (brokerUrl, opts) { if ((typeof brokerUrl === 'object') && !opts) { opts = brokerUrl brokerUrl = null } opts = opts || {} if (brokerUrl) { var parsed = url.parse(brokerUrl, true) if (parsed.port != null) { parsed.port = Number(parsed.port) } opts = xtend(parsed, opts) if (opts.protocol === null) { throw new Error('Missing protocol') } opts.protocol = opts.protocol.replace(/:$/, '') } // merge in the auth options if supplied parseAuthOptions(opts) // support clientId passed in the query string of the url if (opts.query && typeof opts.query.clientId === 'string') { opts.clientId = opts.query.clientId } if (opts.cert && opts.key) { if (opts.protocol) { if (['mqtts', 'wss', 'wxs'].indexOf(opts.protocol) === -1) { switch (opts.protocol) { case 'mqtt': opts.protocol = 'mqtts' break case 'ws': opts.protocol = 'wss' break case 'wx': opts.protocol = 'wxs' break default: throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!') } } } else { // don't know what protocol he want to use, mqtts or wss throw new Error('Missing secure protocol key') } } if (!protocols[opts.protocol]) { var isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1 opts.protocol = [ 'mqtt', 'mqtts', 'ws', 'wss', 'wx', 'wxs' ].filter(function (key, index) { if (isSecure && index % 2 === 0) { // Skip insecure protocols when requesting a secure one. return false } return (typeof protocols[key] === 'function') })[0] } if (opts.clean === false && !opts.clientId) { throw new Error('Missing clientId for unclean clients') } if (opts.protocol) { opts.defaultProtocol = opts.protocol } function wrapper (client) { if (opts.servers) { if (!client._reconnectCount || client._reconnectCount === opts.servers.length) { client._reconnectCount = 0 } opts.host = opts.servers[client._reconnectCount].host opts.port = opts.servers[client._reconnectCount].port opts.protocol = (!opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol) opts.hostname = opts.host client._reconnectCount++ } return protocols[opts.protocol](client, opts) } return new MqttClient(wrapper, opts) } module.exports = connect module.exports.connect = connect module.exports.MqttClient = MqttClient module.exports.Store = Store /***/ }), /***/ 1243: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var net = __nccwpck_require__(9278) /* variables port and host can be removed since you have all required information in opts object */ function buildBuilder (client, opts) { var port, host opts.port = opts.port || 1883 opts.hostname = opts.hostname || opts.host || 'localhost' port = opts.port host = opts.hostname return net.createConnection(port, host) } module.exports = buildBuilder /***/ }), /***/ 7033: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var tls = __nccwpck_require__(4756) function buildBuilder (mqttClient, opts) { var connection opts.port = opts.port || 8883 opts.host = opts.hostname || opts.host || 'localhost' opts.rejectUnauthorized = opts.rejectUnauthorized !== false delete opts.path connection = tls.connect(opts) /* eslint no-use-before-define: [2, "nofunc"] */ connection.on('secureConnect', function () { if (opts.rejectUnauthorized && !connection.authorized) { connection.emit('error', new Error('TLS not authorized')) } else { connection.removeListener('error', handleTLSerrors) } }) function handleTLSerrors (err) { // How can I get verify this error is a tls error? if (opts.rejectUnauthorized) { mqttClient.emit('error', err) } // close this connection to match the behaviour of net // otherwise all we get is an error from the connection // and close event doesn't fire. This is a work around // to enable the reconnect code to work the same as with // net.createConnection connection.end() } connection.on('error', handleTLSerrors) return connection } module.exports = buildBuilder /***/ }), /***/ 5400: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var websocket = __nccwpck_require__(6302) var urlModule = __nccwpck_require__(7016) var WSS_OPTIONS = [ 'rejectUnauthorized', 'ca', 'cert', 'key', 'pfx', 'passphrase' ] var IS_BROWSER = process.title === 'browser' function buildUrl (opts, client) { var url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path if (typeof (opts.transformWsUrl) === 'function') { url = opts.transformWsUrl(url, opts, client) } return url } function setDefaultOpts (opts) { if (!opts.hostname) { opts.hostname = 'localhost' } if (!opts.port) { if (opts.protocol === 'wss') { opts.port = 443 } else { opts.port = 80 } } if (!opts.path) { opts.path = '/' } if (!opts.wsOptions) { opts.wsOptions = {} } if (!IS_BROWSER && opts.protocol === 'wss') { // Add cert/key/ca etc options WSS_OPTIONS.forEach(function (prop) { if (opts.hasOwnProperty(prop) && !opts.wsOptions.hasOwnProperty(prop)) { opts.wsOptions[prop] = opts[prop] } }) } } function createWebSocket (client, opts) { var websocketSubProtocol = (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3) ? 'mqttv3.1' : 'mqtt' setDefaultOpts(opts) var url = buildUrl(opts, client) return websocket(url, [websocketSubProtocol], opts.wsOptions) } function buildBuilder (client, opts) { return createWebSocket(client, opts) } function buildBuilderBrowser (client, opts) { if (!opts.hostname) { opts.hostname = opts.host } if (!opts.hostname) { // Throwing an error in a Web Worker if no `hostname` is given, because we // can not determine the `hostname` automatically. If connecting to // localhost, please supply the `hostname` as an argument. if (typeof (document) === 'undefined') { throw new Error('Could not determine host. Specify host manually.') } var parsed = urlModule.parse(document.URL) opts.hostname = parsed.hostname if (!opts.port) { opts.port = parsed.port } } return createWebSocket(client, opts) } if (IS_BROWSER) { module.exports = buildBuilderBrowser } else { module.exports = buildBuilder } /***/ }), /***/ 1577: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* global wx */ var socketOpen = false var socketMsgQueue = [] function sendSocketMessage (msg) { if (socketOpen) { wx.sendSocketMessage({ data: msg.buffer || msg }) } else { socketMsgQueue.push(msg) } } function WebSocket (url, protocols) { var ws = { OPEN: 1, CLOSING: 2, CLOSED: 3, readyState: socketOpen ? 1 : 0, send: sendSocketMessage, close: wx.closeSocket, onopen: null, onmessage: null, onclose: null, onerror: null } wx.connectSocket({ url: url, protocols: protocols }) wx.onSocketOpen(function (res) { ws.readyState = ws.OPEN socketOpen = true for (var i = 0; i < socketMsgQueue.length; i++) { sendSocketMessage(socketMsgQueue[i]) } socketMsgQueue = [] ws.onopen && ws.onopen.apply(ws, arguments) }) wx.onSocketMessage(function (res) { ws.onmessage && ws.onmessage.apply(ws, arguments) }) wx.onSocketClose(function () { ws.onclose && ws.onclose.apply(ws, arguments) ws.readyState = ws.CLOSED socketOpen = false }) wx.onSocketError(function () { ws.onerror && ws.onerror.apply(ws, arguments) ws.readyState = ws.CLOSED socketOpen = false }) return ws } var websocket = __nccwpck_require__(6302) function buildUrl (opts, client) { var protocol = opts.protocol === 'wxs' ? 'wss' : 'ws' var url = protocol + '://' + opts.hostname + opts.path if (opts.port && opts.port !== 80 && opts.port !== 443) { url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path } if (typeof (opts.transformWsUrl) === 'function') { url = opts.transformWsUrl(url, opts, client) } return url } function setDefaultOpts (opts) { if (!opts.hostname) { opts.hostname = 'localhost' } if (!opts.path) { opts.path = '/' } if (!opts.wsOptions) { opts.wsOptions = {} } } function createWebSocket (client, opts) { var websocketSubProtocol = (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3) ? 'mqttv3.1' : 'mqtt' setDefaultOpts(opts) var url = buildUrl(opts, client) return websocket(WebSocket(url, [websocketSubProtocol])) } function buildBuilder (client, opts) { opts.hostname = opts.hostname || opts.host if (!opts.hostname) { throw new Error('Could not determine host. Specify host manually.') } return createWebSocket(client, opts) } module.exports = buildBuilder /***/ }), /***/ 2764: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /** * Module dependencies */ var xtend = __nccwpck_require__(869) var Readable = (__nccwpck_require__(6131).Readable) var streamsOpts = { objectMode: true } var defaultStoreOptions = { clean: true } /** * es6-map can preserve insertion order even if ES version is older. * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Description * It should be noted that a Map which is a map of an object, especially * a dictionary of dictionaries, will only map to the object's insertion * order. In ES2015 this is ordered for objects but for older versions of * ES, this may be random and not ordered. * */ var Map = __nccwpck_require__(2761) /** * In-memory implementation of the message store * This can actually be saved into files. * * @param {Object} [options] - store options */ function Store (options) { if (!(this instanceof Store)) { return new Store(options) } this.options = options || {} // Defaults this.options = xtend(defaultStoreOptions, options) this._inflights = new Map() } /** * Adds a packet to the store, a packet is * anything that has a messageId property. * */ Store.prototype.put = function (packet, cb) { this._inflights.set(packet.messageId, packet) if (cb) { cb() } return this } /** * Creates a stream with all the packets in the store * */ Store.prototype.createStream = function () { var stream = new Readable(streamsOpts) var destroyed = false var values = [] var i = 0 this._inflights.forEach(function (value, key) { values.push(value) }) stream._read = function () { if (!destroyed && i < values.length) { this.push(values[i++]) } else { this.push(null) } } stream.destroy = function () { if (destroyed) { return } var self = this destroyed = true process.nextTick(function () { self.emit('close') }) } return stream } /** * deletes a packet from the store. */ Store.prototype.del = function (packet, cb) { packet = this._inflights.get(packet.messageId) if (packet) { this._inflights.delete(packet.messageId) cb(null, packet) } else if (cb) { cb(new Error('missing packet')) } return this } /** * get a packet from the store. */ Store.prototype.get = function (packet, cb) { packet = this._inflights.get(packet.messageId) if (packet) { cb(null, packet) } else if (cb) { cb(new Error('missing packet')) } return this } /** * Close the store */ Store.prototype.close = function (cb) { if (this.options.clean) { this._inflights = null } if (cb) { cb() } } module.exports = Store /***/ }), /***/ 2581: /***/ ((module) => { "use strict"; /** * Validate a topic to see if it's valid or not. * A topic is valid if it follow below rules: * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#' * - Rule #2: Part `#` must be located at the end of the mailbox * * @param {String} topic - A topic * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false. */ function validateTopic (topic) { var parts = topic.split('/') for (var i = 0; i < parts.length; i++) { if (parts[i] === '+') { continue } if (parts[i] === '#') { // for Rule #2 return i === parts.length - 1 } if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) { return false } } return true } /** * Validate an array of topics to see if any of them is valid or not * @param {Array} topics - Array of topics * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one */ function validateTopics (topics) { if (topics.length === 0) { return 'empty_topic_list' } for (var i = 0; i < topics.length; i++) { if (!validateTopic(topics[i])) { return topics[i] } } return null } module.exports = { validateTopics: validateTopics } /***/ }), /***/ 4879: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* * Copyright (c) 2015-2015 MQTT.js contributors. * Copyright (c) 2011-2014 Adam Rudd. * * See LICENSE for more information */ var MqttClient = __nccwpck_require__(3246) var connect = __nccwpck_require__(1260) var Store = __nccwpck_require__(2764) module.exports.connect = connect // Expose MqttClient module.exports.MqttClient = MqttClient module.exports.Client = MqttClient module.exports.Store = Store function cli () { var commist = __nccwpck_require__(2273)() var helpMe = __nccwpck_require__(6197)() commist.register('publish', __nccwpck_require__(4768)) commist.register('subscribe', __nccwpck_require__(881)) commist.register('version', function () { console.log('MQTT.js version:', (__nccwpck_require__(9417)/* .version */ .rE)) }) commist.register('help', helpMe.toStdout) if (commist.parse(process.argv.slice(2)) !== null) { console.log('No such command:', process.argv[2], '\n') helpMe.toStdout() } } if (false) {} /***/ }), /***/ 2077: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* Copyright (c) 2014-2016, Matteo Collina Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ var through = __nccwpck_require__(4612) var StringDecoder = (__nccwpck_require__(5574).StringDecoder) function transform (chunk, enc, cb) { this._last += this._decoder.write(chunk) if (this._last.length > this.maxLength) { return cb(new Error('maximum buffer reached')) } var list = this._last.split(this.matcher) this._last = list.pop() for (var i = 0; i < list.length; i++) { push(this, this.mapper(list[i])) } cb() } function flush (cb) { // forward any gibberish left in there this._last += this._decoder.end() if (this._last) { push(this, this.mapper(this._last)) } cb() } function push (self, val) { if (val !== undefined) { self.push(val) } } function noop (incoming) { return incoming } function split (matcher, mapper, options) { // Set defaults for any arguments not supplied. matcher = matcher || /\r?\n/ mapper = mapper || noop options = options || {} // Test arguments explicitly. switch (arguments.length) { case 1: // If mapper is only argument. if (typeof matcher === 'function') { mapper = matcher matcher = /\r?\n/ // If options is only argument. } else if (typeof matcher === 'object' && !(matcher instanceof RegExp)) { options = matcher matcher = /\r?\n/ } break case 2: // If mapper and options are arguments. if (typeof matcher === 'function') { options = mapper mapper = matcher matcher = /\r?\n/ // If matcher and options are arguments. } else if (typeof mapper === 'object') { options = mapper mapper = noop } } var stream = through(options, transform, flush) // this stream is in objectMode only in the readable part stream._readableState.objectMode = true // objectMode default hwm is 16 and not 16384 if (stream._readableState.highWaterMark && !options.highWaterMark) { stream._readableState.highWaterMark = 16 } stream._last = '' stream._decoder = new StringDecoder('utf8') stream.matcher = matcher stream.mapper = mapper stream.maxLength = options.maxLength return stream } module.exports = split /***/ }), /***/ 2693: /***/ ((module) => { "use strict"; function Queue(options) { if (!(this instanceof Queue)) { return new Queue(options); } options = options || {}; this.concurrency = options.concurrency || Infinity; this.pending = 0; this.jobs = []; this.cbs = []; this._done = done.bind(this); } var arrayAddMethods = [ 'push', 'unshift', 'splice' ]; arrayAddMethods.forEach(function(method) { Queue.prototype[method] = function() { var methodResult = Array.prototype[method].apply(this.jobs, arguments); this._run(); return methodResult; }; }); Object.defineProperty(Queue.prototype, 'length', { get: function() { return this.pending + this.jobs.length; } }); Queue.prototype._run = function() { if (this.pending === this.concurrency) { return; } if (this.jobs.length) { var job = this.jobs.shift(); this.pending++; job(this._done); this._run(); } if (this.pending === 0) { while (this.cbs.length !== 0) { var cb = this.cbs.pop(); process.nextTick(cb); } } }; Queue.prototype.onDone = function(cb) { if (typeof cb === 'function') { this.cbs.push(cb); this._run(); } }; function done() { this.pending--; this._run(); } module.exports = Queue; /***/ }), /***/ 4922: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(3732); /***/ }), /***/ 127: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(9743); var settle = __nccwpck_require__(5529); var buildURL = __nccwpck_require__(4267); var http = __nccwpck_require__(8611); var https = __nccwpck_require__(5692); var httpFollow = (__nccwpck_require__(1573).http); var httpsFollow = (__nccwpck_require__(1573).https); var url = __nccwpck_require__(7016); var zlib = __nccwpck_require__(3106); var pkg = __nccwpck_require__(4198); var createError = __nccwpck_require__(2254); var enhanceError = __nccwpck_require__(4506); /*eslint consistent-return:0*/ module.exports = function httpAdapter(config) { return new Promise(function dispatchHttpRequest(resolve, reject) { var data = config.data; var headers = config.headers; var timer; // Set User-Agent (required by some servers) // Only set header if it hasn't been set in config // See https://github.com/axios/axios/issues/69 if (!headers['User-Agent'] && !headers['user-agent']) { headers['User-Agent'] = 'axios/' + pkg.version; } if (data && !utils.isStream(data)) { if (Buffer.isBuffer(data)) { // Nothing to do... } else if (utils.isArrayBuffer(data)) { data = new Buffer(new Uint8Array(data)); } else if (utils.isString(data)) { data = new Buffer(data, 'utf-8'); } else { return reject(createError( 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', config )); } // Add Content-Length header if data exists headers['Content-Length'] = data.length; } // HTTP basic authentication var auth = undefined; if (config.auth) { var username = config.auth.username || ''; var password = config.auth.password || ''; auth = username + ':' + password; } // Parse url var parsed = url.parse(config.url); var protocol = parsed.protocol || 'http:'; if (!auth && parsed.auth) { var urlAuth = parsed.auth.split(':'); var urlUsername = urlAuth[0] || ''; var urlPassword = urlAuth[1] || ''; auth = urlUsername + ':' + urlPassword; } if (auth) { delete headers.Authorization; } var isHttps = protocol === 'https:'; var agent = isHttps ? config.httpsAgent : config.httpAgent; var options = { path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), method: config.method, headers: headers, agent: agent, auth: auth }; if (config.socketPath) { options.socketPath = config.socketPath; } else { options.hostname = parsed.hostname; options.port = parsed.port; } var proxy = config.proxy; if (!proxy && proxy !== false) { var proxyEnv = protocol.slice(0, -1) + '_proxy'; var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; if (proxyUrl) { var parsedProxyUrl = url.parse(proxyUrl); proxy = { host: parsedProxyUrl.hostname, port: parsedProxyUrl.port }; if (parsedProxyUrl.auth) { var proxyUrlAuth = parsedProxyUrl.auth.split(':'); proxy.auth = { username: proxyUrlAuth[0], password: proxyUrlAuth[1] }; } } } if (proxy) { options.hostname = proxy.host; options.host = proxy.host; options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); options.port = proxy.port; options.path = protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path; // Basic proxy authorization if (proxy.auth) { var base64 = new Buffer(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); options.headers['Proxy-Authorization'] = 'Basic ' + base64; } } var transport; if (config.transport) { transport = config.transport; } else if (config.maxRedirects === 0) { transport = isHttps ? https : http; } else { if (config.maxRedirects) { options.maxRedirects = config.maxRedirects; } transport = isHttps ? httpsFollow : httpFollow; } if (config.maxContentLength && config.maxContentLength > -1) { options.maxBodyLength = config.maxContentLength; } // Create the request var req = transport.request(options, function handleResponse(res) { if (req.aborted) return; // Response has been received so kill timer that handles request timeout clearTimeout(timer); timer = null; // uncompress the response body transparently if required var stream = res; switch (res.headers['content-encoding']) { /*eslint default-case:0*/ case 'gzip': case 'compress': case 'deflate': // add the unzipper to the body stream processing pipeline stream = stream.pipe(zlib.createUnzip()); // remove the content-encoding in order to not confuse downstream operations delete res.headers['content-encoding']; break; } // return the last request in case of redirects var lastRequest = res.req || req; var response = { status: res.statusCode, statusText: res.statusMessage, headers: res.headers, config: config, request: lastRequest }; if (config.responseType === 'stream') { response.data = stream; settle(resolve, reject, response); } else { var responseBuffer = []; stream.on('data', function handleStreamData(chunk) { responseBuffer.push(chunk); // make sure the content length is not over the maxContentLength if specified if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) { stream.destroy(); reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded', config, null, lastRequest)); } }); stream.on('error', function handleStreamError(err) { if (req.aborted) return; reject(enhanceError(err, config, null, lastRequest)); }); stream.on('end', function handleStreamEnd() { var responseData = Buffer.concat(responseBuffer); if (config.responseType !== 'arraybuffer') { responseData = responseData.toString('utf8'); } response.data = responseData; settle(resolve, reject, response); }); } }); // Handle errors req.on('error', function handleRequestError(err) { if (req.aborted) return; reject(enhanceError(err, config, null, req)); }); // Handle request timeout if (config.timeout && !timer) { timer = setTimeout(function handleRequestTimeout() { req.abort(); reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req)); }, config.timeout); } if (config.cancelToken) { // Handle cancellation config.cancelToken.promise.then(function onCanceled(cancel) { if (req.aborted) return; req.abort(); reject(cancel); }); } // Send the request if (utils.isStream(data)) { data.pipe(req); } else { req.end(data); } }); }; /***/ }), /***/ 5465: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(9743); var settle = __nccwpck_require__(5529); var buildURL = __nccwpck_require__(4267); var parseHeaders = __nccwpck_require__(4465); var isURLSameOrigin = __nccwpck_require__(3093); var createError = __nccwpck_require__(2254); module.exports = function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { var requestData = config.data; var requestHeaders = config.headers; if (utils.isFormData(requestData)) { delete requestHeaders['Content-Type']; // Let the browser set it } var request = new XMLHttpRequest(); // HTTP basic authentication if (config.auth) { var username = config.auth.username || ''; var password = config.auth.password || ''; requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); } request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true); // Set the request timeout in MS request.timeout = config.timeout; // Listen for ready state request.onreadystatechange = function handleLoad() { if (!request || request.readyState !== 4) { return; } // The request errored out and we didn't get a response, this will be // handled by onerror instead // With one exception: request that using file: protocol, most browsers // will return status as 0 even though it's a successful request if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { return; } // Prepare the response var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // Clean up request request = null; }; // Handle low level network errors request.onerror = function handleError() { // Real errors are hidden from us by the browser // onerror should only fire if it's a network error reject(createError('Network Error', config, null, request)); // Clean up request request = null; }; // Handle timeout request.ontimeout = function handleTimeout() { reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', request)); // Clean up request request = null; }; // Add xsrf header // This is only done if running in a standard browser environment. // Specifically not if we're in a web worker, or react-native. if (utils.isStandardBrowserEnv()) { var cookies = __nccwpck_require__(9427); // Add xsrf header var xsrfValue = (config.withCredentials || isURLSameOrigin(config.url)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName] = xsrfValue; } } // Add headers to the request if ('setRequestHeader' in request) { utils.forEach(requestHeaders, function setRequestHeader(val, key) { if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { // Remove Content-Type if data is undefined delete requestHeaders[key]; } else { // Otherwise add header to the request request.setRequestHeader(key, val); } }); } // Add withCredentials to request if needed if (config.withCredentials) { request.withCredentials = true; } // Add responseType to request if needed if (config.responseType) { try { request.responseType = config.responseType; } catch (e) { // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. if (config.responseType !== 'json') { throw e; } } } // Handle progress if needed if (typeof config.onDownloadProgress === 'function') { request.addEventListener('progress', config.onDownloadProgress); } // Not all browsers support upload events if (typeof config.onUploadProgress === 'function' && request.upload) { request.upload.addEventListener('progress', config.onUploadProgress); } if (config.cancelToken) { // Handle cancellation config.cancelToken.promise.then(function onCanceled(cancel) { if (!request) { return; } request.abort(); reject(cancel); // Clean up request request = null; }); } if (requestData === undefined) { requestData = null; } // Send the request request.send(requestData); }); }; /***/ }), /***/ 3732: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(9743); var bind = __nccwpck_require__(7313); var Axios = __nccwpck_require__(8542); var defaults = __nccwpck_require__(6594); /** * Create an instance of Axios * * @param {Object} defaultConfig The default config for the instance * @return {Axios} A new instance of Axios */ function createInstance(defaultConfig) { var context = new Axios(defaultConfig); var instance = bind(Axios.prototype.request, context); // Copy axios.prototype to instance utils.extend(instance, Axios.prototype, context); // Copy context to instance utils.extend(instance, context); return instance; } // Create the default instance to be exported var axios = createInstance(defaults); // Expose Axios class to allow class inheritance axios.Axios = Axios; // Factory for creating new instances axios.create = function create(instanceConfig) { return createInstance(utils.merge(defaults, instanceConfig)); }; // Expose Cancel & CancelToken axios.Cancel = __nccwpck_require__(9015); axios.CancelToken = __nccwpck_require__(6390); axios.isCancel = __nccwpck_require__(843); // Expose all/spread axios.all = function all(promises) { return Promise.all(promises); }; axios.spread = __nccwpck_require__(401); module.exports = axios; // Allow use of default import syntax in TypeScript module.exports["default"] = axios; /***/ }), /***/ 9015: /***/ ((module) => { "use strict"; /** * A `Cancel` is an object that is thrown when an operation is canceled. * * @class * @param {string=} message The message. */ function Cancel(message) { this.message = message; } Cancel.prototype.toString = function toString() { return 'Cancel' + (this.message ? ': ' + this.message : ''); }; Cancel.prototype.__CANCEL__ = true; module.exports = Cancel; /***/ }), /***/ 6390: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Cancel = __nccwpck_require__(9015); /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * * @class * @param {Function} executor The executor function. */ function CancelToken(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); } var resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); var token = this; executor(function cancel(message) { if (token.reason) { // Cancellation has already been requested return; } token.reason = new Cancel(message); resolvePromise(token.reason); }); } /** * Throws a `Cancel` if cancellation has been requested. */ CancelToken.prototype.throwIfRequested = function throwIfRequested() { if (this.reason) { throw this.reason; } }; /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. */ CancelToken.source = function source() { var cancel; var token = new CancelToken(function executor(c) { cancel = c; }); return { token: token, cancel: cancel }; }; module.exports = CancelToken; /***/ }), /***/ 843: /***/ ((module) => { "use strict"; module.exports = function isCancel(value) { return !!(value && value.__CANCEL__); }; /***/ }), /***/ 8542: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var defaults = __nccwpck_require__(6594); var utils = __nccwpck_require__(9743); var InterceptorManager = __nccwpck_require__(9132); var dispatchRequest = __nccwpck_require__(9255); /** * Create a new instance of Axios * * @param {Object} instanceConfig The default config for the instance */ function Axios(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; } /** * Dispatch a request * * @param {Object} config The config specific for this request (merged with this.defaults) */ Axios.prototype.request = function request(config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof config === 'string') { config = utils.merge({ url: arguments[0] }, arguments[1]); } config = utils.merge(defaults, {method: 'get'}, this.defaults, config); config.method = config.method.toLowerCase(); // Hook up interceptors middleware var chain = [dispatchRequest, undefined]; var promise = Promise.resolve(config); this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { chain.unshift(interceptor.fulfilled, interceptor.rejected); }); this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { chain.push(interceptor.fulfilled, interceptor.rejected); }); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; }; // Provide aliases for supported request methods utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { return this.request(utils.merge(config || {}, { method: method, url: url })); }; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, data, config) { return this.request(utils.merge(config || {}, { method: method, url: url, data: data })); }; }); module.exports = Axios; /***/ }), /***/ 9132: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(9743); function InterceptorManager() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ InterceptorManager.prototype.use = function use(fulfilled, rejected) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected }); return this.handlers.length - 1; }; /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` */ InterceptorManager.prototype.eject = function eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } }; /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `eject`. * * @param {Function} fn The function to call for each interceptor */ InterceptorManager.prototype.forEach = function forEach(fn) { utils.forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } }); }; module.exports = InterceptorManager; /***/ }), /***/ 2254: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var enhanceError = __nccwpck_require__(4506); /** * Create an Error with the specified message, config, error code, request and response. * * @param {string} message The error message. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The created error. */ module.exports = function createError(message, config, code, request, response) { var error = new Error(message); return enhanceError(error, config, code, request, response); }; /***/ }), /***/ 9255: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(9743); var transformData = __nccwpck_require__(388); var isCancel = __nccwpck_require__(843); var defaults = __nccwpck_require__(6594); var isAbsoluteURL = __nccwpck_require__(9726); var combineURLs = __nccwpck_require__(4271); /** * Throws a `Cancel` if cancellation has been requested. */ function throwIfCancellationRequested(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } } /** * Dispatch a request to the server using the configured adapter. * * @param {object} config The config that is to be used for the request * @returns {Promise} The Promise to be fulfilled */ module.exports = function dispatchRequest(config) { throwIfCancellationRequested(config); // Support baseURL config if (config.baseURL && !isAbsoluteURL(config.url)) { config.url = combineURLs(config.baseURL, config.url); } // Ensure headers exist config.headers = config.headers || {}; // Transform request data config.data = transformData( config.data, config.headers, config.transformRequest ); // Flatten headers config.headers = utils.merge( config.headers.common || {}, config.headers[config.method] || {}, config.headers || {} ); utils.forEach( ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { delete config.headers[method]; } ); var adapter = config.adapter || defaults.adapter; return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); // Transform response data response.data = transformData( response.data, response.headers, config.transformResponse ); return response; }, function onAdapterRejection(reason) { if (!isCancel(reason)) { throwIfCancellationRequested(config); // Transform response data if (reason && reason.response) { reason.response.data = transformData( reason.response.data, reason.response.headers, config.transformResponse ); } } return Promise.reject(reason); }); }; /***/ }), /***/ 4506: /***/ ((module) => { "use strict"; /** * Update an Error with the specified config, error code, and response. * * @param {Error} error The error to update. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The error. */ module.exports = function enhanceError(error, config, code, request, response) { error.config = config; if (code) { error.code = code; } error.request = request; error.response = response; return error; }; /***/ }), /***/ 5529: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var createError = __nccwpck_require__(2254); /** * Resolve or reject a Promise based on response status. * * @param {Function} resolve A function that resolves the promise. * @param {Function} reject A function that rejects the promise. * @param {object} response The response. */ module.exports = function settle(resolve, reject, response) { var validateStatus = response.config.validateStatus; // Note: status is not exposed by XDomainRequest if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { reject(createError( 'Request failed with status code ' + response.status, response.config, null, response.request, response )); } }; /***/ }), /***/ 388: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(9743); /** * Transform the data for a request or a response * * @param {Object|String} data The data to be transformed * @param {Array} headers The headers for the request or response * @param {Array|Function} fns A single function or Array of functions * @returns {*} The resulting transformed data */ module.exports = function transformData(data, headers, fns) { /*eslint no-param-reassign:0*/ utils.forEach(fns, function transform(fn) { data = fn(data, headers); }); return data; }; /***/ }), /***/ 6594: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(9743); var normalizeHeaderName = __nccwpck_require__(1981); var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } function getDefaultAdapter() { var adapter; if (typeof XMLHttpRequest !== 'undefined') { // For browsers use XHR adapter adapter = __nccwpck_require__(5465); } else if (typeof process !== 'undefined') { // For node use HTTP adapter adapter = __nccwpck_require__(127); } return adapter; } var defaults = { adapter: getDefaultAdapter(), transformRequest: [function transformRequest(data, headers) { normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } if (utils.isObject(data)) { setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); return JSON.stringify(data); } return data; }], transformResponse: [function transformResponse(data) { /*eslint no-param-reassign:0*/ if (typeof data === 'string') { try { data = JSON.parse(data); } catch (e) { /* Ignore */ } } return data; }], /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; } }; defaults.headers = { common: { 'Accept': 'application/json, text/plain, */*' } }; utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { defaults.headers[method] = {}; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); }); module.exports = defaults; /***/ }), /***/ 7313: /***/ ((module) => { "use strict"; module.exports = function bind(fn, thisArg) { return function wrap() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; }; /***/ }), /***/ 4267: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(9743); function encode(val) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, '+'). replace(/%5B/gi, '['). replace(/%5D/gi, ']'); } /** * Build a URL by appending params to the end * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended * @returns {string} The formatted url */ module.exports = function buildURL(url, params, paramsSerializer) { /*eslint no-param-reassign:0*/ if (!params) { return url; } var serializedParams; if (paramsSerializer) { serializedParams = paramsSerializer(params); } else if (utils.isURLSearchParams(params)) { serializedParams = params.toString(); } else { var parts = []; utils.forEach(params, function serialize(val, key) { if (val === null || typeof val === 'undefined') { return; } if (utils.isArray(val)) { key = key + '[]'; } else { val = [val]; } utils.forEach(val, function parseValue(v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); } parts.push(encode(key) + '=' + encode(v)); }); }); serializedParams = parts.join('&'); } if (serializedParams) { url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } return url; }; /***/ }), /***/ 4271: /***/ ((module) => { "use strict"; /** * Creates a new URL by combining the specified URLs * * @param {string} baseURL The base URL * @param {string} relativeURL The relative URL * @returns {string} The combined URL */ module.exports = function combineURLs(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; }; /***/ }), /***/ 9427: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(9743); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs support document.cookie (function standardBrowserEnv() { return { write: function write(name, value, expires, path, domain, secure) { var cookie = []; cookie.push(name + '=' + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push('expires=' + new Date(expires).toGMTString()); } if (utils.isString(path)) { cookie.push('path=' + path); } if (utils.isString(domain)) { cookie.push('domain=' + domain); } if (secure === true) { cookie.push('secure'); } document.cookie = cookie.join('; '); }, read: function read(name) { var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); return (match ? decodeURIComponent(match[3]) : null); }, remove: function remove(name) { this.write(name, '', Date.now() - 86400000); } }; })() : // Non standard browser env (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return { write: function write() {}, read: function read() { return null; }, remove: function remove() {} }; })() ); /***/ }), /***/ 9726: /***/ ((module) => { "use strict"; /** * Determines whether the specified URL is absolute * * @param {string} url The URL to test * @returns {boolean} True if the specified URL is absolute, otherwise false */ module.exports = function isAbsoluteURL(url) { // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed // by any combination of letters, digits, plus, period, or hyphen. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); }; /***/ }), /***/ 3093: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(9743); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. (function standardBrowserEnv() { var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement('a'); var originURL; /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ function resolveURL(url) { var href = url; if (msie) { // IE needs attribute set twice to normalize properties urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); /** * Determine if a URL shares the same origin as the current location * * @param {String} requestURL The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ return function isURLSameOrigin(requestURL) { var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); }; })() : // Non standard browser envs (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return function isURLSameOrigin() { return true; }; })() ); /***/ }), /***/ 1981: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(9743); module.exports = function normalizeHeaderName(headers, normalizedName) { utils.forEach(headers, function processHeader(value, name) { if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { headers[normalizedName] = value; delete headers[name]; } }); }; /***/ }), /***/ 4465: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(9743); // Headers whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers var ignoreDuplicateOf = [ 'age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent' ]; /** * Parse headers into an object * * ``` * Date: Wed, 27 Aug 2014 08:58:49 GMT * Content-Type: application/json * Connection: keep-alive * Transfer-Encoding: chunked * ``` * * @param {String} headers Headers needing to be parsed * @returns {Object} Headers parsed into an object */ module.exports = function parseHeaders(headers) { var parsed = {}; var key; var val; var i; if (!headers) { return parsed; } utils.forEach(headers.split('\n'), function parser(line) { i = line.indexOf(':'); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { return; } if (key === 'set-cookie') { parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); } else { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } } }); return parsed; }; /***/ }), /***/ 401: /***/ ((module) => { "use strict"; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ module.exports = function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; }; /***/ }), /***/ 9743: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var bind = __nccwpck_require__(7313); var isBuffer = __nccwpck_require__(4097); /*global toString:true*/ // utils is a library of generic helper functions non-specific to axios var toString = Object.prototype.toString; /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray(val) { return toString.call(val) === '[object Array]'; } /** * Determine if a value is an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ function isArrayBuffer(val) { return toString.call(val) === '[object ArrayBuffer]'; } /** * Determine if a value is a FormData * * @param {Object} val The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(val) { return (typeof FormData !== 'undefined') && (val instanceof FormData); } /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { var result; if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { result = ArrayBuffer.isView(val); } else { result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); } return result; } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber(val) { return typeof val === 'number'; } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined(val) { return typeof val === 'undefined'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a Date * * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ function isDate(val) { return toString.call(val) === '[object Date]'; } /** * Determine if a value is a File * * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ function isFile(val) { return toString.call(val) === '[object File]'; } /** * Determine if a value is a Blob * * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ function isBlob(val) { return toString.call(val) === '[object Blob]'; } /** * Determine if a value is a Function * * @param {Object} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ function isFunction(val) { return toString.call(val) === '[object Function]'; } /** * Determine if a value is a Stream * * @param {Object} val The value to test * @returns {boolean} True if value is a Stream, otherwise false */ function isStream(val) { return isObject(val) && isFunction(val.pipe); } /** * Determine if a value is a URLSearchParams object * * @param {Object} val The value to test * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ function isURLSearchParams(val) { return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; } /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim(str) { return str.replace(/^\s*/, '').replace(/\s*$/, ''); } /** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: * typeof window -> undefined * typeof document -> undefined * * react-native: * navigator.product -> 'ReactNative' */ function isStandardBrowserEnv() { if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { return false; } return ( typeof window !== 'undefined' && typeof document !== 'undefined' ); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object') { /*eslint no-param-reassign:0*/ obj = [obj]; } if (isArray(obj)) { // Iterate over array values for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (typeof result[key] === 'object' && typeof val === 'object') { result[key] = merge(result[key], val); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } /** * Extends object a by mutably adding to it the properties of object b. * * @param {Object} a The object to be extended * @param {Object} b The object to copy properties from * @param {Object} thisArg The object to bind function to * @return {Object} The resulting value of object a */ function extend(a, b, thisArg) { forEach(b, function assignValue(val, key) { if (thisArg && typeof val === 'function') { a[key] = bind(val, thisArg); } else { a[key] = val; } }); return a; } module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, isBuffer: isBuffer, isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString, isNumber: isNumber, isObject: isObject, isUndefined: isUndefined, isDate: isDate, isFile: isFile, isBlob: isBlob, isFunction: isFunction, isStream: isStream, isURLSearchParams: isURLSearchParams, isStandardBrowserEnv: isStandardBrowserEnv, forEach: forEach, merge: merge, extend: extend, trim: trim }; /***/ }), /***/ 9380: /***/ ((module) => { "use strict"; module.exports = balanced; function balanced(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced.range = range; function range(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { if(a===b) { return [ai, bi]; } begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } /***/ }), /***/ 5234: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Buffer } = __nccwpck_require__(181) const symbol = Symbol.for('BufferList') function BufferList (buf) { if (!(this instanceof BufferList)) { return new BufferList(buf) } BufferList._init.call(this, buf) } BufferList._init = function _init (buf) { Object.defineProperty(this, symbol, { value: true }) this._bufs = [] this.length = 0 if (buf) { this.append(buf) } } BufferList.prototype._new = function _new (buf) { return new BufferList(buf) } BufferList.prototype._offset = function _offset (offset) { if (offset === 0) { return [0, 0] } let tot = 0 for (let i = 0; i < this._bufs.length; i++) { const _t = tot + this._bufs[i].length if (offset < _t || i === this._bufs.length - 1) { return [i, offset - tot] } tot = _t } } BufferList.prototype._reverseOffset = function (blOffset) { const bufferId = blOffset[0] let offset = blOffset[1] for (let i = 0; i < bufferId; i++) { offset += this._bufs[i].length } return offset } BufferList.prototype.getBuffers = function getBuffers () { return this._bufs } BufferList.prototype.get = function get (index) { if (index > this.length || index < 0) { return undefined } const offset = this._offset(index) return this._bufs[offset[0]][offset[1]] } BufferList.prototype.slice = function slice (start, end) { if (typeof start === 'number' && start < 0) { start += this.length } if (typeof end === 'number' && end < 0) { end += this.length } return this.copy(null, 0, start, end) } BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { if (typeof srcStart !== 'number' || srcStart < 0) { srcStart = 0 } if (typeof srcEnd !== 'number' || srcEnd > this.length) { srcEnd = this.length } if (srcStart >= this.length) { return dst || Buffer.alloc(0) } if (srcEnd <= 0) { return dst || Buffer.alloc(0) } const copy = !!dst const off = this._offset(srcStart) const len = srcEnd - srcStart let bytes = len let bufoff = (copy && dstStart) || 0 let start = off[1] // copy/slice everything if (srcStart === 0 && srcEnd === this.length) { if (!copy) { // slice, but full concat if multiple buffers return this._bufs.length === 1 ? this._bufs[0] : Buffer.concat(this._bufs, this.length) } // copy, need to copy individual buffers for (let i = 0; i < this._bufs.length; i++) { this._bufs[i].copy(dst, bufoff) bufoff += this._bufs[i].length } return dst } // easy, cheap case where it's a subset of one of the buffers if (bytes <= this._bufs[off[0]].length - start) { return copy ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) : this._bufs[off[0]].slice(start, start + bytes) } if (!copy) { // a slice, we need something to copy in to dst = Buffer.allocUnsafe(len) } for (let i = off[0]; i < this._bufs.length; i++) { const l = this._bufs[i].length - start if (bytes > l) { this._bufs[i].copy(dst, bufoff, start) bufoff += l } else { this._bufs[i].copy(dst, bufoff, start, start + bytes) bufoff += l break } bytes -= l if (start) { start = 0 } } // safeguard so that we don't return uninitialized memory if (dst.length > bufoff) return dst.slice(0, bufoff) return dst } BufferList.prototype.shallowSlice = function shallowSlice (start, end) { start = start || 0 end = typeof end !== 'number' ? this.length : end if (start < 0) { start += this.length } if (end < 0) { end += this.length } if (start === end) { return this._new() } const startOffset = this._offset(start) const endOffset = this._offset(end) const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) if (endOffset[1] === 0) { buffers.pop() } else { buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]) } if (startOffset[1] !== 0) { buffers[0] = buffers[0].slice(startOffset[1]) } return this._new(buffers) } BufferList.prototype.toString = function toString (encoding, start, end) { return this.slice(start, end).toString(encoding) } BufferList.prototype.consume = function consume (bytes) { // first, normalize the argument, in accordance with how Buffer does it bytes = Math.trunc(bytes) // do nothing if not a positive number if (Number.isNaN(bytes) || bytes <= 0) return this while (this._bufs.length) { if (bytes >= this._bufs[0].length) { bytes -= this._bufs[0].length this.length -= this._bufs[0].length this._bufs.shift() } else { this._bufs[0] = this._bufs[0].slice(bytes) this.length -= bytes break } } return this } BufferList.prototype.duplicate = function duplicate () { const copy = this._new() for (let i = 0; i < this._bufs.length; i++) { copy.append(this._bufs[i]) } return copy } BufferList.prototype.append = function append (buf) { return this._attach(buf, BufferList.prototype._appendBuffer) } BufferList.prototype.prepend = function prepend (buf) { return this._attach(buf, BufferList.prototype._prependBuffer, true) } BufferList.prototype._attach = function _attach (buf, attacher, prepend) { if (buf == null) { return this } if (buf.buffer) { // append/prepend a view of the underlying ArrayBuffer attacher.call(this, Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)) } else if (Array.isArray(buf)) { const [starting, modifier] = prepend ? [buf.length - 1, -1] : [0, 1] for (let i = starting; i >= 0 && i < buf.length; i += modifier) { this._attach(buf[i], attacher, prepend) } } else if (this._isBufferList(buf)) { // unwrap argument into individual BufferLists const [starting, modifier] = prepend ? [buf._bufs.length - 1, -1] : [0, 1] for (let i = starting; i >= 0 && i < buf._bufs.length; i += modifier) { this._attach(buf._bufs[i], attacher, prepend) } } else { // coerce number arguments to strings, since Buffer(number) does // uninitialized memory allocation if (typeof buf === 'number') { buf = buf.toString() } attacher.call(this, Buffer.from(buf)) } return this } BufferList.prototype._appendBuffer = function appendBuffer (buf) { this._bufs.push(buf) this.length += buf.length } BufferList.prototype._prependBuffer = function prependBuffer (buf) { this._bufs.unshift(buf) this.length += buf.length } BufferList.prototype.indexOf = function (search, offset, encoding) { if (encoding === undefined && typeof offset === 'string') { encoding = offset offset = undefined } if (typeof search === 'function' || Array.isArray(search)) { throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') } else if (typeof search === 'number') { search = Buffer.from([search]) } else if (typeof search === 'string') { search = Buffer.from(search, encoding) } else if (this._isBufferList(search)) { search = search.slice() } else if (Array.isArray(search.buffer)) { search = Buffer.from(search.buffer, search.byteOffset, search.byteLength) } else if (!Buffer.isBuffer(search)) { search = Buffer.from(search) } offset = Number(offset || 0) if (isNaN(offset)) { offset = 0 } if (offset < 0) { offset = this.length + offset } if (offset < 0) { offset = 0 } if (search.length === 0) { return offset > this.length ? this.length : offset } const blOffset = this._offset(offset) let blIndex = blOffset[0] // index of which internal buffer we're working on let buffOffset = blOffset[1] // offset of the internal buffer we're working on // scan over each buffer for (; blIndex < this._bufs.length; blIndex++) { const buff = this._bufs[blIndex] while (buffOffset < buff.length) { const availableWindow = buff.length - buffOffset if (availableWindow >= search.length) { const nativeSearchResult = buff.indexOf(search, buffOffset) if (nativeSearchResult !== -1) { return this._reverseOffset([blIndex, nativeSearchResult]) } buffOffset = buff.length - search.length + 1 // end of native search window } else { const revOffset = this._reverseOffset([blIndex, buffOffset]) if (this._match(revOffset, search)) { return revOffset } buffOffset++ } } buffOffset = 0 } return -1 } BufferList.prototype._match = function (offset, search) { if (this.length - offset < search.length) { return false } for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { if (this.get(offset + searchOffset) !== search[searchOffset]) { return false } } return true } ;(function () { const methods = { readDoubleBE: 8, readDoubleLE: 8, readFloatBE: 4, readFloatLE: 4, readBigInt64BE: 8, readBigInt64LE: 8, readBigUInt64BE: 8, readBigUInt64LE: 8, readInt32BE: 4, readInt32LE: 4, readUInt32BE: 4, readUInt32LE: 4, readInt16BE: 2, readInt16LE: 2, readUInt16BE: 2, readUInt16LE: 2, readInt8: 1, readUInt8: 1, readIntBE: null, readIntLE: null, readUIntBE: null, readUIntLE: null } for (const m in methods) { (function (m) { if (methods[m] === null) { BufferList.prototype[m] = function (offset, byteLength) { return this.slice(offset, offset + byteLength)[m](0, byteLength) } } else { BufferList.prototype[m] = function (offset = 0) { return this.slice(offset, offset + methods[m])[m](0) } } }(m)) } }()) // Used internally by the class and also as an indicator of this object being // a `BufferList`. It's not possible to use `instanceof BufferList` in a browser // environment because there could be multiple different copies of the // BufferList class and some `BufferList`s might be `BufferList`s. BufferList.prototype._isBufferList = function _isBufferList (b) { return b instanceof BufferList || BufferList.isBufferList(b) } BufferList.isBufferList = function isBufferList (b) { return b != null && b[symbol] } module.exports = BufferList /***/ }), /***/ 794: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const DuplexStream = (__nccwpck_require__(8893).Duplex) const inherits = __nccwpck_require__(9598) const BufferList = __nccwpck_require__(5234) function BufferListStream (callback) { if (!(this instanceof BufferListStream)) { return new BufferListStream(callback) } if (typeof callback === 'function') { this._callback = callback const piper = function piper (err) { if (this._callback) { this._callback(err) this._callback = null } }.bind(this) this.on('pipe', function onPipe (src) { src.on('error', piper) }) this.on('unpipe', function onUnpipe (src) { src.removeListener('error', piper) }) callback = null } BufferList._init.call(this, callback) DuplexStream.call(this) } inherits(BufferListStream, DuplexStream) Object.assign(BufferListStream.prototype, BufferList.prototype) BufferListStream.prototype._new = function _new (callback) { return new BufferListStream(callback) } BufferListStream.prototype._write = function _write (buf, encoding, callback) { this._appendBuffer(buf) if (typeof callback === 'function') { callback() } } BufferListStream.prototype._read = function _read (size) { if (!this.length) { return this.push(null) } size = Math.min(size, this.length) this.push(this.slice(0, size)) this.consume(size) } BufferListStream.prototype.end = function end (chunk) { DuplexStream.prototype.end.call(this, chunk) if (this._callback) { this._callback(null, this.slice()) this._callback = null } } BufferListStream.prototype._destroy = function _destroy (err, cb) { this._bufs.length = 0 this.length = 0 cb(err) } BufferListStream.prototype._isBufferList = function _isBufferList (b) { return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) } BufferListStream.isBufferList = BufferList.isBufferList module.exports = BufferListStream module.exports.BufferListStream = BufferListStream module.exports.BufferList = BufferList /***/ }), /***/ 6942: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { SymbolDispose } = __nccwpck_require__(9229) const { AbortError, codes } = __nccwpck_require__(6786) const { isNodeStream, isWebStream, kControllerErrorFunction } = __nccwpck_require__(3892) const eos = __nccwpck_require__(1897) const { ERR_INVALID_ARG_TYPE } = codes let addAbortListener // This method is inlined here for readable-stream // It also does not allow for signal to not exist on the stream // https://github.com/nodejs/node/pull/36061#discussion_r533718029 const validateAbortSignal = (signal, name) => { if (typeof signal !== 'object' || !('aborted' in signal)) { throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) } } module.exports.addAbortSignal = function addAbortSignal(signal, stream) { validateAbortSignal(signal, 'signal') if (!isNodeStream(stream) && !isWebStream(stream)) { throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) } return module.exports.addAbortSignalNoValidate(signal, stream) } module.exports.addAbortSignalNoValidate = function (signal, stream) { if (typeof signal !== 'object' || !('aborted' in signal)) { return stream } const onAbort = isNodeStream(stream) ? () => { stream.destroy( new AbortError(undefined, { cause: signal.reason }) ) } : () => { stream[kControllerErrorFunction]( new AbortError(undefined, { cause: signal.reason }) ) } if (signal.aborted) { onAbort() } else { addAbortListener = addAbortListener || (__nccwpck_require__(3165).addAbortListener) const disposable = addAbortListener(signal, onAbort) eos(stream, disposable[SymbolDispose]) } return stream } /***/ }), /***/ 7406: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array } = __nccwpck_require__(9229) const { Buffer } = __nccwpck_require__(181) const { inspect } = __nccwpck_require__(3165) module.exports = class BufferList { constructor() { this.head = null this.tail = null this.length = 0 } push(v) { const entry = { data: v, next: null } if (this.length > 0) this.tail.next = entry else this.head = entry this.tail = entry ++this.length } unshift(v) { const entry = { data: v, next: this.head } if (this.length === 0) this.tail = entry this.head = entry ++this.length } shift() { if (this.length === 0) return const ret = this.head.data if (this.length === 1) this.head = this.tail = null else this.head = this.head.next --this.length return ret } clear() { this.head = this.tail = null this.length = 0 } join(s) { if (this.length === 0) return '' let p = this.head let ret = '' + p.data while ((p = p.next) !== null) ret += s + p.data return ret } concat(n) { if (this.length === 0) return Buffer.alloc(0) const ret = Buffer.allocUnsafe(n >>> 0) let p = this.head let i = 0 while (p) { TypedArrayPrototypeSet(ret, p.data, i) i += p.data.length p = p.next } return ret } // Consumes a specified amount of bytes or characters from the buffered data. consume(n, hasStrings) { const data = this.head.data if (n < data.length) { // `slice` is the same for buffers and strings. const slice = data.slice(0, n) this.head.data = data.slice(n) return slice } if (n === data.length) { // First chunk is a perfect match. return this.shift() } // Result spans more than one buffer. return hasStrings ? this._getString(n) : this._getBuffer(n) } first() { return this.head.data } *[SymbolIterator]() { for (let p = this.head; p; p = p.next) { yield p.data } } // Consumes a specified amount of characters from the buffered data. _getString(n) { let ret = '' let p = this.head let c = 0 do { const str = p.data if (n > str.length) { ret += str n -= str.length } else { if (n === str.length) { ret += str ++c if (p.next) this.head = p.next else this.head = this.tail = null } else { ret += StringPrototypeSlice(str, 0, n) this.head = p p.data = StringPrototypeSlice(str, n) } break } ++c } while ((p = p.next) !== null) this.length -= c return ret } // Consumes a specified amount of bytes from the buffered data. _getBuffer(n) { const ret = Buffer.allocUnsafe(n) const retLen = n let p = this.head let c = 0 do { const buf = p.data if (n > buf.length) { TypedArrayPrototypeSet(ret, buf, retLen - n) n -= buf.length } else { if (n === buf.length) { TypedArrayPrototypeSet(ret, buf, retLen - n) ++c if (p.next) this.head = p.next else this.head = this.tail = null } else { TypedArrayPrototypeSet(ret, new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n) this.head = p p.data = buf.slice(n) } break } ++c } while ((p = p.next) !== null) this.length -= c return ret } // Make sure the linked list only shows the minimal necessary information. [Symbol.for('nodejs.util.inspect.custom')](_, options) { return inspect(this, { ...options, // Only inspect one level. depth: 0, // It should not recurse. customInspect: false }) } } /***/ }), /***/ 7741: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { pipeline } = __nccwpck_require__(8219) const Duplex = __nccwpck_require__(8915) const { destroyer } = __nccwpck_require__(8403) const { isNodeStream, isReadable, isWritable, isWebStream, isTransformStream, isWritableStream, isReadableStream } = __nccwpck_require__(3892) const { AbortError, codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS } } = __nccwpck_require__(6786) const eos = __nccwpck_require__(1897) module.exports = function compose(...streams) { if (streams.length === 0) { throw new ERR_MISSING_ARGS('streams') } if (streams.length === 1) { return Duplex.from(streams[0]) } const orgStreams = [...streams] if (typeof streams[0] === 'function') { streams[0] = Duplex.from(streams[0]) } if (typeof streams[streams.length - 1] === 'function') { const idx = streams.length - 1 streams[idx] = Duplex.from(streams[idx]) } for (let n = 0; n < streams.length; ++n) { if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) { // TODO(ronag): Add checks for non streams. continue } if ( n < streams.length - 1 && !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n])) ) { throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be readable') } if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) { throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be writable') } } let ondrain let onfinish let onreadable let onclose let d function onfinished(err) { const cb = onclose onclose = null if (cb) { cb(err) } else if (err) { d.destroy(err) } else if (!readable && !writable) { d.destroy() } } const head = streams[0] const tail = pipeline(streams, onfinished) const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head)) const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail)) // TODO(ronag): Avoid double buffering. // Implement Writable/Readable/Duplex traits. // See, https://github.com/nodejs/node/pull/33515. d = new Duplex({ // TODO (ronag): highWaterMark? writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode), readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode), writable, readable }) if (writable) { if (isNodeStream(head)) { d._write = function (chunk, encoding, callback) { if (head.write(chunk, encoding)) { callback() } else { ondrain = callback } } d._final = function (callback) { head.end() onfinish = callback } head.on('drain', function () { if (ondrain) { const cb = ondrain ondrain = null cb() } }) } else if (isWebStream(head)) { const writable = isTransformStream(head) ? head.writable : head const writer = writable.getWriter() d._write = async function (chunk, encoding, callback) { try { await writer.ready writer.write(chunk).catch(() => {}) callback() } catch (err) { callback(err) } } d._final = async function (callback) { try { await writer.ready writer.close().catch(() => {}) onfinish = callback } catch (err) { callback(err) } } } const toRead = isTransformStream(tail) ? tail.readable : tail eos(toRead, () => { if (onfinish) { const cb = onfinish onfinish = null cb() } }) } if (readable) { if (isNodeStream(tail)) { tail.on('readable', function () { if (onreadable) { const cb = onreadable onreadable = null cb() } }) tail.on('end', function () { d.push(null) }) d._read = function () { while (true) { const buf = tail.read() if (buf === null) { onreadable = d._read return } if (!d.push(buf)) { return } } } } else if (isWebStream(tail)) { const readable = isTransformStream(tail) ? tail.readable : tail const reader = readable.getReader() d._read = async function () { while (true) { try { const { value, done } = await reader.read() if (!d.push(value)) { return } if (done) { d.push(null) return } } catch { return } } } } } d._destroy = function (err, callback) { if (!err && onclose !== null) { err = new AbortError() } onreadable = null ondrain = null onfinish = null if (onclose === null) { callback(err) } else { onclose = callback if (isNodeStream(tail)) { destroyer(tail, err) } } } return d } /***/ }), /***/ 8403: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ const { aggregateTwoErrors, codes: { ERR_MULTIPLE_CALLBACK }, AbortError } = __nccwpck_require__(6786) const { Symbol } = __nccwpck_require__(9229) const { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = __nccwpck_require__(3892) const kDestroy = Symbol('kDestroy') const kConstruct = Symbol('kConstruct') function checkError(err, w, r) { if (err) { // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 err.stack // eslint-disable-line no-unused-expressions if (w && !w.errored) { w.errored = err } if (r && !r.errored) { r.errored = err } } } // Backwards compat. cb() is undocumented and unused in core but // unfortunately might be used by modules. function destroy(err, cb) { const r = this._readableState const w = this._writableState // With duplex streams we use the writable side for state. const s = w || r if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { if (typeof cb === 'function') { cb() } return this } // We set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks checkError(err, w, r) if (w) { w.destroyed = true } if (r) { r.destroyed = true } // If still constructing then defer calling _destroy. if (!s.constructed) { this.once(kDestroy, function (er) { _destroy(this, aggregateTwoErrors(er, err), cb) }) } else { _destroy(this, err, cb) } return this } function _destroy(self, err, cb) { let called = false function onDestroy(err) { if (called) { return } called = true const r = self._readableState const w = self._writableState checkError(err, w, r) if (w) { w.closed = true } if (r) { r.closed = true } if (typeof cb === 'function') { cb(err) } if (err) { process.nextTick(emitErrorCloseNT, self, err) } else { process.nextTick(emitCloseNT, self) } } try { self._destroy(err || null, onDestroy) } catch (err) { onDestroy(err) } } function emitErrorCloseNT(self, err) { emitErrorNT(self, err) emitCloseNT(self) } function emitCloseNT(self) { const r = self._readableState const w = self._writableState if (w) { w.closeEmitted = true } if (r) { r.closeEmitted = true } if ((w !== null && w !== undefined && w.emitClose) || (r !== null && r !== undefined && r.emitClose)) { self.emit('close') } } function emitErrorNT(self, err) { const r = self._readableState const w = self._writableState if ((w !== null && w !== undefined && w.errorEmitted) || (r !== null && r !== undefined && r.errorEmitted)) { return } if (w) { w.errorEmitted = true } if (r) { r.errorEmitted = true } self.emit('error', err) } function undestroy() { const r = this._readableState const w = this._writableState if (r) { r.constructed = true r.closed = false r.closeEmitted = false r.destroyed = false r.errored = null r.errorEmitted = false r.reading = false r.ended = r.readable === false r.endEmitted = r.readable === false } if (w) { w.constructed = true w.destroyed = false w.closed = false w.closeEmitted = false w.errored = null w.errorEmitted = false w.finalCalled = false w.prefinished = false w.ended = w.writable === false w.ending = w.writable === false w.finished = w.writable === false } } function errorOrDestroy(stream, err, sync) { // We have tests that rely on errors being emitted // in the same tick, so changing this is semver major. // For now when you opt-in to autoDestroy we allow // the error to be emitted nextTick. In a future // semver major update we should change the default to this. const r = stream._readableState const w = stream._writableState if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { return this } if ((r !== null && r !== undefined && r.autoDestroy) || (w !== null && w !== undefined && w.autoDestroy)) stream.destroy(err) else if (err) { // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 err.stack // eslint-disable-line no-unused-expressions if (w && !w.errored) { w.errored = err } if (r && !r.errored) { r.errored = err } if (sync) { process.nextTick(emitErrorNT, stream, err) } else { emitErrorNT(stream, err) } } } function construct(stream, cb) { if (typeof stream._construct !== 'function') { return } const r = stream._readableState const w = stream._writableState if (r) { r.constructed = false } if (w) { w.constructed = false } stream.once(kConstruct, cb) if (stream.listenerCount(kConstruct) > 1) { // Duplex return } process.nextTick(constructNT, stream) } function constructNT(stream) { let called = false function onConstruct(err) { if (called) { errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK()) return } called = true const r = stream._readableState const w = stream._writableState const s = w || r if (r) { r.constructed = true } if (w) { w.constructed = true } if (s.destroyed) { stream.emit(kDestroy, err) } else if (err) { errorOrDestroy(stream, err, true) } else { process.nextTick(emitConstructNT, stream) } } try { stream._construct((err) => { process.nextTick(onConstruct, err) }) } catch (err) { process.nextTick(onConstruct, err) } } function emitConstructNT(stream) { stream.emit(kConstruct) } function isRequest(stream) { return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === 'function' } function emitCloseLegacy(stream) { stream.emit('close') } function emitErrorCloseLegacy(stream, err) { stream.emit('error', err) process.nextTick(emitCloseLegacy, stream) } // Normalize destroy for legacy. function destroyer(stream, err) { if (!stream || isDestroyed(stream)) { return } if (!err && !isFinished(stream)) { err = new AbortError() } // TODO: Remove isRequest branches. if (isServerRequest(stream)) { stream.socket = null stream.destroy(err) } else if (isRequest(stream)) { stream.abort() } else if (isRequest(stream.req)) { stream.req.abort() } else if (typeof stream.destroy === 'function') { stream.destroy(err) } else if (typeof stream.close === 'function') { // TODO: Don't lose err? stream.close() } else if (err) { process.nextTick(emitErrorCloseLegacy, stream, err) } else { process.nextTick(emitCloseLegacy, stream) } if (!stream.destroyed) { stream[kIsDestroyed] = true } } module.exports = { construct, destroyer, destroy, undestroy, errorOrDestroy } /***/ }), /***/ 8915: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototype inheritance, this class // prototypically inherits from Readable, and then parasitically from // Writable. const { ObjectDefineProperties, ObjectGetOwnPropertyDescriptor, ObjectKeys, ObjectSetPrototypeOf } = __nccwpck_require__(9229) module.exports = Duplex const Readable = __nccwpck_require__(9569) const Writable = __nccwpck_require__(9745) ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype) ObjectSetPrototypeOf(Duplex, Readable) { const keys = ObjectKeys(Writable.prototype) // Allow the keys array to be GC'ed. for (let i = 0; i < keys.length; i++) { const method = keys[i] if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method] } } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options) Readable.call(this, options) Writable.call(this, options) if (options) { this.allowHalfOpen = options.allowHalfOpen !== false if (options.readable === false) { this._readableState.readable = false this._readableState.ended = true this._readableState.endEmitted = true } if (options.writable === false) { this._writableState.writable = false this._writableState.ending = true this._writableState.ended = true this._writableState.finished = true } } else { this.allowHalfOpen = true } } ObjectDefineProperties(Duplex.prototype, { writable: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable') }, writableHighWaterMark: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark') }, writableObjectMode: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode') }, writableBuffer: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer') }, writableLength: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength') }, writableFinished: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished') }, writableCorked: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked') }, writableEnded: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded') }, writableNeedDrain: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain') }, destroyed: { __proto__: null, get() { if (this._readableState === undefined || this._writableState === undefined) { return false } return this._readableState.destroyed && this._writableState.destroyed }, set(value) { // Backward compatibility, the user is explicitly // managing destroyed. if (this._readableState && this._writableState) { this._readableState.destroyed = value this._writableState.destroyed = value } } } }) let webStreamsAdapters // Lazy to avoid circular references function lazyWebStreams() { if (webStreamsAdapters === undefined) webStreamsAdapters = {} return webStreamsAdapters } Duplex.fromWeb = function (pair, options) { return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options) } Duplex.toWeb = function (duplex) { return lazyWebStreams().newReadableWritablePairFromDuplex(duplex) } let duplexify Duplex.from = function (body) { if (!duplexify) { duplexify = __nccwpck_require__(8449) } return duplexify(body, 'body') } /***/ }), /***/ 8449: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ ;('use strict') const bufferModule = __nccwpck_require__(181) const { isReadable, isWritable, isIterable, isNodeStream, isReadableNodeStream, isWritableNodeStream, isDuplexNodeStream, isReadableStream, isWritableStream } = __nccwpck_require__(3892) const eos = __nccwpck_require__(1897) const { AbortError, codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE } } = __nccwpck_require__(6786) const { destroyer } = __nccwpck_require__(8403) const Duplex = __nccwpck_require__(8915) const Readable = __nccwpck_require__(9569) const Writable = __nccwpck_require__(9745) const { createDeferredPromise } = __nccwpck_require__(3165) const from = __nccwpck_require__(7617) const Blob = globalThis.Blob || bufferModule.Blob const isBlob = typeof Blob !== 'undefined' ? function isBlob(b) { return b instanceof Blob } : function isBlob(b) { return false } const AbortController = globalThis.AbortController || (__nccwpck_require__(7413).AbortController) const { FunctionPrototypeCall } = __nccwpck_require__(9229) // This is needed for pre node 17. class Duplexify extends Duplex { constructor(options) { super(options) // https://github.com/nodejs/node/pull/34385 if ((options === null || options === undefined ? undefined : options.readable) === false) { this._readableState.readable = false this._readableState.ended = true this._readableState.endEmitted = true } if ((options === null || options === undefined ? undefined : options.writable) === false) { this._writableState.writable = false this._writableState.ending = true this._writableState.ended = true this._writableState.finished = true } } } module.exports = function duplexify(body, name) { if (isDuplexNodeStream(body)) { return body } if (isReadableNodeStream(body)) { return _duplexify({ readable: body }) } if (isWritableNodeStream(body)) { return _duplexify({ writable: body }) } if (isNodeStream(body)) { return _duplexify({ writable: false, readable: false }) } if (isReadableStream(body)) { return _duplexify({ readable: Readable.fromWeb(body) }) } if (isWritableStream(body)) { return _duplexify({ writable: Writable.fromWeb(body) }) } if (typeof body === 'function') { const { value, write, final, destroy } = fromAsyncGen(body) if (isIterable(value)) { return from(Duplexify, value, { // TODO (ronag): highWaterMark? objectMode: true, write, final, destroy }) } const then = value === null || value === undefined ? undefined : value.then if (typeof then === 'function') { let d const promise = FunctionPrototypeCall( then, value, (val) => { if (val != null) { throw new ERR_INVALID_RETURN_VALUE('nully', 'body', val) } }, (err) => { destroyer(d, err) } ) return (d = new Duplexify({ // TODO (ronag): highWaterMark? objectMode: true, readable: false, write, final(cb) { final(async () => { try { await promise process.nextTick(cb, null) } catch (err) { process.nextTick(cb, err) } }) }, destroy })) } throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or AsyncFunction', name, value) } if (isBlob(body)) { return duplexify(body.arrayBuffer()) } if (isIterable(body)) { return from(Duplexify, body, { // TODO (ronag): highWaterMark? objectMode: true, writable: false }) } if ( isReadableStream(body === null || body === undefined ? undefined : body.readable) && isWritableStream(body === null || body === undefined ? undefined : body.writable) ) { return Duplexify.fromWeb(body) } if ( typeof (body === null || body === undefined ? undefined : body.writable) === 'object' || typeof (body === null || body === undefined ? undefined : body.readable) === 'object' ) { const readable = body !== null && body !== undefined && body.readable ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable) ? body === null || body === undefined ? undefined : body.readable : duplexify(body.readable) : undefined const writable = body !== null && body !== undefined && body.writable ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable) ? body === null || body === undefined ? undefined : body.writable : duplexify(body.writable) : undefined return _duplexify({ readable, writable }) } const then = body === null || body === undefined ? undefined : body.then if (typeof then === 'function') { let d FunctionPrototypeCall( then, body, (val) => { if (val != null) { d.push(val) } d.push(null) }, (err) => { destroyer(d, err) } ) return (d = new Duplexify({ objectMode: true, writable: false, read() {} })) } throw new ERR_INVALID_ARG_TYPE( name, [ 'Blob', 'ReadableStream', 'WritableStream', 'Stream', 'Iterable', 'AsyncIterable', 'Function', '{ readable, writable } pair', 'Promise' ], body ) } function fromAsyncGen(fn) { let { promise, resolve } = createDeferredPromise() const ac = new AbortController() const signal = ac.signal const value = fn( (async function* () { while (true) { const _promise = promise promise = null const { chunk, done, cb } = await _promise process.nextTick(cb) if (done) return if (signal.aborted) throw new AbortError(undefined, { cause: signal.reason }) ;({ promise, resolve } = createDeferredPromise()) yield chunk } })(), { signal } ) return { value, write(chunk, encoding, cb) { const _resolve = resolve resolve = null _resolve({ chunk, done: false, cb }) }, final(cb) { const _resolve = resolve resolve = null _resolve({ done: true, cb }) }, destroy(err, cb) { ac.abort() cb(err) } } } function _duplexify(pair) { const r = pair.readable && typeof pair.readable.read !== 'function' ? Readable.wrap(pair.readable) : pair.readable const w = pair.writable let readable = !!isReadable(r) let writable = !!isWritable(w) let ondrain let onfinish let onreadable let onclose let d function onfinished(err) { const cb = onclose onclose = null if (cb) { cb(err) } else if (err) { d.destroy(err) } } // TODO(ronag): Avoid double buffering. // Implement Writable/Readable/Duplex traits. // See, https://github.com/nodejs/node/pull/33515. d = new Duplexify({ // TODO (ronag): highWaterMark? readableObjectMode: !!(r !== null && r !== undefined && r.readableObjectMode), writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode), readable, writable }) if (writable) { eos(w, (err) => { writable = false if (err) { destroyer(r, err) } onfinished(err) }) d._write = function (chunk, encoding, callback) { if (w.write(chunk, encoding)) { callback() } else { ondrain = callback } } d._final = function (callback) { w.end() onfinish = callback } w.on('drain', function () { if (ondrain) { const cb = ondrain ondrain = null cb() } }) w.on('finish', function () { if (onfinish) { const cb = onfinish onfinish = null cb() } }) } if (readable) { eos(r, (err) => { readable = false if (err) { destroyer(r, err) } onfinished(err) }) r.on('readable', function () { if (onreadable) { const cb = onreadable onreadable = null cb() } }) r.on('end', function () { d.push(null) }) d._read = function () { while (true) { const buf = r.read() if (buf === null) { onreadable = d._read return } if (!d.push(buf)) { return } } } } d._destroy = function (err, callback) { if (!err && onclose !== null) { err = new AbortError() } onreadable = null ondrain = null onfinish = null if (onclose === null) { callback(err) } else { onclose = callback destroyer(w, err) destroyer(r, err) } } return d } /***/ }), /***/ 1897: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Ported from https://github.com/mafintosh/end-of-stream with // permission from the author, Mathias Buus (@mafintosh). /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ const { AbortError, codes } = __nccwpck_require__(6786) const { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes const { kEmptyObject, once } = __nccwpck_require__(3165) const { validateAbortSignal, validateFunction, validateObject, validateBoolean } = __nccwpck_require__(5988) const { Promise, PromisePrototypeThen, SymbolDispose } = __nccwpck_require__(9229) const { isClosed, isReadable, isReadableNodeStream, isReadableStream, isReadableFinished, isReadableErrored, isWritable, isWritableNodeStream, isWritableStream, isWritableFinished, isWritableErrored, isNodeStream, willEmitClose: _willEmitClose, kIsClosedPromise } = __nccwpck_require__(3892) let addAbortListener function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function' } const nop = () => {} function eos(stream, options, callback) { var _options$readable, _options$writable if (arguments.length === 2) { callback = options options = kEmptyObject } else if (options == null) { options = kEmptyObject } else { validateObject(options, 'options') } validateFunction(callback, 'callback') validateAbortSignal(options.signal, 'options.signal') callback = once(callback) if (isReadableStream(stream) || isWritableStream(stream)) { return eosWeb(stream, options, callback) } if (!isNodeStream(stream)) { throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) } const readable = (_options$readable = options.readable) !== null && _options$readable !== undefined ? _options$readable : isReadableNodeStream(stream) const writable = (_options$writable = options.writable) !== null && _options$writable !== undefined ? _options$writable : isWritableNodeStream(stream) const wState = stream._writableState const rState = stream._readableState const onlegacyfinish = () => { if (!stream.writable) { onfinish() } } // TODO (ronag): Improve soft detection to include core modules and // common ecosystem modules that do properly emit 'close' but fail // this generic check. let willEmitClose = _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable let writableFinished = isWritableFinished(stream, false) const onfinish = () => { writableFinished = true // Stream should not be destroyed here. If it is that // means that user space is doing something differently and // we cannot trust willEmitClose. if (stream.destroyed) { willEmitClose = false } if (willEmitClose && (!stream.readable || readable)) { return } if (!readable || readableFinished) { callback.call(stream) } } let readableFinished = isReadableFinished(stream, false) const onend = () => { readableFinished = true // Stream should not be destroyed here. If it is that // means that user space is doing something differently and // we cannot trust willEmitClose. if (stream.destroyed) { willEmitClose = false } if (willEmitClose && (!stream.writable || writable)) { return } if (!writable || writableFinished) { callback.call(stream) } } const onerror = (err) => { callback.call(stream, err) } let closed = isClosed(stream) const onclose = () => { closed = true const errored = isWritableErrored(stream) || isReadableErrored(stream) if (errored && typeof errored !== 'boolean') { return callback.call(stream, errored) } if (readable && !readableFinished && isReadableNodeStream(stream, true)) { if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) } if (writable && !writableFinished) { if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) } callback.call(stream) } const onclosed = () => { closed = true const errored = isWritableErrored(stream) || isReadableErrored(stream) if (errored && typeof errored !== 'boolean') { return callback.call(stream, errored) } callback.call(stream) } const onrequest = () => { stream.req.on('finish', onfinish) } if (isRequest(stream)) { stream.on('complete', onfinish) if (!willEmitClose) { stream.on('abort', onclose) } if (stream.req) { onrequest() } else { stream.on('request', onrequest) } } else if (writable && !wState) { // legacy streams stream.on('end', onlegacyfinish) stream.on('close', onlegacyfinish) } // Not all streams will emit 'close' after 'aborted'. if (!willEmitClose && typeof stream.aborted === 'boolean') { stream.on('aborted', onclose) } stream.on('end', onend) stream.on('finish', onfinish) if (options.error !== false) { stream.on('error', onerror) } stream.on('close', onclose) if (closed) { process.nextTick(onclose) } else if ( (wState !== null && wState !== undefined && wState.errorEmitted) || (rState !== null && rState !== undefined && rState.errorEmitted) ) { if (!willEmitClose) { process.nextTick(onclosed) } } else if ( !readable && (!willEmitClose || isReadable(stream)) && (writableFinished || isWritable(stream) === false) ) { process.nextTick(onclosed) } else if ( !writable && (!willEmitClose || isWritable(stream)) && (readableFinished || isReadable(stream) === false) ) { process.nextTick(onclosed) } else if (rState && stream.req && stream.aborted) { process.nextTick(onclosed) } const cleanup = () => { callback = nop stream.removeListener('aborted', onclose) stream.removeListener('complete', onfinish) stream.removeListener('abort', onclose) stream.removeListener('request', onrequest) if (stream.req) stream.req.removeListener('finish', onfinish) stream.removeListener('end', onlegacyfinish) stream.removeListener('close', onlegacyfinish) stream.removeListener('finish', onfinish) stream.removeListener('end', onend) stream.removeListener('error', onerror) stream.removeListener('close', onclose) } if (options.signal && !closed) { const abort = () => { // Keep it because cleanup removes it. const endCallback = callback cleanup() endCallback.call( stream, new AbortError(undefined, { cause: options.signal.reason }) ) } if (options.signal.aborted) { process.nextTick(abort) } else { addAbortListener = addAbortListener || (__nccwpck_require__(3165).addAbortListener) const disposable = addAbortListener(options.signal, abort) const originalCallback = callback callback = once((...args) => { disposable[SymbolDispose]() originalCallback.apply(stream, args) }) } } return cleanup } function eosWeb(stream, options, callback) { let isAborted = false let abort = nop if (options.signal) { abort = () => { isAborted = true callback.call( stream, new AbortError(undefined, { cause: options.signal.reason }) ) } if (options.signal.aborted) { process.nextTick(abort) } else { addAbortListener = addAbortListener || (__nccwpck_require__(3165).addAbortListener) const disposable = addAbortListener(options.signal, abort) const originalCallback = callback callback = once((...args) => { disposable[SymbolDispose]() originalCallback.apply(stream, args) }) } } const resolverFn = (...args) => { if (!isAborted) { process.nextTick(() => callback.apply(stream, args)) } } PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn) return nop } function finished(stream, opts) { var _opts let autoCleanup = false if (opts === null) { opts = kEmptyObject } if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup) { validateBoolean(opts.cleanup, 'cleanup') autoCleanup = opts.cleanup } return new Promise((resolve, reject) => { const cleanup = eos(stream, opts, (err) => { if (autoCleanup) { cleanup() } if (err) { reject(err) } else { resolve() } }) }) } module.exports = eos module.exports.finished = finished /***/ }), /***/ 7617: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ const { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = __nccwpck_require__(9229) const { Buffer } = __nccwpck_require__(181) const { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = (__nccwpck_require__(6786).codes) function from(Readable, iterable, opts) { let iterator if (typeof iterable === 'string' || iterable instanceof Buffer) { return new Readable({ objectMode: true, ...opts, read() { this.push(iterable) this.push(null) } }) } let isAsync if (iterable && iterable[SymbolAsyncIterator]) { isAsync = true iterator = iterable[SymbolAsyncIterator]() } else if (iterable && iterable[SymbolIterator]) { isAsync = false iterator = iterable[SymbolIterator]() } else { throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable) } const readable = new Readable({ objectMode: true, highWaterMark: 1, // TODO(ronag): What options should be allowed? ...opts }) // Flag to protect against _read // being called before last iteration completion. let reading = false readable._read = function () { if (!reading) { reading = true next() } } readable._destroy = function (error, cb) { PromisePrototypeThen( close(error), () => process.nextTick(cb, error), // nextTick is here in case cb throws (e) => process.nextTick(cb, e || error) ) } async function close(error) { const hadError = error !== undefined && error !== null const hasThrow = typeof iterator.throw === 'function' if (hadError && hasThrow) { const { value, done } = await iterator.throw(error) await value if (done) { return } } if (typeof iterator.return === 'function') { const { value } = await iterator.return() await value } } async function next() { for (;;) { try { const { value, done } = isAsync ? await iterator.next() : iterator.next() if (done) { readable.push(null) } else { const res = value && typeof value.then === 'function' ? await value : value if (res === null) { reading = false throw new ERR_STREAM_NULL_VALUES() } else if (readable.push(res)) { continue } else { reading = false } } } catch (err) { readable.destroy(err) } break } } return readable } module.exports = from /***/ }), /***/ 770: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { ArrayIsArray, ObjectSetPrototypeOf } = __nccwpck_require__(9229) const { EventEmitter: EE } = __nccwpck_require__(4434) function Stream(opts) { EE.call(this, opts) } ObjectSetPrototypeOf(Stream.prototype, EE.prototype) ObjectSetPrototypeOf(Stream, EE) Stream.prototype.pipe = function (dest, options) { const source = this function ondata(chunk) { if (dest.writable && dest.write(chunk) === false && source.pause) { source.pause() } } source.on('data', ondata) function ondrain() { if (source.readable && source.resume) { source.resume() } } dest.on('drain', ondrain) // If the 'end' option is not supplied, dest.end() will be called when // source gets the 'end' or 'close' events. Only dest.end() once. if (!dest._isStdio && (!options || options.end !== false)) { source.on('end', onend) source.on('close', onclose) } let didOnEnd = false function onend() { if (didOnEnd) return didOnEnd = true dest.end() } function onclose() { if (didOnEnd) return didOnEnd = true if (typeof dest.destroy === 'function') dest.destroy() } // Don't leave dangling pipes when there are errors. function onerror(er) { cleanup() if (EE.listenerCount(this, 'error') === 0) { this.emit('error', er) } } prependListener(source, 'error', onerror) prependListener(dest, 'error', onerror) // Remove all the event listeners that were added. function cleanup() { source.removeListener('data', ondata) dest.removeListener('drain', ondrain) source.removeListener('end', onend) source.removeListener('close', onclose) source.removeListener('error', onerror) dest.removeListener('error', onerror) source.removeListener('end', cleanup) source.removeListener('close', cleanup) dest.removeListener('close', cleanup) } source.on('end', cleanup) source.on('close', cleanup) dest.on('close', cleanup) dest.emit('pipe', source) // Allow for unix-like usage: A.pipe(B).pipe(C) return dest } function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn) // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn) else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn) else emitter._events[event] = [fn, emitter._events[event]] } module.exports = { Stream, prependListener } /***/ }), /***/ 7080: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const AbortController = globalThis.AbortController || (__nccwpck_require__(7413).AbortController) const { codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE }, AbortError } = __nccwpck_require__(6786) const { validateAbortSignal, validateInteger, validateObject } = __nccwpck_require__(5988) const kWeakHandler = (__nccwpck_require__(9229).Symbol)('kWeak') const kResistStopPropagation = (__nccwpck_require__(9229).Symbol)('kResistStopPropagation') const { finished } = __nccwpck_require__(1897) const staticCompose = __nccwpck_require__(7741) const { addAbortSignalNoValidate } = __nccwpck_require__(6942) const { isWritable, isNodeStream } = __nccwpck_require__(3892) const { deprecate } = __nccwpck_require__(3165) const { ArrayPrototypePush, Boolean, MathFloor, Number, NumberIsNaN, Promise, PromiseReject, PromiseResolve, PromisePrototypeThen, Symbol } = __nccwpck_require__(9229) const kEmpty = Symbol('kEmpty') const kEof = Symbol('kEof') function compose(stream, options) { if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } if (isNodeStream(stream) && !isWritable(stream)) { throw new ERR_INVALID_ARG_VALUE('stream', stream, 'must be writable') } const composedStream = staticCompose(this, stream) if (options !== null && options !== undefined && options.signal) { // Not validating as we already validated before addAbortSignalNoValidate(options.signal, composedStream) } return composedStream } function map(fn, options) { if (typeof fn !== 'function') { throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) } if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } let concurrency = 1 if ((options === null || options === undefined ? undefined : options.concurrency) != null) { concurrency = MathFloor(options.concurrency) } let highWaterMark = concurrency - 1 if ((options === null || options === undefined ? undefined : options.highWaterMark) != null) { highWaterMark = MathFloor(options.highWaterMark) } validateInteger(concurrency, 'options.concurrency', 1) validateInteger(highWaterMark, 'options.highWaterMark', 0) highWaterMark += concurrency return async function* map() { const signal = (__nccwpck_require__(3165).AbortSignalAny)( [options === null || options === undefined ? undefined : options.signal].filter(Boolean) ) const stream = this const queue = [] const signalOpt = { signal } let next let resume let done = false let cnt = 0 function onCatch() { done = true afterItemProcessed() } function afterItemProcessed() { cnt -= 1 maybeResume() } function maybeResume() { if (resume && !done && cnt < concurrency && queue.length < highWaterMark) { resume() resume = null } } async function pump() { try { for await (let val of stream) { if (done) { return } if (signal.aborted) { throw new AbortError() } try { val = fn(val, signalOpt) if (val === kEmpty) { continue } val = PromiseResolve(val) } catch (err) { val = PromiseReject(err) } cnt += 1 PromisePrototypeThen(val, afterItemProcessed, onCatch) queue.push(val) if (next) { next() next = null } if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) { await new Promise((resolve) => { resume = resolve }) } } queue.push(kEof) } catch (err) { const val = PromiseReject(err) PromisePrototypeThen(val, afterItemProcessed, onCatch) queue.push(val) } finally { done = true if (next) { next() next = null } } } pump() try { while (true) { while (queue.length > 0) { const val = await queue[0] if (val === kEof) { return } if (signal.aborted) { throw new AbortError() } if (val !== kEmpty) { yield val } queue.shift() maybeResume() } await new Promise((resolve) => { next = resolve }) } } finally { done = true if (resume) { resume() resume = null } } }.call(this) } function asIndexedPairs(options = undefined) { if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } return async function* asIndexedPairs() { let index = 0 for await (const val of this) { var _options$signal if ( options !== null && options !== undefined && (_options$signal = options.signal) !== null && _options$signal !== undefined && _options$signal.aborted ) { throw new AbortError({ cause: options.signal.reason }) } yield [index++, val] } }.call(this) } async function some(fn, options = undefined) { for await (const unused of filter.call(this, fn, options)) { return true } return false } async function every(fn, options = undefined) { if (typeof fn !== 'function') { throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) } // https://en.wikipedia.org/wiki/De_Morgan%27s_laws return !(await some.call( this, async (...args) => { return !(await fn(...args)) }, options )) } async function find(fn, options) { for await (const result of filter.call(this, fn, options)) { return result } return undefined } async function forEach(fn, options) { if (typeof fn !== 'function') { throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) } async function forEachFn(value, options) { await fn(value, options) return kEmpty } // eslint-disable-next-line no-unused-vars for await (const unused of map.call(this, forEachFn, options)); } function filter(fn, options) { if (typeof fn !== 'function') { throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) } async function filterFn(value, options) { if (await fn(value, options)) { return value } return kEmpty } return map.call(this, filterFn, options) } // Specific to provide better error to reduce since the argument is only // missing if the stream has no items in it - but the code is still appropriate class ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS { constructor() { super('reduce') this.message = 'Reduce of an empty stream requires an initial value' } } async function reduce(reducer, initialValue, options) { var _options$signal2 if (typeof reducer !== 'function') { throw new ERR_INVALID_ARG_TYPE('reducer', ['Function', 'AsyncFunction'], reducer) } if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } let hasInitialValue = arguments.length > 1 if ( options !== null && options !== undefined && (_options$signal2 = options.signal) !== null && _options$signal2 !== undefined && _options$signal2.aborted ) { const err = new AbortError(undefined, { cause: options.signal.reason }) this.once('error', () => {}) // The error is already propagated await finished(this.destroy(err)) throw err } const ac = new AbortController() const signal = ac.signal if (options !== null && options !== undefined && options.signal) { const opts = { once: true, [kWeakHandler]: this, [kResistStopPropagation]: true } options.signal.addEventListener('abort', () => ac.abort(), opts) } let gotAnyItemFromStream = false try { for await (const value of this) { var _options$signal3 gotAnyItemFromStream = true if ( options !== null && options !== undefined && (_options$signal3 = options.signal) !== null && _options$signal3 !== undefined && _options$signal3.aborted ) { throw new AbortError() } if (!hasInitialValue) { initialValue = value hasInitialValue = true } else { initialValue = await reducer(initialValue, value, { signal }) } } if (!gotAnyItemFromStream && !hasInitialValue) { throw new ReduceAwareErrMissingArgs() } } finally { ac.abort() } return initialValue } async function toArray(options) { if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } const result = [] for await (const val of this) { var _options$signal4 if ( options !== null && options !== undefined && (_options$signal4 = options.signal) !== null && _options$signal4 !== undefined && _options$signal4.aborted ) { throw new AbortError(undefined, { cause: options.signal.reason }) } ArrayPrototypePush(result, val) } return result } function flatMap(fn, options) { const values = map.call(this, fn, options) return async function* flatMap() { for await (const val of values) { yield* val } }.call(this) } function toIntegerOrInfinity(number) { // We coerce here to align with the spec // https://github.com/tc39/proposal-iterator-helpers/issues/169 number = Number(number) if (NumberIsNaN(number)) { return 0 } if (number < 0) { throw new ERR_OUT_OF_RANGE('number', '>= 0', number) } return number } function drop(number, options = undefined) { if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } number = toIntegerOrInfinity(number) return async function* drop() { var _options$signal5 if ( options !== null && options !== undefined && (_options$signal5 = options.signal) !== null && _options$signal5 !== undefined && _options$signal5.aborted ) { throw new AbortError() } for await (const val of this) { var _options$signal6 if ( options !== null && options !== undefined && (_options$signal6 = options.signal) !== null && _options$signal6 !== undefined && _options$signal6.aborted ) { throw new AbortError() } if (number-- <= 0) { yield val } } }.call(this) } function take(number, options = undefined) { if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } number = toIntegerOrInfinity(number) return async function* take() { var _options$signal7 if ( options !== null && options !== undefined && (_options$signal7 = options.signal) !== null && _options$signal7 !== undefined && _options$signal7.aborted ) { throw new AbortError() } for await (const val of this) { var _options$signal8 if ( options !== null && options !== undefined && (_options$signal8 = options.signal) !== null && _options$signal8 !== undefined && _options$signal8.aborted ) { throw new AbortError() } if (number-- > 0) { yield val } // Don't get another item from iterator in case we reached the end if (number <= 0) { return } } }.call(this) } module.exports.streamReturningOperators = { asIndexedPairs: deprecate(asIndexedPairs, 'readable.asIndexedPairs will be removed in a future version.'), drop, filter, flatMap, map, take, compose } module.exports.promiseReturningOperators = { every, forEach, reduce, toArray, some, find } /***/ }), /***/ 5023: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. const { ObjectSetPrototypeOf } = __nccwpck_require__(9229) module.exports = PassThrough const Transform = __nccwpck_require__(9253) ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype) ObjectSetPrototypeOf(PassThrough, Transform) function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options) Transform.call(this, options) } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk) } /***/ }), /***/ 8219: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ // Ported from https://github.com/mafintosh/pump with // permission from the author, Mathias Buus (@mafintosh). ;('use strict') const { ArrayIsArray, Promise, SymbolAsyncIterator, SymbolDispose } = __nccwpck_require__(9229) const eos = __nccwpck_require__(1897) const { once } = __nccwpck_require__(3165) const destroyImpl = __nccwpck_require__(8403) const Duplex = __nccwpck_require__(8915) const { aggregateTwoErrors, codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE, ERR_MISSING_ARGS, ERR_STREAM_DESTROYED, ERR_STREAM_PREMATURE_CLOSE }, AbortError } = __nccwpck_require__(6786) const { validateFunction, validateAbortSignal } = __nccwpck_require__(5988) const { isIterable, isReadable, isReadableNodeStream, isNodeStream, isTransformStream, isWebStream, isReadableStream, isReadableFinished } = __nccwpck_require__(3892) const AbortController = globalThis.AbortController || (__nccwpck_require__(7413).AbortController) let PassThrough let Readable let addAbortListener function destroyer(stream, reading, writing) { let finished = false stream.on('close', () => { finished = true }) const cleanup = eos( stream, { readable: reading, writable: writing }, (err) => { finished = !err } ) return { destroy: (err) => { if (finished) return finished = true destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED('pipe')) }, cleanup } } function popCallback(streams) { // Streams should never be an empty array. It should always contain at least // a single stream. Therefore optimize for the average case instead of // checking for length === 0 as well. validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]') return streams.pop() } function makeAsyncIterable(val) { if (isIterable(val)) { return val } else if (isReadableNodeStream(val)) { // Legacy streams are not Iterable. return fromReadable(val) } throw new ERR_INVALID_ARG_TYPE('val', ['Readable', 'Iterable', 'AsyncIterable'], val) } async function* fromReadable(val) { if (!Readable) { Readable = __nccwpck_require__(9569) } yield* Readable.prototype[SymbolAsyncIterator].call(val) } async function pumpToNode(iterable, writable, finish, { end }) { let error let onresolve = null const resume = (err) => { if (err) { error = err } if (onresolve) { const callback = onresolve onresolve = null callback() } } const wait = () => new Promise((resolve, reject) => { if (error) { reject(error) } else { onresolve = () => { if (error) { reject(error) } else { resolve() } } } }) writable.on('drain', resume) const cleanup = eos( writable, { readable: false }, resume ) try { if (writable.writableNeedDrain) { await wait() } for await (const chunk of iterable) { if (!writable.write(chunk)) { await wait() } } if (end) { writable.end() await wait() } finish() } catch (err) { finish(error !== err ? aggregateTwoErrors(error, err) : err) } finally { cleanup() writable.off('drain', resume) } } async function pumpToWeb(readable, writable, finish, { end }) { if (isTransformStream(writable)) { writable = writable.writable } // https://streams.spec.whatwg.org/#example-manual-write-with-backpressure const writer = writable.getWriter() try { for await (const chunk of readable) { await writer.ready writer.write(chunk).catch(() => {}) } await writer.ready if (end) { await writer.close() } finish() } catch (err) { try { await writer.abort(err) finish(err) } catch (err) { finish(err) } } } function pipeline(...streams) { return pipelineImpl(streams, once(popCallback(streams))) } function pipelineImpl(streams, callback, opts) { if (streams.length === 1 && ArrayIsArray(streams[0])) { streams = streams[0] } if (streams.length < 2) { throw new ERR_MISSING_ARGS('streams') } const ac = new AbortController() const signal = ac.signal const outerSignal = opts === null || opts === undefined ? undefined : opts.signal // Need to cleanup event listeners if last stream is readable // https://github.com/nodejs/node/issues/35452 const lastStreamCleanup = [] validateAbortSignal(outerSignal, 'options.signal') function abort() { finishImpl(new AbortError()) } addAbortListener = addAbortListener || (__nccwpck_require__(3165).addAbortListener) let disposable if (outerSignal) { disposable = addAbortListener(outerSignal, abort) } let error let value const destroys = [] let finishCount = 0 function finish(err) { finishImpl(err, --finishCount === 0) } function finishImpl(err, final) { var _disposable if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) { error = err } if (!error && !final) { return } while (destroys.length) { destroys.shift()(error) } ;(_disposable = disposable) === null || _disposable === undefined ? undefined : _disposable[SymbolDispose]() ac.abort() if (final) { if (!error) { lastStreamCleanup.forEach((fn) => fn()) } process.nextTick(callback, error, value) } } let ret for (let i = 0; i < streams.length; i++) { const stream = streams[i] const reading = i < streams.length - 1 const writing = i > 0 const end = reading || (opts === null || opts === undefined ? undefined : opts.end) !== false const isLastStream = i === streams.length - 1 if (isNodeStream(stream)) { if (end) { const { destroy, cleanup } = destroyer(stream, reading, writing) destroys.push(destroy) if (isReadable(stream) && isLastStream) { lastStreamCleanup.push(cleanup) } } // Catch stream errors that occur after pipe/pump has completed. function onError(err) { if (err && err.name !== 'AbortError' && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { finish(err) } } stream.on('error', onError) if (isReadable(stream) && isLastStream) { lastStreamCleanup.push(() => { stream.removeListener('error', onError) }) } } if (i === 0) { if (typeof stream === 'function') { ret = stream({ signal }) if (!isIterable(ret)) { throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or Stream', 'source', ret) } } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) { ret = stream } else { ret = Duplex.from(stream) } } else if (typeof stream === 'function') { if (isTransformStream(ret)) { var _ret ret = makeAsyncIterable((_ret = ret) === null || _ret === undefined ? undefined : _ret.readable) } else { ret = makeAsyncIterable(ret) } ret = stream(ret, { signal }) if (reading) { if (!isIterable(ret, true)) { throw new ERR_INVALID_RETURN_VALUE('AsyncIterable', `transform[${i - 1}]`, ret) } } else { var _ret2 if (!PassThrough) { PassThrough = __nccwpck_require__(5023) } // If the last argument to pipeline is not a stream // we must create a proxy stream so that pipeline(...) // always returns a stream which can be further // composed through `.pipe(stream)`. const pt = new PassThrough({ objectMode: true }) // Handle Promises/A+ spec, `then` could be a getter that throws on // second use. const then = (_ret2 = ret) === null || _ret2 === undefined ? undefined : _ret2.then if (typeof then === 'function') { finishCount++ then.call( ret, (val) => { value = val if (val != null) { pt.write(val) } if (end) { pt.end() } process.nextTick(finish) }, (err) => { pt.destroy(err) process.nextTick(finish, err) } ) } else if (isIterable(ret, true)) { finishCount++ pumpToNode(ret, pt, finish, { end }) } else if (isReadableStream(ret) || isTransformStream(ret)) { const toRead = ret.readable || ret finishCount++ pumpToNode(toRead, pt, finish, { end }) } else { throw new ERR_INVALID_RETURN_VALUE('AsyncIterable or Promise', 'destination', ret) } ret = pt const { destroy, cleanup } = destroyer(ret, false, true) destroys.push(destroy) if (isLastStream) { lastStreamCleanup.push(cleanup) } } } else if (isNodeStream(stream)) { if (isReadableNodeStream(ret)) { finishCount += 2 const cleanup = pipe(ret, stream, finish, { end }) if (isReadable(stream) && isLastStream) { lastStreamCleanup.push(cleanup) } } else if (isTransformStream(ret) || isReadableStream(ret)) { const toRead = ret.readable || ret finishCount++ pumpToNode(toRead, stream, finish, { end }) } else if (isIterable(ret)) { finishCount++ pumpToNode(ret, stream, finish, { end }) } else { throw new ERR_INVALID_ARG_TYPE( 'val', ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'], ret ) } ret = stream } else if (isWebStream(stream)) { if (isReadableNodeStream(ret)) { finishCount++ pumpToWeb(makeAsyncIterable(ret), stream, finish, { end }) } else if (isReadableStream(ret) || isIterable(ret)) { finishCount++ pumpToWeb(ret, stream, finish, { end }) } else if (isTransformStream(ret)) { finishCount++ pumpToWeb(ret.readable, stream, finish, { end }) } else { throw new ERR_INVALID_ARG_TYPE( 'val', ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'], ret ) } ret = stream } else { ret = Duplex.from(stream) } } if ( (signal !== null && signal !== undefined && signal.aborted) || (outerSignal !== null && outerSignal !== undefined && outerSignal.aborted) ) { process.nextTick(abort) } return ret } function pipe(src, dst, finish, { end }) { let ended = false dst.on('close', () => { if (!ended) { // Finish if the destination closes before the source has completed. finish(new ERR_STREAM_PREMATURE_CLOSE()) } }) src.pipe(dst, { end: false }) // If end is true we already will have a listener to end dst. if (end) { // Compat. Before node v10.12.0 stdio used to throw an error so // pipe() did/does not end() stdio destinations. // Now they allow it but "secretly" don't close the underlying fd. function endFn() { ended = true dst.end() } if (isReadableFinished(src)) { // End the destination if the source has already ended. process.nextTick(endFn) } else { src.once('end', endFn) } } else { finish() } eos( src, { readable: true, writable: false }, (err) => { const rState = src._readableState if ( err && err.code === 'ERR_STREAM_PREMATURE_CLOSE' && rState && rState.ended && !rState.errored && !rState.errorEmitted ) { // Some readable streams will emit 'close' before 'end'. However, since // this is on the readable side 'end' should still be emitted if the // stream has been ended and no error emitted. This should be allowed in // favor of backwards compatibility. Since the stream is piped to a // destination this should not result in any observable difference. // We don't need to check if this is a writable premature close since // eos will only fail with premature close on the reading side for // duplex streams. src.once('end', finish).once('error', finish) } else { finish(err) } } ) return eos( dst, { readable: false, writable: true }, finish ) } module.exports = { pipelineImpl, pipeline } /***/ }), /***/ 9569: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ const { ArrayPrototypeIndexOf, NumberIsInteger, NumberIsNaN, NumberParseInt, ObjectDefineProperties, ObjectKeys, ObjectSetPrototypeOf, Promise, SafeSet, SymbolAsyncDispose, SymbolAsyncIterator, Symbol } = __nccwpck_require__(9229) module.exports = Readable Readable.ReadableState = ReadableState const { EventEmitter: EE } = __nccwpck_require__(4434) const { Stream, prependListener } = __nccwpck_require__(770) const { Buffer } = __nccwpck_require__(181) const { addAbortSignal } = __nccwpck_require__(6942) const eos = __nccwpck_require__(1897) let debug = (__nccwpck_require__(3165).debuglog)('stream', (fn) => { debug = fn }) const BufferList = __nccwpck_require__(7406) const destroyImpl = __nccwpck_require__(8403) const { getHighWaterMark, getDefaultHighWaterMark } = __nccwpck_require__(4124) const { aggregateTwoErrors, codes: { ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED, ERR_OUT_OF_RANGE, ERR_STREAM_PUSH_AFTER_EOF, ERR_STREAM_UNSHIFT_AFTER_END_EVENT }, AbortError } = __nccwpck_require__(6786) const { validateObject } = __nccwpck_require__(5988) const kPaused = Symbol('kPaused') const { StringDecoder } = __nccwpck_require__(6660) const from = __nccwpck_require__(7617) ObjectSetPrototypeOf(Readable.prototype, Stream.prototype) ObjectSetPrototypeOf(Readable, Stream) const nop = () => {} const { errorOrDestroy } = destroyImpl const kObjectMode = 1 << 0 const kEnded = 1 << 1 const kEndEmitted = 1 << 2 const kReading = 1 << 3 const kConstructed = 1 << 4 const kSync = 1 << 5 const kNeedReadable = 1 << 6 const kEmittedReadable = 1 << 7 const kReadableListening = 1 << 8 const kResumeScheduled = 1 << 9 const kErrorEmitted = 1 << 10 const kEmitClose = 1 << 11 const kAutoDestroy = 1 << 12 const kDestroyed = 1 << 13 const kClosed = 1 << 14 const kCloseEmitted = 1 << 15 const kMultiAwaitDrain = 1 << 16 const kReadingMore = 1 << 17 const kDataEmitted = 1 << 18 // TODO(benjamingr) it is likely slower to do it this way than with free functions function makeBitMapDescriptor(bit) { return { enumerable: false, get() { return (this.state & bit) !== 0 }, set(value) { if (value) this.state |= bit else this.state &= ~bit } } } ObjectDefineProperties(ReadableState.prototype, { objectMode: makeBitMapDescriptor(kObjectMode), ended: makeBitMapDescriptor(kEnded), endEmitted: makeBitMapDescriptor(kEndEmitted), reading: makeBitMapDescriptor(kReading), // Stream is still being constructed and cannot be // destroyed until construction finished or failed. // Async construction is opt in, therefore we start as // constructed. constructed: makeBitMapDescriptor(kConstructed), // A flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. sync: makeBitMapDescriptor(kSync), // Whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. needReadable: makeBitMapDescriptor(kNeedReadable), emittedReadable: makeBitMapDescriptor(kEmittedReadable), readableListening: makeBitMapDescriptor(kReadableListening), resumeScheduled: makeBitMapDescriptor(kResumeScheduled), // True if the error was already emitted and should not be thrown again. errorEmitted: makeBitMapDescriptor(kErrorEmitted), emitClose: makeBitMapDescriptor(kEmitClose), autoDestroy: makeBitMapDescriptor(kAutoDestroy), // Has it been destroyed. destroyed: makeBitMapDescriptor(kDestroyed), // Indicates whether the stream has finished destroying. closed: makeBitMapDescriptor(kClosed), // True if close has been emitted or would have been emitted // depending on emitClose. closeEmitted: makeBitMapDescriptor(kCloseEmitted), multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain), // If true, a maybeReadMore has been scheduled. readingMore: makeBitMapDescriptor(kReadingMore), dataEmitted: makeBitMapDescriptor(kDataEmitted) }) function ReadableState(options, stream, isDuplex) { // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof __nccwpck_require__(8915) // Bit map field to store ReadableState more effciently with 1 bit per field // instead of a V8 slot per field. this.state = kEmitClose | kAutoDestroy | kConstructed | kSync // Object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away. if (options && options.objectMode) this.state |= kObjectMode if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode // The point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" this.highWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex) : getDefaultHighWaterMark(false) // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift(). this.buffer = new BufferList() this.length = 0 this.pipes = [] this.flowing = null this[kPaused] = null // Should close be emitted on destroy. Defaults to true. if (options && options.emitClose === false) this.state &= ~kEmitClose // Should .destroy() be called after 'end' (and potentially 'finish'). if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy // Indicates whether the stream has errored. When true no further // _read calls, 'data' or 'readable' events should occur. This is needed // since when autoDestroy is disabled we need a way to tell whether the // stream has failed. this.errored = null // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = (options && options.defaultEncoding) || 'utf8' // Ref the piped dest which we need a drain event on it // type: null | Writable | Set. this.awaitDrainWriters = null this.decoder = null this.encoding = null if (options && options.encoding) { this.decoder = new StringDecoder(options.encoding) this.encoding = options.encoding } } function Readable(options) { if (!(this instanceof Readable)) return new Readable(options) // Checking for a Stream.Duplex instance is faster here instead of inside // the ReadableState constructor, at least with V8 6.5. const isDuplex = this instanceof __nccwpck_require__(8915) this._readableState = new ReadableState(options, this, isDuplex) if (options) { if (typeof options.read === 'function') this._read = options.read if (typeof options.destroy === 'function') this._destroy = options.destroy if (typeof options.construct === 'function') this._construct = options.construct if (options.signal && !isDuplex) addAbortSignal(options.signal, this) } Stream.call(this, options) destroyImpl.construct(this, () => { if (this._readableState.needReadable) { maybeReadMore(this, this._readableState) } }) } Readable.prototype.destroy = destroyImpl.destroy Readable.prototype._undestroy = destroyImpl.undestroy Readable.prototype._destroy = function (err, cb) { cb(err) } Readable.prototype[EE.captureRejectionSymbol] = function (err) { this.destroy(err) } Readable.prototype[SymbolAsyncDispose] = function () { let error if (!this.destroyed) { error = this.readableEnded ? null : new AbortError() this.destroy(error) } return new Promise((resolve, reject) => eos(this, (err) => (err && err !== error ? reject(err) : resolve(null)))) } // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { return readableAddChunk(this, chunk, encoding, false) } // Unshift should *always* be something directly out of read(). Readable.prototype.unshift = function (chunk, encoding) { return readableAddChunk(this, chunk, encoding, true) } function readableAddChunk(stream, chunk, encoding, addToFront) { debug('readableAddChunk', chunk) const state = stream._readableState let err if ((state.state & kObjectMode) === 0) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding if (state.encoding !== encoding) { if (addToFront && state.encoding) { // When unshifting, if state.encoding is set, we have to save // the string in the BufferList with the state encoding. chunk = Buffer.from(chunk, encoding).toString(state.encoding) } else { chunk = Buffer.from(chunk, encoding) encoding = '' } } } else if (chunk instanceof Buffer) { encoding = '' } else if (Stream._isUint8Array(chunk)) { chunk = Stream._uint8ArrayToBuffer(chunk) encoding = '' } else if (chunk != null) { err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk) } } if (err) { errorOrDestroy(stream, err) } else if (chunk === null) { state.state &= ~kReading onEofChunk(stream, state) } else if ((state.state & kObjectMode) !== 0 || (chunk && chunk.length > 0)) { if (addToFront) { if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()) else if (state.destroyed || state.errored) return false else addChunk(stream, state, chunk, true) } else if (state.ended) { errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()) } else if (state.destroyed || state.errored) { return false } else { state.state &= ~kReading if (state.decoder && !encoding) { chunk = state.decoder.write(chunk) if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false) else maybeReadMore(stream, state) } else { addChunk(stream, state, chunk, false) } } } else if (!addToFront) { state.state &= ~kReading maybeReadMore(stream, state) } // We can push more data if we are below the highWaterMark. // Also, if we have no data yet, we can stand some more bytes. // This is to work around cases where hwm=0, such as the repl. return !state.ended && (state.length < state.highWaterMark || state.length === 0) } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount('data') > 0) { // Use the guard to avoid creating `Set()` repeatedly // when we have multiple pipes. if ((state.state & kMultiAwaitDrain) !== 0) { state.awaitDrainWriters.clear() } else { state.awaitDrainWriters = null } state.dataEmitted = true stream.emit('data', chunk) } else { // Update the buffer info. state.length += state.objectMode ? 1 : chunk.length if (addToFront) state.buffer.unshift(chunk) else state.buffer.push(chunk) if ((state.state & kNeedReadable) !== 0) emitReadable(stream) } maybeReadMore(stream, state) } Readable.prototype.isPaused = function () { const state = this._readableState return state[kPaused] === true || state.flowing === false } // Backwards compatibility. Readable.prototype.setEncoding = function (enc) { const decoder = new StringDecoder(enc) this._readableState.decoder = decoder // If setEncoding(null), decoder.encoding equals utf8. this._readableState.encoding = this._readableState.decoder.encoding const buffer = this._readableState.buffer // Iterate over current buffer to convert already stored Buffers: let content = '' for (const data of buffer) { content += decoder.write(data) } buffer.clear() if (content !== '') buffer.push(content) this._readableState.length = content.length return this } // Don't raise the hwm > 1GB. const MAX_HWM = 0x40000000 function computeNewHighWaterMark(n) { if (n > MAX_HWM) { throw new ERR_OUT_OF_RANGE('size', '<= 1GiB', n) } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts. n-- n |= n >>> 1 n |= n >>> 2 n |= n >>> 4 n |= n >>> 8 n |= n >>> 16 n++ } return n } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || (state.length === 0 && state.ended)) return 0 if ((state.state & kObjectMode) !== 0) return 1 if (NumberIsNaN(n)) { // Only flow one buffer at a time. if (state.flowing && state.length) return state.buffer.first().length return state.length } if (n <= state.length) return n return state.ended ? state.length : 0 } // You can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n) // Same as parseInt(undefined, 10), however V8 7.3 performance regressed // in this scenario, so we are doing it manually. if (n === undefined) { n = NaN } else if (!NumberIsInteger(n)) { n = NumberParseInt(n, 10) } const state = this._readableState const nOrig = n // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n) if (n !== 0) state.state &= ~kEmittedReadable // If we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if ( n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended) ) { debug('read: emitReadable', state.length, state.ended) if (state.length === 0 && state.ended) endReadable(this) else emitReadable(this) return null } n = howMuchToRead(n, state) // If we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this) return null } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. let doRead = (state.state & kNeedReadable) !== 0 debug('need readable', doRead) // If we currently have less than the highWaterMark, then also read some. if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true debug('length less than watermark', doRead) } // However, if we've ended, then there's no point, if we're already // reading, then it's unnecessary, if we're constructing we have to wait, // and if we're destroyed or errored, then it's not allowed, if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) { doRead = false debug('reading, ended or constructing', doRead) } else if (doRead) { debug('do read') state.state |= kReading | kSync // If the length is currently zero, then we *need* a readable event. if (state.length === 0) state.state |= kNeedReadable // Call internal read method try { this._read(state.highWaterMark) } catch (err) { errorOrDestroy(this, err) } state.state &= ~kSync // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state) } let ret if (n > 0) ret = fromList(n, state) else ret = null if (ret === null) { state.needReadable = state.length <= state.highWaterMark n = 0 } else { state.length -= n if (state.multiAwaitDrain) { state.awaitDrainWriters.clear() } else { state.awaitDrainWriters = null } } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this) } if (ret !== null && !state.errorEmitted && !state.closeEmitted) { state.dataEmitted = true this.emit('data', ret) } return ret } function onEofChunk(stream, state) { debug('onEofChunk') if (state.ended) return if (state.decoder) { const chunk = state.decoder.end() if (chunk && chunk.length) { state.buffer.push(chunk) state.length += state.objectMode ? 1 : chunk.length } } state.ended = true if (state.sync) { // If we are sync, wait until next tick to emit the data. // Otherwise we risk emitting data in the flow() // the readable code triggers during a read() call. emitReadable(stream) } else { // Emit 'readable' now to make sure it gets picked up. state.needReadable = false state.emittedReadable = true // We have to emit readable now that we are EOF. Modules // in the ecosystem (e.g. dicer) rely on this event being sync. emitReadable_(stream) } } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { const state = stream._readableState debug('emitReadable', state.needReadable, state.emittedReadable) state.needReadable = false if (!state.emittedReadable) { debug('emitReadable', state.flowing) state.emittedReadable = true process.nextTick(emitReadable_, stream) } } function emitReadable_(stream) { const state = stream._readableState debug('emitReadable_', state.destroyed, state.length, state.ended) if (!state.destroyed && !state.errored && (state.length || state.ended)) { stream.emit('readable') state.emittedReadable = false } // The stream needs another readable event if: // 1. It is not flowing, as the flow mechanism will take // care of it. // 2. It is not ended. // 3. It is below the highWaterMark, so we can schedule // another readable later. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark flow(stream) } // At this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore && state.constructed) { state.readingMore = true process.nextTick(maybeReadMore_, stream, state) } } function maybeReadMore_(stream, state) { // Attempt to read more data if we should. // // The conditions for reading more data are (one of): // - Not enough data buffered (state.length < state.highWaterMark). The loop // is responsible for filling the buffer with enough data if such data // is available. If highWaterMark is 0 and we are not in the flowing mode // we should _not_ attempt to buffer any extra data. We'll get more data // when the stream consumer calls read() instead. // - No data in the buffer, and the stream is in flowing mode. In this mode // the loop below is responsible for ensuring read() is called. Failing to // call read here would abort the flow and there's no other mechanism for // continuing the flow if the stream consumer has just subscribed to the // 'data' event. // // In addition to the above conditions to keep reading data, the following // conditions prevent the data from being read: // - The stream has ended (state.ended). // - There is already a pending 'read' operation (state.reading). This is a // case where the stream has called the implementation defined _read() // method, but they are processing the call asynchronously and have _not_ // called push() with new data. In this case we skip performing more // read()s. The execution ends in this method again after the _read() ends // up calling push() with more data. while ( !state.reading && !state.ended && (state.length < state.highWaterMark || (state.flowing && state.length === 0)) ) { const len = state.length debug('maybeReadMore read 0') stream.read(0) if (len === state.length) // Didn't get any data, stop spinning. break } state.readingMore = false } // Abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { throw new ERR_METHOD_NOT_IMPLEMENTED('_read()') } Readable.prototype.pipe = function (dest, pipeOpts) { const src = this const state = this._readableState if (state.pipes.length === 1) { if (!state.multiAwaitDrain) { state.multiAwaitDrain = true state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : []) } } state.pipes.push(dest) debug('pipe count=%d opts=%j', state.pipes.length, pipeOpts) const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr const endFn = doEnd ? onend : unpipe if (state.endEmitted) process.nextTick(endFn) else src.once('end', endFn) dest.on('unpipe', onunpipe) function onunpipe(readable, unpipeInfo) { debug('onunpipe') if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true cleanup() } } } function onend() { debug('onend') dest.end() } let ondrain let cleanedUp = false function cleanup() { debug('cleanup') // Cleanup event handlers once the pipe is broken. dest.removeListener('close', onclose) dest.removeListener('finish', onfinish) if (ondrain) { dest.removeListener('drain', ondrain) } dest.removeListener('error', onerror) dest.removeListener('unpipe', onunpipe) src.removeListener('end', onend) src.removeListener('end', unpipe) src.removeListener('data', ondata) cleanedUp = true // If the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain() } function pause() { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if (!cleanedUp) { if (state.pipes.length === 1 && state.pipes[0] === dest) { debug('false write response, pause', 0) state.awaitDrainWriters = dest state.multiAwaitDrain = false } else if (state.pipes.length > 1 && state.pipes.includes(dest)) { debug('false write response, pause', state.awaitDrainWriters.size) state.awaitDrainWriters.add(dest) } src.pause() } if (!ondrain) { // When the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. ondrain = pipeOnDrain(src, dest) dest.on('drain', ondrain) } } src.on('data', ondata) function ondata(chunk) { debug('ondata') const ret = dest.write(chunk) debug('dest.write', ret) if (ret === false) { pause() } } // If the dest has an error, then stop piping into it. // However, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er) unpipe() dest.removeListener('error', onerror) if (dest.listenerCount('error') === 0) { const s = dest._writableState || dest._readableState if (s && !s.errorEmitted) { // User incorrectly emitted 'error' directly on the stream. errorOrDestroy(dest, er) } else { dest.emit('error', er) } } } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror) // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish) unpipe() } dest.once('close', onclose) function onfinish() { debug('onfinish') dest.removeListener('close', onclose) unpipe() } dest.once('finish', onfinish) function unpipe() { debug('unpipe') src.unpipe(dest) } // Tell the dest that it's being piped to. dest.emit('pipe', src) // Start the flow if it hasn't been started already. if (dest.writableNeedDrain === true) { pause() } else if (!state.flowing) { debug('pipe resume') src.resume() } return dest } function pipeOnDrain(src, dest) { return function pipeOnDrainFunctionResult() { const state = src._readableState // `ondrain` will call directly, // `this` maybe not a reference to dest, // so we use the real dest here. if (state.awaitDrainWriters === dest) { debug('pipeOnDrain', 1) state.awaitDrainWriters = null } else if (state.multiAwaitDrain) { debug('pipeOnDrain', state.awaitDrainWriters.size) state.awaitDrainWriters.delete(dest) } if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount('data')) { src.resume() } } } Readable.prototype.unpipe = function (dest) { const state = this._readableState const unpipeInfo = { hasUnpiped: false } // If we're not piping anywhere, then do nothing. if (state.pipes.length === 0) return this if (!dest) { // remove all. const dests = state.pipes state.pipes = [] this.pause() for (let i = 0; i < dests.length; i++) dests[i].emit('unpipe', this, { hasUnpiped: false }) return this } // Try to find the right one. const index = ArrayPrototypeIndexOf(state.pipes, dest) if (index === -1) return this state.pipes.splice(index, 1) if (state.pipes.length === 0) this.pause() dest.emit('unpipe', this, unpipeInfo) return this } // Set up data events if they are asked for // Ensure readable listeners eventually get something. Readable.prototype.on = function (ev, fn) { const res = Stream.prototype.on.call(this, ev, fn) const state = this._readableState if (ev === 'data') { // Update readableListening so that resume() may be a no-op // a few lines down. This is needed to support once('readable'). state.readableListening = this.listenerCount('readable') > 0 // Try start flowing on next tick if stream isn't explicitly paused. if (state.flowing !== false) this.resume() } else if (ev === 'readable') { if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true state.flowing = false state.emittedReadable = false debug('on readable', state.length, state.reading) if (state.length) { emitReadable(this) } else if (!state.reading) { process.nextTick(nReadingNextTick, this) } } } return res } Readable.prototype.addListener = Readable.prototype.on Readable.prototype.removeListener = function (ev, fn) { const res = Stream.prototype.removeListener.call(this, ev, fn) if (ev === 'readable') { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen // after readable has been emitted but before I/O (nextTick) to // support once('readable', fn) cycles. This means that calling // resume within the same tick will have no // effect. process.nextTick(updateReadableListening, this) } return res } Readable.prototype.off = Readable.prototype.removeListener Readable.prototype.removeAllListeners = function (ev) { const res = Stream.prototype.removeAllListeners.apply(this, arguments) if (ev === 'readable' || ev === undefined) { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen // after readable has been emitted but before I/O (nextTick) to // support once('readable', fn) cycles. This means that calling // resume within the same tick will have no // effect. process.nextTick(updateReadableListening, this) } return res } function updateReadableListening(self) { const state = self._readableState state.readableListening = self.listenerCount('readable') > 0 if (state.resumeScheduled && state[kPaused] === false) { // Flowing needs to be set to true now, otherwise // the upcoming resume will not flow. state.flowing = true // Crude way to check if we should resume. } else if (self.listenerCount('data') > 0) { self.resume() } else if (!state.readableListening) { state.flowing = null } } function nReadingNextTick(self) { debug('readable nexttick read 0') self.read(0) } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { const state = this._readableState if (!state.flowing) { debug('resume') // We flow only if there is no one listening // for readable, but we still have to call // resume(). state.flowing = !state.readableListening resume(this, state) } state[kPaused] = false return this } function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true process.nextTick(resume_, stream, state) } } function resume_(stream, state) { debug('resume', state.reading) if (!state.reading) { stream.read(0) } state.resumeScheduled = false stream.emit('resume') flow(stream) if (state.flowing && !state.reading) stream.read(0) } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing) if (this._readableState.flowing !== false) { debug('pause') this._readableState.flowing = false this.emit('pause') } this._readableState[kPaused] = true return this } function flow(stream) { const state = stream._readableState debug('flow', state.flowing) while (state.flowing && stream.read() !== null); } // Wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { let paused = false // TODO (ronag): Should this.destroy(err) emit // 'error' on the wrapped stream? Would require // a static factory method, e.g. Readable.wrap(stream). stream.on('data', (chunk) => { if (!this.push(chunk) && stream.pause) { paused = true stream.pause() } }) stream.on('end', () => { this.push(null) }) stream.on('error', (err) => { errorOrDestroy(this, err) }) stream.on('close', () => { this.destroy() }) stream.on('destroy', () => { this.destroy() }) this._read = () => { if (paused && stream.resume) { paused = false stream.resume() } } // Proxy all the other methods. Important when wrapping filters and duplexes. const streamKeys = ObjectKeys(stream) for (let j = 1; j < streamKeys.length; j++) { const i = streamKeys[j] if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = stream[i].bind(stream) } } return this } Readable.prototype[SymbolAsyncIterator] = function () { return streamToAsyncIterator(this) } Readable.prototype.iterator = function (options) { if (options !== undefined) { validateObject(options, 'options') } return streamToAsyncIterator(this, options) } function streamToAsyncIterator(stream, options) { if (typeof stream.read !== 'function') { stream = Readable.wrap(stream, { objectMode: true }) } const iter = createAsyncIterator(stream, options) iter.stream = stream return iter } async function* createAsyncIterator(stream, options) { let callback = nop function next(resolve) { if (this === stream) { callback() callback = nop } else { callback = resolve } } stream.on('readable', next) let error const cleanup = eos( stream, { writable: false }, (err) => { error = err ? aggregateTwoErrors(error, err) : null callback() callback = nop } ) try { while (true) { const chunk = stream.destroyed ? null : stream.read() if (chunk !== null) { yield chunk } else if (error) { throw error } else if (error === null) { return } else { await new Promise(next) } } } catch (err) { error = aggregateTwoErrors(error, err) throw error } finally { if ( (error || (options === null || options === undefined ? undefined : options.destroyOnReturn) !== false) && (error === undefined || stream._readableState.autoDestroy) ) { destroyImpl.destroyer(stream, null) } else { stream.off('readable', next) cleanup() } } } // Making it explicit these properties are not enumerable // because otherwise some prototype manipulation in // userland will fail. ObjectDefineProperties(Readable.prototype, { readable: { __proto__: null, get() { const r = this._readableState // r.readable === false means that this is part of a Duplex stream // where the readable side was disabled upon construction. // Compat. The user might manually disable readable side through // deprecated setter. return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted }, set(val) { // Backwards compat. if (this._readableState) { this._readableState.readable = !!val } } }, readableDidRead: { __proto__: null, enumerable: false, get: function () { return this._readableState.dataEmitted } }, readableAborted: { __proto__: null, enumerable: false, get: function () { return !!( this._readableState.readable !== false && (this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted ) } }, readableHighWaterMark: { __proto__: null, enumerable: false, get: function () { return this._readableState.highWaterMark } }, readableBuffer: { __proto__: null, enumerable: false, get: function () { return this._readableState && this._readableState.buffer } }, readableFlowing: { __proto__: null, enumerable: false, get: function () { return this._readableState.flowing }, set: function (state) { if (this._readableState) { this._readableState.flowing = state } } }, readableLength: { __proto__: null, enumerable: false, get() { return this._readableState.length } }, readableObjectMode: { __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.objectMode : false } }, readableEncoding: { __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.encoding : null } }, errored: { __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.errored : null } }, closed: { __proto__: null, get() { return this._readableState ? this._readableState.closed : false } }, destroyed: { __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.destroyed : false }, set(value) { // We ignore the value if the stream // has not been initialized yet. if (!this._readableState) { return } // Backward compatibility, the user is explicitly // managing destroyed. this._readableState.destroyed = value } }, readableEnded: { __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.endEmitted : false } } }) ObjectDefineProperties(ReadableState.prototype, { // Legacy getter for `pipesCount`. pipesCount: { __proto__: null, get() { return this.pipes.length } }, // Legacy property for `paused`. paused: { __proto__: null, get() { return this[kPaused] !== false }, set(value) { this[kPaused] = !!value } } }) // Exposed for testing purposes only. Readable._fromList = fromList // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered. if (state.length === 0) return null let ret if (state.objectMode) ret = state.buffer.shift() else if (!n || n >= state.length) { // Read it all, truncate the list. if (state.decoder) ret = state.buffer.join('') else if (state.buffer.length === 1) ret = state.buffer.first() else ret = state.buffer.concat(state.length) state.buffer.clear() } else { // read part of list. ret = state.buffer.consume(n, state.decoder) } return ret } function endReadable(stream) { const state = stream._readableState debug('endReadable', state.endEmitted) if (!state.endEmitted) { state.ended = true process.nextTick(endReadableNT, state, stream) } } function endReadableNT(state, stream) { debug('endReadableNT', state.endEmitted, state.length) // Check that we didn't get one last unshift. if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) { state.endEmitted = true stream.emit('end') if (stream.writable && stream.allowHalfOpen === false) { process.nextTick(endWritableNT, stream) } else if (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the writable side is ready for autoDestroy as well. const wState = stream._writableState const autoDestroy = !wState || (wState.autoDestroy && // We don't expect the writable to ever 'finish' // if writable is explicitly set to false. (wState.finished || wState.writable === false)) if (autoDestroy) { stream.destroy() } } } } function endWritableNT(stream) { const writable = stream.writable && !stream.writableEnded && !stream.destroyed if (writable) { stream.end() } } Readable.from = function (iterable, opts) { return from(Readable, iterable, opts) } let webStreamsAdapters // Lazy to avoid circular references function lazyWebStreams() { if (webStreamsAdapters === undefined) webStreamsAdapters = {} return webStreamsAdapters } Readable.fromWeb = function (readableStream, options) { return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options) } Readable.toWeb = function (streamReadable, options) { return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options) } Readable.wrap = function (src, options) { var _ref, _src$readableObjectMo return new Readable({ objectMode: (_ref = (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== undefined ? _src$readableObjectMo : src.objectMode) !== null && _ref !== undefined ? _ref : true, ...options, destroy(err, callback) { destroyImpl.destroyer(src, err) callback(err) } }).wrap(src) } /***/ }), /***/ 4124: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { MathFloor, NumberIsInteger } = __nccwpck_require__(9229) const { validateInteger } = __nccwpck_require__(5988) const { ERR_INVALID_ARG_VALUE } = (__nccwpck_require__(6786).codes) let defaultHighWaterMarkBytes = 16 * 1024 let defaultHighWaterMarkObjectMode = 16 function highWaterMarkFrom(options, isDuplex, duplexKey) { return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null } function getDefaultHighWaterMark(objectMode) { return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes } function setDefaultHighWaterMark(objectMode, value) { validateInteger(value, 'value', 0) if (objectMode) { defaultHighWaterMarkObjectMode = value } else { defaultHighWaterMarkBytes = value } } function getHighWaterMark(state, options, duplexKey, isDuplex) { const hwm = highWaterMarkFrom(options, isDuplex, duplexKey) if (hwm != null) { if (!NumberIsInteger(hwm) || hwm < 0) { const name = isDuplex ? `options.${duplexKey}` : 'options.highWaterMark' throw new ERR_INVALID_ARG_VALUE(name, hwm) } return MathFloor(hwm) } // Default value return getDefaultHighWaterMark(state.objectMode) } module.exports = { getHighWaterMark, getDefaultHighWaterMark, setDefaultHighWaterMark } /***/ }), /***/ 9253: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. const { ObjectSetPrototypeOf, Symbol } = __nccwpck_require__(9229) module.exports = Transform const { ERR_METHOD_NOT_IMPLEMENTED } = (__nccwpck_require__(6786).codes) const Duplex = __nccwpck_require__(8915) const { getHighWaterMark } = __nccwpck_require__(4124) ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype) ObjectSetPrototypeOf(Transform, Duplex) const kCallback = Symbol('kCallback') function Transform(options) { if (!(this instanceof Transform)) return new Transform(options) // TODO (ronag): This should preferably always be // applied but would be semver-major. Or even better; // make Transform a Readable with the Writable interface. const readableHighWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', true) : null if (readableHighWaterMark === 0) { // A Duplex will buffer both on the writable and readable side while // a Transform just wants to buffer hwm number of elements. To avoid // buffering twice we disable buffering on the writable side. options = { ...options, highWaterMark: null, readableHighWaterMark, // TODO (ronag): 0 is not optimal since we have // a "bug" where we check needDrain before calling _write and not after. // Refs: https://github.com/nodejs/node/pull/32887 // Refs: https://github.com/nodejs/node/pull/35941 writableHighWaterMark: options.writableHighWaterMark || 0 } } Duplex.call(this, options) // We have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false this[kCallback] = null if (options) { if (typeof options.transform === 'function') this._transform = options.transform if (typeof options.flush === 'function') this._flush = options.flush } // When the writable side finishes, then flush out anything remaining. // Backwards compat. Some Transform streams incorrectly implement _final // instead of or in addition to _flush. By using 'prefinish' instead of // implementing _final we continue supporting this unfortunate use case. this.on('prefinish', prefinish) } function final(cb) { if (typeof this._flush === 'function' && !this.destroyed) { this._flush((er, data) => { if (er) { if (cb) { cb(er) } else { this.destroy(er) } return } if (data != null) { this.push(data) } this.push(null) if (cb) { cb() } }) } else { this.push(null) if (cb) { cb() } } } function prefinish() { if (this._final !== final) { final.call(this) } } Transform.prototype._final = final Transform.prototype._transform = function (chunk, encoding, callback) { throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()') } Transform.prototype._write = function (chunk, encoding, callback) { const rState = this._readableState const wState = this._writableState const length = rState.length this._transform(chunk, encoding, (err, val) => { if (err) { callback(err) return } if (val != null) { this.push(val) } if ( wState.ended || // Backwards compat. length === rState.length || // Backwards compat. rState.length < rState.highWaterMark ) { callback() } else { this[kCallback] = callback } }) } Transform.prototype._read = function () { if (this[kCallback]) { const callback = this[kCallback] this[kCallback] = null callback() } } /***/ }), /***/ 3892: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { SymbolAsyncIterator, SymbolIterator, SymbolFor } = __nccwpck_require__(9229) // We need to use SymbolFor to make these globally available // for interopt with readable-stream, i.e. readable-stream // and node core needs to be able to read/write private state // from each other for proper interoperability. const kIsDestroyed = SymbolFor('nodejs.stream.destroyed') const kIsErrored = SymbolFor('nodejs.stream.errored') const kIsReadable = SymbolFor('nodejs.stream.readable') const kIsWritable = SymbolFor('nodejs.stream.writable') const kIsDisturbed = SymbolFor('nodejs.stream.disturbed') const kIsClosedPromise = SymbolFor('nodejs.webstream.isClosedPromise') const kControllerErrorFunction = SymbolFor('nodejs.webstream.controllerErrorFunction') function isReadableNodeStream(obj, strict = false) { var _obj$_readableState return !!( ( obj && typeof obj.pipe === 'function' && typeof obj.on === 'function' && (!strict || (typeof obj.pause === 'function' && typeof obj.resume === 'function')) && (!obj._writableState || ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === undefined ? undefined : _obj$_readableState.readable) !== false) && // Duplex (!obj._writableState || obj._readableState) ) // Writable has .pipe. ) } function isWritableNodeStream(obj) { var _obj$_writableState return !!( ( obj && typeof obj.write === 'function' && typeof obj.on === 'function' && (!obj._readableState || ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === undefined ? undefined : _obj$_writableState.writable) !== false) ) // Duplex ) } function isDuplexNodeStream(obj) { return !!( obj && typeof obj.pipe === 'function' && obj._readableState && typeof obj.on === 'function' && typeof obj.write === 'function' ) } function isNodeStream(obj) { return ( obj && (obj._readableState || obj._writableState || (typeof obj.write === 'function' && typeof obj.on === 'function') || (typeof obj.pipe === 'function' && typeof obj.on === 'function')) ) } function isReadableStream(obj) { return !!( obj && !isNodeStream(obj) && typeof obj.pipeThrough === 'function' && typeof obj.getReader === 'function' && typeof obj.cancel === 'function' ) } function isWritableStream(obj) { return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === 'function' && typeof obj.abort === 'function') } function isTransformStream(obj) { return !!(obj && !isNodeStream(obj) && typeof obj.readable === 'object' && typeof obj.writable === 'object') } function isWebStream(obj) { return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj) } function isIterable(obj, isAsync) { if (obj == null) return false if (isAsync === true) return typeof obj[SymbolAsyncIterator] === 'function' if (isAsync === false) return typeof obj[SymbolIterator] === 'function' return typeof obj[SymbolAsyncIterator] === 'function' || typeof obj[SymbolIterator] === 'function' } function isDestroyed(stream) { if (!isNodeStream(stream)) return null const wState = stream._writableState const rState = stream._readableState const state = wState || rState return !!(stream.destroyed || stream[kIsDestroyed] || (state !== null && state !== undefined && state.destroyed)) } // Have been end():d. function isWritableEnded(stream) { if (!isWritableNodeStream(stream)) return null if (stream.writableEnded === true) return true const wState = stream._writableState if (wState !== null && wState !== undefined && wState.errored) return false if (typeof (wState === null || wState === undefined ? undefined : wState.ended) !== 'boolean') return null return wState.ended } // Have emitted 'finish'. function isWritableFinished(stream, strict) { if (!isWritableNodeStream(stream)) return null if (stream.writableFinished === true) return true const wState = stream._writableState if (wState !== null && wState !== undefined && wState.errored) return false if (typeof (wState === null || wState === undefined ? undefined : wState.finished) !== 'boolean') return null return !!(wState.finished || (strict === false && wState.ended === true && wState.length === 0)) } // Have been push(null):d. function isReadableEnded(stream) { if (!isReadableNodeStream(stream)) return null if (stream.readableEnded === true) return true const rState = stream._readableState if (!rState || rState.errored) return false if (typeof (rState === null || rState === undefined ? undefined : rState.ended) !== 'boolean') return null return rState.ended } // Have emitted 'end'. function isReadableFinished(stream, strict) { if (!isReadableNodeStream(stream)) return null const rState = stream._readableState if (rState !== null && rState !== undefined && rState.errored) return false if (typeof (rState === null || rState === undefined ? undefined : rState.endEmitted) !== 'boolean') return null return !!(rState.endEmitted || (strict === false && rState.ended === true && rState.length === 0)) } function isReadable(stream) { if (stream && stream[kIsReadable] != null) return stream[kIsReadable] if (typeof (stream === null || stream === undefined ? undefined : stream.readable) !== 'boolean') return null if (isDestroyed(stream)) return false return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream) } function isWritable(stream) { if (stream && stream[kIsWritable] != null) return stream[kIsWritable] if (typeof (stream === null || stream === undefined ? undefined : stream.writable) !== 'boolean') return null if (isDestroyed(stream)) return false return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream) } function isFinished(stream, opts) { if (!isNodeStream(stream)) { return null } if (isDestroyed(stream)) { return true } if ((opts === null || opts === undefined ? undefined : opts.readable) !== false && isReadable(stream)) { return false } if ((opts === null || opts === undefined ? undefined : opts.writable) !== false && isWritable(stream)) { return false } return true } function isWritableErrored(stream) { var _stream$_writableStat, _stream$_writableStat2 if (!isNodeStream(stream)) { return null } if (stream.writableErrored) { return stream.writableErrored } return (_stream$_writableStat = (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === undefined ? undefined : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== undefined ? _stream$_writableStat : null } function isReadableErrored(stream) { var _stream$_readableStat, _stream$_readableStat2 if (!isNodeStream(stream)) { return null } if (stream.readableErrored) { return stream.readableErrored } return (_stream$_readableStat = (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === undefined ? undefined : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== undefined ? _stream$_readableStat : null } function isClosed(stream) { if (!isNodeStream(stream)) { return null } if (typeof stream.closed === 'boolean') { return stream.closed } const wState = stream._writableState const rState = stream._readableState if ( typeof (wState === null || wState === undefined ? undefined : wState.closed) === 'boolean' || typeof (rState === null || rState === undefined ? undefined : rState.closed) === 'boolean' ) { return ( (wState === null || wState === undefined ? undefined : wState.closed) || (rState === null || rState === undefined ? undefined : rState.closed) ) } if (typeof stream._closed === 'boolean' && isOutgoingMessage(stream)) { return stream._closed } return null } function isOutgoingMessage(stream) { return ( typeof stream._closed === 'boolean' && typeof stream._defaultKeepAlive === 'boolean' && typeof stream._removedConnection === 'boolean' && typeof stream._removedContLen === 'boolean' ) } function isServerResponse(stream) { return typeof stream._sent100 === 'boolean' && isOutgoingMessage(stream) } function isServerRequest(stream) { var _stream$req return ( typeof stream._consuming === 'boolean' && typeof stream._dumped === 'boolean' && ((_stream$req = stream.req) === null || _stream$req === undefined ? undefined : _stream$req.upgradeOrConnect) === undefined ) } function willEmitClose(stream) { if (!isNodeStream(stream)) return null const wState = stream._writableState const rState = stream._readableState const state = wState || rState return ( (!state && isServerResponse(stream)) || !!(state && state.autoDestroy && state.emitClose && state.closed === false) ) } function isDisturbed(stream) { var _stream$kIsDisturbed return !!( stream && ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== undefined ? _stream$kIsDisturbed : stream.readableDidRead || stream.readableAborted) ) } function isErrored(stream) { var _ref, _ref2, _ref3, _ref4, _ref5, _stream$kIsErrored, _stream$_readableStat3, _stream$_writableStat3, _stream$_readableStat4, _stream$_writableStat4 return !!( stream && ((_ref = (_ref2 = (_ref3 = (_ref4 = (_ref5 = (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== undefined ? _stream$kIsErrored : stream.readableErrored) !== null && _ref5 !== undefined ? _ref5 : stream.writableErrored) !== null && _ref4 !== undefined ? _ref4 : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === undefined ? undefined : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== undefined ? _ref3 : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === undefined ? undefined : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== undefined ? _ref2 : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === undefined ? undefined : _stream$_readableStat4.errored) !== null && _ref !== undefined ? _ref : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === undefined ? undefined : _stream$_writableStat4.errored) ) } module.exports = { isDestroyed, kIsDestroyed, isDisturbed, kIsDisturbed, isErrored, kIsErrored, isReadable, kIsReadable, kIsClosedPromise, kControllerErrorFunction, kIsWritable, isClosed, isDuplexNodeStream, isFinished, isIterable, isReadableNodeStream, isReadableStream, isReadableEnded, isReadableFinished, isReadableErrored, isNodeStream, isWebStream, isWritable, isWritableNodeStream, isWritableStream, isWritableEnded, isWritableFinished, isWritableErrored, isServerRequest, isServerResponse, willEmitClose, isTransformStream } /***/ }), /***/ 9745: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ const { ArrayPrototypeSlice, Error, FunctionPrototypeSymbolHasInstance, ObjectDefineProperty, ObjectDefineProperties, ObjectSetPrototypeOf, StringPrototypeToLowerCase, Symbol, SymbolHasInstance } = __nccwpck_require__(9229) module.exports = Writable Writable.WritableState = WritableState const { EventEmitter: EE } = __nccwpck_require__(4434) const Stream = (__nccwpck_require__(770).Stream) const { Buffer } = __nccwpck_require__(181) const destroyImpl = __nccwpck_require__(8403) const { addAbortSignal } = __nccwpck_require__(6942) const { getHighWaterMark, getDefaultHighWaterMark } = __nccwpck_require__(4124) const { ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED, ERR_STREAM_ALREADY_FINISHED, ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING } = (__nccwpck_require__(6786).codes) const { errorOrDestroy } = destroyImpl ObjectSetPrototypeOf(Writable.prototype, Stream.prototype) ObjectSetPrototypeOf(Writable, Stream) function nop() {} const kOnFinished = Symbol('kOnFinished') function WritableState(options, stream, isDuplex) { // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream, // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof __nccwpck_require__(8915) // Object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!(options && options.objectMode) if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode) // The point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write(). this.highWaterMark = options ? getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex) : getDefaultHighWaterMark(false) // if _final has been called. this.finalCalled = false // drain event flag. this.needDrain = false // At the start of calling end() this.ending = false // When end() has been called, and returned. this.ended = false // When 'finish' is emitted. this.finished = false // Has it been destroyed this.destroyed = false // Should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. const noDecode = !!(options && options.decodeStrings === false) this.decodeStrings = !noDecode // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = (options && options.defaultEncoding) || 'utf8' // Not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0 // A flag to see when we're in the middle of a write. this.writing = false // When true all writes will be buffered until .uncork() call. this.corked = 0 // A flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true // A flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false // The callback that's passed to _write(chunk, cb). this.onwrite = onwrite.bind(undefined, stream) // The callback that the user supplies to write(chunk, encoding, cb). this.writecb = null // The amount that is being written when _write is called. this.writelen = 0 // Storage for data passed to the afterWrite() callback in case of // synchronous _write() completion. this.afterWriteTickInfo = null resetBuffer(this) // Number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted. this.pendingcb = 0 // Stream is still being constructed and cannot be // destroyed until construction finished or failed. // Async construction is opt in, therefore we start as // constructed. this.constructed = true // Emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams. this.prefinished = false // True if the error was already emitted and should not be thrown again. this.errorEmitted = false // Should close be emitted on destroy. Defaults to true. this.emitClose = !options || options.emitClose !== false // Should .destroy() be called after 'finish' (and potentially 'end'). this.autoDestroy = !options || options.autoDestroy !== false // Indicates whether the stream has errored. When true all write() calls // should return false. This is needed since when autoDestroy // is disabled we need a way to tell whether the stream has failed. this.errored = null // Indicates whether the stream has finished destroying. this.closed = false // True if close has been emitted or would have been emitted // depending on emitClose. this.closeEmitted = false this[kOnFinished] = [] } function resetBuffer(state) { state.buffered = [] state.bufferedIndex = 0 state.allBuffers = true state.allNoop = true } WritableState.prototype.getBuffer = function getBuffer() { return ArrayPrototypeSlice(this.buffered, this.bufferedIndex) } ObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', { __proto__: null, get() { return this.buffered.length - this.bufferedIndex } }) function Writable(options) { // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. // Checking for a Stream.Duplex instance is faster here instead of inside // the WritableState constructor, at least with V8 6.5. const isDuplex = this instanceof __nccwpck_require__(8915) if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options) this._writableState = new WritableState(options, this, isDuplex) if (options) { if (typeof options.write === 'function') this._write = options.write if (typeof options.writev === 'function') this._writev = options.writev if (typeof options.destroy === 'function') this._destroy = options.destroy if (typeof options.final === 'function') this._final = options.final if (typeof options.construct === 'function') this._construct = options.construct if (options.signal) addAbortSignal(options.signal, this) } Stream.call(this, options) destroyImpl.construct(this, () => { const state = this._writableState if (!state.writing) { clearBuffer(this, state) } finishMaybe(this, state) }) } ObjectDefineProperty(Writable, SymbolHasInstance, { __proto__: null, value: function (object) { if (FunctionPrototypeSymbolHasInstance(this, object)) return true if (this !== Writable) return false return object && object._writableState instanceof WritableState } }) // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()) } function _write(stream, chunk, encoding, cb) { const state = stream._writableState if (typeof encoding === 'function') { cb = encoding encoding = state.defaultEncoding } else { if (!encoding) encoding = state.defaultEncoding else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding) if (typeof cb !== 'function') cb = nop } if (chunk === null) { throw new ERR_STREAM_NULL_VALUES() } else if (!state.objectMode) { if (typeof chunk === 'string') { if (state.decodeStrings !== false) { chunk = Buffer.from(chunk, encoding) encoding = 'buffer' } } else if (chunk instanceof Buffer) { encoding = 'buffer' } else if (Stream._isUint8Array(chunk)) { chunk = Stream._uint8ArrayToBuffer(chunk) encoding = 'buffer' } else { throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk) } } let err if (state.ending) { err = new ERR_STREAM_WRITE_AFTER_END() } else if (state.destroyed) { err = new ERR_STREAM_DESTROYED('write') } if (err) { process.nextTick(cb, err) errorOrDestroy(stream, err, true) return err } state.pendingcb++ return writeOrBuffer(stream, state, chunk, encoding, cb) } Writable.prototype.write = function (chunk, encoding, cb) { return _write(this, chunk, encoding, cb) === true } Writable.prototype.cork = function () { this._writableState.corked++ } Writable.prototype.uncork = function () { const state = this._writableState if (state.corked) { state.corked-- if (!state.writing) clearBuffer(this, state) } } Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = StringPrototypeToLowerCase(encoding) if (!Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding) this._writableState.defaultEncoding = encoding return this } // If we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, chunk, encoding, callback) { const len = state.objectMode ? 1 : chunk.length state.length += len // stream._write resets state.length const ret = state.length < state.highWaterMark // We must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true if (state.writing || state.corked || state.errored || !state.constructed) { state.buffered.push({ chunk, encoding, callback }) if (state.allBuffers && encoding !== 'buffer') { state.allBuffers = false } if (state.allNoop && callback !== nop) { state.allNoop = false } } else { state.writelen = len state.writecb = callback state.writing = true state.sync = true stream._write(chunk, encoding, state.onwrite) state.sync = false } // Return false if errored or destroyed in order to break // any synchronous while(stream.write(data)) loops. return ret && !state.errored && !state.destroyed } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len state.writecb = cb state.writing = true state.sync = true if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write')) else if (writev) stream._writev(chunk, state.onwrite) else stream._write(chunk, encoding, state.onwrite) state.sync = false } function onwriteError(stream, state, er, cb) { --state.pendingcb cb(er) // Ensure callbacks are invoked even when autoDestroy is // not enabled. Passing `er` here doesn't make sense since // it's related to one specific write, not to the buffered // writes. errorBuffer(state) // This can emit error, but error must always follow cb. errorOrDestroy(stream, er) } function onwrite(stream, er) { const state = stream._writableState const sync = state.sync const cb = state.writecb if (typeof cb !== 'function') { errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK()) return } state.writing = false state.writecb = null state.length -= state.writelen state.writelen = 0 if (er) { // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 er.stack // eslint-disable-line no-unused-expressions if (!state.errored) { state.errored = er } // In case of duplex streams we need to notify the readable side of the // error. if (stream._readableState && !stream._readableState.errored) { stream._readableState.errored = er } if (sync) { process.nextTick(onwriteError, stream, state, er, cb) } else { onwriteError(stream, state, er, cb) } } else { if (state.buffered.length > state.bufferedIndex) { clearBuffer(stream, state) } if (sync) { // It is a common case that the callback passed to .write() is always // the same. In that case, we do not schedule a new nextTick(), but // rather just increase a counter, to improve performance and avoid // memory allocations. if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) { state.afterWriteTickInfo.count++ } else { state.afterWriteTickInfo = { count: 1, cb, stream, state } process.nextTick(afterWriteTick, state.afterWriteTickInfo) } } else { afterWrite(stream, state, 1, cb) } } } function afterWriteTick({ stream, state, count, cb }) { state.afterWriteTickInfo = null return afterWrite(stream, state, count, cb) } function afterWrite(stream, state, count, cb) { const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain if (needDrain) { state.needDrain = false stream.emit('drain') } while (count-- > 0) { state.pendingcb-- cb() } if (state.destroyed) { errorBuffer(state) } finishMaybe(stream, state) } // If there's something in the buffer waiting, then invoke callbacks. function errorBuffer(state) { if (state.writing) { return } for (let n = state.bufferedIndex; n < state.buffered.length; ++n) { var _state$errored const { chunk, callback } = state.buffered[n] const len = state.objectMode ? 1 : chunk.length state.length -= len callback( (_state$errored = state.errored) !== null && _state$errored !== undefined ? _state$errored : new ERR_STREAM_DESTROYED('write') ) } const onfinishCallbacks = state[kOnFinished].splice(0) for (let i = 0; i < onfinishCallbacks.length; i++) { var _state$errored2 onfinishCallbacks[i]( (_state$errored2 = state.errored) !== null && _state$errored2 !== undefined ? _state$errored2 : new ERR_STREAM_DESTROYED('end') ) } resetBuffer(state) } // If there's something in the buffer waiting, then process it. function clearBuffer(stream, state) { if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) { return } const { buffered, bufferedIndex, objectMode } = state const bufferedLength = buffered.length - bufferedIndex if (!bufferedLength) { return } let i = bufferedIndex state.bufferProcessing = true if (bufferedLength > 1 && stream._writev) { state.pendingcb -= bufferedLength - 1 const callback = state.allNoop ? nop : (err) => { for (let n = i; n < buffered.length; ++n) { buffered[n].callback(err) } } // Make a copy of `buffered` if it's going to be used by `callback` above, // since `doWrite` will mutate the array. const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i) chunks.allBuffers = state.allBuffers doWrite(stream, state, true, state.length, chunks, '', callback) resetBuffer(state) } else { do { const { chunk, encoding, callback } = buffered[i] buffered[i++] = null const len = objectMode ? 1 : chunk.length doWrite(stream, state, false, len, chunk, encoding, callback) } while (i < buffered.length && !state.writing) if (i === buffered.length) { resetBuffer(state) } else if (i > 256) { buffered.splice(0, i) state.bufferedIndex = 0 } else { state.bufferedIndex = i } } state.bufferProcessing = false } Writable.prototype._write = function (chunk, encoding, cb) { if (this._writev) { this._writev( [ { chunk, encoding } ], cb ) } else { throw new ERR_METHOD_NOT_IMPLEMENTED('_write()') } } Writable.prototype._writev = null Writable.prototype.end = function (chunk, encoding, cb) { const state = this._writableState if (typeof chunk === 'function') { cb = chunk chunk = null encoding = null } else if (typeof encoding === 'function') { cb = encoding encoding = null } let err if (chunk !== null && chunk !== undefined) { const ret = _write(this, chunk, encoding) if (ret instanceof Error) { err = ret } } // .end() fully uncorks. if (state.corked) { state.corked = 1 this.uncork() } if (err) { // Do nothing... } else if (!state.errored && !state.ending) { // This is forgiving in terms of unnecessary calls to end() and can hide // logic errors. However, usually such errors are harmless and causing a // hard error can be disproportionately destructive. It is not always // trivial for the user to determine whether end() needs to be called // or not. state.ending = true finishMaybe(this, state, true) state.ended = true } else if (state.finished) { err = new ERR_STREAM_ALREADY_FINISHED('end') } else if (state.destroyed) { err = new ERR_STREAM_DESTROYED('end') } if (typeof cb === 'function') { if (err || state.finished) { process.nextTick(cb, err) } else { state[kOnFinished].push(cb) } } return this } function needFinish(state) { return ( state.ending && !state.destroyed && state.constructed && state.length === 0 && !state.errored && state.buffered.length === 0 && !state.finished && !state.writing && !state.errorEmitted && !state.closeEmitted ) } function callFinal(stream, state) { let called = false function onFinish(err) { if (called) { errorOrDestroy(stream, err !== null && err !== undefined ? err : ERR_MULTIPLE_CALLBACK()) return } called = true state.pendingcb-- if (err) { const onfinishCallbacks = state[kOnFinished].splice(0) for (let i = 0; i < onfinishCallbacks.length; i++) { onfinishCallbacks[i](err) } errorOrDestroy(stream, err, state.sync) } else if (needFinish(state)) { state.prefinished = true stream.emit('prefinish') // Backwards compat. Don't check state.sync here. // Some streams assume 'finish' will be emitted // asynchronously relative to _final callback. state.pendingcb++ process.nextTick(finish, stream, state) } } state.sync = true state.pendingcb++ try { stream._final(onFinish) } catch (err) { onFinish(err) } state.sync = false } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function' && !state.destroyed) { state.finalCalled = true callFinal(stream, state) } else { state.prefinished = true stream.emit('prefinish') } } } function finishMaybe(stream, state, sync) { if (needFinish(state)) { prefinish(stream, state) if (state.pendingcb === 0) { if (sync) { state.pendingcb++ process.nextTick( (stream, state) => { if (needFinish(state)) { finish(stream, state) } else { state.pendingcb-- } }, stream, state ) } else if (needFinish(state)) { state.pendingcb++ finish(stream, state) } } } } function finish(stream, state) { state.pendingcb-- state.finished = true const onfinishCallbacks = state[kOnFinished].splice(0) for (let i = 0; i < onfinishCallbacks.length; i++) { onfinishCallbacks[i]() } stream.emit('finish') if (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the readable side is ready for autoDestroy as well. const rState = stream._readableState const autoDestroy = !rState || (rState.autoDestroy && // We don't expect the readable to ever 'end' // if readable is explicitly set to false. (rState.endEmitted || rState.readable === false)) if (autoDestroy) { stream.destroy() } } } ObjectDefineProperties(Writable.prototype, { closed: { __proto__: null, get() { return this._writableState ? this._writableState.closed : false } }, destroyed: { __proto__: null, get() { return this._writableState ? this._writableState.destroyed : false }, set(value) { // Backward compatibility, the user is explicitly managing destroyed. if (this._writableState) { this._writableState.destroyed = value } } }, writable: { __proto__: null, get() { const w = this._writableState // w.writable === false means that this is part of a Duplex stream // where the writable side was disabled upon construction. // Compat. The user might manually disable writable side through // deprecated setter. return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended }, set(val) { // Backwards compatible. if (this._writableState) { this._writableState.writable = !!val } } }, writableFinished: { __proto__: null, get() { return this._writableState ? this._writableState.finished : false } }, writableObjectMode: { __proto__: null, get() { return this._writableState ? this._writableState.objectMode : false } }, writableBuffer: { __proto__: null, get() { return this._writableState && this._writableState.getBuffer() } }, writableEnded: { __proto__: null, get() { return this._writableState ? this._writableState.ending : false } }, writableNeedDrain: { __proto__: null, get() { const wState = this._writableState if (!wState) return false return !wState.destroyed && !wState.ending && wState.needDrain } }, writableHighWaterMark: { __proto__: null, get() { return this._writableState && this._writableState.highWaterMark } }, writableCorked: { __proto__: null, get() { return this._writableState ? this._writableState.corked : 0 } }, writableLength: { __proto__: null, get() { return this._writableState && this._writableState.length } }, errored: { __proto__: null, enumerable: false, get() { return this._writableState ? this._writableState.errored : null } }, writableAborted: { __proto__: null, enumerable: false, get: function () { return !!( this._writableState.writable !== false && (this._writableState.destroyed || this._writableState.errored) && !this._writableState.finished ) } } }) const destroy = destroyImpl.destroy Writable.prototype.destroy = function (err, cb) { const state = this._writableState // Invoke pending callbacks. if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) { process.nextTick(errorBuffer, state) } destroy.call(this, err, cb) return this } Writable.prototype._undestroy = destroyImpl.undestroy Writable.prototype._destroy = function (err, cb) { cb(err) } Writable.prototype[EE.captureRejectionSymbol] = function (err) { this.destroy(err) } let webStreamsAdapters // Lazy to avoid circular references function lazyWebStreams() { if (webStreamsAdapters === undefined) webStreamsAdapters = {} return webStreamsAdapters } Writable.fromWeb = function (writableStream, options) { return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options) } Writable.toWeb = function (streamWritable) { return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable) } /***/ }), /***/ 5988: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint jsdoc/require-jsdoc: "error" */ const { ArrayIsArray, ArrayPrototypeIncludes, ArrayPrototypeJoin, ArrayPrototypeMap, NumberIsInteger, NumberIsNaN, NumberMAX_SAFE_INTEGER, NumberMIN_SAFE_INTEGER, NumberParseInt, ObjectPrototypeHasOwnProperty, RegExpPrototypeExec, String, StringPrototypeToUpperCase, StringPrototypeTrim } = __nccwpck_require__(9229) const { hideStackFrames, codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL } } = __nccwpck_require__(6786) const { normalizeEncoding } = __nccwpck_require__(3165) const { isAsyncFunction, isArrayBufferView } = (__nccwpck_require__(3165).types) const signals = {} /** * @param {*} value * @returns {boolean} */ function isInt32(value) { return value === (value | 0) } /** * @param {*} value * @returns {boolean} */ function isUint32(value) { return value === value >>> 0 } const octalReg = /^[0-7]+$/ const modeDesc = 'must be a 32-bit unsigned integer or an octal string' /** * Parse and validate values that will be converted into mode_t (the S_* * constants). Only valid numbers and octal strings are allowed. They could be * converted to 32-bit unsigned integers or non-negative signed integers in the * C++ land, but any value higher than 0o777 will result in platform-specific * behaviors. * @param {*} value Values to be validated * @param {string} name Name of the argument * @param {number} [def] If specified, will be returned for invalid values * @returns {number} */ function parseFileMode(value, name, def) { if (typeof value === 'undefined') { value = def } if (typeof value === 'string') { if (RegExpPrototypeExec(octalReg, value) === null) { throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc) } value = NumberParseInt(value, 8) } validateUint32(value, name) return value } /** * @callback validateInteger * @param {*} value * @param {string} name * @param {number} [min] * @param {number} [max] * @returns {asserts value is number} */ /** @type {validateInteger} */ const validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => { if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value) if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, 'an integer', value) if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) }) /** * @callback validateInt32 * @param {*} value * @param {string} name * @param {number} [min] * @param {number} [max] * @returns {asserts value is number} */ /** @type {validateInt32} */ const validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => { // The defaults for min and max correspond to the limits of 32-bit integers. if (typeof value !== 'number') { throw new ERR_INVALID_ARG_TYPE(name, 'number', value) } if (!NumberIsInteger(value)) { throw new ERR_OUT_OF_RANGE(name, 'an integer', value) } if (value < min || value > max) { throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) } }) /** * @callback validateUint32 * @param {*} value * @param {string} name * @param {number|boolean} [positive=false] * @returns {asserts value is number} */ /** @type {validateUint32} */ const validateUint32 = hideStackFrames((value, name, positive = false) => { if (typeof value !== 'number') { throw new ERR_INVALID_ARG_TYPE(name, 'number', value) } if (!NumberIsInteger(value)) { throw new ERR_OUT_OF_RANGE(name, 'an integer', value) } const min = positive ? 1 : 0 // 2 ** 32 === 4294967296 const max = 4294967295 if (value < min || value > max) { throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) } }) /** * @callback validateString * @param {*} value * @param {string} name * @returns {asserts value is string} */ /** @type {validateString} */ function validateString(value, name) { if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value) } /** * @callback validateNumber * @param {*} value * @param {string} name * @param {number} [min] * @param {number} [max] * @returns {asserts value is number} */ /** @type {validateNumber} */ function validateNumber(value, name, min = undefined, max) { if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value) if ( (min != null && value < min) || (max != null && value > max) || ((min != null || max != null) && NumberIsNaN(value)) ) { throw new ERR_OUT_OF_RANGE( name, `${min != null ? `>= ${min}` : ''}${min != null && max != null ? ' && ' : ''}${max != null ? `<= ${max}` : ''}`, value ) } } /** * @callback validateOneOf * @template T * @param {T} value * @param {string} name * @param {T[]} oneOf */ /** @type {validateOneOf} */ const validateOneOf = hideStackFrames((value, name, oneOf) => { if (!ArrayPrototypeIncludes(oneOf, value)) { const allowed = ArrayPrototypeJoin( ArrayPrototypeMap(oneOf, (v) => (typeof v === 'string' ? `'${v}'` : String(v))), ', ' ) const reason = 'must be one of: ' + allowed throw new ERR_INVALID_ARG_VALUE(name, value, reason) } }) /** * @callback validateBoolean * @param {*} value * @param {string} name * @returns {asserts value is boolean} */ /** @type {validateBoolean} */ function validateBoolean(value, name) { if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value) } /** * @param {any} options * @param {string} key * @param {boolean} defaultValue * @returns {boolean} */ function getOwnPropertyValueOrDefault(options, key, defaultValue) { return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key] } /** * @callback validateObject * @param {*} value * @param {string} name * @param {{ * allowArray?: boolean, * allowFunction?: boolean, * nullable?: boolean * }} [options] */ /** @type {validateObject} */ const validateObject = hideStackFrames((value, name, options = null) => { const allowArray = getOwnPropertyValueOrDefault(options, 'allowArray', false) const allowFunction = getOwnPropertyValueOrDefault(options, 'allowFunction', false) const nullable = getOwnPropertyValueOrDefault(options, 'nullable', false) if ( (!nullable && value === null) || (!allowArray && ArrayIsArray(value)) || (typeof value !== 'object' && (!allowFunction || typeof value !== 'function')) ) { throw new ERR_INVALID_ARG_TYPE(name, 'Object', value) } }) /** * @callback validateDictionary - We are using the Web IDL Standard definition * of "dictionary" here, which means any value * whose Type is either Undefined, Null, or * Object (which includes functions). * @param {*} value * @param {string} name * @see https://webidl.spec.whatwg.org/#es-dictionary * @see https://tc39.es/ecma262/#table-typeof-operator-results */ /** @type {validateDictionary} */ const validateDictionary = hideStackFrames((value, name) => { if (value != null && typeof value !== 'object' && typeof value !== 'function') { throw new ERR_INVALID_ARG_TYPE(name, 'a dictionary', value) } }) /** * @callback validateArray * @param {*} value * @param {string} name * @param {number} [minLength] * @returns {asserts value is any[]} */ /** @type {validateArray} */ const validateArray = hideStackFrames((value, name, minLength = 0) => { if (!ArrayIsArray(value)) { throw new ERR_INVALID_ARG_TYPE(name, 'Array', value) } if (value.length < minLength) { const reason = `must be longer than ${minLength}` throw new ERR_INVALID_ARG_VALUE(name, value, reason) } }) /** * @callback validateStringArray * @param {*} value * @param {string} name * @returns {asserts value is string[]} */ /** @type {validateStringArray} */ function validateStringArray(value, name) { validateArray(value, name) for (let i = 0; i < value.length; i++) { validateString(value[i], `${name}[${i}]`) } } /** * @callback validateBooleanArray * @param {*} value * @param {string} name * @returns {asserts value is boolean[]} */ /** @type {validateBooleanArray} */ function validateBooleanArray(value, name) { validateArray(value, name) for (let i = 0; i < value.length; i++) { validateBoolean(value[i], `${name}[${i}]`) } } /** * @callback validateAbortSignalArray * @param {*} value * @param {string} name * @returns {asserts value is AbortSignal[]} */ /** @type {validateAbortSignalArray} */ function validateAbortSignalArray(value, name) { validateArray(value, name) for (let i = 0; i < value.length; i++) { const signal = value[i] const indexedName = `${name}[${i}]` if (signal == null) { throw new ERR_INVALID_ARG_TYPE(indexedName, 'AbortSignal', signal) } validateAbortSignal(signal, indexedName) } } /** * @param {*} signal * @param {string} [name='signal'] * @returns {asserts signal is keyof signals} */ function validateSignalName(signal, name = 'signal') { validateString(signal, name) if (signals[signal] === undefined) { if (signals[StringPrototypeToUpperCase(signal)] !== undefined) { throw new ERR_UNKNOWN_SIGNAL(signal + ' (signals must use all capital letters)') } throw new ERR_UNKNOWN_SIGNAL(signal) } } /** * @callback validateBuffer * @param {*} buffer * @param {string} [name='buffer'] * @returns {asserts buffer is ArrayBufferView} */ /** @type {validateBuffer} */ const validateBuffer = hideStackFrames((buffer, name = 'buffer') => { if (!isArrayBufferView(buffer)) { throw new ERR_INVALID_ARG_TYPE(name, ['Buffer', 'TypedArray', 'DataView'], buffer) } }) /** * @param {string} data * @param {string} encoding */ function validateEncoding(data, encoding) { const normalizedEncoding = normalizeEncoding(encoding) const length = data.length if (normalizedEncoding === 'hex' && length % 2 !== 0) { throw new ERR_INVALID_ARG_VALUE('encoding', encoding, `is invalid for data of length ${length}`) } } /** * Check that the port number is not NaN when coerced to a number, * is an integer and that it falls within the legal range of port numbers. * @param {*} port * @param {string} [name='Port'] * @param {boolean} [allowZero=true] * @returns {number} */ function validatePort(port, name = 'Port', allowZero = true) { if ( (typeof port !== 'number' && typeof port !== 'string') || (typeof port === 'string' && StringPrototypeTrim(port).length === 0) || +port !== +port >>> 0 || port > 0xffff || (port === 0 && !allowZero) ) { throw new ERR_SOCKET_BAD_PORT(name, port, allowZero) } return port | 0 } /** * @callback validateAbortSignal * @param {*} signal * @param {string} name */ /** @type {validateAbortSignal} */ const validateAbortSignal = hideStackFrames((signal, name) => { if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) { throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) } }) /** * @callback validateFunction * @param {*} value * @param {string} name * @returns {asserts value is Function} */ /** @type {validateFunction} */ const validateFunction = hideStackFrames((value, name) => { if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) }) /** * @callback validatePlainFunction * @param {*} value * @param {string} name * @returns {asserts value is Function} */ /** @type {validatePlainFunction} */ const validatePlainFunction = hideStackFrames((value, name) => { if (typeof value !== 'function' || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) }) /** * @callback validateUndefined * @param {*} value * @param {string} name * @returns {asserts value is undefined} */ /** @type {validateUndefined} */ const validateUndefined = hideStackFrames((value, name) => { if (value !== undefined) throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value) }) /** * @template T * @param {T} value * @param {string} name * @param {T[]} union */ function validateUnion(value, name, union) { if (!ArrayPrototypeIncludes(union, value)) { throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value) } } /* The rules for the Link header field are described here: https://www.rfc-editor.org/rfc/rfc8288.html#section-3 This regex validates any string surrounded by angle brackets (not necessarily a valid URI reference) followed by zero or more link-params separated by semicolons. */ const linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/ /** * @param {any} value * @param {string} name */ function validateLinkHeaderFormat(value, name) { if (typeof value === 'undefined' || !RegExpPrototypeExec(linkValueRegExp, value)) { throw new ERR_INVALID_ARG_VALUE( name, value, 'must be an array or string of format "; rel=preload; as=style"' ) } } /** * @param {any} hints * @return {string} */ function validateLinkHeaderValue(hints) { if (typeof hints === 'string') { validateLinkHeaderFormat(hints, 'hints') return hints } else if (ArrayIsArray(hints)) { const hintsLength = hints.length let result = '' if (hintsLength === 0) { return result } for (let i = 0; i < hintsLength; i++) { const link = hints[i] validateLinkHeaderFormat(link, 'hints') result += link if (i !== hintsLength - 1) { result += ', ' } } return result } throw new ERR_INVALID_ARG_VALUE( 'hints', hints, 'must be an array or string of format "; rel=preload; as=style"' ) } module.exports = { isInt32, isUint32, parseFileMode, validateArray, validateStringArray, validateBooleanArray, validateAbortSignalArray, validateBoolean, validateBuffer, validateDictionary, validateEncoding, validateFunction, validateInt32, validateInteger, validateNumber, validateObject, validateOneOf, validatePlainFunction, validatePort, validateSignalName, validateString, validateUint32, validateUndefined, validateUnion, validateAbortSignal, validateLinkHeaderValue } /***/ }), /***/ 6786: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { format, inspect } = __nccwpck_require__(8050) const { AggregateError: CustomAggregateError } = __nccwpck_require__(9229) /* This file is a reduced and adapted version of the main lib/internal/errors.js file defined at https://github.com/nodejs/node/blob/main/lib/internal/errors.js Don't try to replace with the original file and keep it up to date (starting from E(...) definitions) with the upstream file. */ const AggregateError = globalThis.AggregateError || CustomAggregateError const kIsNodeError = Symbol('kIsNodeError') const kTypes = [ 'string', 'function', 'number', 'object', // Accept 'Function' and 'Object' as alternative to the lower cased version. 'Function', 'Object', 'boolean', 'bigint', 'symbol' ] const classRegExp = /^([A-Z][a-z0-9]*)+$/ const nodeInternalPrefix = '__node_internal_' const codes = {} function assert(value, message) { if (!value) { throw new codes.ERR_INTERNAL_ASSERTION(message) } } // Only use this for integers! Decimal numbers do not work with this function. function addNumericalSeparator(val) { let res = '' let i = val.length const start = val[0] === '-' ? 1 : 0 for (; i >= start + 4; i -= 3) { res = `_${val.slice(i - 3, i)}${res}` } return `${val.slice(0, i)}${res}` } function getMessage(key, msg, args) { if (typeof msg === 'function') { assert( msg.length <= args.length, // Default options do not count. `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).` ) return msg(...args) } const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length assert( expectedLength === args.length, `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).` ) if (args.length === 0) { return msg } return format(msg, ...args) } function E(code, message, Base) { if (!Base) { Base = Error } class NodeError extends Base { constructor(...args) { super(getMessage(code, message, args)) } toString() { return `${this.name} [${code}]: ${this.message}` } } Object.defineProperties(NodeError.prototype, { name: { value: Base.name, writable: true, enumerable: false, configurable: true }, toString: { value() { return `${this.name} [${code}]: ${this.message}` }, writable: true, enumerable: false, configurable: true } }) NodeError.prototype.code = code NodeError.prototype[kIsNodeError] = true codes[code] = NodeError } function hideStackFrames(fn) { // We rename the functions that will be hidden to cut off the stacktrace // at the outermost one const hidden = nodeInternalPrefix + fn.name Object.defineProperty(fn, 'name', { value: hidden }) return fn } function aggregateTwoErrors(innerError, outerError) { if (innerError && outerError && innerError !== outerError) { if (Array.isArray(outerError.errors)) { // If `outerError` is already an `AggregateError`. outerError.errors.push(innerError) return outerError } const err = new AggregateError([outerError, innerError], outerError.message) err.code = outerError.code return err } return innerError || outerError } class AbortError extends Error { constructor(message = 'The operation was aborted', options = undefined) { if (options !== undefined && typeof options !== 'object') { throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options) } super(message, options) this.code = 'ABORT_ERR' this.name = 'AbortError' } } E('ERR_ASSERTION', '%s', Error) E( 'ERR_INVALID_ARG_TYPE', (name, expected, actual) => { assert(typeof name === 'string', "'name' must be a string") if (!Array.isArray(expected)) { expected = [expected] } let msg = 'The ' if (name.endsWith(' argument')) { // For cases like 'first argument' msg += `${name} ` } else { msg += `"${name}" ${name.includes('.') ? 'property' : 'argument'} ` } msg += 'must be ' const types = [] const instances = [] const other = [] for (const value of expected) { assert(typeof value === 'string', 'All expected entries have to be of type string') if (kTypes.includes(value)) { types.push(value.toLowerCase()) } else if (classRegExp.test(value)) { instances.push(value) } else { assert(value !== 'object', 'The value "object" should be written as "Object"') other.push(value) } } // Special handle `object` in case other instances are allowed to outline // the differences between each other. if (instances.length > 0) { const pos = types.indexOf('object') if (pos !== -1) { types.splice(types, pos, 1) instances.push('Object') } } if (types.length > 0) { switch (types.length) { case 1: msg += `of type ${types[0]}` break case 2: msg += `one of type ${types[0]} or ${types[1]}` break default: { const last = types.pop() msg += `one of type ${types.join(', ')}, or ${last}` } } if (instances.length > 0 || other.length > 0) { msg += ' or ' } } if (instances.length > 0) { switch (instances.length) { case 1: msg += `an instance of ${instances[0]}` break case 2: msg += `an instance of ${instances[0]} or ${instances[1]}` break default: { const last = instances.pop() msg += `an instance of ${instances.join(', ')}, or ${last}` } } if (other.length > 0) { msg += ' or ' } } switch (other.length) { case 0: break case 1: if (other[0].toLowerCase() !== other[0]) { msg += 'an ' } msg += `${other[0]}` break case 2: msg += `one of ${other[0]} or ${other[1]}` break default: { const last = other.pop() msg += `one of ${other.join(', ')}, or ${last}` } } if (actual == null) { msg += `. Received ${actual}` } else if (typeof actual === 'function' && actual.name) { msg += `. Received function ${actual.name}` } else if (typeof actual === 'object') { var _actual$constructor if ( (_actual$constructor = actual.constructor) !== null && _actual$constructor !== undefined && _actual$constructor.name ) { msg += `. Received an instance of ${actual.constructor.name}` } else { const inspected = inspect(actual, { depth: -1 }) msg += `. Received ${inspected}` } } else { let inspected = inspect(actual, { colors: false }) if (inspected.length > 25) { inspected = `${inspected.slice(0, 25)}...` } msg += `. Received type ${typeof actual} (${inspected})` } return msg }, TypeError ) E( 'ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => { let inspected = inspect(value) if (inspected.length > 128) { inspected = inspected.slice(0, 128) + '...' } const type = name.includes('.') ? 'property' : 'argument' return `The ${type} '${name}' ${reason}. Received ${inspected}` }, TypeError ) E( 'ERR_INVALID_RETURN_VALUE', (input, name, value) => { var _value$constructor const type = value !== null && value !== undefined && (_value$constructor = value.constructor) !== null && _value$constructor !== undefined && _value$constructor.name ? `instance of ${value.constructor.name}` : `type ${typeof value}` return `Expected ${input} to be returned from the "${name}"` + ` function but got ${type}.` }, TypeError ) E( 'ERR_MISSING_ARGS', (...args) => { assert(args.length > 0, 'At least one arg needs to be specified') let msg const len = args.length args = (Array.isArray(args) ? args : [args]).map((a) => `"${a}"`).join(' or ') switch (len) { case 1: msg += `The ${args[0]} argument` break case 2: msg += `The ${args[0]} and ${args[1]} arguments` break default: { const last = args.pop() msg += `The ${args.join(', ')}, and ${last} arguments` } break } return `${msg} must be specified` }, TypeError ) E( 'ERR_OUT_OF_RANGE', (str, range, input) => { assert(range, 'Missing "range" argument') let received if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { received = addNumericalSeparator(String(input)) } else if (typeof input === 'bigint') { received = String(input) const limit = BigInt(2) ** BigInt(32) if (input > limit || input < -limit) { received = addNumericalSeparator(received) } received += 'n' } else { received = inspect(input) } return `The value of "${str}" is out of range. It must be ${range}. Received ${received}` }, RangeError ) E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error) E('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error) E('ERR_STREAM_ALREADY_FINISHED', 'Cannot call %s after a stream was finished', Error) E('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error) E('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error) E('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError) E('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error) E('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error) E('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event', Error) E('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error) E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError) module.exports = { AbortError, aggregateTwoErrors: hideStackFrames(aggregateTwoErrors), hideStackFrames, codes } /***/ }), /***/ 8893: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Stream = __nccwpck_require__(2203) if (Stream && process.env.READABLE_STREAM === 'disable') { const promises = Stream.promises // Explicit export naming is needed for ESM module.exports._uint8ArrayToBuffer = Stream._uint8ArrayToBuffer module.exports._isUint8Array = Stream._isUint8Array module.exports.isDisturbed = Stream.isDisturbed module.exports.isErrored = Stream.isErrored module.exports.isReadable = Stream.isReadable module.exports.Readable = Stream.Readable module.exports.Writable = Stream.Writable module.exports.Duplex = Stream.Duplex module.exports.Transform = Stream.Transform module.exports.PassThrough = Stream.PassThrough module.exports.addAbortSignal = Stream.addAbortSignal module.exports.finished = Stream.finished module.exports.destroy = Stream.destroy module.exports.pipeline = Stream.pipeline module.exports.compose = Stream.compose Object.defineProperty(Stream, 'promises', { configurable: true, enumerable: true, get() { return promises } }) module.exports.Stream = Stream.Stream } else { const CustomStream = __nccwpck_require__(2469) const promises = __nccwpck_require__(6974) const originalDestroy = CustomStream.Readable.destroy module.exports = CustomStream.Readable // Explicit export naming is needed for ESM module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer module.exports._isUint8Array = CustomStream._isUint8Array module.exports.isDisturbed = CustomStream.isDisturbed module.exports.isErrored = CustomStream.isErrored module.exports.isReadable = CustomStream.isReadable module.exports.Readable = CustomStream.Readable module.exports.Writable = CustomStream.Writable module.exports.Duplex = CustomStream.Duplex module.exports.Transform = CustomStream.Transform module.exports.PassThrough = CustomStream.PassThrough module.exports.addAbortSignal = CustomStream.addAbortSignal module.exports.finished = CustomStream.finished module.exports.destroy = CustomStream.destroy module.exports.destroy = originalDestroy module.exports.pipeline = CustomStream.pipeline module.exports.compose = CustomStream.compose Object.defineProperty(CustomStream, 'promises', { configurable: true, enumerable: true, get() { return promises } }) module.exports.Stream = CustomStream.Stream } // Allow default importing module.exports["default"] = module.exports /***/ }), /***/ 9229: /***/ ((module) => { "use strict"; /* This file is a reduced and adapted version of the main lib/internal/per_context/primordials.js file defined at https://github.com/nodejs/node/blob/main/lib/internal/per_context/primordials.js Don't try to replace with the original file and keep it up to date with the upstream file. */ // This is a simplified version of AggregateError class AggregateError extends Error { constructor(errors) { if (!Array.isArray(errors)) { throw new TypeError(`Expected input to be an Array, got ${typeof errors}`) } let message = '' for (let i = 0; i < errors.length; i++) { message += ` ${errors[i].stack}\n` } super(message) this.name = 'AggregateError' this.errors = errors } } module.exports = { AggregateError, ArrayIsArray(self) { return Array.isArray(self) }, ArrayPrototypeIncludes(self, el) { return self.includes(el) }, ArrayPrototypeIndexOf(self, el) { return self.indexOf(el) }, ArrayPrototypeJoin(self, sep) { return self.join(sep) }, ArrayPrototypeMap(self, fn) { return self.map(fn) }, ArrayPrototypePop(self, el) { return self.pop(el) }, ArrayPrototypePush(self, el) { return self.push(el) }, ArrayPrototypeSlice(self, start, end) { return self.slice(start, end) }, Error, FunctionPrototypeCall(fn, thisArgs, ...args) { return fn.call(thisArgs, ...args) }, FunctionPrototypeSymbolHasInstance(self, instance) { return Function.prototype[Symbol.hasInstance].call(self, instance) }, MathFloor: Math.floor, Number, NumberIsInteger: Number.isInteger, NumberIsNaN: Number.isNaN, NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, NumberParseInt: Number.parseInt, ObjectDefineProperties(self, props) { return Object.defineProperties(self, props) }, ObjectDefineProperty(self, name, prop) { return Object.defineProperty(self, name, prop) }, ObjectGetOwnPropertyDescriptor(self, name) { return Object.getOwnPropertyDescriptor(self, name) }, ObjectKeys(obj) { return Object.keys(obj) }, ObjectSetPrototypeOf(target, proto) { return Object.setPrototypeOf(target, proto) }, Promise, PromisePrototypeCatch(self, fn) { return self.catch(fn) }, PromisePrototypeThen(self, thenFn, catchFn) { return self.then(thenFn, catchFn) }, PromiseReject(err) { return Promise.reject(err) }, PromiseResolve(val) { return Promise.resolve(val) }, ReflectApply: Reflect.apply, RegExpPrototypeTest(self, value) { return self.test(value) }, SafeSet: Set, String, StringPrototypeSlice(self, start, end) { return self.slice(start, end) }, StringPrototypeToLowerCase(self) { return self.toLowerCase() }, StringPrototypeToUpperCase(self) { return self.toUpperCase() }, StringPrototypeTrim(self) { return self.trim() }, Symbol, SymbolFor: Symbol.for, SymbolAsyncIterator: Symbol.asyncIterator, SymbolHasInstance: Symbol.hasInstance, SymbolIterator: Symbol.iterator, SymbolDispose: Symbol.dispose || Symbol('Symbol.dispose'), SymbolAsyncDispose: Symbol.asyncDispose || Symbol('Symbol.asyncDispose'), TypedArrayPrototypeSet(self, buf, len) { return self.set(buf, len) }, Boolean, Uint8Array } /***/ }), /***/ 3165: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const bufferModule = __nccwpck_require__(181) const { format, inspect } = __nccwpck_require__(8050) const { codes: { ERR_INVALID_ARG_TYPE } } = __nccwpck_require__(6786) const { kResistStopPropagation, AggregateError, SymbolDispose } = __nccwpck_require__(9229) const AbortSignal = globalThis.AbortSignal || (__nccwpck_require__(7413).AbortSignal) const AbortController = globalThis.AbortController || (__nccwpck_require__(7413).AbortController) const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor const Blob = globalThis.Blob || bufferModule.Blob /* eslint-disable indent */ const isBlob = typeof Blob !== 'undefined' ? function isBlob(b) { // eslint-disable-next-line indent return b instanceof Blob } : function isBlob(b) { return false } /* eslint-enable indent */ const validateAbortSignal = (signal, name) => { if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) { throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) } } const validateFunction = (value, name) => { if (typeof value !== 'function') { throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) } } module.exports = { AggregateError, kEmptyObject: Object.freeze({}), once(callback) { let called = false return function (...args) { if (called) { return } called = true callback.apply(this, args) } }, createDeferredPromise: function () { let resolve let reject // eslint-disable-next-line promise/param-names const promise = new Promise((res, rej) => { resolve = res reject = rej }) return { promise, resolve, reject } }, promisify(fn) { return new Promise((resolve, reject) => { fn((err, ...args) => { if (err) { return reject(err) } return resolve(...args) }) }) }, debuglog() { return function () {} }, format, inspect, types: { isAsyncFunction(fn) { return fn instanceof AsyncFunction }, isArrayBufferView(arr) { return ArrayBuffer.isView(arr) } }, isBlob, deprecate(fn, message) { return fn }, addAbortListener: (__nccwpck_require__(4434).addAbortListener) || function addAbortListener(signal, listener) { if (signal === undefined) { throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal) } validateAbortSignal(signal, 'signal') validateFunction(listener, 'listener') let removeEventListener if (signal.aborted) { queueMicrotask(() => listener()) } else { signal.addEventListener('abort', listener, { __proto__: null, once: true, [kResistStopPropagation]: true }) removeEventListener = () => { signal.removeEventListener('abort', listener) } } return { __proto__: null, [SymbolDispose]() { var _removeEventListener ;(_removeEventListener = removeEventListener) === null || _removeEventListener === undefined ? undefined : _removeEventListener() } } }, AbortSignalAny: AbortSignal.any || function AbortSignalAny(signals) { // Fast path if there is only one signal. if (signals.length === 1) { return signals[0] } const ac = new AbortController() const abort = () => ac.abort() signals.forEach((signal) => { validateAbortSignal(signal, 'signals') signal.addEventListener('abort', abort, { once: true }) }) ac.signal.addEventListener( 'abort', () => { signals.forEach((signal) => signal.removeEventListener('abort', abort)) }, { once: true } ) return ac.signal } } module.exports.promisify.custom = Symbol.for('nodejs.util.promisify.custom') /***/ }), /***/ 8050: /***/ ((module) => { "use strict"; /* This file is a reduced and adapted version of the main lib/internal/util/inspect.js file defined at https://github.com/nodejs/node/blob/main/lib/internal/util/inspect.js Don't try to replace with the original file and keep it up to date with the upstream file. */ module.exports = { format(format, ...args) { // Simplified version of https://nodejs.org/api/util.html#utilformatformat-args return format.replace(/%([sdifj])/g, function (...[_unused, type]) { const replacement = args.shift() if (type === 'f') { return replacement.toFixed(6) } else if (type === 'j') { return JSON.stringify(replacement) } else if (type === 's' && typeof replacement === 'object') { const ctor = replacement.constructor !== Object ? replacement.constructor.name : '' return `${ctor} {}`.trim() } else { return replacement.toString() } }) }, inspect(value) { // Vastly simplified version of https://nodejs.org/api/util.html#utilinspectobject-options switch (typeof value) { case 'string': if (value.includes("'")) { if (!value.includes('"')) { return `"${value}"` } else if (!value.includes('`') && !value.includes('${')) { return `\`${value}\`` } } return `'${value}'` case 'number': if (isNaN(value)) { return 'NaN' } else if (Object.is(value, -0)) { return String(value) } return value case 'bigint': return `${String(value)}n` case 'boolean': case 'undefined': return String(value) case 'object': return '{}' } } } /***/ }), /***/ 2469: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* replacement start */ const { Buffer } = __nccwpck_require__(181) /* replacement end */ const { ObjectDefineProperty, ObjectKeys, ReflectApply } = __nccwpck_require__(9229) const { promisify: { custom: customPromisify } } = __nccwpck_require__(3165) const { streamReturningOperators, promiseReturningOperators } = __nccwpck_require__(7080) const { codes: { ERR_ILLEGAL_CONSTRUCTOR } } = __nccwpck_require__(6786) const compose = __nccwpck_require__(7741) const { setDefaultHighWaterMark, getDefaultHighWaterMark } = __nccwpck_require__(4124) const { pipeline } = __nccwpck_require__(8219) const { destroyer } = __nccwpck_require__(8403) const eos = __nccwpck_require__(1897) const internalBuffer = {} const promises = __nccwpck_require__(6974) const utils = __nccwpck_require__(3892) const Stream = (module.exports = __nccwpck_require__(770).Stream) Stream.isDestroyed = utils.isDestroyed Stream.isDisturbed = utils.isDisturbed Stream.isErrored = utils.isErrored Stream.isReadable = utils.isReadable Stream.isWritable = utils.isWritable Stream.Readable = __nccwpck_require__(9569) for (const key of ObjectKeys(streamReturningOperators)) { const op = streamReturningOperators[key] function fn(...args) { if (new.target) { throw ERR_ILLEGAL_CONSTRUCTOR() } return Stream.Readable.from(ReflectApply(op, this, args)) } ObjectDefineProperty(fn, 'name', { __proto__: null, value: op.name }) ObjectDefineProperty(fn, 'length', { __proto__: null, value: op.length }) ObjectDefineProperty(Stream.Readable.prototype, key, { __proto__: null, value: fn, enumerable: false, configurable: true, writable: true }) } for (const key of ObjectKeys(promiseReturningOperators)) { const op = promiseReturningOperators[key] function fn(...args) { if (new.target) { throw ERR_ILLEGAL_CONSTRUCTOR() } return ReflectApply(op, this, args) } ObjectDefineProperty(fn, 'name', { __proto__: null, value: op.name }) ObjectDefineProperty(fn, 'length', { __proto__: null, value: op.length }) ObjectDefineProperty(Stream.Readable.prototype, key, { __proto__: null, value: fn, enumerable: false, configurable: true, writable: true }) } Stream.Writable = __nccwpck_require__(9745) Stream.Duplex = __nccwpck_require__(8915) Stream.Transform = __nccwpck_require__(9253) Stream.PassThrough = __nccwpck_require__(5023) Stream.pipeline = pipeline const { addAbortSignal } = __nccwpck_require__(6942) Stream.addAbortSignal = addAbortSignal Stream.finished = eos Stream.destroy = destroyer Stream.compose = compose Stream.setDefaultHighWaterMark = setDefaultHighWaterMark Stream.getDefaultHighWaterMark = getDefaultHighWaterMark ObjectDefineProperty(Stream, 'promises', { __proto__: null, configurable: true, enumerable: true, get() { return promises } }) ObjectDefineProperty(pipeline, customPromisify, { __proto__: null, enumerable: true, get() { return promises.pipeline } }) ObjectDefineProperty(eos, customPromisify, { __proto__: null, enumerable: true, get() { return promises.finished } }) // Backwards-compat with node 0.4.x Stream.Stream = Stream Stream._isUint8Array = function isUint8Array(value) { return value instanceof Uint8Array } Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) } /***/ }), /***/ 6974: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { ArrayPrototypePop, Promise } = __nccwpck_require__(9229) const { isIterable, isNodeStream, isWebStream } = __nccwpck_require__(3892) const { pipelineImpl: pl } = __nccwpck_require__(8219) const { finished } = __nccwpck_require__(1897) __nccwpck_require__(2469) function pipeline(...streams) { return new Promise((resolve, reject) => { let signal let end const lastArg = streams[streams.length - 1] if ( lastArg && typeof lastArg === 'object' && !isNodeStream(lastArg) && !isIterable(lastArg) && !isWebStream(lastArg) ) { const options = ArrayPrototypePop(streams) signal = options.signal end = options.end } pl( streams, (err, value) => { if (err) { reject(err) } else { resolve(value) } }, { signal, end } ) }) } module.exports = { finished, pipeline } /***/ }), /***/ 9536: /***/ ((module, exports, __nccwpck_require__) => { /*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = __nccwpck_require__(181) var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } SafeBuffer.prototype = Object.create(Buffer.prototype) // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } /***/ }), /***/ 6660: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /**/ var Buffer = (__nccwpck_require__(9536).Buffer); /**/ var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.StringDecoder = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. If an invalid byte is detected, -2 is returned. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return byte >> 6 === 0x02 ? -1 : -2; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'; } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'; } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'; } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character is added when ending on a partial // character. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'; return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } /***/ }), /***/ 8577: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { (function (global, factory) { true ? factory(exports, __nccwpck_require__(2979), __nccwpck_require__(5300), __nccwpck_require__(8208), __nccwpck_require__(7228), __nccwpck_require__(215)) : 0; })(this, (function (exports, fastUniqueNumbers, _defineProperty, _slicedToArray, _asyncToGenerator, _regeneratorRuntime) { 'use strict'; function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } var createBrokerFactory = function createBrokerFactory(createOrGetOngoingRequests, extendBrokerImplementation, generateUniqueNumber, isMessagePort) { return function (brokerImplementation) { var fullBrokerImplementation = extendBrokerImplementation(brokerImplementation); return function (sender) { var ongoingRequests = createOrGetOngoingRequests(sender); sender.addEventListener('message', function (_ref) { var message = _ref.data; var id = message.id; if (id !== null && ongoingRequests.has(id)) { var _ongoingRequests$get = ongoingRequests.get(id), reject = _ongoingRequests$get.reject, resolve = _ongoingRequests$get.resolve; ongoingRequests["delete"](id); if (message.error === undefined) { resolve(message.result); } else { reject(new Error(message.error.message)); } } }); if (isMessagePort(sender)) { sender.start(); } var call = function call(method) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var transferables = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; return new Promise(function (resolve, reject) { var id = generateUniqueNumber(ongoingRequests); ongoingRequests.set(id, { reject: reject, resolve: resolve }); if (params === null) { sender.postMessage({ id: id, method: method }, transferables); } else { sender.postMessage({ id: id, method: method, params: params }, transferables); } }); }; var notify = function notify(method, params) { var transferables = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; sender.postMessage({ id: null, method: method, params: params }, transferables); }; var functions = {}; for (var _i = 0, _Object$entries = Object.entries(fullBrokerImplementation); _i < _Object$entries.length; _i++) { var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), key = _Object$entries$_i[0], handler = _Object$entries$_i[1]; functions = _objectSpread$1(_objectSpread$1({}, functions), {}, _defineProperty({}, key, handler({ call: call, notify: notify }))); } return _objectSpread$1({}, functions); }; }; }; var createCreateOrGetOngoingRequests = function createCreateOrGetOngoingRequests(ongoingRequestsMap) { return function (sender) { if (ongoingRequestsMap.has(sender)) { // @todo TypeScript needs to be convinced that has() works as expected. return ongoingRequestsMap.get(sender); } var ongoingRequests = new Map(); ongoingRequestsMap.set(sender, ongoingRequests); return ongoingRequests; }; }; function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } var createExtendBrokerImplementation = function createExtendBrokerImplementation(portMap) { return function (partialBrokerImplementation) { return _objectSpread(_objectSpread({}, partialBrokerImplementation), {}, { connect: function connect(_ref) { var call = _ref.call; return /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee() { var _MessageChannel, port1, port2, portId; return _regeneratorRuntime.wrap(function (_context) { while (1) switch (_context.prev = _context.next) { case 0: _MessageChannel = new MessageChannel(), port1 = _MessageChannel.port1, port2 = _MessageChannel.port2; _context.next = 1; return call('connect', { port: port1 }, [port1]); case 1: portId = _context.sent; portMap.set(port2, portId); return _context.abrupt("return", port2); case 2: case "end": return _context.stop(); } }, _callee); })); }, disconnect: function disconnect(_ref3) { var call = _ref3.call; return /*#__PURE__*/function () { var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(port) { var portId; return _regeneratorRuntime.wrap(function (_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: portId = portMap.get(port); if (!(portId === undefined)) { _context2.next = 1; break; } throw new Error('The given port is not connected.'); case 1: _context2.next = 2; return call('disconnect', { portId: portId }); case 2: case "end": return _context2.stop(); } }, _callee2); })); return function (_x) { return _ref4.apply(this, arguments); }; }(); }, isSupported: function isSupported(_ref5) { var call = _ref5.call; return function () { return call('isSupported'); }; } }); }; }; var isMessagePort = function isMessagePort(sender) { return typeof sender.start === 'function'; }; var createBroker = createBrokerFactory(createCreateOrGetOngoingRequests(new WeakMap()), createExtendBrokerImplementation(new WeakMap()), fastUniqueNumbers.generateUniqueNumber, isMessagePort); exports.createBroker = createBroker; })); /***/ }), /***/ 4718: /***/ ((module) => { /* eslint-disable node/no-deprecated-api */ var toString = Object.prototype.toString var isModern = ( typeof Buffer !== 'undefined' && typeof Buffer.alloc === 'function' && typeof Buffer.allocUnsafe === 'function' && typeof Buffer.from === 'function' ) function isArrayBuffer (input) { return toString.call(input).slice(8, -1) === 'ArrayBuffer' } function fromArrayBuffer (obj, byteOffset, length) { byteOffset >>>= 0 var maxLength = obj.byteLength - byteOffset if (maxLength < 0) { throw new RangeError("'offset' is out of bounds") } if (length === undefined) { length = maxLength } else { length >>>= 0 if (length > maxLength) { throw new RangeError("'length' is out of bounds") } } return isModern ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } return isModern ? Buffer.from(string, encoding) : new Buffer(string, encoding) } function bufferFrom (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (isArrayBuffer(value)) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(value, encodingOrOffset) } return isModern ? Buffer.from(value) : new Buffer(value) } module.exports = bufferFrom /***/ }), /***/ 2639: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var bind = __nccwpck_require__(7564); var $apply = __nccwpck_require__(3945); var $call = __nccwpck_require__(8093); var $reflectApply = __nccwpck_require__(1330); /** @type {import('./actualApply')} */ module.exports = $reflectApply || bind.call($call, $apply); /***/ }), /***/ 3945: /***/ ((module) => { "use strict"; /** @type {import('./functionApply')} */ module.exports = Function.prototype.apply; /***/ }), /***/ 8093: /***/ ((module) => { "use strict"; /** @type {import('./functionCall')} */ module.exports = Function.prototype.call; /***/ }), /***/ 8705: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var bind = __nccwpck_require__(7564); var $TypeError = __nccwpck_require__(3314); var $call = __nccwpck_require__(8093); var $actualApply = __nccwpck_require__(2639); /** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ module.exports = function callBindBasic(args) { if (args.length < 1 || typeof args[0] !== 'function') { throw new $TypeError('a function is required'); } return $actualApply(bind, $call, args); }; /***/ }), /***/ 1330: /***/ ((module) => { "use strict"; /** @type {import('./reflectApply')} */ module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; /***/ }), /***/ 3105: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var GetIntrinsic = __nccwpck_require__(470); var callBindBasic = __nccwpck_require__(8705); /** @type {(thisArg: string, searchString: string, position?: number) => number} */ var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]); /** @type {import('.')} */ module.exports = function callBoundIntrinsic(name, allowMissing) { /* eslint no-extra-parens: 0 */ var intrinsic = /** @type {(this: unknown, ...args: unknown[]) => unknown} */ (GetIntrinsic(name, !!allowMissing)); if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { return callBindBasic(/** @type {const} */ ([intrinsic])); } return intrinsic; }; /***/ }), /***/ 8626: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Writable = (__nccwpck_require__(6131).Writable) var inherits = __nccwpck_require__(9598) function CallbackStream (options, callback) { if (!(this instanceof CallbackStream)) { return new CallbackStream(options, callback) } if (typeof options === 'function') { callback = options options = {} } Writable.call(this, options) this.results = [] this.callback = callback this.on('finish', deliversCallback) this.once('pipe', handlePipe) } function deliversCallback () { this.callback(null, this.results) } function handlePipe (source) { source.on('error', this.callback) } inherits(CallbackStream, Writable) CallbackStream.prototype._write = function (data, encoding, done) { this.results.push(data) done() } CallbackStream.obj = function (options, callback) { if (typeof options === 'function') { callback = options options = {} } options.objectMode = true return new CallbackStream(options, callback) } module.exports = CallbackStream /***/ }), /***/ 9468: /***/ ((module) => { module.exports = function (xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { var x = fn(xs[i], i); if (isArray(x)) res.push.apply(res, x); else res.push(x); } return res; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; /***/ }), /***/ 5481: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = __nccwpck_require__(181).Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } /***/ }), /***/ 749: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isValue = __nccwpck_require__(3796) , ensureValue = __nccwpck_require__(7362) , ensurePlainFunction = __nccwpck_require__(8650) , copy = __nccwpck_require__(4880) , normalizeOptions = __nccwpck_require__(4201) , map = __nccwpck_require__(3511); var bind = Function.prototype.bind , defineProperty = Object.defineProperty , hasOwnProperty = Object.prototype.hasOwnProperty , define; define = function (name, desc, options) { var value = ensureValue(desc) && ensurePlainFunction(desc.value), dgs; dgs = copy(desc); delete dgs.writable; delete dgs.value; dgs.get = function () { if (!options.overwriteDefinition && hasOwnProperty.call(this, name)) return value; desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this); defineProperty(this, name, desc); return this[name]; }; return dgs; }; module.exports = function (props/*, options*/) { var options = normalizeOptions(arguments[1]); if (isValue(options.resolveContext)) ensurePlainFunction(options.resolveContext); return map(props, function (desc, name) { return define(name, desc, options); }); }; /***/ }), /***/ 8792: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isValue = __nccwpck_require__(3796) , isPlainFunction = __nccwpck_require__(4031) , assign = __nccwpck_require__(5771) , normalizeOpts = __nccwpck_require__(4201) , contains = __nccwpck_require__(1691); var d = (module.exports = function (dscr, value/*, options*/) { var c, e, w, options, desc; if (arguments.length < 2 || typeof dscr !== "string") { options = value; value = dscr; dscr = null; } else { options = arguments[2]; } if (isValue(dscr)) { c = contains.call(dscr, "c"); e = contains.call(dscr, "e"); w = contains.call(dscr, "w"); } else { c = w = true; e = false; } desc = { value: value, configurable: c, enumerable: e, writable: w }; return !options ? desc : assign(normalizeOpts(options), desc); }); d.gs = function (dscr, get, set/*, options*/) { var c, e, options, desc; if (typeof dscr !== "string") { options = set; set = get; get = dscr; dscr = null; } else { options = arguments[3]; } if (!isValue(get)) { get = undefined; } else if (!isPlainFunction(get)) { options = get; get = set = undefined; } else if (!isValue(set)) { set = undefined; } else if (!isPlainFunction(set)) { options = set; set = undefined; } if (isValue(dscr)) { c = contains.call(dscr, "c"); e = contains.call(dscr, "e"); } else { c = true; e = false; } desc = { get: get, set: set, configurable: c, enumerable: e }; return !options ? desc : assign(normalizeOpts(options), desc); }; /***/ }), /***/ 6110: /***/ ((module, exports, __nccwpck_require__) => { /* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } let m; // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 // eslint-disable-next-line no-return-assign return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = __nccwpck_require__(897)(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; /***/ }), /***/ 897: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = __nccwpck_require__(744); createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; const split = (typeof namespaces === 'string' ? namespaces : '') .trim() .replace(' ', ',') .split(',') .filter(Boolean); for (const ns of split) { if (ns[0] === '-') { createDebug.skips.push(ns.slice(1)); } else { createDebug.names.push(ns); } } } /** * Checks if the given string matches a namespace template, honoring * asterisks as wildcards. * * @param {String} search * @param {String} template * @return {Boolean} */ function matchesTemplate(search, template) { let searchIndex = 0; let templateIndex = 0; let starIndex = -1; let matchIndex = 0; while (searchIndex < search.length) { if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { // Match character or proceed with wildcard if (template[templateIndex] === '*') { starIndex = templateIndex; matchIndex = searchIndex; templateIndex++; // Skip the '*' } else { searchIndex++; templateIndex++; } } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition // Backtrack to the last '*' and try to match more characters templateIndex = starIndex + 1; matchIndex++; searchIndex = matchIndex; } else { return false; // No match } } // Handle trailing '*' in template while (templateIndex < template.length && template[templateIndex] === '*') { templateIndex++; } return templateIndex === template.length; } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names, ...createDebug.skips.map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { for (const skip of createDebug.skips) { if (matchesTemplate(name, skip)) { return false; } } for (const ns of createDebug.names) { if (matchesTemplate(name, ns)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } module.exports = setup; /***/ }), /***/ 2830: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { module.exports = __nccwpck_require__(6110); } else { module.exports = __nccwpck_require__(5108); } /***/ }), /***/ 5108: /***/ ((module, exports, __nccwpck_require__) => { /** * Module dependencies. */ const tty = __nccwpck_require__(2018); const util = __nccwpck_require__(9023); /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = __nccwpck_require__(1450); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = __nccwpck_require__(897)(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; /***/ }), /***/ 6669: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var callBind = __nccwpck_require__(8705); var gOPD = __nccwpck_require__(3170); var hasProtoAccessor; try { // eslint-disable-next-line no-extra-parens, no-proto hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; } catch (e) { if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { throw e; } } // eslint-disable-next-line no-extra-parens var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); var $Object = Object; var $getPrototypeOf = $Object.getPrototypeOf; /** @type {import('./get')} */ module.exports = desc && typeof desc.get === 'function' ? callBind([desc.get]) : typeof $getPrototypeOf === 'function' ? /** @type {import('./get')} */ function getDunder(value) { // eslint-disable-next-line eqeqeq return $getPrototypeOf(value == null ? value : $Object(value)); } : false; /***/ }), /***/ 9112: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var stream = __nccwpck_require__(6131) var eos = __nccwpck_require__(1424) var inherits = __nccwpck_require__(9598) var shift = __nccwpck_require__(4633) var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from) ? Buffer.from([0]) : new Buffer([0]) var onuncork = function(self, fn) { if (self._corked) self.once('uncork', fn) else fn() } var autoDestroy = function (self, err) { if (self._autoDestroy) self.destroy(err) } var destroyer = function(self, end) { return function(err) { if (err) autoDestroy(self, err.message === 'premature close' ? null : err) else if (end && !self._ended) self.end() } } var end = function(ws, fn) { if (!ws) return fn() if (ws._writableState && ws._writableState.finished) return fn() if (ws._writableState) return ws.end(fn) ws.end() fn() } var toStreams2 = function(rs) { return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs) } var Duplexify = function(writable, readable, opts) { if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts) stream.Duplex.call(this, opts) this._writable = null this._readable = null this._readable2 = null this._autoDestroy = !opts || opts.autoDestroy !== false this._forwardDestroy = !opts || opts.destroy !== false this._forwardEnd = !opts || opts.end !== false this._corked = 1 // start corked this._ondrain = null this._drained = false this._forwarding = false this._unwrite = null this._unread = null this._ended = false this.destroyed = false if (writable) this.setWritable(writable) if (readable) this.setReadable(readable) } inherits(Duplexify, stream.Duplex) Duplexify.obj = function(writable, readable, opts) { if (!opts) opts = {} opts.objectMode = true opts.highWaterMark = 16 return new Duplexify(writable, readable, opts) } Duplexify.prototype.cork = function() { if (++this._corked === 1) this.emit('cork') } Duplexify.prototype.uncork = function() { if (this._corked && --this._corked === 0) this.emit('uncork') } Duplexify.prototype.setWritable = function(writable) { if (this._unwrite) this._unwrite() if (this.destroyed) { if (writable && writable.destroy) writable.destroy() return } if (writable === null || writable === false) { this.end() return } var self = this var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd)) var ondrain = function() { var ondrain = self._ondrain self._ondrain = null if (ondrain) ondrain() } var clear = function() { self._writable.removeListener('drain', ondrain) unend() } if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks this._writable = writable this._writable.on('drain', ondrain) this._unwrite = clear this.uncork() // always uncork setWritable } Duplexify.prototype.setReadable = function(readable) { if (this._unread) this._unread() if (this.destroyed) { if (readable && readable.destroy) readable.destroy() return } if (readable === null || readable === false) { this.push(null) this.resume() return } var self = this var unend = eos(readable, {writable:false, readable:true}, destroyer(this)) var onreadable = function() { self._forward() } var onend = function() { self.push(null) } var clear = function() { self._readable2.removeListener('readable', onreadable) self._readable2.removeListener('end', onend) unend() } this._drained = true this._readable = readable this._readable2 = readable._readableState ? readable : toStreams2(readable) this._readable2.on('readable', onreadable) this._readable2.on('end', onend) this._unread = clear this._forward() } Duplexify.prototype._read = function() { this._drained = true this._forward() } Duplexify.prototype._forward = function() { if (this._forwarding || !this._readable2 || !this._drained) return this._forwarding = true var data while (this._drained && (data = shift(this._readable2)) !== null) { if (this.destroyed) continue this._drained = this.push(data) } this._forwarding = false } Duplexify.prototype.destroy = function(err) { if (this.destroyed) return this.destroyed = true var self = this process.nextTick(function() { self._destroy(err) }) } Duplexify.prototype._destroy = function(err) { if (err) { var ondrain = this._ondrain this._ondrain = null if (ondrain) ondrain(err) else this.emit('error', err) } if (this._forwardDestroy) { if (this._readable && this._readable.destroy) this._readable.destroy() if (this._writable && this._writable.destroy) this._writable.destroy() } this.emit('close') } Duplexify.prototype._write = function(data, enc, cb) { if (this.destroyed) return cb() if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)) if (data === SIGNAL_FLUSH) return this._finish(cb) if (!this._writable) return cb() if (this._writable.write(data) === false) this._ondrain = cb else cb() } Duplexify.prototype._finish = function(cb) { var self = this this.emit('preend') onuncork(this, function() { end(self._forwardEnd && self._writable, function() { // haxx to not emit prefinish twice if (self._writableState.prefinished === false) self._writableState.prefinished = true self.emit('prefinish') onuncork(self, cb) }) }) } Duplexify.prototype.end = function(data, enc, cb) { if (typeof data === 'function') return this.end(null, null, data) if (typeof enc === 'function') return this.end(data, null, enc) this._ended = true if (data) this.write(data) if (!this._writableState.ending) this.write(SIGNAL_FLUSH) return stream.Writable.prototype.end.call(this, cb) } module.exports = Duplexify /***/ }), /***/ 1424: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var once = __nccwpck_require__(5560); var noop = function() {}; var qnt = global.Bare ? queueMicrotask : process.nextTick.bind(process); var isRequest = function(stream) { return stream.setHeader && typeof stream.abort === 'function'; }; var isChildProcess = function(stream) { return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 }; var eos = function(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var ws = stream._writableState; var rs = stream._readableState; var readable = opts.readable || (opts.readable !== false && stream.readable); var writable = opts.writable || (opts.writable !== false && stream.writable); var cancelled = false; var onlegacyfinish = function() { if (!stream.writable) onfinish(); }; var onfinish = function() { writable = false; if (!readable) callback.call(stream); }; var onend = function() { readable = false; if (!writable) callback.call(stream); }; var onexit = function(exitCode) { callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); }; var onerror = function(err) { callback.call(stream, err); }; var onclose = function() { qnt(onclosenexttick); }; var onclosenexttick = function() { if (cancelled) return; if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); }; var onrequest = function() { stream.req.on('finish', onfinish); }; if (isRequest(stream)) { stream.on('complete', onfinish); stream.on('abort', onclose); if (stream.req) onrequest(); else stream.on('request', onrequest); } else if (writable && !ws) { // legacy streams stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } if (isChildProcess(stream)) stream.on('exit', onexit); stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', onerror); stream.on('close', onclose); return function() { cancelled = true; stream.removeListener('complete', onfinish); stream.removeListener('abort', onclose); stream.removeListener('request', onrequest); if (stream.req) stream.req.removeListener('finish', onfinish); stream.removeListener('end', onlegacyfinish); stream.removeListener('close', onlegacyfinish); stream.removeListener('finish', onfinish); stream.removeListener('exit', onexit); stream.removeListener('end', onend); stream.removeListener('error', onerror); stream.removeListener('close', onclose); }; }; module.exports = eos; /***/ }), /***/ 9094: /***/ ((module) => { "use strict"; /** @type {import('.')} */ var $defineProperty = Object.defineProperty || false; if ($defineProperty) { try { $defineProperty({}, 'a', { value: 1 }); } catch (e) { // IE 8 has a broken defineProperty $defineProperty = false; } } module.exports = $defineProperty; /***/ }), /***/ 3056: /***/ ((module) => { "use strict"; /** @type {import('./eval')} */ module.exports = EvalError; /***/ }), /***/ 1620: /***/ ((module) => { "use strict"; /** @type {import('.')} */ module.exports = Error; /***/ }), /***/ 4585: /***/ ((module) => { "use strict"; /** @type {import('./range')} */ module.exports = RangeError; /***/ }), /***/ 6905: /***/ ((module) => { "use strict"; /** @type {import('./ref')} */ module.exports = ReferenceError; /***/ }), /***/ 105: /***/ ((module) => { "use strict"; /** @type {import('./syntax')} */ module.exports = SyntaxError; /***/ }), /***/ 3314: /***/ ((module) => { "use strict"; /** @type {import('./type')} */ module.exports = TypeError; /***/ }), /***/ 2578: /***/ ((module) => { "use strict"; /** @type {import('./uri')} */ module.exports = URIError; /***/ }), /***/ 5399: /***/ ((module) => { "use strict"; /** @type {import('.')} */ module.exports = Object; /***/ }), /***/ 7896: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Inspired by Google Closure: // http://closure-library.googlecode.com/svn/docs/ // closure_goog_array_array.js.html#goog.array.clear var value = __nccwpck_require__(7643); module.exports = function () { value(this).length = 0; return this; }; /***/ }), /***/ 6649: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var numberIsNaN = __nccwpck_require__(1524) , toPosInt = __nccwpck_require__(94) , value = __nccwpck_require__(7643) , indexOf = Array.prototype.indexOf , objHasOwnProperty = Object.prototype.hasOwnProperty , abs = Math.abs , floor = Math.floor; module.exports = function (searchElement /*, fromIndex*/) { var i, length, fromIndex, val; if (!numberIsNaN(searchElement)) return indexOf.apply(this, arguments); length = toPosInt(value(this).length); fromIndex = arguments[1]; if (isNaN(fromIndex)) fromIndex = 0; else if (fromIndex >= 0) fromIndex = floor(fromIndex); else fromIndex = toPosInt(this.length) - floor(abs(fromIndex)); for (i = fromIndex; i < length; ++i) { if (objHasOwnProperty.call(this, i)) { val = this[i]; if (numberIsNaN(val)) return i; // Jslint: ignore } } return -1; }; /***/ }), /***/ 1232: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(7831)() ? Array.from : __nccwpck_require__(7311); /***/ }), /***/ 7831: /***/ ((module) => { "use strict"; module.exports = function () { var from = Array.from, arr, result; if (typeof from !== "function") return false; arr = ["raz", "dwa"]; result = from(arr); return Boolean(result && result !== arr && result[1] === "dwa"); }; /***/ }), /***/ 7311: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var iteratorSymbol = (__nccwpck_require__(9425).iterator) , isArguments = __nccwpck_require__(1941) , isFunction = __nccwpck_require__(7777) , toPosInt = __nccwpck_require__(94) , callable = __nccwpck_require__(1352) , validValue = __nccwpck_require__(7643) , isValue = __nccwpck_require__(8765) , isString = __nccwpck_require__(7005) , isArray = Array.isArray , call = Function.prototype.call , desc = { configurable: true, enumerable: true, writable: true, value: null } , defineProperty = Object.defineProperty; // eslint-disable-next-line complexity, max-lines-per-function module.exports = function (arrayLike /*, mapFn, thisArg*/) { var mapFn = arguments[1] , thisArg = arguments[2] , Context , i , j , arr , length , code , iterator , result , getIterator , value; arrayLike = Object(validValue(arrayLike)); if (isValue(mapFn)) callable(mapFn); if (!this || this === Array || !isFunction(this)) { // Result: Plain array if (!mapFn) { if (isArguments(arrayLike)) { // Source: Arguments length = arrayLike.length; if (length !== 1) return Array.apply(null, arrayLike); arr = new Array(1); arr[0] = arrayLike[0]; return arr; } if (isArray(arrayLike)) { // Source: Array arr = new Array((length = arrayLike.length)); for (i = 0; i < length; ++i) arr[i] = arrayLike[i]; return arr; } } arr = []; } else { // Result: Non plain array Context = this; } if (!isArray(arrayLike)) { if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) { // Source: Iterator iterator = callable(getIterator).call(arrayLike); if (Context) arr = new Context(); result = iterator.next(); i = 0; while (!result.done) { value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value; if (Context) { desc.value = value; defineProperty(arr, i, desc); } else { arr[i] = value; } result = iterator.next(); ++i; } length = i; } else if (isString(arrayLike)) { // Source: String length = arrayLike.length; if (Context) arr = new Context(); for (i = 0, j = 0; i < length; ++i) { value = arrayLike[i]; if (i + 1 < length) { code = value.charCodeAt(0); // eslint-disable-next-line max-depth if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i]; } value = mapFn ? call.call(mapFn, thisArg, value, j) : value; if (Context) { desc.value = value; defineProperty(arr, j, desc); } else { arr[j] = value; } ++j; } length = j; } } if (length === undefined) { // Source: array or array-like length = toPosInt(arrayLike.length); if (Context) arr = new Context(length); for (i = 0; i < length; ++i) { value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i]; if (Context) { desc.value = value; defineProperty(arr, i, desc); } else { arr[i] = value; } } } if (Context) { desc.value = null; arr.length = length; } return arr; }; /***/ }), /***/ 1941: /***/ ((module) => { "use strict"; var objToString = Object.prototype.toString , id = objToString.call((function () { return arguments; })()); module.exports = function (value) { return objToString.call(value) === id; }; /***/ }), /***/ 7777: /***/ ((module) => { "use strict"; var objToString = Object.prototype.toString , isFunctionStringTag = RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/); module.exports = function (value) { return typeof value === "function" && isFunctionStringTag(objToString.call(value)); }; /***/ }), /***/ 9688: /***/ ((module) => { "use strict"; // eslint-disable-next-line no-empty-function module.exports = function () {}; /***/ }), /***/ 1608: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(351)() ? Math.sign : __nccwpck_require__(9719); /***/ }), /***/ 351: /***/ ((module) => { "use strict"; module.exports = function () { var sign = Math.sign; if (typeof sign !== "function") return false; return sign(10) === 1 && sign(-20) === -1; }; /***/ }), /***/ 9719: /***/ ((module) => { "use strict"; module.exports = function (value) { value = Number(value); if (isNaN(value) || value === 0) return value; return value > 0 ? 1 : -1; }; /***/ }), /***/ 1524: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(2875)() ? Number.isNaN : __nccwpck_require__(6443); /***/ }), /***/ 2875: /***/ ((module) => { "use strict"; module.exports = function () { var numberIsNaN = Number.isNaN; if (typeof numberIsNaN !== "function") return false; return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34); }; /***/ }), /***/ 6443: /***/ ((module) => { "use strict"; module.exports = function (value) { // eslint-disable-next-line no-self-compare return value !== value; }; /***/ }), /***/ 5077: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var sign = __nccwpck_require__(1608) , abs = Math.abs , floor = Math.floor; module.exports = function (value) { if (isNaN(value)) return 0; value = Number(value); if (value === 0 || !isFinite(value)) return value; return sign(value) * floor(abs(value)); }; /***/ }), /***/ 94: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var toInteger = __nccwpck_require__(5077) , max = Math.max; module.exports = function (value) { return max(0, toInteger(value)); }; /***/ }), /***/ 3392: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Internal method, used by iteration functions. // Calls a function for each key-value pair found in object // Optionally takes compareFn to iterate object in specific order var callable = __nccwpck_require__(1352) , value = __nccwpck_require__(7643) , bind = Function.prototype.bind , call = Function.prototype.call , keys = Object.keys , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function (method, defVal) { return function (obj, cb /*, thisArg, compareFn*/) { var list, thisArg = arguments[2], compareFn = arguments[3]; obj = Object(value(obj)); callable(cb); list = keys(obj); if (compareFn) { list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined); } if (typeof method !== "function") method = list[method]; return call.call(method, list, function (key, index) { if (!objPropertyIsEnumerable.call(obj, key)) return defVal; return call.call(cb, thisArg, obj[key], key, obj, index); }); }; }; /***/ }), /***/ 5771: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(386)() ? Object.assign : __nccwpck_require__(2034); /***/ }), /***/ 386: /***/ ((module) => { "use strict"; module.exports = function () { var assign = Object.assign, obj; if (typeof assign !== "function") return false; obj = { foo: "raz" }; assign(obj, { bar: "dwa" }, { trzy: "trzy" }); return obj.foo + obj.bar + obj.trzy === "razdwatrzy"; }; /***/ }), /***/ 2034: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var keys = __nccwpck_require__(3766) , value = __nccwpck_require__(7643) , max = Math.max; module.exports = function (dest, src /*, …srcn*/) { var error, i, length = max(arguments.length, 2), assign; dest = Object(value(dest)); assign = function (key) { try { dest[key] = src[key]; } catch (e) { if (!error) error = e; } }; for (i = 1; i < length; ++i) { src = arguments[i]; keys(src).forEach(assign); } if (error !== undefined) throw error; return dest; }; /***/ }), /***/ 4880: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var aFrom = __nccwpck_require__(1232) , assign = __nccwpck_require__(5771) , value = __nccwpck_require__(7643); module.exports = function (obj /*, propertyNames, options*/) { var copy = Object(value(obj)), propertyNames = arguments[1], options = Object(arguments[2]); if (copy !== obj && !propertyNames) return copy; var result = {}; if (propertyNames) { aFrom(propertyNames, function (propertyName) { if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName]; }); } else { assign(result, obj); } return result; }; /***/ }), /***/ 8469: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Workaround for http://code.google.com/p/v8/issues/detail?id=2804 var create = Object.create, shim; if (!__nccwpck_require__(2656)()) { shim = __nccwpck_require__(1212); } module.exports = (function () { var nullObject, polyProps, desc; if (!shim) return create; if (shim.level !== 1) return create; nullObject = {}; polyProps = {}; desc = { configurable: false, enumerable: false, writable: true, value: undefined }; Object.getOwnPropertyNames(Object.prototype).forEach(function (name) { if (name === "__proto__") { polyProps[name] = { configurable: true, enumerable: false, writable: true, value: undefined }; return; } polyProps[name] = desc; }); Object.defineProperties(nullObject, polyProps); Object.defineProperty(shim, "nullPolyfill", { configurable: false, enumerable: false, writable: false, value: nullObject }); return function (prototype, props) { return create(prototype === null ? nullObject : prototype, props); }; })(); /***/ }), /***/ 8618: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(3392)("forEach"); /***/ }), /***/ 8525: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isValue = __nccwpck_require__(8765); var map = { function: true, object: true }; module.exports = function (value) { return (isValue(value) && map[typeof value]) || false; }; /***/ }), /***/ 8765: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var _undefined = __nccwpck_require__(9688)(); // Support ES3 engines module.exports = function (val) { return val !== _undefined && val !== null; }; /***/ }), /***/ 3766: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(3533)() ? Object.keys : __nccwpck_require__(6833); /***/ }), /***/ 3533: /***/ ((module) => { "use strict"; module.exports = function () { try { Object.keys("primitive"); return true; } catch (e) { return false; } }; /***/ }), /***/ 6833: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isValue = __nccwpck_require__(8765); var keys = Object.keys; module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); }; /***/ }), /***/ 3511: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var callable = __nccwpck_require__(1352) , forEach = __nccwpck_require__(8618) , call = Function.prototype.call; module.exports = function (obj, cb /*, thisArg*/) { var result = {}, thisArg = arguments[2]; callable(cb); forEach(obj, function (value, key, targetObj, index) { result[key] = call.call(cb, thisArg, value, key, targetObj, index); }); return result; }; /***/ }), /***/ 4201: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isValue = __nccwpck_require__(8765); var forEach = Array.prototype.forEach, create = Object.create; var process = function (src, obj) { var key; for (key in src) obj[key] = src[key]; }; // eslint-disable-next-line no-unused-vars module.exports = function (opts1 /*, …options*/) { var result = create(null); forEach.call(arguments, function (options) { if (!isValue(options)) return; process(Object(options), result); }); return result; }; /***/ }), /***/ 3053: /***/ ((module) => { "use strict"; var forEach = Array.prototype.forEach, create = Object.create; // eslint-disable-next-line no-unused-vars module.exports = function (arg /*, …args*/) { var set = create(null); forEach.call(arguments, function (name) { set[name] = true; }); return set; }; /***/ }), /***/ 2345: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(2656)() ? Object.setPrototypeOf : __nccwpck_require__(1212); /***/ }), /***/ 2656: /***/ ((module) => { "use strict"; var create = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {}; module.exports = function (/* CustomCreate*/) { var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || create; if (typeof setPrototypeOf !== "function") return false; return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject; }; /***/ }), /***/ 1212: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint no-proto: "off" */ // Big thanks to @WebReflection for sorting this out // https://gist.github.com/WebReflection/5593554 var isObject = __nccwpck_require__(8525) , value = __nccwpck_require__(7643) , objIsPrototypeOf = Object.prototype.isPrototypeOf , defineProperty = Object.defineProperty , nullDesc = { configurable: true, enumerable: false, writable: true, value: undefined } , validate; validate = function (obj, prototype) { value(obj); if (prototype === null || isObject(prototype)) return obj; throw new TypeError("Prototype must be null or an object"); }; module.exports = (function (status) { var fn, set; if (!status) return null; if (status.level === 2) { if (status.set) { set = status.set; fn = function (obj, prototype) { set.call(validate(obj, prototype), prototype); return obj; }; } else { fn = function (obj, prototype) { validate(obj, prototype).__proto__ = prototype; return obj; }; } } else { fn = function self(obj, prototype) { var isNullBase; validate(obj, prototype); isNullBase = objIsPrototypeOf.call(self.nullPolyfill, obj); if (isNullBase) delete self.nullPolyfill.__proto__; if (prototype === null) prototype = self.nullPolyfill; obj.__proto__ = prototype; if (isNullBase) defineProperty(self.nullPolyfill, "__proto__", nullDesc); return obj; }; } return Object.defineProperty(fn, "level", { configurable: false, enumerable: false, writable: false, value: status.level }); })( (function () { var tmpObj1 = Object.create(null) , tmpObj2 = {} , set , desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__"); if (desc) { try { set = desc.set; // Opera crashes at this point set.call(tmpObj1, tmpObj2); } catch (ignore) {} if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set: set, level: 2 }; } tmpObj1.__proto__ = tmpObj2; if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 }; tmpObj1 = {}; tmpObj1.__proto__ = tmpObj2; if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 }; return false; })() ); __nccwpck_require__(8469); /***/ }), /***/ 1352: /***/ ((module) => { "use strict"; module.exports = function (fn) { if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); return fn; }; /***/ }), /***/ 7643: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isValue = __nccwpck_require__(8765); module.exports = function (value) { if (!isValue(value)) throw new TypeError("Cannot use null or undefined"); return value; }; /***/ }), /***/ 1691: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(3714)() ? String.prototype.contains : __nccwpck_require__(4130); /***/ }), /***/ 3714: /***/ ((module) => { "use strict"; var str = "razdwatrzy"; module.exports = function () { if (typeof str.contains !== "function") return false; return str.contains("dwa") === true && str.contains("foo") === false; }; /***/ }), /***/ 4130: /***/ ((module) => { "use strict"; var indexOf = String.prototype.indexOf; module.exports = function (searchString /*, position*/) { return indexOf.call(this, searchString, arguments[1]) > -1; }; /***/ }), /***/ 7005: /***/ ((module) => { "use strict"; var objToString = Object.prototype.toString, id = objToString.call(""); module.exports = function (value) { return ( typeof value === "string" || (value && typeof value === "object" && (value instanceof String || objToString.call(value) === id)) || false ); }; /***/ }), /***/ 6614: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var setPrototypeOf = __nccwpck_require__(2345) , contains = __nccwpck_require__(1691) , d = __nccwpck_require__(8792) , Symbol = __nccwpck_require__(9425) , Iterator = __nccwpck_require__(5664); var defineProperty = Object.defineProperty, ArrayIterator; ArrayIterator = module.exports = function (arr, kind) { if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'"); Iterator.call(this, arr); if (!kind) kind = "value"; else if (contains.call(kind, "key+value")) kind = "key+value"; else if (contains.call(kind, "key")) kind = "key"; else kind = "value"; defineProperty(this, "__kind__", d("", kind)); }; if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator); // Internal %ArrayIteratorPrototype% doesn't expose its constructor delete ArrayIterator.prototype.constructor; ArrayIterator.prototype = Object.create(Iterator.prototype, { _resolve: d(function (i) { if (this.__kind__ === "value") return this.__list__[i]; if (this.__kind__ === "key+value") return [i, this.__list__[i]]; return i; }) }); defineProperty(ArrayIterator.prototype, Symbol.toStringTag, d("c", "Array Iterator")); /***/ }), /***/ 4812: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isArguments = __nccwpck_require__(1941) , callable = __nccwpck_require__(1352) , isString = __nccwpck_require__(7005) , get = __nccwpck_require__(8163); var isArray = Array.isArray, call = Function.prototype.call, some = Array.prototype.some; module.exports = function (iterable, cb /*, thisArg*/) { var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code; if (isArray(iterable) || isArguments(iterable)) mode = "array"; else if (isString(iterable)) mode = "string"; else iterable = get(iterable); callable(cb); doBreak = function () { broken = true; }; if (mode === "array") { some.call(iterable, function (value) { call.call(cb, thisArg, value, doBreak); return broken; }); return; } if (mode === "string") { length = iterable.length; for (i = 0; i < length; ++i) { char = iterable[i]; if (i + 1 < length) { code = char.charCodeAt(0); if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i]; } call.call(cb, thisArg, char, doBreak); if (broken) break; } return; } result = iterable.next(); while (!result.done) { call.call(cb, thisArg, result.value, doBreak); if (broken) return; result = iterable.next(); } }; /***/ }), /***/ 8163: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isArguments = __nccwpck_require__(1941) , isString = __nccwpck_require__(7005) , ArrayIterator = __nccwpck_require__(6614) , StringIterator = __nccwpck_require__(8730) , iterable = __nccwpck_require__(3200) , iteratorSymbol = (__nccwpck_require__(9425).iterator); module.exports = function (obj) { if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[iteratorSymbol](); if (isArguments(obj)) return new ArrayIterator(obj); if (isString(obj)) return new StringIterator(obj); return new ArrayIterator(obj); }; /***/ }), /***/ 5664: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var clear = __nccwpck_require__(7896) , assign = __nccwpck_require__(5771) , callable = __nccwpck_require__(1352) , value = __nccwpck_require__(7643) , d = __nccwpck_require__(8792) , autoBind = __nccwpck_require__(749) , Symbol = __nccwpck_require__(9425); var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator; module.exports = Iterator = function (list, context) { if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'"); defineProperties(this, { __list__: d("w", value(list)), __context__: d("w", context), __nextIndex__: d("w", 0) }); if (!context) return; callable(context.on); context.on("_add", this._onAdd); context.on("_delete", this._onDelete); context.on("_clear", this._onClear); }; // Internal %IteratorPrototype% doesn't expose its constructor delete Iterator.prototype.constructor; defineProperties( Iterator.prototype, assign( { _next: d(function () { var i; if (!this.__list__) return undefined; if (this.__redo__) { i = this.__redo__.shift(); if (i !== undefined) return i; } if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++; this._unBind(); return undefined; }), next: d(function () { return this._createResult(this._next()); }), _createResult: d(function (i) { if (i === undefined) return { done: true, value: undefined }; return { done: false, value: this._resolve(i) }; }), _resolve: d(function (i) { return this.__list__[i]; }), _unBind: d(function () { this.__list__ = null; delete this.__redo__; if (!this.__context__) return; this.__context__.off("_add", this._onAdd); this.__context__.off("_delete", this._onDelete); this.__context__.off("_clear", this._onClear); this.__context__ = null; }), toString: d(function () { return "[object " + (this[Symbol.toStringTag] || "Object") + "]"; }) }, autoBind({ _onAdd: d(function (index) { if (index >= this.__nextIndex__) return; ++this.__nextIndex__; if (!this.__redo__) { defineProperty(this, "__redo__", d("c", [index])); return; } this.__redo__.forEach(function (redo, i) { if (redo >= index) this.__redo__[i] = ++redo; }, this); this.__redo__.push(index); }), _onDelete: d(function (index) { var i; if (index >= this.__nextIndex__) return; --this.__nextIndex__; if (!this.__redo__) return; i = this.__redo__.indexOf(index); if (i !== -1) this.__redo__.splice(i, 1); this.__redo__.forEach(function (redo, j) { if (redo > index) this.__redo__[j] = --redo; }, this); }), _onClear: d(function () { if (this.__redo__) clear.call(this.__redo__); this.__nextIndex__ = 0; }) }) ) ); defineProperty( Iterator.prototype, Symbol.iterator, d(function () { return this; }) ); /***/ }), /***/ 9174: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isArguments = __nccwpck_require__(1941) , isValue = __nccwpck_require__(8765) , isString = __nccwpck_require__(7005); var iteratorSymbol = (__nccwpck_require__(9425).iterator) , isArray = Array.isArray; module.exports = function (value) { if (!isValue(value)) return false; if (isArray(value)) return true; if (isString(value)) return true; if (isArguments(value)) return true; return typeof value[iteratorSymbol] === "function"; }; /***/ }), /***/ 8730: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Thanks @mathiasbynens // http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols var setPrototypeOf = __nccwpck_require__(2345) , d = __nccwpck_require__(8792) , Symbol = __nccwpck_require__(9425) , Iterator = __nccwpck_require__(5664); var defineProperty = Object.defineProperty, StringIterator; StringIterator = module.exports = function (str) { if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'"); str = String(str); Iterator.call(this, str); defineProperty(this, "__length__", d("", str.length)); }; if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator); // Internal %ArrayIteratorPrototype% doesn't expose its constructor delete StringIterator.prototype.constructor; StringIterator.prototype = Object.create(Iterator.prototype, { _next: d(function () { if (!this.__list__) return undefined; if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; this._unBind(); return undefined; }), _resolve: d(function (i) { var char = this.__list__[i], code; if (this.__nextIndex__ === this.__length__) return char; code = char.charCodeAt(0); if (code >= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++]; return char; }) }); defineProperty(StringIterator.prototype, Symbol.toStringTag, d("c", "String Iterator")); /***/ }), /***/ 3200: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isIterable = __nccwpck_require__(9174); module.exports = function (value) { if (!isIterable(value)) throw new TypeError(value + " is not iterable"); return value; }; /***/ }), /***/ 2761: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(3872)() ? Map : __nccwpck_require__(7982); /***/ }), /***/ 3872: /***/ ((module) => { "use strict"; module.exports = function () { var map, iterator, result; if (typeof Map !== 'function') return false; try { // WebKit doesn't support arguments and crashes map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]); } catch (e) { return false; } if (String(map) !== '[object Map]') return false; if (map.size !== 3) return false; if (typeof map.clear !== 'function') return false; if (typeof map.delete !== 'function') return false; if (typeof map.entries !== 'function') return false; if (typeof map.forEach !== 'function') return false; if (typeof map.get !== 'function') return false; if (typeof map.has !== 'function') return false; if (typeof map.keys !== 'function') return false; if (typeof map.set !== 'function') return false; if (typeof map.values !== 'function') return false; iterator = map.entries(); result = iterator.next(); if (result.done !== false) return false; if (!result.value) return false; if (result.value[0] !== 'raz') return false; if (result.value[1] !== 'one') return false; return true; }; /***/ }), /***/ 5568: /***/ ((module) => { "use strict"; // Exports true if environment provides native `Map` implementation, // whatever that is. module.exports = (function () { if (typeof Map === 'undefined') return false; return (Object.prototype.toString.call(new Map()) === '[object Map]'); }()); /***/ }), /***/ 8333: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(3053)('key', 'value', 'key+value'); /***/ }), /***/ 9687: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var setPrototypeOf = __nccwpck_require__(2345) , d = __nccwpck_require__(8792) , Iterator = __nccwpck_require__(5664) , toStringTagSymbol = (__nccwpck_require__(9425).toStringTag) , kinds = __nccwpck_require__(8333) , defineProperties = Object.defineProperties , unBind = Iterator.prototype._unBind , MapIterator; MapIterator = module.exports = function (map, kind) { if (!(this instanceof MapIterator)) return new MapIterator(map, kind); Iterator.call(this, map.__mapKeysData__, map); if (!kind || !kinds[kind]) kind = 'key+value'; defineProperties(this, { __kind__: d('', kind), __values__: d('w', map.__mapValuesData__) }); }; if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator); MapIterator.prototype = Object.create(Iterator.prototype, { constructor: d(MapIterator), _resolve: d(function (i) { if (this.__kind__ === 'value') return this.__values__[i]; if (this.__kind__ === 'key') return this.__list__[i]; return [this.__list__[i], this.__values__[i]]; }), _unBind: d(function () { this.__values__ = null; unBind.call(this); }), toString: d(function () { return '[object Map Iterator]'; }) }); Object.defineProperty(MapIterator.prototype, toStringTagSymbol, d('c', 'Map Iterator')); /***/ }), /***/ 7982: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var clear = __nccwpck_require__(7896) , eIndexOf = __nccwpck_require__(6649) , setPrototypeOf = __nccwpck_require__(2345) , callable = __nccwpck_require__(1352) , validValue = __nccwpck_require__(7643) , d = __nccwpck_require__(8792) , ee = __nccwpck_require__(4943) , Symbol = __nccwpck_require__(9425) , iterator = __nccwpck_require__(3200) , forOf = __nccwpck_require__(4812) , Iterator = __nccwpck_require__(9687) , isNative = __nccwpck_require__(5568) , call = Function.prototype.call , defineProperties = Object.defineProperties, getPrototypeOf = Object.getPrototypeOf , MapPoly; module.exports = MapPoly = function (/*iterable*/) { var iterable = arguments[0], keys, values, self; if (!(this instanceof MapPoly)) throw new TypeError('Constructor requires \'new\''); if (isNative && setPrototypeOf && (Map !== MapPoly)) { self = setPrototypeOf(new Map(), getPrototypeOf(this)); } else { self = this; } if (iterable != null) iterator(iterable); defineProperties(self, { __mapKeysData__: d('c', keys = []), __mapValuesData__: d('c', values = []) }); if (!iterable) return self; forOf(iterable, function (value) { var key = validValue(value)[0]; value = value[1]; if (eIndexOf.call(keys, key) !== -1) return; keys.push(key); values.push(value); }, self); return self; }; if (isNative) { if (setPrototypeOf) setPrototypeOf(MapPoly, Map); MapPoly.prototype = Object.create(Map.prototype, { constructor: d(MapPoly) }); } ee(defineProperties(MapPoly.prototype, { clear: d(function () { if (!this.__mapKeysData__.length) return; clear.call(this.__mapKeysData__); clear.call(this.__mapValuesData__); this.emit('_clear'); }), delete: d(function (key) { var index = eIndexOf.call(this.__mapKeysData__, key); if (index === -1) return false; this.__mapKeysData__.splice(index, 1); this.__mapValuesData__.splice(index, 1); this.emit('_delete', index, key); return true; }), entries: d(function () { return new Iterator(this, 'key+value'); }), forEach: d(function (cb/*, thisArg*/) { var thisArg = arguments[1], iterator, result; callable(cb); iterator = this.entries(); result = iterator._next(); while (result !== undefined) { call.call(cb, thisArg, this.__mapValuesData__[result], this.__mapKeysData__[result], this); result = iterator._next(); } }), get: d(function (key) { var index = eIndexOf.call(this.__mapKeysData__, key); if (index === -1) return; return this.__mapValuesData__[index]; }), has: d(function (key) { return (eIndexOf.call(this.__mapKeysData__, key) !== -1); }), keys: d(function () { return new Iterator(this, 'key'); }), set: d(function (key, value) { var index = eIndexOf.call(this.__mapKeysData__, key), emit; if (index === -1) { index = this.__mapKeysData__.push(key) - 1; emit = true; } this.__mapValuesData__[index] = value; if (emit) this.emit('_add', index, key); return this; }), size: d.gs(function () { return this.__mapKeysData__.length; }), values: d(function () { return new Iterator(this, 'value'); }), toString: d(function () { return '[object Map]'; }) })); Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () { return this.entries(); })); Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map')); /***/ }), /***/ 9425: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(5480)() ? (__nccwpck_require__(6506).Symbol) : __nccwpck_require__(4566); /***/ }), /***/ 5480: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var global = __nccwpck_require__(6506) , validTypes = { object: true, symbol: true }; module.exports = function () { var Symbol = global.Symbol; var symbol; if (typeof Symbol !== "function") return false; symbol = Symbol("test symbol"); try { String(symbol); } catch (e) { return false; } // Return 'true' also for polyfills if (!validTypes[typeof Symbol.iterator]) return false; if (!validTypes[typeof Symbol.toPrimitive]) return false; if (!validTypes[typeof Symbol.toStringTag]) return false; return true; }; /***/ }), /***/ 494: /***/ ((module) => { "use strict"; module.exports = function (value) { if (!value) return false; if (typeof value === "symbol") return true; if (!value.constructor) return false; if (value.constructor.name !== "Symbol") return false; return value[value.constructor.toStringTag] === "Symbol"; }; /***/ }), /***/ 3640: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var d = __nccwpck_require__(8792); var create = Object.create, defineProperty = Object.defineProperty, objPrototype = Object.prototype; var created = create(null); module.exports = function (desc) { var postfix = 0, name, ie11BugWorkaround; while (created[desc + (postfix || "")]) ++postfix; desc += postfix || ""; created[desc] = true; name = "@@" + desc; defineProperty( objPrototype, name, d.gs(null, function (value) { // For IE11 issue see: // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/ // ie11-broken-getters-on-dom-objects // https://github.com/medikoo/es6-symbol/issues/12 if (ie11BugWorkaround) return; ie11BugWorkaround = true; defineProperty(this, name, d(value)); ie11BugWorkaround = false; }) ); return name; }; /***/ }), /***/ 3902: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var d = __nccwpck_require__(8792) , NativeSymbol = (__nccwpck_require__(6506).Symbol); module.exports = function (SymbolPolyfill) { return Object.defineProperties(SymbolPolyfill, { // To ensure proper interoperability with other native functions (e.g. Array.from) // fallback to eventual native implementation of given symbol hasInstance: d( "", (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill("hasInstance") ), isConcatSpreadable: d( "", (NativeSymbol && NativeSymbol.isConcatSpreadable) || SymbolPolyfill("isConcatSpreadable") ), iterator: d("", (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill("iterator")), match: d("", (NativeSymbol && NativeSymbol.match) || SymbolPolyfill("match")), replace: d("", (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill("replace")), search: d("", (NativeSymbol && NativeSymbol.search) || SymbolPolyfill("search")), species: d("", (NativeSymbol && NativeSymbol.species) || SymbolPolyfill("species")), split: d("", (NativeSymbol && NativeSymbol.split) || SymbolPolyfill("split")), toPrimitive: d( "", (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill("toPrimitive") ), toStringTag: d( "", (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill("toStringTag") ), unscopables: d( "", (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill("unscopables") ) }); }; /***/ }), /***/ 8483: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var d = __nccwpck_require__(8792) , validateSymbol = __nccwpck_require__(3736); var registry = Object.create(null); module.exports = function (SymbolPolyfill) { return Object.defineProperties(SymbolPolyfill, { for: d(function (key) { if (registry[key]) return registry[key]; return (registry[key] = SymbolPolyfill(String(key))); }), keyFor: d(function (symbol) { var key; validateSymbol(symbol); for (key in registry) { if (registry[key] === symbol) return key; } return undefined; }) }); }; /***/ }), /***/ 4566: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // ES2015 Symbol polyfill for environments that do not (or partially) support it var d = __nccwpck_require__(8792) , validateSymbol = __nccwpck_require__(3736) , NativeSymbol = (__nccwpck_require__(6506).Symbol) , generateName = __nccwpck_require__(3640) , setupStandardSymbols = __nccwpck_require__(3902) , setupSymbolRegistry = __nccwpck_require__(8483); var create = Object.create , defineProperties = Object.defineProperties , defineProperty = Object.defineProperty; var SymbolPolyfill, HiddenSymbol, isNativeSafe; if (typeof NativeSymbol === "function") { try { String(NativeSymbol()); isNativeSafe = true; } catch (ignore) {} } else { NativeSymbol = null; } // Internal constructor (not one exposed) for creating Symbol instances. // This one is used to ensure that `someSymbol instanceof Symbol` always return false HiddenSymbol = function Symbol(description) { if (this instanceof HiddenSymbol) throw new TypeError("Symbol is not a constructor"); return SymbolPolyfill(description); }; // Exposed `Symbol` constructor // (returns instances of HiddenSymbol) module.exports = SymbolPolyfill = function Symbol(description) { var symbol; if (this instanceof Symbol) throw new TypeError("Symbol is not a constructor"); if (isNativeSafe) return NativeSymbol(description); symbol = create(HiddenSymbol.prototype); description = description === undefined ? "" : String(description); return defineProperties(symbol, { __description__: d("", description), __name__: d("", generateName(description)) }); }; setupStandardSymbols(SymbolPolyfill); setupSymbolRegistry(SymbolPolyfill); // Internal tweaks for real symbol producer defineProperties(HiddenSymbol.prototype, { constructor: d(SymbolPolyfill), toString: d("", function () { return this.__name__; }) }); // Proper implementation of methods exposed on Symbol.prototype // They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype defineProperties(SymbolPolyfill.prototype, { toString: d(function () { return "Symbol (" + validateSymbol(this).__description__ + ")"; }), valueOf: d(function () { return validateSymbol(this); }) }); defineProperty( SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d("", function () { var symbol = validateSymbol(this); if (typeof symbol === "symbol") return symbol; return symbol.toString(); }) ); defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d("c", "Symbol")); // Proper implementaton of toPrimitive and toStringTag for returned symbol instances defineProperty( HiddenSymbol.prototype, SymbolPolyfill.toStringTag, d("c", SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]) ); // Note: It's important to define `toPrimitive` as last one, as some implementations // implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols) // And that may invoke error in definition flow: // See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149 defineProperty( HiddenSymbol.prototype, SymbolPolyfill.toPrimitive, d("c", SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]) ); /***/ }), /***/ 3736: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isSymbol = __nccwpck_require__(494); module.exports = function (value) { if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); return value; }; /***/ }), /***/ 4943: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; var d = __nccwpck_require__(8792) , callable = __nccwpck_require__(1352) , apply = Function.prototype.apply, call = Function.prototype.call , create = Object.create, defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , hasOwnProperty = Object.prototype.hasOwnProperty , descriptor = { configurable: true, enumerable: false, writable: true } , on, once, off, emit, methods, descriptors, base; on = function (type, listener) { var data; callable(listener); if (!hasOwnProperty.call(this, '__ee__')) { data = descriptor.value = create(null); defineProperty(this, '__ee__', descriptor); descriptor.value = null; } else { data = this.__ee__; } if (!data[type]) data[type] = listener; else if (typeof data[type] === 'object') data[type].push(listener); else data[type] = [data[type], listener]; return this; }; once = function (type, listener) { var once, self; callable(listener); self = this; on.call(this, type, once = function () { off.call(self, type, once); apply.call(listener, this, arguments); }); once.__eeOnceListener__ = listener; return this; }; off = function (type, listener) { var data, listeners, candidate, i; callable(listener); if (!hasOwnProperty.call(this, '__ee__')) return this; data = this.__ee__; if (!data[type]) return this; listeners = data[type]; if (typeof listeners === 'object') { for (i = 0; (candidate = listeners[i]); ++i) { if ((candidate === listener) || (candidate.__eeOnceListener__ === listener)) { if (listeners.length === 2) data[type] = listeners[i ? 0 : 1]; else listeners.splice(i, 1); } } } else { if ((listeners === listener) || (listeners.__eeOnceListener__ === listener)) { delete data[type]; } } return this; }; emit = function (type) { var i, l, listener, listeners, args; if (!hasOwnProperty.call(this, '__ee__')) return; listeners = this.__ee__[type]; if (!listeners) return; if (typeof listeners === 'object') { l = arguments.length; args = new Array(l - 1); for (i = 1; i < l; ++i) args[i - 1] = arguments[i]; listeners = listeners.slice(); for (i = 0; (listener = listeners[i]); ++i) { apply.call(listener, this, args); } } else { switch (arguments.length) { case 1: call.call(listeners, this); break; case 2: call.call(listeners, this, arguments[1]); break; case 3: call.call(listeners, this, arguments[1], arguments[2]); break; default: l = arguments.length; args = new Array(l - 1); for (i = 1; i < l; ++i) { args[i - 1] = arguments[i]; } apply.call(listeners, this, args); } } }; methods = { on: on, once: once, off: off, emit: emit }; descriptors = { on: d(on), once: d(once), off: d(off), emit: d(emit) }; base = defineProperties({}, descriptors); module.exports = exports = function (o) { return (o == null) ? create(base) : defineProperties(Object(o), descriptors); }; exports.methods = methods; /***/ }), /***/ 6577: /***/ ((module, exports) => { "use strict"; /** * @author Toru Nagashima * @copyright 2015 Toru Nagashima. All rights reserved. * See LICENSE file in root directory for full license. */ Object.defineProperty(exports, "__esModule", ({ value: true })); /** * @typedef {object} PrivateData * @property {EventTarget} eventTarget The event target. * @property {{type:string}} event The original event object. * @property {number} eventPhase The current event phase. * @property {EventTarget|null} currentTarget The current event target. * @property {boolean} canceled The flag to prevent default. * @property {boolean} stopped The flag to stop propagation. * @property {boolean} immediateStopped The flag to stop propagation immediately. * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. * @property {number} timeStamp The unix time. * @private */ /** * Private data for event wrappers. * @type {WeakMap} * @private */ const privateData = new WeakMap(); /** * Cache for wrapper classes. * @type {WeakMap} * @private */ const wrappers = new WeakMap(); /** * Get private data. * @param {Event} event The event object to get private data. * @returns {PrivateData} The private data of the event. * @private */ function pd(event) { const retv = privateData.get(event); console.assert( retv != null, "'this' is expected an Event object, but got", event ); return retv } /** * https://dom.spec.whatwg.org/#set-the-canceled-flag * @param data {PrivateData} private data. */ function setCancelFlag(data) { if (data.passiveListener != null) { if ( typeof console !== "undefined" && typeof console.error === "function" ) { console.error( "Unable to preventDefault inside passive event listener invocation.", data.passiveListener ); } return } if (!data.event.cancelable) { return } data.canceled = true; if (typeof data.event.preventDefault === "function") { data.event.preventDefault(); } } /** * @see https://dom.spec.whatwg.org/#interface-event * @private */ /** * The event wrapper. * @constructor * @param {EventTarget} eventTarget The event target of this dispatching. * @param {Event|{type:string}} event The original event to wrap. */ function Event(eventTarget, event) { privateData.set(this, { eventTarget, event, eventPhase: 2, currentTarget: eventTarget, canceled: false, stopped: false, immediateStopped: false, passiveListener: null, timeStamp: event.timeStamp || Date.now(), }); // https://heycam.github.io/webidl/#Unforgeable Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); // Define accessors const keys = Object.keys(event); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (!(key in this)) { Object.defineProperty(this, key, defineRedirectDescriptor(key)); } } } // Should be enumerable, but class methods are not enumerable. Event.prototype = { /** * The type of this event. * @type {string} */ get type() { return pd(this).event.type }, /** * The target of this event. * @type {EventTarget} */ get target() { return pd(this).eventTarget }, /** * The target of this event. * @type {EventTarget} */ get currentTarget() { return pd(this).currentTarget }, /** * @returns {EventTarget[]} The composed path of this event. */ composedPath() { const currentTarget = pd(this).currentTarget; if (currentTarget == null) { return [] } return [currentTarget] }, /** * Constant of NONE. * @type {number} */ get NONE() { return 0 }, /** * Constant of CAPTURING_PHASE. * @type {number} */ get CAPTURING_PHASE() { return 1 }, /** * Constant of AT_TARGET. * @type {number} */ get AT_TARGET() { return 2 }, /** * Constant of BUBBLING_PHASE. * @type {number} */ get BUBBLING_PHASE() { return 3 }, /** * The target of this event. * @type {number} */ get eventPhase() { return pd(this).eventPhase }, /** * Stop event bubbling. * @returns {void} */ stopPropagation() { const data = pd(this); data.stopped = true; if (typeof data.event.stopPropagation === "function") { data.event.stopPropagation(); } }, /** * Stop event bubbling. * @returns {void} */ stopImmediatePropagation() { const data = pd(this); data.stopped = true; data.immediateStopped = true; if (typeof data.event.stopImmediatePropagation === "function") { data.event.stopImmediatePropagation(); } }, /** * The flag to be bubbling. * @type {boolean} */ get bubbles() { return Boolean(pd(this).event.bubbles) }, /** * The flag to be cancelable. * @type {boolean} */ get cancelable() { return Boolean(pd(this).event.cancelable) }, /** * Cancel this event. * @returns {void} */ preventDefault() { setCancelFlag(pd(this)); }, /** * The flag to indicate cancellation state. * @type {boolean} */ get defaultPrevented() { return pd(this).canceled }, /** * The flag to be composed. * @type {boolean} */ get composed() { return Boolean(pd(this).event.composed) }, /** * The unix time of this event. * @type {number} */ get timeStamp() { return pd(this).timeStamp }, /** * The target of this event. * @type {EventTarget} * @deprecated */ get srcElement() { return pd(this).eventTarget }, /** * The flag to stop event bubbling. * @type {boolean} * @deprecated */ get cancelBubble() { return pd(this).stopped }, set cancelBubble(value) { if (!value) { return } const data = pd(this); data.stopped = true; if (typeof data.event.cancelBubble === "boolean") { data.event.cancelBubble = true; } }, /** * The flag to indicate cancellation state. * @type {boolean} * @deprecated */ get returnValue() { return !pd(this).canceled }, set returnValue(value) { if (!value) { setCancelFlag(pd(this)); } }, /** * Initialize this event object. But do nothing under event dispatching. * @param {string} type The event type. * @param {boolean} [bubbles=false] The flag to be possible to bubble up. * @param {boolean} [cancelable=false] The flag to be possible to cancel. * @deprecated */ initEvent() { // Do nothing. }, }; // `constructor` is not enumerable. Object.defineProperty(Event.prototype, "constructor", { value: Event, configurable: true, writable: true, }); // Ensure `event instanceof window.Event` is `true`. if (typeof window !== "undefined" && typeof window.Event !== "undefined") { Object.setPrototypeOf(Event.prototype, window.Event.prototype); // Make association for wrappers. wrappers.set(window.Event.prototype, Event); } /** * Get the property descriptor to redirect a given property. * @param {string} key Property name to define property descriptor. * @returns {PropertyDescriptor} The property descriptor to redirect the property. * @private */ function defineRedirectDescriptor(key) { return { get() { return pd(this).event[key] }, set(value) { pd(this).event[key] = value; }, configurable: true, enumerable: true, } } /** * Get the property descriptor to call a given method property. * @param {string} key Property name to define property descriptor. * @returns {PropertyDescriptor} The property descriptor to call the method property. * @private */ function defineCallDescriptor(key) { return { value() { const event = pd(this).event; return event[key].apply(event, arguments) }, configurable: true, enumerable: true, } } /** * Define new wrapper class. * @param {Function} BaseEvent The base wrapper class. * @param {Object} proto The prototype of the original event. * @returns {Function} The defined wrapper class. * @private */ function defineWrapper(BaseEvent, proto) { const keys = Object.keys(proto); if (keys.length === 0) { return BaseEvent } /** CustomEvent */ function CustomEvent(eventTarget, event) { BaseEvent.call(this, eventTarget, event); } CustomEvent.prototype = Object.create(BaseEvent.prototype, { constructor: { value: CustomEvent, configurable: true, writable: true }, }); // Define accessors. for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (!(key in BaseEvent.prototype)) { const descriptor = Object.getOwnPropertyDescriptor(proto, key); const isFunc = typeof descriptor.value === "function"; Object.defineProperty( CustomEvent.prototype, key, isFunc ? defineCallDescriptor(key) : defineRedirectDescriptor(key) ); } } return CustomEvent } /** * Get the wrapper class of a given prototype. * @param {Object} proto The prototype of the original event to get its wrapper. * @returns {Function} The wrapper class. * @private */ function getWrapper(proto) { if (proto == null || proto === Object.prototype) { return Event } let wrapper = wrappers.get(proto); if (wrapper == null) { wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); wrappers.set(proto, wrapper); } return wrapper } /** * Wrap a given event to management a dispatching. * @param {EventTarget} eventTarget The event target of this dispatching. * @param {Object} event The event to wrap. * @returns {Event} The wrapper instance. * @private */ function wrapEvent(eventTarget, event) { const Wrapper = getWrapper(Object.getPrototypeOf(event)); return new Wrapper(eventTarget, event) } /** * Get the immediateStopped flag of a given event. * @param {Event} event The event to get. * @returns {boolean} The flag to stop propagation immediately. * @private */ function isStopped(event) { return pd(event).immediateStopped } /** * Set the current event phase of a given event. * @param {Event} event The event to set current target. * @param {number} eventPhase New event phase. * @returns {void} * @private */ function setEventPhase(event, eventPhase) { pd(event).eventPhase = eventPhase; } /** * Set the current target of a given event. * @param {Event} event The event to set current target. * @param {EventTarget|null} currentTarget New current target. * @returns {void} * @private */ function setCurrentTarget(event, currentTarget) { pd(event).currentTarget = currentTarget; } /** * Set a passive listener of a given event. * @param {Event} event The event to set current target. * @param {Function|null} passiveListener New passive listener. * @returns {void} * @private */ function setPassiveListener(event, passiveListener) { pd(event).passiveListener = passiveListener; } /** * @typedef {object} ListenerNode * @property {Function} listener * @property {1|2|3} listenerType * @property {boolean} passive * @property {boolean} once * @property {ListenerNode|null} next * @private */ /** * @type {WeakMap>} * @private */ const listenersMap = new WeakMap(); // Listener types const CAPTURE = 1; const BUBBLE = 2; const ATTRIBUTE = 3; /** * Check whether a given value is an object or not. * @param {any} x The value to check. * @returns {boolean} `true` if the value is an object. */ function isObject(x) { return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax } /** * Get listeners. * @param {EventTarget} eventTarget The event target to get. * @returns {Map} The listeners. * @private */ function getListeners(eventTarget) { const listeners = listenersMap.get(eventTarget); if (listeners == null) { throw new TypeError( "'this' is expected an EventTarget object, but got another value." ) } return listeners } /** * Get the property descriptor for the event attribute of a given event. * @param {string} eventName The event name to get property descriptor. * @returns {PropertyDescriptor} The property descriptor. * @private */ function defineEventAttributeDescriptor(eventName) { return { get() { const listeners = getListeners(this); let node = listeners.get(eventName); while (node != null) { if (node.listenerType === ATTRIBUTE) { return node.listener } node = node.next; } return null }, set(listener) { if (typeof listener !== "function" && !isObject(listener)) { listener = null; // eslint-disable-line no-param-reassign } const listeners = getListeners(this); // Traverse to the tail while removing old value. let prev = null; let node = listeners.get(eventName); while (node != null) { if (node.listenerType === ATTRIBUTE) { // Remove old value. if (prev !== null) { prev.next = node.next; } else if (node.next !== null) { listeners.set(eventName, node.next); } else { listeners.delete(eventName); } } else { prev = node; } node = node.next; } // Add new value. if (listener !== null) { const newNode = { listener, listenerType: ATTRIBUTE, passive: false, once: false, next: null, }; if (prev === null) { listeners.set(eventName, newNode); } else { prev.next = newNode; } } }, configurable: true, enumerable: true, } } /** * Define an event attribute (e.g. `eventTarget.onclick`). * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. * @param {string} eventName The event name to define. * @returns {void} */ function defineEventAttribute(eventTargetPrototype, eventName) { Object.defineProperty( eventTargetPrototype, `on${eventName}`, defineEventAttributeDescriptor(eventName) ); } /** * Define a custom EventTarget with event attributes. * @param {string[]} eventNames Event names for event attributes. * @returns {EventTarget} The custom EventTarget. * @private */ function defineCustomEventTarget(eventNames) { /** CustomEventTarget */ function CustomEventTarget() { EventTarget.call(this); } CustomEventTarget.prototype = Object.create(EventTarget.prototype, { constructor: { value: CustomEventTarget, configurable: true, writable: true, }, }); for (let i = 0; i < eventNames.length; ++i) { defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); } return CustomEventTarget } /** * EventTarget. * * - This is constructor if no arguments. * - This is a function which returns a CustomEventTarget constructor if there are arguments. * * For example: * * class A extends EventTarget {} * class B extends EventTarget("message") {} * class C extends EventTarget("message", "error") {} * class D extends EventTarget(["message", "error"]) {} */ function EventTarget() { /*eslint-disable consistent-return */ if (this instanceof EventTarget) { listenersMap.set(this, new Map()); return } if (arguments.length === 1 && Array.isArray(arguments[0])) { return defineCustomEventTarget(arguments[0]) } if (arguments.length > 0) { const types = new Array(arguments.length); for (let i = 0; i < arguments.length; ++i) { types[i] = arguments[i]; } return defineCustomEventTarget(types) } throw new TypeError("Cannot call a class as a function") /*eslint-enable consistent-return */ } // Should be enumerable, but class methods are not enumerable. EventTarget.prototype = { /** * Add a given listener to this event target. * @param {string} eventName The event name to add. * @param {Function} listener The listener to add. * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. * @returns {void} */ addEventListener(eventName, listener, options) { if (listener == null) { return } if (typeof listener !== "function" && !isObject(listener)) { throw new TypeError("'listener' should be a function or an object.") } const listeners = getListeners(this); const optionsIsObj = isObject(options); const capture = optionsIsObj ? Boolean(options.capture) : Boolean(options); const listenerType = capture ? CAPTURE : BUBBLE; const newNode = { listener, listenerType, passive: optionsIsObj && Boolean(options.passive), once: optionsIsObj && Boolean(options.once), next: null, }; // Set it as the first node if the first node is null. let node = listeners.get(eventName); if (node === undefined) { listeners.set(eventName, newNode); return } // Traverse to the tail while checking duplication.. let prev = null; while (node != null) { if ( node.listener === listener && node.listenerType === listenerType ) { // Should ignore duplication. return } prev = node; node = node.next; } // Add it. prev.next = newNode; }, /** * Remove a given listener from this event target. * @param {string} eventName The event name to remove. * @param {Function} listener The listener to remove. * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. * @returns {void} */ removeEventListener(eventName, listener, options) { if (listener == null) { return } const listeners = getListeners(this); const capture = isObject(options) ? Boolean(options.capture) : Boolean(options); const listenerType = capture ? CAPTURE : BUBBLE; let prev = null; let node = listeners.get(eventName); while (node != null) { if ( node.listener === listener && node.listenerType === listenerType ) { if (prev !== null) { prev.next = node.next; } else if (node.next !== null) { listeners.set(eventName, node.next); } else { listeners.delete(eventName); } return } prev = node; node = node.next; } }, /** * Dispatch a given event. * @param {Event|{type:string}} event The event to dispatch. * @returns {boolean} `false` if canceled. */ dispatchEvent(event) { if (event == null || typeof event.type !== "string") { throw new TypeError('"event.type" should be a string.') } // If listeners aren't registered, terminate. const listeners = getListeners(this); const eventName = event.type; let node = listeners.get(eventName); if (node == null) { return true } // Since we cannot rewrite several properties, so wrap object. const wrappedEvent = wrapEvent(this, event); // This doesn't process capturing phase and bubbling phase. // This isn't participating in a tree. let prev = null; while (node != null) { // Remove this listener if it's once if (node.once) { if (prev !== null) { prev.next = node.next; } else if (node.next !== null) { listeners.set(eventName, node.next); } else { listeners.delete(eventName); } } else { prev = node; } // Call this listener setPassiveListener( wrappedEvent, node.passive ? node.listener : null ); if (typeof node.listener === "function") { try { node.listener.call(this, wrappedEvent); } catch (err) { if ( typeof console !== "undefined" && typeof console.error === "function" ) { console.error(err); } } } else if ( node.listenerType !== ATTRIBUTE && typeof node.listener.handleEvent === "function" ) { node.listener.handleEvent(wrappedEvent); } // Break if `event.stopImmediatePropagation` was called. if (isStopped(wrappedEvent)) { break } node = node.next; } setPassiveListener(wrappedEvent, null); setEventPhase(wrappedEvent, 0); setCurrentTarget(wrappedEvent, null); return !wrappedEvent.defaultPrevented }, }; // `constructor` is not enumerable. Object.defineProperty(EventTarget.prototype, "constructor", { value: EventTarget, configurable: true, writable: true, }); // Ensure `eventTarget instanceof window.EventTarget` is `true`. if ( typeof window !== "undefined" && typeof window.EventTarget !== "undefined" ) { Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); } exports.defineEventAttribute = defineEventAttribute; exports.EventTarget = EventTarget; exports["default"] = EventTarget; module.exports = EventTarget module.exports.EventTarget = module.exports["default"] = EventTarget module.exports.defineEventAttribute = defineEventAttribute //# sourceMappingURL=event-target-shim.js.map /***/ }), /***/ 6946: /***/ ((module) => { var naiveFallback = function () { if (typeof self === "object" && self) return self; if (typeof window === "object" && window) return window; throw new Error("Unable to resolve global `this`"); }; module.exports = (function () { if (this) return this; // Unexpected strict mode (may happen if e.g. bundled into ESM module) // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis // In all ES5+ engines global object inherits from Object.prototype // (if you approached one that doesn't please report) try { Object.defineProperty(Object.prototype, "__global__", { get: function () { return this; }, configurable: true }); } catch (error) { // Unfortunate case of Object.prototype being sealed (via preventExtensions, seal or freeze) return naiveFallback(); } try { // Safari case (window.__global__ is resolved with global context, but __global__ does not) if (!__global__) return naiveFallback(); return __global__; } finally { delete Object.prototype.__global__; } })(); /***/ }), /***/ 6506: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(6497)() ? globalThis : __nccwpck_require__(6946); /***/ }), /***/ 6497: /***/ ((module) => { "use strict"; module.exports = function () { if (typeof globalThis !== "object") return false; if (!globalThis) return false; return globalThis.Array === Array; }; /***/ }), /***/ 3860: /***/ ((module) => { "use strict"; var hasOwn = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var defineProperty = Object.defineProperty; var gOPD = Object.getOwnPropertyDescriptor; var isArray = function isArray(arr) { if (typeof Array.isArray === 'function') { return Array.isArray(arr); } return toStr.call(arr) === '[object Array]'; }; var isPlainObject = function isPlainObject(obj) { if (!obj || toStr.call(obj) !== '[object Object]') { return false; } var hasOwnConstructor = hasOwn.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); // Not own constructor property must be Object if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) { /**/ } return typeof key === 'undefined' || hasOwn.call(obj, key); }; // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target var setProperty = function setProperty(target, options) { if (defineProperty && options.name === '__proto__') { defineProperty(target, options.name, { enumerable: true, configurable: true, value: options.newValue, writable: true }); } else { target[options.name] = options.newValue; } }; // Return undefined instead of __proto__ if '__proto__' is not an own property var getProperty = function getProperty(obj, name) { if (name === '__proto__') { if (!hasOwn.call(obj, name)) { return void 0; } else if (gOPD) { // In early versions of node, obj['__proto__'] is buggy when obj has // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. return gOPD(obj, name).value; } } return obj[name]; }; module.exports = function extend() { var options, name, src, copy, copyIsArray, clone; var target = arguments[0]; var i = 1; var length = arguments.length; var deep = false; // Handle a deep copy situation if (typeof target === 'boolean') { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { target = {}; } for (; i < length; ++i) { options = arguments[i]; // Only deal with non-null/undefined values if (options != null) { // Extend the base object for (name in options) { src = getProperty(target, name); copy = getProperty(options, name); // Prevent never-ending loop if (target !== copy) { // Recurse if we're merging plain objects or arrays if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); // Don't bring in undefined values } else if (typeof copy !== 'undefined') { setProperty(target, { name: name, newValue: copy }); } } } } } // Return the modified object return target; }; /***/ }), /***/ 8139: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createAddUniqueNumber = void 0; const createAddUniqueNumber = generateUniqueNumber => { return set => { const number = generateUniqueNumber(set); set.add(number); return number; }; }; exports.createAddUniqueNumber = createAddUniqueNumber; /***/ }), /***/ 4168: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createCache = void 0; const createCache = lastNumberWeakMap => { return (collection, nextNumber) => { lastNumberWeakMap.set(collection, nextNumber); return nextNumber; }; }; exports.createCache = createCache; /***/ }), /***/ 8517: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createGenerateUniqueNumber = void 0; /* * The value of the constant Number.MAX_SAFE_INTEGER equals (2 ** 53 - 1) but it * is fairly new. */ const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER === undefined ? 9007199254740991 : Number.MAX_SAFE_INTEGER; const TWO_TO_THE_POWER_OF_TWENTY_NINE = 536870912; const TWO_TO_THE_POWER_OF_THIRTY = TWO_TO_THE_POWER_OF_TWENTY_NINE * 2; const createGenerateUniqueNumber = (cache, lastNumberWeakMap) => { return collection => { const lastNumber = lastNumberWeakMap.get(collection); /* * Let's try the cheapest algorithm first. It might fail to produce a new * number, but it is so cheap that it is okay to take the risk. Just * increase the last number by one or reset it to 0 if we reached the upper * bound of SMIs (which stands for small integers). When the last number is * unknown it is assumed that the collection contains zero based consecutive * numbers. */ let nextNumber = lastNumber === undefined ? collection.size : lastNumber < TWO_TO_THE_POWER_OF_THIRTY ? lastNumber + 1 : 0; if (!collection.has(nextNumber)) { return cache(collection, nextNumber); } /* * If there are less than half of 2 ** 30 numbers stored in the collection, * the chance to generate a new random number in the range from 0 to 2 ** 30 * is at least 50%. It's benifitial to use only SMIs because they perform * much better in any environment based on V8. */ if (collection.size < TWO_TO_THE_POWER_OF_TWENTY_NINE) { while (collection.has(nextNumber)) { nextNumber = Math.floor(Math.random() * TWO_TO_THE_POWER_OF_THIRTY); } return cache(collection, nextNumber); } // Quickly check if there is a theoretical chance to generate a new number. if (collection.size > MAX_SAFE_INTEGER) { throw new Error('Congratulations, you created a collection of unique numbers which uses all available integers!'); } // Otherwise use the full scale of safely usable integers. while (collection.has(nextNumber)) { nextNumber = Math.floor(Math.random() * MAX_SAFE_INTEGER); } return cache(collection, nextNumber); }; }; exports.createGenerateUniqueNumber = createGenerateUniqueNumber; /***/ }), /***/ 2979: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.generateUniqueNumber = exports.addUniqueNumber = void 0; var _addUniqueNumber = __nccwpck_require__(8139); var _cache = __nccwpck_require__(4168); var _generateUniqueNumber = __nccwpck_require__(8517); const LAST_NUMBER_WEAK_MAP = new WeakMap(); const cache = (0, _cache.createCache)(LAST_NUMBER_WEAK_MAP); const generateUniqueNumber = exports.generateUniqueNumber = (0, _generateUniqueNumber.createGenerateUniqueNumber)(cache, LAST_NUMBER_WEAK_MAP); const addUniqueNumber = exports.addUniqueNumber = (0, _addUniqueNumber.createAddUniqueNumber)(generateUniqueNumber); /***/ }), /***/ 1573: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var url = __nccwpck_require__(7016); var http = __nccwpck_require__(8611); var https = __nccwpck_require__(5692); var assert = __nccwpck_require__(2613); var Writable = (__nccwpck_require__(2203).Writable); var debug = __nccwpck_require__(9897)("follow-redirects"); // RFC7231§4.2.1: Of the request methods defined by this specification, // the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe. var SAFE_METHODS = { GET: true, HEAD: true, OPTIONS: true, TRACE: true }; // Create handlers that pass events from native requests var eventHandlers = Object.create(null); ["abort", "aborted", "error", "socket", "timeout"].forEach(function (event) { eventHandlers[event] = function (arg) { this._redirectable.emit(event, arg); }; }); // An HTTP(S) request that can be redirected function RedirectableRequest(options, responseCallback) { // Initialize the request Writable.call(this); options.headers = options.headers || {}; this._options = options; this._redirectCount = 0; this._redirects = []; this._requestBodyLength = 0; this._requestBodyBuffers = []; // Since http.request treats host as an alias of hostname, // but the url module interprets host as hostname plus port, // eliminate the host property to avoid confusion. if (options.host) { // Use hostname if set, because it has precedence if (!options.hostname) { options.hostname = options.host; } delete options.host; } // Attach a callback if passed if (responseCallback) { this.on("response", responseCallback); } // React to responses of native requests var self = this; this._onNativeResponse = function (response) { self._processResponse(response); }; // Complete the URL object when necessary if (!options.pathname && options.path) { var searchPos = options.path.indexOf("?"); if (searchPos < 0) { options.pathname = options.path; } else { options.pathname = options.path.substring(0, searchPos); options.search = options.path.substring(searchPos); } } // Perform the first request this._performRequest(); } RedirectableRequest.prototype = Object.create(Writable.prototype); // Writes buffered data to the current native request RedirectableRequest.prototype.write = function (data, encoding, callback) { // Validate input and shift parameters if necessary if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { throw new Error("data should be a string, Buffer or Uint8Array"); } if (typeof encoding === "function") { callback = encoding; encoding = null; } // Ignore empty buffers, since writing them doesn't invoke the callback // https://github.com/nodejs/node/issues/22066 if (data.length === 0) { if (callback) { callback(); } return; } // Only write when we don't exceed the maximum body length if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { this._requestBodyLength += data.length; this._requestBodyBuffers.push({ data: data, encoding: encoding }); this._currentRequest.write(data, encoding, callback); } // Error when we exceed the maximum body length else { this.emit("error", new Error("Request body larger than maxBodyLength limit")); this.abort(); } }; // Ends the current native request RedirectableRequest.prototype.end = function (data, encoding, callback) { // Shift parameters if necessary if (typeof data === "function") { callback = data; data = encoding = null; } else if (typeof encoding === "function") { callback = encoding; encoding = null; } // Write data and end var currentRequest = this._currentRequest; this.write(data || "", encoding, function () { currentRequest.end(null, null, callback); }); }; // Sets a header value on the current native request RedirectableRequest.prototype.setHeader = function (name, value) { this._options.headers[name] = value; this._currentRequest.setHeader(name, value); }; // Clears a header value on the current native request RedirectableRequest.prototype.removeHeader = function (name) { delete this._options.headers[name]; this._currentRequest.removeHeader(name); }; // Proxy all other public ClientRequest methods [ "abort", "flushHeaders", "getHeader", "setNoDelay", "setSocketKeepAlive", "setTimeout", ].forEach(function (method) { RedirectableRequest.prototype[method] = function (a, b) { return this._currentRequest[method](a, b); }; }); // Proxy all public ClientRequest properties ["aborted", "connection", "socket"].forEach(function (property) { Object.defineProperty(RedirectableRequest.prototype, property, { get: function () { return this._currentRequest[property]; }, }); }); // Executes the next native request (initial or redirect) RedirectableRequest.prototype._performRequest = function () { // Load the native protocol var protocol = this._options.protocol; var nativeProtocol = this._options.nativeProtocols[protocol]; if (!nativeProtocol) { this.emit("error", new Error("Unsupported protocol " + protocol)); return; } // If specified, use the agent corresponding to the protocol // (HTTP and HTTPS use different types of agents) if (this._options.agents) { var scheme = protocol.substr(0, protocol.length - 1); this._options.agent = this._options.agents[scheme]; } // Create the native request var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse); this._currentUrl = url.format(this._options); // Set up event handlers request._redirectable = this; for (var event in eventHandlers) { /* istanbul ignore else */ if (event) { request.on(event, eventHandlers[event]); } } // End a redirected request // (The first request must be ended explicitly with RedirectableRequest#end) if (this._isRedirect) { // Write the request entity and end. var i = 0; var buffers = this._requestBodyBuffers; (function writeNext() { if (i < buffers.length) { var buffer = buffers[i++]; request.write(buffer.data, buffer.encoding, writeNext); } else { request.end(); } }()); } }; // Processes a response from the current native request RedirectableRequest.prototype._processResponse = function (response) { // Store the redirected response if (this._options.trackRedirects) { this._redirects.push({ url: this._currentUrl, headers: response.headers, statusCode: response.statusCode, }); } // RFC7231§6.4: The 3xx (Redirection) class of status code indicates // that further action needs to be taken by the user agent in order to // fulfill the request. If a Location header field is provided, // the user agent MAY automatically redirect its request to the URI // referenced by the Location field value, // even if the specific status code is not understood. var location = response.headers.location; if (location && this._options.followRedirects !== false && response.statusCode >= 300 && response.statusCode < 400) { // RFC7231§6.4: A client SHOULD detect and intervene // in cyclical redirections (i.e., "infinite" redirection loops). if (++this._redirectCount > this._options.maxRedirects) { this.emit("error", new Error("Max redirects exceeded.")); return; } // RFC7231§6.4: Automatic redirection needs to done with // care for methods not known to be safe […], // since the user might not wish to redirect an unsafe request. // RFC7231§6.4.7: The 307 (Temporary Redirect) status code indicates // that the target resource resides temporarily under a different URI // and the user agent MUST NOT change the request method // if it performs an automatic redirection to that URI. var header; var headers = this._options.headers; if (response.statusCode !== 307 && !(this._options.method in SAFE_METHODS)) { this._options.method = "GET"; // Drop a possible entity and headers related to it this._requestBodyBuffers = []; for (header in headers) { if (/^content-/i.test(header)) { delete headers[header]; } } } // Drop the Host header, as the redirect might lead to a different host if (!this._isRedirect) { for (header in headers) { if (/^host$/i.test(header)) { delete headers[header]; } } } // Perform the redirected request var redirectUrl = url.resolve(this._currentUrl, location); debug("redirecting to", redirectUrl); Object.assign(this._options, url.parse(redirectUrl)); this._isRedirect = true; this._performRequest(); // Discard the remainder of the response to avoid waiting for data response.destroy(); } else { // The response is not a redirect; return it as-is response.responseUrl = this._currentUrl; response.redirects = this._redirects; this.emit("response", response); // Clean up this._requestBodyBuffers = []; } }; // Wraps the key/value object of protocols with redirect functionality function wrap(protocols) { // Default settings var exports = { maxRedirects: 21, maxBodyLength: 10 * 1024 * 1024, }; // Wrap each protocol var nativeProtocols = {}; Object.keys(protocols).forEach(function (scheme) { var protocol = scheme + ":"; var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); // Executes a request, following redirects wrappedProtocol.request = function (options, callback) { if (typeof options === "string") { options = url.parse(options); options.maxRedirects = exports.maxRedirects; } else { options = Object.assign({ protocol: protocol, maxRedirects: exports.maxRedirects, maxBodyLength: exports.maxBodyLength, }, options); } options.nativeProtocols = nativeProtocols; assert.equal(options.protocol, protocol, "protocol mismatch"); debug("options", options); return new RedirectableRequest(options, callback); }; // Executes a GET request, following redirects wrappedProtocol.get = function (options, callback) { var request = wrappedProtocol.request(options, callback); request.end(); return request; }; }); return exports; } // Exports module.exports = wrap({ http: http, https: https }); module.exports.wrap = wrap; /***/ }), /***/ 6729: /***/ ((module, exports, __nccwpck_require__) => { /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = __nccwpck_require__(8470); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return; var c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit') // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { r = exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { return window.localStorage; } catch (e) {} } /***/ }), /***/ 8470: /***/ ((module, exports, __nccwpck_require__) => { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = __nccwpck_require__(7577); /** * Active `debug` instances. */ exports.instances = []; /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { var prevTime; function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %O args.unshift('%O'); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); debug.destroy = destroy; // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } exports.instances.push(debug); return debug; } function destroy () { var index = exports.instances.indexOf(this); if (index !== -1) { exports.instances.splice(index, 1); return true; } else { return false; } } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); exports.names = []; exports.skips = []; var i; var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); var len = split.length; for (i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } for (i = 0; i < exports.instances.length; i++) { var instance = exports.instances[i]; instance.enabled = exports.enabled(instance.namespace); } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } /***/ }), /***/ 9897: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** * Detect Electron renderer process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer') { module.exports = __nccwpck_require__(6729); } else { module.exports = __nccwpck_require__(977); } /***/ }), /***/ 977: /***/ ((module, exports, __nccwpck_require__) => { /** * Module dependencies. */ var tty = __nccwpck_require__(2018); var util = __nccwpck_require__(9023); /** * This is the Node.js implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = __nccwpck_require__(8470); exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; /** * Colors. */ exports.colors = [ 6, 2, 3, 4, 5, 1 ]; try { var supportsColor = __nccwpck_require__(1450); if (supportsColor && supportsColor.level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (err) { // swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(function (key) { return /^debug_/i.test(key); }).reduce(function (obj, key) { // camel-case var prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); // coerce string value into JS value var val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) val = true; else if (/^(no|off|false|disabled)$/i.test(val)) val = false; else if (val === 'null') val = null; else val = Number(val); obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Map %o to `util.inspect()`, all on a single line. */ exports.formatters.o = function(v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n').map(function(str) { return str.trim() }).join(' '); }; /** * Map %o to `util.inspect()`, allowing multiple lines if needed. */ exports.formatters.O = function(v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { var name = this.namespace; var useColors = this.useColors; if (useColors) { var c = this.color; var colorCode = '\u001b[3' + (c < 8 ? c : '8;5;' + c); var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m'; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } else { return new Date().toISOString() + ' '; } } /** * Invokes `util.format()` with the specified arguments and writes to stderr. */ function log() { return process.stderr.write(util.format.apply(util, arguments) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (null == namespaces) { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } else { process.env.DEBUG = namespaces; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init (debug) { debug.inspectOpts = {}; var keys = Object.keys(exports.inspectOpts); for (var i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } /** * Enable namespaces listed in `process.env.DEBUG` initially. */ exports.enable(load()); /***/ }), /***/ 7577: /***/ ((module) => { /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd'; } if (ms >= h) { return Math.round(ms / h) + 'h'; } if (ms >= m) { return Math.round(ms / m) + 'm'; } if (ms >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return; } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name; } return Math.ceil(ms / n) + ' ' + name + 's'; } /***/ }), /***/ 9728: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = realpath realpath.realpath = realpath realpath.sync = realpathSync realpath.realpathSync = realpathSync realpath.monkeypatch = monkeypatch realpath.unmonkeypatch = unmonkeypatch var fs = __nccwpck_require__(9896) var origRealpath = fs.realpath var origRealpathSync = fs.realpathSync var version = process.version var ok = /^v[0-5]\./.test(version) var old = __nccwpck_require__(1201) function newError (er) { return er && er.syscall === 'realpath' && ( er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG' ) } function realpath (p, cache, cb) { if (ok) { return origRealpath(p, cache, cb) } if (typeof cache === 'function') { cb = cache cache = null } origRealpath(p, cache, function (er, result) { if (newError(er)) { old.realpath(p, cache, cb) } else { cb(er, result) } }) } function realpathSync (p, cache) { if (ok) { return origRealpathSync(p, cache) } try { return origRealpathSync(p, cache) } catch (er) { if (newError(er)) { return old.realpathSync(p, cache) } else { throw er } } } function monkeypatch () { fs.realpath = realpath fs.realpathSync = realpathSync } function unmonkeypatch () { fs.realpath = origRealpath fs.realpathSync = origRealpathSync } /***/ }), /***/ 1201: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var pathModule = __nccwpck_require__(6928); var isWindows = process.platform === 'win32'; var fs = __nccwpck_require__(9896); // JavaScript implementation of realpath, ported from node pre-v6 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } var normalize = pathModule.normalize; // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } exports.realpathSync = function realpathSync(p, cache) { // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs.lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs.statSync(base); linkTarget = fs.readlinkSync(base); } resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; exports.realpath = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs.lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs.stat(base, function(err) { if (err) return cb(err); fs.readlink(base, function(err, target) { if (!isWindows) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = pathModule.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } }; /***/ }), /***/ 9808: /***/ ((module) => { "use strict"; /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var toStr = Object.prototype.toString; var max = Math.max; var funcType = '[object Function]'; var concatty = function concatty(a, b) { var arr = []; for (var i = 0; i < a.length; i += 1) { arr[i] = a[i]; } for (var j = 0; j < b.length; j += 1) { arr[j + a.length] = b[j]; } return arr; }; var slicy = function slicy(arrLike, offset) { var arr = []; for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { arr[j] = arrLike[i]; } return arr; }; var joiny = function (arr, joiner) { var str = ''; for (var i = 0; i < arr.length; i += 1) { str += arr[i]; if (i + 1 < arr.length) { str += joiner; } } return str; }; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.apply(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slicy(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, concatty(args, arguments) ); if (Object(result) === result) { return result; } return this; } return target.apply( that, concatty(args, arguments) ); }; var boundLength = max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs[i] = '$' + i; } bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; /***/ }), /***/ 7564: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var implementation = __nccwpck_require__(9808); module.exports = Function.prototype.bind || implementation; /***/ }), /***/ 470: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var undefined; var $Object = __nccwpck_require__(5399); var $Error = __nccwpck_require__(1620); var $EvalError = __nccwpck_require__(3056); var $RangeError = __nccwpck_require__(4585); var $ReferenceError = __nccwpck_require__(6905); var $SyntaxError = __nccwpck_require__(105); var $TypeError = __nccwpck_require__(3314); var $URIError = __nccwpck_require__(2578); var abs = __nccwpck_require__(5641); var floor = __nccwpck_require__(6171); var max = __nccwpck_require__(7147); var min = __nccwpck_require__(1017); var pow = __nccwpck_require__(6947); var round = __nccwpck_require__(2621); var sign = __nccwpck_require__(156); var $Function = Function; // eslint-disable-next-line consistent-return var getEvalledConstructor = function (expressionSyntax) { try { return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); } catch (e) {} }; var $gOPD = __nccwpck_require__(3170); var $defineProperty = __nccwpck_require__(9094); var throwTypeError = function () { throw new $TypeError(); }; var ThrowTypeError = $gOPD ? (function () { try { // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties arguments.callee; // IE 8 does not throw here return throwTypeError; } catch (calleeThrows) { try { // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') return $gOPD(arguments, 'callee').get; } catch (gOPDthrows) { return throwTypeError; } } }()) : throwTypeError; var hasSymbols = __nccwpck_require__(3336)(); var getProto = __nccwpck_require__(1967); var $ObjectGPO = __nccwpck_require__(1311); var $ReflectGPO = __nccwpck_require__(8681); var $apply = __nccwpck_require__(3945); var $call = __nccwpck_require__(8093); var needsEval = {}; var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); var INTRINSICS = { __proto__: null, '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, '%Array%': Array, '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, '%AsyncFromSyncIteratorPrototype%': undefined, '%AsyncFunction%': needsEval, '%AsyncGenerator%': needsEval, '%AsyncGeneratorFunction%': needsEval, '%AsyncIteratorPrototype%': needsEval, '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, '%Boolean%': Boolean, '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, '%Date%': Date, '%decodeURI%': decodeURI, '%decodeURIComponent%': decodeURIComponent, '%encodeURI%': encodeURI, '%encodeURIComponent%': encodeURIComponent, '%Error%': $Error, '%eval%': eval, // eslint-disable-line no-eval '%EvalError%': $EvalError, '%Float16Array%': typeof Float16Array === 'undefined' ? undefined : Float16Array, '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, '%Function%': $Function, '%GeneratorFunction%': needsEval, '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, '%isFinite%': isFinite, '%isNaN%': isNaN, '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, '%JSON%': typeof JSON === 'object' ? JSON : undefined, '%Map%': typeof Map === 'undefined' ? undefined : Map, '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), '%Math%': Math, '%Number%': Number, '%Object%': $Object, '%Object.getOwnPropertyDescriptor%': $gOPD, '%parseFloat%': parseFloat, '%parseInt%': parseInt, '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, '%RangeError%': $RangeError, '%ReferenceError%': $ReferenceError, '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, '%RegExp%': RegExp, '%Set%': typeof Set === 'undefined' ? undefined : Set, '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, '%String%': String, '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, '%Symbol%': hasSymbols ? Symbol : undefined, '%SyntaxError%': $SyntaxError, '%ThrowTypeError%': ThrowTypeError, '%TypedArray%': TypedArray, '%TypeError%': $TypeError, '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, '%URIError%': $URIError, '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, '%Function.prototype.call%': $call, '%Function.prototype.apply%': $apply, '%Object.defineProperty%': $defineProperty, '%Object.getPrototypeOf%': $ObjectGPO, '%Math.abs%': abs, '%Math.floor%': floor, '%Math.max%': max, '%Math.min%': min, '%Math.pow%': pow, '%Math.round%': round, '%Math.sign%': sign, '%Reflect.getPrototypeOf%': $ReflectGPO }; if (getProto) { try { null.error; // eslint-disable-line no-unused-expressions } catch (e) { // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 var errorProto = getProto(getProto(e)); INTRINSICS['%Error.prototype%'] = errorProto; } } var doEval = function doEval(name) { var value; if (name === '%AsyncFunction%') { value = getEvalledConstructor('async function () {}'); } else if (name === '%GeneratorFunction%') { value = getEvalledConstructor('function* () {}'); } else if (name === '%AsyncGeneratorFunction%') { value = getEvalledConstructor('async function* () {}'); } else if (name === '%AsyncGenerator%') { var fn = doEval('%AsyncGeneratorFunction%'); if (fn) { value = fn.prototype; } } else if (name === '%AsyncIteratorPrototype%') { var gen = doEval('%AsyncGenerator%'); if (gen && getProto) { value = getProto(gen.prototype); } } INTRINSICS[name] = value; return value; }; var LEGACY_ALIASES = { __proto__: null, '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], '%ArrayPrototype%': ['Array', 'prototype'], '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], '%ArrayProto_values%': ['Array', 'prototype', 'values'], '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], '%BooleanPrototype%': ['Boolean', 'prototype'], '%DataViewPrototype%': ['DataView', 'prototype'], '%DatePrototype%': ['Date', 'prototype'], '%ErrorPrototype%': ['Error', 'prototype'], '%EvalErrorPrototype%': ['EvalError', 'prototype'], '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], '%FunctionPrototype%': ['Function', 'prototype'], '%Generator%': ['GeneratorFunction', 'prototype'], '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], '%JSONParse%': ['JSON', 'parse'], '%JSONStringify%': ['JSON', 'stringify'], '%MapPrototype%': ['Map', 'prototype'], '%NumberPrototype%': ['Number', 'prototype'], '%ObjectPrototype%': ['Object', 'prototype'], '%ObjProto_toString%': ['Object', 'prototype', 'toString'], '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], '%PromisePrototype%': ['Promise', 'prototype'], '%PromiseProto_then%': ['Promise', 'prototype', 'then'], '%Promise_all%': ['Promise', 'all'], '%Promise_reject%': ['Promise', 'reject'], '%Promise_resolve%': ['Promise', 'resolve'], '%RangeErrorPrototype%': ['RangeError', 'prototype'], '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], '%RegExpPrototype%': ['RegExp', 'prototype'], '%SetPrototype%': ['Set', 'prototype'], '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], '%StringPrototype%': ['String', 'prototype'], '%SymbolPrototype%': ['Symbol', 'prototype'], '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], '%TypedArrayPrototype%': ['TypedArray', 'prototype'], '%TypeErrorPrototype%': ['TypeError', 'prototype'], '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], '%URIErrorPrototype%': ['URIError', 'prototype'], '%WeakMapPrototype%': ['WeakMap', 'prototype'], '%WeakSetPrototype%': ['WeakSet', 'prototype'] }; var bind = __nccwpck_require__(7564); var hasOwn = __nccwpck_require__(4076); var $concat = bind.call($call, Array.prototype.concat); var $spliceApply = bind.call($apply, Array.prototype.splice); var $replace = bind.call($call, String.prototype.replace); var $strSlice = bind.call($call, String.prototype.slice); var $exec = bind.call($call, RegExp.prototype.exec); /* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ var stringToPath = function stringToPath(string) { var first = $strSlice(string, 0, 1); var last = $strSlice(string, -1); if (first === '%' && last !== '%') { throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); } else if (last === '%' && first !== '%') { throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); } var result = []; $replace(string, rePropName, function (match, number, quote, subString) { result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; }); return result; }; /* end adaptation */ var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { var intrinsicName = name; var alias; if (hasOwn(LEGACY_ALIASES, intrinsicName)) { alias = LEGACY_ALIASES[intrinsicName]; intrinsicName = '%' + alias[0] + '%'; } if (hasOwn(INTRINSICS, intrinsicName)) { var value = INTRINSICS[intrinsicName]; if (value === needsEval) { value = doEval(intrinsicName); } if (typeof value === 'undefined' && !allowMissing) { throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); } return { alias: alias, name: intrinsicName, value: value }; } throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); }; module.exports = function GetIntrinsic(name, allowMissing) { if (typeof name !== 'string' || name.length === 0) { throw new $TypeError('intrinsic name must be a non-empty string'); } if (arguments.length > 1 && typeof allowMissing !== 'boolean') { throw new $TypeError('"allowMissing" argument must be a boolean'); } if ($exec(/^%?[^%]*%?$/, name) === null) { throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); } var parts = stringToPath(name); var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); var intrinsicRealName = intrinsic.name; var value = intrinsic.value; var skipFurtherCaching = false; var alias = intrinsic.alias; if (alias) { intrinsicBaseName = alias[0]; $spliceApply(parts, $concat([0, 1], alias)); } for (var i = 1, isOwn = true; i < parts.length; i += 1) { var part = parts[i]; var first = $strSlice(part, 0, 1); var last = $strSlice(part, -1); if ( ( (first === '"' || first === "'" || first === '`') || (last === '"' || last === "'" || last === '`') ) && first !== last ) { throw new $SyntaxError('property names with quotes must have matching quotes'); } if (part === 'constructor' || !isOwn) { skipFurtherCaching = true; } intrinsicBaseName += '.' + part; intrinsicRealName = '%' + intrinsicBaseName + '%'; if (hasOwn(INTRINSICS, intrinsicRealName)) { value = INTRINSICS[intrinsicRealName]; } else if (value != null) { if (!(part in value)) { if (!allowMissing) { throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); } return void undefined; } if ($gOPD && (i + 1) >= parts.length) { var desc = $gOPD(value, part); isOwn = !!desc; // By convention, when a data property is converted to an accessor // property to emulate a data property that does not suffer from // the override mistake, that accessor's getter is marked with // an `originalValue` property. Here, when we detect this, we // uphold the illusion by pretending to see that original data // property, i.e., returning the value rather than the getter // itself. if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { value = desc.get; } else { value = value[part]; } } else { isOwn = hasOwn(value, part); value = value[part]; } if (isOwn && !skipFurtherCaching) { INTRINSICS[intrinsicRealName] = value; } } } return value; }; /***/ }), /***/ 1311: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var $Object = __nccwpck_require__(5399); /** @type {import('./Object.getPrototypeOf')} */ module.exports = $Object.getPrototypeOf || null; /***/ }), /***/ 8681: /***/ ((module) => { "use strict"; /** @type {import('./Reflect.getPrototypeOf')} */ module.exports = (typeof Reflect !== 'undefined' && Reflect.getPrototypeOf) || null; /***/ }), /***/ 1967: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var reflectGetProto = __nccwpck_require__(8681); var originalGetProto = __nccwpck_require__(1311); var getDunderProto = __nccwpck_require__(6669); /** @type {import('.')} */ module.exports = reflectGetProto ? function getProto(O) { // @ts-expect-error TS can't narrow inside a closure, for some reason return reflectGetProto(O); } : originalGetProto ? function getProto(O) { if (!O || (typeof O !== 'object' && typeof O !== 'function')) { throw new TypeError('getProto: not an object'); } // @ts-expect-error TS can't narrow inside a closure, for some reason return originalGetProto(O); } : getDunderProto ? function getProto(O) { // @ts-expect-error TS can't narrow inside a closure, for some reason return getDunderProto(O); } : null; /***/ }), /***/ 8505: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var path = __nccwpck_require__(6928); var isglob = __nccwpck_require__(1925); var pathDirname = __nccwpck_require__(9782); var isWin32 = (__nccwpck_require__(857).platform)() === 'win32'; module.exports = function globParent(str) { // flip windows path separators if (isWin32 && str.indexOf('/') < 0) str = str.split('\\').join('/'); // special case for strings ending in enclosure containing path separator if (/[\{\[].*[\/]*.*[\}\]]$/.test(str)) str += '/'; // preserves full path in case of trailing path separator str += 'a'; // remove path parts that are globby do {str = pathDirname.posix(str)} while (isglob(str) || /(^|[^\\])([\{\[]|\([^\)]+$)/.test(str)); // remove escape chars and return result return str.replace(/\\([\*\?\|\[\]\(\)\{\}])/g, '$1'); }; /***/ }), /***/ 8625: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Combine = __nccwpck_require__(5992); var unique = __nccwpck_require__(3966); var pumpify = __nccwpck_require__(2432); var isNegatedGlob = __nccwpck_require__(228); var extend = __nccwpck_require__(3860); var GlobStream = __nccwpck_require__(7014); function globStream(globs, opt) { if (!opt) { opt = {}; } var ourOpt = extend({}, opt); var ignore = ourOpt.ignore; ourOpt.cwd = typeof ourOpt.cwd === 'string' ? ourOpt.cwd : process.cwd(); ourOpt.dot = typeof ourOpt.dot === 'boolean' ? ourOpt.dot : false; ourOpt.silent = typeof ourOpt.silent === 'boolean' ? ourOpt.silent : true; ourOpt.cwdbase = typeof ourOpt.cwdbase === 'boolean' ? ourOpt.cwdbase : false; ourOpt.uniqueBy = typeof ourOpt.uniqueBy === 'string' || typeof ourOpt.uniqueBy === 'function' ? ourOpt.uniqueBy : 'path'; if (ourOpt.cwdbase) { ourOpt.base = ourOpt.cwd; } // Normalize string `ignore` to array if (typeof ignore === 'string') { ignore = [ignore]; } // Ensure `ignore` is an array if (!Array.isArray(ignore)) { ignore = []; } // Only one glob no need to aggregate if (!Array.isArray(globs)) { globs = [globs]; } var positives = []; var negatives = []; globs.forEach(sortGlobs); function sortGlobs(globString, index) { if (typeof globString !== 'string') { throw new Error('Invalid glob at index ' + index); } var glob = isNegatedGlob(globString); var globArray = glob.negated ? negatives : positives; globArray.push({ index: index, glob: glob.pattern, }); } if (positives.length === 0) { throw new Error('Missing positive glob'); } // Create all individual streams var streams = positives.map(streamFromPositive); // Then just pipe them to a single unique stream and return it var aggregate = new Combine(streams); var uniqueStream = unique(ourOpt.uniqueBy); return pumpify.obj(aggregate, uniqueStream); function streamFromPositive(positive) { var negativeGlobs = negatives .filter(indexGreaterThan(positive.index)) .map(toGlob) .concat(ignore); return new GlobStream(positive.glob, negativeGlobs, ourOpt); } } function indexGreaterThan(index) { return function(obj) { return obj.index > index; }; } function toGlob(obj) { return obj.glob; } module.exports = globStream; /***/ }), /***/ 9436: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var concatMap = __nccwpck_require__(9468); var balanced = __nccwpck_require__(9380); module.exports = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str, options) { if (!str) return []; options = options || {}; var max = options.max == null ? Infinity : options.max; // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, // but a{},b}c will be expanded to [a}c,abc]. // One could argue that this is a bug in Bash, but since the goal of // this module is to match Bash's rules, we escape a leading {} if (str.substr(0, 2) === '{}') { str = '\\{\\}' + str.substr(2); } return expand(escapeBraces(str), max, true).map(unescapeBraces); } function identity(e) { return e; } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand(str, max, isTop) { var expansions = []; var m = balanced('{', '}', str); if (!m || /\$$/.test(m.pre)) return [str]; var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,(?!,).*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str, max, true); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand(n[0], max, false).map(embrace); if (n.length === 1) { var post = m.post.length ? expand(m.post, max, false) : ['']; return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand(m.post, max, false) : ['']; var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length) var incr = n.length == 3 ? Math.max(Math.abs(numeric(n[2])), 1) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = concatMap(n, function(el) { return expand(el, max, false) }); } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length && expansions.length < max; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } return expansions; } /***/ }), /***/ 4162: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { exports.setopts = setopts exports.ownProp = ownProp exports.makeAbs = makeAbs exports.finish = finish exports.mark = mark exports.isIgnored = isIgnored exports.childrenIgnored = childrenIgnored function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var fs = __nccwpck_require__(9896) var path = __nccwpck_require__(6928) var minimatch = __nccwpck_require__(7151) var isAbsolute = __nccwpck_require__(9024) var Minimatch = minimatch.Minimatch function alphasort (a, b) { return a.localeCompare(b, 'en') } function setupIgnores (self, options) { self.ignore = options.ignore || [] if (!Array.isArray(self.ignore)) self.ignore = [self.ignore] if (self.ignore.length) { self.ignore = self.ignore.map(ignoreMap) } } // ignore patterns are always in dot:true mode. function ignoreMap (pattern) { var gmatcher = null if (pattern.slice(-3) === '/**') { var gpattern = pattern.replace(/(\/\*\*)+$/, '') gmatcher = new Minimatch(gpattern, { dot: true }) } return { matcher: new Minimatch(pattern, { dot: true }), gmatcher: gmatcher } } function setopts (self, pattern, options) { if (!options) options = {} // base-matching: just use globstar for that. if (options.matchBase && -1 === pattern.indexOf("/")) { if (options.noglobstar) { throw new Error("base matching requires globstar") } pattern = "**/" + pattern } self.silent = !!options.silent self.pattern = pattern self.strict = options.strict !== false self.realpath = !!options.realpath self.realpathCache = options.realpathCache || Object.create(null) self.follow = !!options.follow self.dot = !!options.dot self.mark = !!options.mark self.nodir = !!options.nodir if (self.nodir) self.mark = true self.sync = !!options.sync self.nounique = !!options.nounique self.nonull = !!options.nonull self.nosort = !!options.nosort self.nocase = !!options.nocase self.stat = !!options.stat self.noprocess = !!options.noprocess self.absolute = !!options.absolute self.fs = options.fs || fs self.maxLength = options.maxLength || Infinity self.cache = options.cache || Object.create(null) self.statCache = options.statCache || Object.create(null) self.symlinks = options.symlinks || Object.create(null) setupIgnores(self, options) self.changedCwd = false var cwd = process.cwd() if (!ownProp(options, "cwd")) self.cwd = cwd else { self.cwd = path.resolve(options.cwd) self.changedCwd = self.cwd !== cwd } self.root = options.root || path.resolve(self.cwd, "/") self.root = path.resolve(self.root) if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/") // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") self.nomount = !!options.nomount // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true options.nocomment = true // always treat \ in patterns as escapes, not path separators options.allowWindowsEscape = false self.minimatch = new Minimatch(pattern, options) self.options = self.minimatch.options } function finish (self) { var nou = self.nounique var all = nou ? [] : Object.create(null) for (var i = 0, l = self.matches.length; i < l; i ++) { var matches = self.matches[i] if (!matches || Object.keys(matches).length === 0) { if (self.nonull) { // do like the shell, and spit out the literal glob var literal = self.minimatch.globSet[i] if (nou) all.push(literal) else all[literal] = true } } else { // had matches var m = Object.keys(matches) if (nou) all.push.apply(all, m) else m.forEach(function (m) { all[m] = true }) } } if (!nou) all = Object.keys(all) if (!self.nosort) all = all.sort(alphasort) // at *some* point we statted all of these if (self.mark) { for (var i = 0; i < all.length; i++) { all[i] = self._mark(all[i]) } if (self.nodir) { all = all.filter(function (e) { var notDir = !(/\/$/.test(e)) var c = self.cache[e] || self.cache[makeAbs(self, e)] if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c) return notDir }) } } if (self.ignore.length) all = all.filter(function(m) { return !isIgnored(self, m) }) self.found = all } function mark (self, p) { var abs = makeAbs(self, p) var c = self.cache[abs] var m = p if (c) { var isDir = c === 'DIR' || Array.isArray(c) var slash = p.slice(-1) === '/' if (isDir && !slash) m += '/' else if (!isDir && slash) m = m.slice(0, -1) if (m !== p) { var mabs = makeAbs(self, m) self.statCache[mabs] = self.statCache[abs] self.cache[mabs] = self.cache[abs] } } return m } // lotta situps... function makeAbs (self, f) { var abs = f if (f.charAt(0) === '/') { abs = path.join(self.root, f) } else if (isAbsolute(f) || f === '') { abs = f } else if (self.changedCwd) { abs = path.resolve(self.cwd, f) } else { abs = path.resolve(f) } if (process.platform === 'win32') abs = abs.replace(/\\/g, '/') return abs } // Return true, if pattern ends with globstar '**', for the accompanying parent directory. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents function isIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) }) } function childrenIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path)) }) } /***/ }), /***/ 349: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. module.exports = glob var rp = __nccwpck_require__(9728) var minimatch = __nccwpck_require__(7151) var Minimatch = minimatch.Minimatch var inherits = __nccwpck_require__(9598) var EE = (__nccwpck_require__(4434).EventEmitter) var path = __nccwpck_require__(6928) var assert = __nccwpck_require__(2613) var isAbsolute = __nccwpck_require__(9024) var globSync = __nccwpck_require__(7104) var common = __nccwpck_require__(4162) var setopts = common.setopts var ownProp = common.ownProp var inflight = __nccwpck_require__(3176) var util = __nccwpck_require__(9023) var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored var once = __nccwpck_require__(5560) function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} if (!options) options = {} if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync var GlobSync = glob.GlobSync = globSync.GlobSync // old api surface glob.glob = glob function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add) var i = keys.length while (i--) { origin[keys[i]] = add[keys[i]] } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_) options.noprocess = true var g = new Glob(pattern, options) var set = g.minimatch.set if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false } glob.Glob = Glob inherits(Glob, EE) function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options options = null } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options) this._didRealPath = false // process each pattern in the minimatch set var n = this.minimatch.set.length // The matches are stored as {: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n) if (typeof cb === 'function') { cb = once(cb) this.on('error', cb) this.on('end', function (matches) { cb(null, matches) }) } var self = this this._processing = 0 this._emitQueue = [] this._processQueue = [] this.paused = false if (this.noprocess) return this if (n === 0) return done() var sync = true for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done) } sync = false function done () { --self._processing if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish() }) } else { self._finish() } } } } Glob.prototype._finish = function () { assert(this instanceof Glob) if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this) this.emit('end', this.found) } Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true var n = this.matches.length if (n === 0) return this._finish() var self = this for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next) function next () { if (--n === 0) self._finish() } } Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index] if (!matchset) return cb() var found = Object.keys(matchset) var self = this var n = found.length if (n === 0) return cb() var set = this.matches[index] = Object.create(null) found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p) rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true else if (er.syscall === 'stat') set[p] = true else self.emit('error', er) // srsly wtf right here if (--n === 0) { self.matches[index] = set cb() } }) }) } Glob.prototype._mark = function (p) { return common.mark(this, p) } Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } Glob.prototype.abort = function () { this.aborted = true this.emit('abort') } Glob.prototype.pause = function () { if (!this.paused) { this.paused = true this.emit('pause') } } Glob.prototype.resume = function () { if (this.paused) { this.emit('resume') this.paused = false if (this._emitQueue.length) { var eq = this._emitQueue.slice(0) this._emitQueue.length = 0 for (var i = 0; i < eq.length; i ++) { var e = eq[i] this._emitMatch(e[0], e[1]) } } if (this._processQueue.length) { var pq = this._processQueue.slice(0) this._processQueue.length = 0 for (var i = 0; i < pq.length; i ++) { var p = pq[i] this._processing-- this._process(p[0], p[1], p[2], p[3]) } } } } Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob) assert(typeof cb === 'function') if (this.aborted) return this._processing++ if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]) return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) { return typeof p === 'string' ? p : '[*]' }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } this._process([e].concat(remain), index, inGlobStar, cb) } cb() } Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]) return } var abs = isAbsolute(e) ? e : this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) e = abs if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true var st = this.statCache[abs] if (st) this.emit('stat', e, st) this.emit('match', e) } Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs var self = this var lstatcb = inflight(lstatkey, lstatcb_) if (lstatcb) self.fs.lstat(abs, lstatcb) function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink() self.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE' cb() } else self._readdir(abs, false, cb) } } Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this self.fs.readdir(abs, readdirCb(this, abs, cb)) } function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb) else self._readdirEntries(abs, entries, cb) } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries return cb(null, entries) } Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code this.emit('error', error) this.abort() } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) { this.emit('error', er) // If the error is handled, then we abort // if not, we threw out of here this.abort() } if (!this.silent) console.error('glob error', er) break } return cb() } Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb) var isSym = this.symlinks[abs] var len = entries.length // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true, cb) var below = gspref.concat(entries[i], remain) this._process(below, index, true, cb) } cb() } Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb) }) } Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) cb() } // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE' if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this var statcb = inflight('stat\0' + abs, lstatcb_) if (statcb) self.fs.lstat(abs, statcb) function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return self.fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb) else self._stat2(f, abs, er, stat, cb) }) } else { self._stat2(f, abs, er, lstat, cb) } } } Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return cb() } var needDir = f.slice(-1) === '/' this.statCache[abs] = stat if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return cb() return cb(null, c, stat) } /***/ }), /***/ 7104: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = globSync globSync.GlobSync = GlobSync var rp = __nccwpck_require__(9728) var minimatch = __nccwpck_require__(7151) var Minimatch = minimatch.Minimatch var Glob = (__nccwpck_require__(349).Glob) var util = __nccwpck_require__(9023) var path = __nccwpck_require__(6928) var assert = __nccwpck_require__(2613) var isAbsolute = __nccwpck_require__(9024) var common = __nccwpck_require__(4162) var setopts = common.setopts var ownProp = common.ownProp var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored function globSync (pattern, options) { if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') return new GlobSync(pattern, options).found } function GlobSync (pattern, options) { if (!pattern) throw new Error('must provide pattern') if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') if (!(this instanceof GlobSync)) return new GlobSync(pattern, options) setopts(this, pattern, options) if (this.noprocess) return this var n = this.minimatch.set.length this.matches = new Array(n) for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false) } this._finish() } GlobSync.prototype._finish = function () { assert.ok(this instanceof GlobSync) if (this.realpath) { var self = this this.matches.forEach(function (matchset, index) { var set = self.matches[index] = Object.create(null) for (var p in matchset) { try { p = self._makeAbs(p) var real = rp.realpathSync(p, self.realpathCache) set[real] = true } catch (er) { if (er.syscall === 'stat') set[self._makeAbs(p)] = true else throw er } } }) } common.finish(this) } GlobSync.prototype._process = function (pattern, index, inGlobStar) { assert.ok(this instanceof GlobSync) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // See if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.map(function (p) { return typeof p === 'string' ? p : '[*]' }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip processing if (childrenIgnored(this, read)) return var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar) } GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // if the abs isn't a dir, then nothing can match! if (!entries) return // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix.slice(-1) !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) newPattern = [prefix, e] else newPattern = [e] this._process(newPattern.concat(remain), index, inGlobStar) } } GlobSync.prototype._emitMatch = function (index, e) { if (isIgnored(this, e)) return var abs = this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) { e = abs } if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true if (this.stat) this._stat(e) } GlobSync.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false) var entries var lstat var stat try { lstat = this.fs.lstatSync(abs) } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist return null } } var isSym = lstat && lstat.isSymbolicLink() this.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE' else entries = this._readdir(abs, false) return entries } GlobSync.prototype._readdir = function (abs, inGlobStar) { var entries if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return null if (Array.isArray(c)) return c } try { return this._readdirEntries(abs, this.fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er) return null } } GlobSync.prototype._readdirEntries = function (abs, entries) { // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries // mark and cache dir-ness return entries } GlobSync.prototype._readdirError = function (f, er) { // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code throw error } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) throw er if (!this.silent) console.error('glob error', er) break } } GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false) var len = entries.length var isSym = this.symlinks[abs] // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true) var below = gspref.concat(entries[i], remain) this._process(below, index, true) } } GlobSync.prototype._processSimple = function (prefix, index) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var exists = this._stat(prefix) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) } // Returns either 'DIR', 'FILE', or false GlobSync.prototype._stat = function (f) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return false if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return c if (needDir && c === 'FILE') return false // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (!stat) { var lstat try { lstat = this.fs.lstatSync(abs) } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return false } } if (lstat && lstat.isSymbolicLink()) { try { stat = this.fs.statSync(abs) } catch (er) { stat = lstat } } else { stat = lstat } } this.statCache[abs] = stat var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return false return c } GlobSync.prototype._mark = function (p) { return common.mark(this, p) } GlobSync.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } /***/ }), /***/ 7151: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = minimatch minimatch.Minimatch = Minimatch var path = (function () { try { return __nccwpck_require__(6928) } catch (e) {}}()) || { sep: '/' } minimatch.sep = path.sep var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} var expand = __nccwpck_require__(9436) var plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, '?': { open: '(?:', close: ')?' }, '+': { open: '(?:', close: ')+' }, '*': { open: '(?:', close: ')*' }, '@': { open: '(?:', close: ')' } } // any single thing other than / // don't need to escape / when using new RegExp() var qmark = '[^/]' // * => any number of characters var star = qmark + '*?' // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' // not a ^ or / followed by a dot, // followed by anything, any number of times. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' // characters that need to be escaped in RegExp. var reSpecials = charSet('().*{}+?[]^$\\!') // "abc" -> { a:true, b:true, c:true } function charSet (s) { return s.split('').reduce(function (set, c) { set[c] = true return set }, {}) } // normalizes slashes. var slashSplit = /\/+/ minimatch.filter = filter function filter (pattern, options) { options = options || {} return function (p, i, list) { return minimatch(p, pattern, options) } } function ext (a, b) { b = b || {} var t = {} Object.keys(a).forEach(function (k) { t[k] = a[k] }) Object.keys(b).forEach(function (k) { t[k] = b[k] }) return t } minimatch.defaults = function (def) { if (!def || typeof def !== 'object' || !Object.keys(def).length) { return minimatch } var orig = minimatch var m = function minimatch (p, pattern, options) { return orig(p, pattern, ext(def, options)) } m.Minimatch = function Minimatch (pattern, options) { return new orig.Minimatch(pattern, ext(def, options)) } m.Minimatch.defaults = function defaults (options) { return orig.defaults(ext(def, options)).Minimatch } m.filter = function filter (pattern, options) { return orig.filter(pattern, ext(def, options)) } m.defaults = function defaults (options) { return orig.defaults(ext(def, options)) } m.makeRe = function makeRe (pattern, options) { return orig.makeRe(pattern, ext(def, options)) } m.braceExpand = function braceExpand (pattern, options) { return orig.braceExpand(pattern, ext(def, options)) } m.match = function (list, pattern, options) { return orig.match(list, pattern, ext(def, options)) } return m } Minimatch.defaults = function (def) { return minimatch.defaults(def).Minimatch } function minimatch (p, pattern, options) { assertValidPattern(pattern) if (!options) options = {} // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false } return new Minimatch(pattern, options).match(p) } function Minimatch (pattern, options) { if (!(this instanceof Minimatch)) { return new Minimatch(pattern, options) } assertValidPattern(pattern) if (!options) options = {} pattern = pattern.trim() // windows support: need to use /, not \ if (!options.allowWindowsEscape && path.sep !== '/') { pattern = pattern.split(path.sep).join('/') } this.options = options this.maxGlobstarRecursion = options.maxGlobstarRecursion !== undefined ? options.maxGlobstarRecursion : 200 this.set = [] this.pattern = pattern this.regexp = null this.negate = false this.comment = false this.empty = false this.partial = !!options.partial // make the set of regexps etc. this.make() } Minimatch.prototype.debug = function () {} Minimatch.prototype.make = make function make () { var pattern = this.pattern var options = this.options // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { this.comment = true return } if (!pattern) { this.empty = true return } // step 1: figure out negation, etc. this.parseNegate() // step 2: expand braces var set = this.globSet = this.braceExpand() if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } this.debug(this.pattern, set) // step 3: now we have a set, so turn each one into a series of path-portion // matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters set = this.globParts = set.map(function (s) { return s.split(slashSplit) }) this.debug(this.pattern, set) // glob --> regexps set = set.map(function (s, si, set) { return s.map(this.parse, this) }, this) this.debug(this.pattern, set) // filter out everything that didn't compile properly. set = set.filter(function (s) { return s.indexOf(false) === -1 }) this.debug(this.pattern, set) this.set = set } Minimatch.prototype.parseNegate = parseNegate function parseNegate () { var pattern = this.pattern var negate = false var options = this.options var negateOffset = 0 if (options.nonegate) return for (var i = 0, l = pattern.length ; i < l && pattern.charAt(i) === '!' ; i++) { negate = !negate negateOffset++ } if (negateOffset) this.pattern = pattern.substr(negateOffset) this.negate = negate } // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c minimatch.braceExpand = function (pattern, options) { return braceExpand(pattern, options) } Minimatch.prototype.braceExpand = braceExpand function braceExpand (pattern, options) { if (!options) { if (this instanceof Minimatch) { options = this.options } else { options = {} } } pattern = typeof pattern === 'undefined' ? this.pattern : pattern assertValidPattern(pattern) // Thanks to Yeting Li for // improving this regexp to avoid a ReDOS vulnerability. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { // shortcut. no need to expand. return [pattern] } return expand(pattern) } var MAX_PATTERN_LENGTH = 1024 * 64 var assertValidPattern = function (pattern) { if (typeof pattern !== 'string') { throw new TypeError('invalid pattern') } if (pattern.length > MAX_PATTERN_LENGTH) { throw new TypeError('pattern is too long') } } // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. Minimatch.prototype.parse = parse var SUBPARSE = {} function parse (pattern, isSub) { assertValidPattern(pattern) var options = this.options // shortcuts if (pattern === '**') { if (!options.noglobstar) return GLOBSTAR else pattern = '*' } if (pattern === '') return '' var re = '' var hasMagic = !!options.nocase var escaping = false // ? => one single character var patternListStack = [] var negativeLists = [] var stateChar var inClass = false var reClassStart = -1 var classStart = -1 // . and .. never match anything that doesn't start with ., // even when options.dot is set. var patternStart = pattern.charAt(0) === '.' ? '' // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)' var self = this function clearStateChar () { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case '*': re += star hasMagic = true break case '?': re += qmark hasMagic = true break default: re += '\\' + stateChar break } self.debug('clearStateChar %j %j', stateChar, re) stateChar = false } } for (var i = 0, len = pattern.length, c ; (i < len) && (c = pattern.charAt(i)) ; i++) { this.debug('%s\t%s %s %j', pattern, i, re, c) // skip over any that are escaped. if (escaping && reSpecials[c]) { re += '\\' + c escaping = false continue } switch (c) { /* istanbul ignore next */ case '/': { // completely not allowed, even escaped. // Should already be path-split by now. return false } case '\\': clearStateChar() escaping = true continue // the various stateChar values // for the "extglob" stuff. case '?': case '*': case '+': case '@': case '!': this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { this.debug(' in class') if (c === '!' && i === classStart + 1) c = '^' re += c continue } // coalesce consecutive non-globstar * characters if (c === '*' && stateChar === '*') continue // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. self.debug('call clearStateChar %j', stateChar) clearStateChar() stateChar = c // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar() continue case '(': if (inClass) { re += '(' continue } if (!stateChar) { re += '\\(' continue } patternListStack.push({ type: stateChar, start: i - 1, reStart: re.length, open: plTypes[stateChar].open, close: plTypes[stateChar].close }) // negation is (?:(?!js)[^/]*) re += stateChar === '!' ? '(?:(?!(?:' : '(?:' this.debug('plType %j %j', stateChar, re) stateChar = false continue case ')': if (inClass || !patternListStack.length) { re += '\\)' continue } clearStateChar() hasMagic = true var pl = patternListStack.pop() // negation is (?:(?!js)[^/]*) // The others are (?:) re += pl.close if (pl.type === '!') { negativeLists.push(pl) } pl.reEnd = re.length continue case '|': if (inClass || !patternListStack.length || escaping) { re += '\\|' escaping = false continue } clearStateChar() re += '|' continue // these are mostly the same in regexp and glob case '[': // swallow any state-tracking char before the [ clearStateChar() if (inClass) { re += '\\' + c continue } inClass = true classStart = i reClassStart = re.length re += c continue case ']': // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += '\\' + c escaping = false continue } // handle the case where we left a class open. // "[z-a]" is valid, equivalent to "\[z-a\]" // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that // were passed through as-is // TODO: It would probably be faster to determine this // without a try/catch and a new RegExp, but it's tricky // to do safely. For now, this is safe and works. var cs = pattern.substring(classStart + 1, i) try { RegExp('[' + cs + ']') } catch (er) { // not a valid class! var sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' hasMagic = hasMagic || sp[1] inClass = false continue } // finish up the class. hasMagic = true inClass = false re += c continue default: // swallow any state char that wasn't consumed clearStateChar() if (escaping) { // no need escaping = false } else if (reSpecials[c] && !(c === '^' && inClass)) { re += '\\' } re += c } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is cs = pattern.substr(classStart + 1) sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] hasMagic = hasMagic || sp[1] } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + pl.open.length) this.debug('setting tail', re, pl) // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { if (!$2) { // the | isn't already escaped, so escape it. $2 = '\\' } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + '|' }) this.debug('tail=%j\n %s', tail, tail, pl, re) var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type hasMagic = true re = re.slice(0, pl.reStart) + t + '\\(' + tail } // handle trailing things that only matter at the very end. clearStateChar() if (escaping) { // trailing \\ re += '\\\\' } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot var addPatternStart = false switch (re.charAt(0)) { case '[': case '.': case '(': addPatternStart = true } // Hack to work around lack of negative lookbehind in JS // A pattern like: *.!(x).!(y|z) needs to ensure that a name // like 'a.xyz.yz' doesn't match. So, the first negative // lookahead, has to look ALL the way ahead, to the end of // the pattern. for (var n = negativeLists.length - 1; n > -1; n--) { var nl = negativeLists[n] var nlBefore = re.slice(0, nl.reStart) var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) var nlAfter = re.slice(nl.reEnd) nlLast += nlAfter // Handle nested stuff like *(*.js|!(*.json)), where open parens // mean that we should *not* include the ) in the bit that is considered // "after" the negated section. var openParensBefore = nlBefore.split('(').length - 1 var cleanAfter = nlAfter for (i = 0; i < openParensBefore; i++) { cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') } nlAfter = cleanAfter var dollar = '' if (nlAfter === '' && isSub !== SUBPARSE) { dollar = '$' } var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast re = newRe } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== '' && hasMagic) { re = '(?=.)' + re } if (addPatternStart) { re = patternStart + re } // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [re, hasMagic] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape(pattern) } var flags = options.nocase ? 'i' : '' try { var regExp = new RegExp('^' + re + '$', flags) } catch (er) /* istanbul ignore next - should be impossible */ { // If it was an invalid regular expression, then it can't match // anything. This trick looks for a character after the end of // the string, which is of course impossible, except in multi-line // mode, but it's not a /m regex. return new RegExp('$.') } regExp._glob = pattern regExp._src = re return regExp } minimatch.makeRe = function (pattern, options) { return new Minimatch(pattern, options || {}).makeRe() } Minimatch.prototype.makeRe = makeRe function makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. var set = this.set if (!set.length) { this.regexp = false return this.regexp } var options = this.options var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot var flags = options.nocase ? 'i' : '' var re = set.map(function (pattern) { return pattern.map(function (p) { return (p === GLOBSTAR) ? twoStar : (typeof p === 'string') ? regExpEscape(p) : p._src }).join('\\\/') }).join('|') // must match entire pattern // ending in a * or ** will make it less strict. re = '^(?:' + re + ')$' // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').*$' try { this.regexp = new RegExp(re, flags) } catch (ex) /* istanbul ignore next - should be impossible */ { this.regexp = false } return this.regexp } minimatch.match = function (list, pattern, options) { options = options || {} var mm = new Minimatch(pattern, options) list = list.filter(function (f) { return mm.match(f) }) if (mm.options.nonull && !list.length) { list.push(pattern) } return list } Minimatch.prototype.match = function match (f, partial) { if (typeof partial === 'undefined') partial = this.partial this.debug('match', f, this.pattern) // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === '' if (f === '/' && partial) return true var options = this.options // windows: need to use /, not \ if (path.sep !== '/') { f = f.split(path.sep).join('/') } // treat the test path as a set of pathparts. f = f.split(slashSplit) this.debug(this.pattern, 'split', f) // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. var set = this.set this.debug(this.pattern, 'set', set) // Find the basename of the path by looking for the last non-empty segment var filename var i for (i = f.length - 1; i >= 0; i--) { filename = f[i] if (filename) break } for (i = 0; i < set.length; i++) { var pattern = set[i] var file = f if (options.matchBase && pattern.length === 1) { file = [filename] } var hit = this.matchOne(file, pattern, partial) if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. Minimatch.prototype.matchOne = function (file, pattern, partial) { if (pattern.indexOf(GLOBSTAR) !== -1) { return this._matchGlobstar(file, pattern, partial, 0, 0) } return this._matchOne(file, pattern, partial, 0, 0) } Minimatch.prototype._matchGlobstar = function (file, pattern, partial, fileIndex, patternIndex) { var i // find first globstar from patternIndex var firstgs = -1 for (i = patternIndex; i < pattern.length; i++) { if (pattern[i] === GLOBSTAR) { firstgs = i; break } } // find last globstar var lastgs = -1 for (i = pattern.length - 1; i >= 0; i--) { if (pattern[i] === GLOBSTAR) { lastgs = i; break } } var head = pattern.slice(patternIndex, firstgs) var body = partial ? pattern.slice(firstgs + 1) : pattern.slice(firstgs + 1, lastgs) var tail = partial ? [] : pattern.slice(lastgs + 1) // check the head if (head.length) { var fileHead = file.slice(fileIndex, fileIndex + head.length) if (!this._matchOne(fileHead, head, partial, 0, 0)) { return false } fileIndex += head.length } // check the tail var fileTailMatch = 0 if (tail.length) { if (tail.length + fileIndex > file.length) return false var tailStart = file.length - tail.length if (this._matchOne(file, tail, partial, tailStart, 0)) { fileTailMatch = tail.length } else { // affordance for stuff like a/**/* matching a/b/ if (file[file.length - 1] !== '' || fileIndex + tail.length === file.length) { return false } tailStart-- if (!this._matchOne(file, tail, partial, tailStart, 0)) { return false } fileTailMatch = tail.length + 1 } } // if body is empty (single ** between head and tail) if (!body.length) { var sawSome = !!fileTailMatch for (i = fileIndex; i < file.length - fileTailMatch; i++) { var f = String(file[i]) sawSome = true if (f === '.' || f === '..' || (!this.options.dot && f.charAt(0) === '.')) { return false } } return partial || sawSome } // split body into segments at each GLOBSTAR var bodySegments = [[[], 0]] var currentBody = bodySegments[0] var nonGsParts = 0 var nonGsPartsSums = [0] for (var bi = 0; bi < body.length; bi++) { var b = body[bi] if (b === GLOBSTAR) { nonGsPartsSums.push(nonGsParts) currentBody = [[], 0] bodySegments.push(currentBody) } else { currentBody[0].push(b) nonGsParts++ } } var idx = bodySegments.length - 1 var fileLength = file.length - fileTailMatch for (var si = 0; si < bodySegments.length; si++) { bodySegments[si][1] = fileLength - (nonGsPartsSums[idx--] + bodySegments[si][0].length) } return !!this._matchGlobStarBodySections( file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch ) } // return false for "nope, not matching" // return null for "not matching, cannot keep trying" Minimatch.prototype._matchGlobStarBodySections = function ( file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail ) { var bs = bodySegments[bodyIndex] if (!bs) { // just make sure there are no bad dots for (var i = fileIndex; i < file.length; i++) { sawTail = true var f = file[i] if (f === '.' || f === '..' || (!this.options.dot && f.charAt(0) === '.')) { return false } } return sawTail } var body = bs[0] var after = bs[1] while (fileIndex <= after) { var m = this._matchOne( file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0 ) // if limit exceeded, no match. intentional false negative, // acceptable break in correctness for security. if (m && globStarDepth < this.maxGlobstarRecursion) { var sub = this._matchGlobStarBodySections( file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail ) if (sub !== false) { return sub } } var f = file[fileIndex] if (f === '.' || f === '..' || (!this.options.dot && f.charAt(0) === '.')) { return false } fileIndex++ } return partial || null } Minimatch.prototype._matchOne = function (file, pattern, partial, fileIndex, patternIndex) { var fi, pi, fl, pl for ( fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length ; (fi < fl) && (pi < pl) ; fi++, pi++ ) { this.debug('matchOne loop') var p = pattern[pi] var f = file[fi] this.debug(pattern, p, f) // should be impossible. // some invalid regexp stuff in the set. /* istanbul ignore if */ if (p === false || p === GLOBSTAR) return false // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit if (typeof p === 'string') { hit = f === p this.debug('string match', p, f, hit) } else { hit = f.match(p) this.debug('pattern match', p, f, hit) } if (!hit) return false } // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else /* istanbul ignore else */ if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ return (fi === fl - 1) && (file[fi] === '') } // should be unreachable. /* istanbul ignore next */ throw new Error('wtf?') } // replace stuff like \* with * function globUnescape (s) { return s.replace(/\\(.)/g, '$1') } function regExpEscape (s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } /***/ }), /***/ 7014: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var inherits = (__nccwpck_require__(9023).inherits); var glob = __nccwpck_require__(349); var extend = __nccwpck_require__(3860); var Readable = (__nccwpck_require__(6131).Readable); var globParent = __nccwpck_require__(8505); var toAbsoluteGlob = __nccwpck_require__(5025); var removeTrailingSeparator = __nccwpck_require__(3961); var globErrMessage1 = 'File not found with singular glob: '; var globErrMessage2 = ' (if this was purposeful, use `allowEmpty` option)'; function getBasePath(ourGlob, opt) { return globParent(toAbsoluteGlob(ourGlob, opt)); } function globIsSingular(glob) { var globSet = glob.minimatch.set; if (globSet.length !== 1) { return false; } return globSet[0].every(function isString(value) { return typeof value === 'string'; }); } function GlobStream(ourGlob, negatives, opt) { if (!(this instanceof GlobStream)) { return new GlobStream(ourGlob, negatives, opt); } var ourOpt = extend({}, opt); Readable.call(this, { objectMode: true, highWaterMark: ourOpt.highWaterMark || 16, }); // Delete `highWaterMark` after inheriting from Readable delete ourOpt.highWaterMark; var self = this; function resolveNegatives(negative) { return toAbsoluteGlob(negative, ourOpt); } var ourNegatives = negatives.map(resolveNegatives); ourOpt.ignore = ourNegatives; var cwd = ourOpt.cwd; var allowEmpty = ourOpt.allowEmpty || false; // Extract base path from glob var basePath = ourOpt.base || getBasePath(ourGlob, ourOpt); // Remove path relativity to make globs make sense ourGlob = toAbsoluteGlob(ourGlob, ourOpt); // Delete `root` after all resolving done delete ourOpt.root; var globber = new glob.Glob(ourGlob, ourOpt); this._globber = globber; var found = false; globber.on('match', function(filepath) { found = true; var obj = { cwd: cwd, base: basePath, path: removeTrailingSeparator(filepath), }; if (!self.push(obj)) { globber.pause(); } }); globber.once('end', function() { if (allowEmpty !== true && !found && globIsSingular(globber)) { var err = new Error(globErrMessage1 + ourGlob + globErrMessage2); return self.destroy(err); } self.push(null); }); function onError(err) { self.destroy(err); } globber.once('error', onError); } inherits(GlobStream, Readable); GlobStream.prototype._read = function() { this._globber.resume(); }; GlobStream.prototype.destroy = function(err) { var self = this; this._globber.abort(); process.nextTick(function() { if (err) { self.emit('error', err); } self.emit('close'); }); }; module.exports = GlobStream; /***/ }), /***/ 1174: /***/ ((module) => { "use strict"; /** @type {import('./gOPD')} */ module.exports = Object.getOwnPropertyDescriptor; /***/ }), /***/ 3170: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /** @type {import('.')} */ var $gOPD = __nccwpck_require__(1174); if ($gOPD) { try { $gOPD([], 'length'); } catch (e) { // IE 8 has a broken gOPD $gOPD = null; } } module.exports = $gOPD; /***/ }), /***/ 3813: /***/ ((module) => { "use strict"; module.exports = (flag, argv = process.argv) => { const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; /***/ }), /***/ 3336: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var origSymbol = typeof Symbol !== 'undefined' && Symbol; var hasSymbolSham = __nccwpck_require__(1114); /** @type {import('.')} */ module.exports = function hasNativeSymbols() { if (typeof origSymbol !== 'function') { return false; } if (typeof Symbol !== 'function') { return false; } if (typeof origSymbol('foo') !== 'symbol') { return false; } if (typeof Symbol('bar') !== 'symbol') { return false; } return hasSymbolSham(); }; /***/ }), /***/ 1114: /***/ ((module) => { "use strict"; /** @type {import('./shams')} */ /* eslint complexity: [2, 18], max-statements: [2, 33] */ module.exports = function hasSymbols() { if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } if (typeof Symbol.iterator === 'symbol') { return true; } /** @type {{ [k in symbol]?: unknown }} */ var obj = {}; var sym = Symbol('test'); var symObj = Object(sym); if (typeof sym === 'string') { return false; } if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } // temp disabled per https://github.com/ljharb/object.assign/issues/17 // if (sym instanceof Symbol) { return false; } // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 // if (!(symObj instanceof Symbol)) { return false; } // if (typeof Symbol.prototype.toString !== 'function') { return false; } // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } var symVal = 42; obj[sym] = symVal; for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } var syms = Object.getOwnPropertySymbols(obj); if (syms.length !== 1 || syms[0] !== sym) { return false; } if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } if (typeof Object.getOwnPropertyDescriptor === 'function') { // eslint-disable-next-line no-extra-parens var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } } return true; }; /***/ }), /***/ 4076: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var call = Function.prototype.call; var $hasOwn = Object.prototype.hasOwnProperty; var bind = __nccwpck_require__(7564); /** @type {import('.')} */ module.exports = bind.call(call, $hasOwn); /***/ }), /***/ 3176: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var wrappy = __nccwpck_require__(5883) var reqs = Object.create(null) var once = __nccwpck_require__(5560) module.exports = wrappy(inflight) function inflight (key, cb) { if (reqs[key]) { reqs[key].push(cb) return null } else { reqs[key] = [cb] return makeres(key) } } function makeres (key) { return once(function RES () { var cbs = reqs[key] var len = cbs.length var args = slice(arguments) // XXX It's somewhat ambiguous whether a new callback added in this // pass should be queued for later execution if something in the // list of callbacks throws, or if it should just be discarded. // However, it's such an edge case that it hardly matters, and either // choice is likely as surprising as the other. // As it happens, we do go ahead and schedule it for later execution. try { for (var i = 0; i < len; i++) { cbs[i].apply(null, args) } } finally { if (cbs.length > len) { // added more in the interim. // de-zalgo, just in case, but don't call again. cbs.splice(0, len) process.nextTick(function () { RES.apply(null, args) }) } else { delete reqs[key] } } }) } function slice (args) { var length = args.length var array = [] for (var i = 0; i < length; i++) array[i] = args[i] return array } /***/ }), /***/ 9598: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { try { var util = __nccwpck_require__(9023); /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { /* istanbul ignore next */ module.exports = __nccwpck_require__(6589); } /***/ }), /***/ 6589: /***/ ((module) => { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }) } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } } /***/ }), /***/ 8850: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AddressError = void 0; class AddressError extends Error { constructor(message, parseMessage) { super(message); this.name = 'AddressError'; this.parseMessage = parseMessage; } } exports.AddressError = AddressError; //# sourceMappingURL=address-error.js.map /***/ }), /***/ 5864: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isInSubnet = isInSubnet; exports.isCorrect = isCorrect; exports.numberToPaddedHex = numberToPaddedHex; exports.stringToPaddedHex = stringToPaddedHex; exports.testBit = testBit; function isInSubnet(address) { if (this.subnetMask < address.subnetMask) { return false; } if (this.mask(address.subnetMask) === address.mask()) { return true; } return false; } function isCorrect(defaultBits) { return function () { if (this.addressMinusSuffix !== this.correctForm()) { return false; } if (this.subnetMask === defaultBits && !this.parsedSubnet) { return true; } return this.parsedSubnet === String(this.subnetMask); }; } function numberToPaddedHex(number) { return number.toString(16).padStart(2, '0'); } function stringToPaddedHex(numberString) { return numberToPaddedHex(parseInt(numberString, 10)); } /** * @param binaryValue Binary representation of a value (e.g. `10`) * @param position Byte position, where 0 is the least significant bit */ function testBit(binaryValue, position) { const { length } = binaryValue; if (position > length) { return false; } const positionInString = length - position; return binaryValue.substring(positionInString, positionInString + 1) === '1'; } //# sourceMappingURL=common.js.map /***/ }), /***/ 1634: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0; var ipv4_1 = __nccwpck_require__(7946); Object.defineProperty(exports, "Address4", ({ enumerable: true, get: function () { return ipv4_1.Address4; } })); var ipv6_1 = __nccwpck_require__(8096); Object.defineProperty(exports, "Address6", ({ enumerable: true, get: function () { return ipv6_1.Address6; } })); var address_error_1 = __nccwpck_require__(8850); Object.defineProperty(exports, "AddressError", ({ enumerable: true, get: function () { return address_error_1.AddressError; } })); const helpers = __importStar(__nccwpck_require__(339)); exports.v6 = { helpers }; //# sourceMappingURL=ip-address.js.map /***/ }), /***/ 7946: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; /* eslint-disable no-param-reassign */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Address4 = void 0; const common = __importStar(__nccwpck_require__(5864)); const constants = __importStar(__nccwpck_require__(6437)); const address_error_1 = __nccwpck_require__(8850); /** * Represents an IPv4 address * @class Address4 * @param {string} address - An IPv4 address string */ class Address4 { constructor(address) { this.groups = constants.GROUPS; this.parsedAddress = []; this.parsedSubnet = ''; this.subnet = '/32'; this.subnetMask = 32; this.v4 = true; /** * Returns true if the address is correct, false otherwise * @memberof Address4 * @instance * @returns {Boolean} */ this.isCorrect = common.isCorrect(constants.BITS); /** * Returns true if the given address is in the subnet of the current address * @memberof Address4 * @instance * @returns {boolean} */ this.isInSubnet = common.isInSubnet; this.address = address; const subnet = constants.RE_SUBNET_STRING.exec(address); if (subnet) { this.parsedSubnet = subnet[0].replace('/', ''); this.subnetMask = parseInt(this.parsedSubnet, 10); this.subnet = `/${this.subnetMask}`; if (this.subnetMask < 0 || this.subnetMask > constants.BITS) { throw new address_error_1.AddressError('Invalid subnet mask.'); } address = address.replace(constants.RE_SUBNET_STRING, ''); } this.addressMinusSuffix = address; this.parsedAddress = this.parse(address); } static isValid(address) { try { // eslint-disable-next-line no-new new Address4(address); return true; } catch (e) { return false; } } /* * Parses a v4 address */ parse(address) { const groups = address.split('.'); if (!address.match(constants.RE_ADDRESS)) { throw new address_error_1.AddressError('Invalid IPv4 address.'); } return groups; } /** * Returns the correct form of an address * @memberof Address4 * @instance * @returns {String} */ correctForm() { return this.parsedAddress.map((part) => parseInt(part, 10)).join('.'); } /** * Converts a hex string to an IPv4 address object * @memberof Address4 * @static * @param {string} hex - a hex string to convert * @returns {Address4} */ static fromHex(hex) { const padded = hex.replace(/:/g, '').padStart(8, '0'); const groups = []; let i; for (i = 0; i < 8; i += 2) { const h = padded.slice(i, i + 2); groups.push(parseInt(h, 16)); } return new Address4(groups.join('.')); } /** * Converts an integer into a IPv4 address object * @memberof Address4 * @static * @param {integer} integer - a number to convert * @returns {Address4} */ static fromInteger(integer) { return Address4.fromHex(integer.toString(16)); } /** * Return an address from in-addr.arpa form * @memberof Address4 * @static * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address * @returns {Adress4} * @example * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.) * address.correctForm(); // '192.0.2.42' */ static fromArpa(arpaFormAddress) { // remove ending ".in-addr.arpa." or just "." const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, ''); const address = leader.split('.').reverse().join('.'); return new Address4(address); } /** * Converts an IPv4 address object to a hex string * @memberof Address4 * @instance * @returns {String} */ toHex() { return this.parsedAddress.map((part) => common.stringToPaddedHex(part)).join(':'); } /** * Converts an IPv4 address object to an array of bytes * @memberof Address4 * @instance * @returns {Array} */ toArray() { return this.parsedAddress.map((part) => parseInt(part, 10)); } /** * Converts an IPv4 address object to an IPv6 address group * @memberof Address4 * @instance * @returns {String} */ toGroup6() { const output = []; let i; for (i = 0; i < constants.GROUPS; i += 2) { output.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i + 1])}`); } return output.join(':'); } /** * Returns the address as a `bigint` * @memberof Address4 * @instance * @returns {bigint} */ bigInt() { return BigInt(`0x${this.parsedAddress.map((n) => common.stringToPaddedHex(n)).join('')}`); } /** * Helper function getting start address. * @memberof Address4 * @instance * @returns {bigint} */ _startAddress() { return BigInt(`0b${this.mask() + '0'.repeat(constants.BITS - this.subnetMask)}`); } /** * The first address in the range given by this address' subnet. * Often referred to as the Network Address. * @memberof Address4 * @instance * @returns {Address4} */ startAddress() { return Address4.fromBigInt(this._startAddress()); } /** * The first host address in the range given by this address's subnet ie * the first address after the Network Address * @memberof Address4 * @instance * @returns {Address4} */ startAddressExclusive() { const adjust = BigInt('1'); return Address4.fromBigInt(this._startAddress() + adjust); } /** * Helper function getting end address. * @memberof Address4 * @instance * @returns {bigint} */ _endAddress() { return BigInt(`0b${this.mask() + '1'.repeat(constants.BITS - this.subnetMask)}`); } /** * The last address in the range given by this address' subnet * Often referred to as the Broadcast * @memberof Address4 * @instance * @returns {Address4} */ endAddress() { return Address4.fromBigInt(this._endAddress()); } /** * The last host address in the range given by this address's subnet ie * the last address prior to the Broadcast Address * @memberof Address4 * @instance * @returns {Address4} */ endAddressExclusive() { const adjust = BigInt('1'); return Address4.fromBigInt(this._endAddress() - adjust); } /** * Converts a BigInt to a v4 address object * @memberof Address4 * @static * @param {bigint} bigInt - a BigInt to convert * @returns {Address4} */ static fromBigInt(bigInt) { return Address4.fromHex(bigInt.toString(16)); } /** * Convert a byte array to an Address4 object * @memberof Address4 * @static * @param {Array} bytes - an array of 4 bytes (0-255) * @returns {Address4} */ static fromByteArray(bytes) { if (bytes.length !== 4) { throw new address_error_1.AddressError('IPv4 addresses require exactly 4 bytes'); } // Validate that all bytes are within valid range (0-255) for (let i = 0; i < bytes.length; i++) { if (!Number.isInteger(bytes[i]) || bytes[i] < 0 || bytes[i] > 255) { throw new address_error_1.AddressError('All bytes must be integers between 0 and 255'); } } return this.fromUnsignedByteArray(bytes); } /** * Convert an unsigned byte array to an Address4 object * @memberof Address4 * @static * @param {Array} bytes - an array of 4 unsigned bytes (0-255) * @returns {Address4} */ static fromUnsignedByteArray(bytes) { if (bytes.length !== 4) { throw new address_error_1.AddressError('IPv4 addresses require exactly 4 bytes'); } const address = bytes.join('.'); return new Address4(address); } /** * Returns the first n bits of the address, defaulting to the * subnet mask * @memberof Address4 * @instance * @returns {String} */ mask(mask) { if (mask === undefined) { mask = this.subnetMask; } return this.getBitsBase2(0, mask); } /** * Returns the bits in the given range as a base-2 string * @memberof Address4 * @instance * @returns {string} */ getBitsBase2(start, end) { return this.binaryZeroPad().slice(start, end); } /** * Return the reversed ip6.arpa form of the address * @memberof Address4 * @param {Object} options * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix * @instance * @returns {String} */ reverseForm(options) { if (!options) { options = {}; } const reversed = this.correctForm().split('.').reverse().join('.'); if (options.omitSuffix) { return reversed; } return `${reversed}.in-addr.arpa.`; } /** * Returns true if the given address is a multicast address * @memberof Address4 * @instance * @returns {boolean} */ isMulticast() { return this.isInSubnet(new Address4('224.0.0.0/4')); } /** * Returns a zero-padded base-2 string representation of the address * @memberof Address4 * @instance * @returns {string} */ binaryZeroPad() { return this.bigInt().toString(2).padStart(constants.BITS, '0'); } /** * Groups an IPv4 address for inclusion at the end of an IPv6 address * @returns {String} */ groupForV6() { const segments = this.parsedAddress; return this.address.replace(constants.RE_ADDRESS, `${segments .slice(0, 2) .join('.')}.${segments .slice(2, 4) .join('.')}`); } } exports.Address4 = Address4; //# sourceMappingURL=ipv4.js.map /***/ }), /***/ 8096: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; /* eslint-disable prefer-destructuring */ /* eslint-disable no-param-reassign */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Address6 = void 0; const common = __importStar(__nccwpck_require__(5864)); const constants4 = __importStar(__nccwpck_require__(6437)); const constants6 = __importStar(__nccwpck_require__(2899)); const helpers = __importStar(__nccwpck_require__(339)); const ipv4_1 = __nccwpck_require__(7946); const regular_expressions_1 = __nccwpck_require__(2016); const address_error_1 = __nccwpck_require__(8850); const common_1 = __nccwpck_require__(5864); function assert(condition) { if (!condition) { throw new Error('Assertion failed.'); } } function addCommas(number) { const r = /(\d+)(\d{3})/; while (r.test(number)) { number = number.replace(r, '$1,$2'); } return number; } function spanLeadingZeroes4(n) { n = n.replace(/^(0{1,})([1-9]+)$/, '$1$2'); n = n.replace(/^(0{1,})(0)$/, '$1$2'); return n; } /* * A helper function to compact an array */ function compact(address, slice) { const s1 = []; const s2 = []; let i; for (i = 0; i < address.length; i++) { if (i < slice[0]) { s1.push(address[i]); } else if (i > slice[1]) { s2.push(address[i]); } } return s1.concat(['compact']).concat(s2); } function paddedHex(octet) { return parseInt(octet, 16).toString(16).padStart(4, '0'); } function unsignByte(b) { // eslint-disable-next-line no-bitwise return b & 0xff; } /** * Represents an IPv6 address * @class Address6 * @param {string} address - An IPv6 address string * @param {number} [groups=8] - How many octets to parse * @example * var address = new Address6('2001::/32'); */ class Address6 { constructor(address, optionalGroups) { this.addressMinusSuffix = ''; this.parsedSubnet = ''; this.subnet = '/128'; this.subnetMask = 128; this.v4 = false; this.zone = ''; // #region Attributes /** * Returns true if the given address is in the subnet of the current address * @memberof Address6 * @instance * @returns {boolean} */ this.isInSubnet = common.isInSubnet; /** * Returns true if the address is correct, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ this.isCorrect = common.isCorrect(constants6.BITS); if (optionalGroups === undefined) { this.groups = constants6.GROUPS; } else { this.groups = optionalGroups; } this.address = address; const subnet = constants6.RE_SUBNET_STRING.exec(address); if (subnet) { this.parsedSubnet = subnet[0].replace('/', ''); this.subnetMask = parseInt(this.parsedSubnet, 10); this.subnet = `/${this.subnetMask}`; if (Number.isNaN(this.subnetMask) || this.subnetMask < 0 || this.subnetMask > constants6.BITS) { throw new address_error_1.AddressError('Invalid subnet mask.'); } address = address.replace(constants6.RE_SUBNET_STRING, ''); } else if (/\//.test(address)) { throw new address_error_1.AddressError('Invalid subnet mask.'); } const zone = constants6.RE_ZONE_STRING.exec(address); if (zone) { this.zone = zone[0]; address = address.replace(constants6.RE_ZONE_STRING, ''); } this.addressMinusSuffix = address; this.parsedAddress = this.parse(this.addressMinusSuffix); } static isValid(address) { try { // eslint-disable-next-line no-new new Address6(address); return true; } catch (e) { return false; } } /** * Convert a BigInt to a v6 address object * @memberof Address6 * @static * @param {bigint} bigInt - a BigInt to convert * @returns {Address6} * @example * var bigInt = BigInt('1000000000000'); * var address = Address6.fromBigInt(bigInt); * address.correctForm(); // '::e8:d4a5:1000' */ static fromBigInt(bigInt) { const hex = bigInt.toString(16).padStart(32, '0'); const groups = []; let i; for (i = 0; i < constants6.GROUPS; i++) { groups.push(hex.slice(i * 4, (i + 1) * 4)); } return new Address6(groups.join(':')); } /** * Convert a URL (with optional port number) to an address object * @memberof Address6 * @static * @param {string} url - a URL with optional port number * @example * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/'); * addressAndPort.address.correctForm(); // 'ffff::' * addressAndPort.port; // 8080 */ static fromURL(url) { let host; let port = null; let result; // If we have brackets parse them and find a port if (url.indexOf('[') !== -1 && url.indexOf(']:') !== -1) { result = constants6.RE_URL_WITH_PORT.exec(url); if (result === null) { return { error: 'failed to parse address with port', address: null, port: null, }; } host = result[1]; port = result[2]; // If there's a URL extract the address } else if (url.indexOf('/') !== -1) { // Remove the protocol prefix url = url.replace(/^[a-z0-9]+:\/\//, ''); // Parse the address result = constants6.RE_URL.exec(url); if (result === null) { return { error: 'failed to parse address from URL', address: null, port: null, }; } host = result[1]; // Otherwise just assign the URL to the host and let the library parse it } else { host = url; } // If there's a port convert it to an integer if (port) { port = parseInt(port, 10); // squelch out of range ports if (port < 0 || port > 65536) { port = null; } } else { // Standardize `undefined` to `null` port = null; } return { address: new Address6(host), port, }; } /** * Create an IPv6-mapped address given an IPv4 address * @memberof Address6 * @static * @param {string} address - An IPv4 address string * @returns {Address6} * @example * var address = Address6.fromAddress4('192.168.0.1'); * address.correctForm(); // '::ffff:c0a8:1' * address.to4in6(); // '::ffff:192.168.0.1' */ static fromAddress4(address) { const address4 = new ipv4_1.Address4(address); const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask); return new Address6(`::ffff:${address4.correctForm()}/${mask6}`); } /** * Return an address from ip6.arpa form * @memberof Address6 * @static * @param {string} arpaFormAddress - an 'ip6.arpa' form address * @returns {Adress6} * @example * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.) * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe' */ static fromArpa(arpaFormAddress) { // remove ending ".ip6.arpa." or just "." let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, ''); const semicolonAmount = 7; // correct ip6.arpa form with ending removed will be 63 characters if (address.length !== 63) { throw new address_error_1.AddressError("Invalid 'ip6.arpa' form."); } const parts = address.split('.').reverse(); for (let i = semicolonAmount; i > 0; i--) { const insertIndex = i * 4; parts.splice(insertIndex, 0, ':'); } address = parts.join(''); return new Address6(address); } /** * Return the Microsoft UNC transcription of the address * @memberof Address6 * @instance * @returns {String} the Microsoft UNC transcription of the address */ microsoftTranscription() { return `${this.correctForm().replace(/:/g, '-')}.ipv6-literal.net`; } /** * Return the first n bits of the address, defaulting to the subnet mask * @memberof Address6 * @instance * @param {number} [mask=subnet] - the number of bits to mask * @returns {String} the first n bits of the address as a string */ mask(mask = this.subnetMask) { return this.getBitsBase2(0, mask); } /** * Return the number of possible subnets of a given size in the address * @memberof Address6 * @instance * @param {number} [subnetSize=128] - the subnet size * @returns {String} */ // TODO: probably useful to have a numeric version of this too possibleSubnets(subnetSize = 128) { const availableBits = constants6.BITS - this.subnetMask; const subnetBits = Math.abs(subnetSize - constants6.BITS); const subnetPowers = availableBits - subnetBits; if (subnetPowers < 0) { return '0'; } return addCommas((BigInt('2') ** BigInt(subnetPowers)).toString(10)); } /** * Helper function getting start address. * @memberof Address6 * @instance * @returns {bigint} */ _startAddress() { return BigInt(`0b${this.mask() + '0'.repeat(constants6.BITS - this.subnetMask)}`); } /** * The first address in the range given by this address' subnet * Often referred to as the Network Address. * @memberof Address6 * @instance * @returns {Address6} */ startAddress() { return Address6.fromBigInt(this._startAddress()); } /** * The first host address in the range given by this address's subnet ie * the first address after the Network Address * @memberof Address6 * @instance * @returns {Address6} */ startAddressExclusive() { const adjust = BigInt('1'); return Address6.fromBigInt(this._startAddress() + adjust); } /** * Helper function getting end address. * @memberof Address6 * @instance * @returns {bigint} */ _endAddress() { return BigInt(`0b${this.mask() + '1'.repeat(constants6.BITS - this.subnetMask)}`); } /** * The last address in the range given by this address' subnet * Often referred to as the Broadcast * @memberof Address6 * @instance * @returns {Address6} */ endAddress() { return Address6.fromBigInt(this._endAddress()); } /** * The last host address in the range given by this address's subnet ie * the last address prior to the Broadcast Address * @memberof Address6 * @instance * @returns {Address6} */ endAddressExclusive() { const adjust = BigInt('1'); return Address6.fromBigInt(this._endAddress() - adjust); } /** * Return the scope of the address * @memberof Address6 * @instance * @returns {String} */ getScope() { let scope = constants6.SCOPES[parseInt(this.getBits(12, 16).toString(10), 10)]; if (this.getType() === 'Global unicast' && scope !== 'Link local') { scope = 'Global'; } return scope || 'Unknown'; } /** * Return the type of the address * @memberof Address6 * @instance * @returns {String} */ getType() { for (const subnet of Object.keys(constants6.TYPES)) { if (this.isInSubnet(new Address6(subnet))) { return constants6.TYPES[subnet]; } } return 'Global unicast'; } /** * Return the bits in the given range as a BigInt * @memberof Address6 * @instance * @returns {bigint} */ getBits(start, end) { return BigInt(`0b${this.getBitsBase2(start, end)}`); } /** * Return the bits in the given range as a base-2 string * @memberof Address6 * @instance * @returns {String} */ getBitsBase2(start, end) { return this.binaryZeroPad().slice(start, end); } /** * Return the bits in the given range as a base-16 string * @memberof Address6 * @instance * @returns {String} */ getBitsBase16(start, end) { const length = end - start; if (length % 4 !== 0) { throw new Error('Length of bits to retrieve must be divisible by four'); } return this.getBits(start, end) .toString(16) .padStart(length / 4, '0'); } /** * Return the bits that are set past the subnet mask length * @memberof Address6 * @instance * @returns {String} */ getBitsPastSubnet() { return this.getBitsBase2(this.subnetMask, constants6.BITS); } /** * Return the reversed ip6.arpa form of the address * @memberof Address6 * @param {Object} options * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix * @instance * @returns {String} */ reverseForm(options) { if (!options) { options = {}; } const characters = Math.floor(this.subnetMask / 4); const reversed = this.canonicalForm() .replace(/:/g, '') .split('') .slice(0, characters) .reverse() .join('.'); if (characters > 0) { if (options.omitSuffix) { return reversed; } return `${reversed}.ip6.arpa.`; } if (options.omitSuffix) { return ''; } return 'ip6.arpa.'; } /** * Return the correct form of the address * @memberof Address6 * @instance * @returns {String} */ correctForm() { let i; let groups = []; let zeroCounter = 0; const zeroes = []; for (i = 0; i < this.parsedAddress.length; i++) { const value = parseInt(this.parsedAddress[i], 16); if (value === 0) { zeroCounter++; } if (value !== 0 && zeroCounter > 0) { if (zeroCounter > 1) { zeroes.push([i - zeroCounter, i - 1]); } zeroCounter = 0; } } // Do we end with a string of zeroes? if (zeroCounter > 1) { zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]); } const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1); if (zeroes.length > 0) { const index = zeroLengths.indexOf(Math.max(...zeroLengths)); groups = compact(this.parsedAddress, zeroes[index]); } else { groups = this.parsedAddress; } for (i = 0; i < groups.length; i++) { if (groups[i] !== 'compact') { groups[i] = parseInt(groups[i], 16).toString(16); } } let correct = groups.join(':'); correct = correct.replace(/^compact$/, '::'); correct = correct.replace(/(^compact)|(compact$)/, ':'); correct = correct.replace(/compact/, ''); return correct; } /** * Return a zero-padded base-2 string representation of the address * @memberof Address6 * @instance * @returns {String} * @example * var address = new Address6('2001:4860:4001:803::1011'); * address.binaryZeroPad(); * // '0010000000000001010010000110000001000000000000010000100000000011 * // 0000000000000000000000000000000000000000000000000001000000010001' */ binaryZeroPad() { return this.bigInt().toString(2).padStart(constants6.BITS, '0'); } // TODO: Improve the semantics of this helper function parse4in6(address) { const groups = address.split(':'); const lastGroup = groups.slice(-1)[0]; const address4 = lastGroup.match(constants4.RE_ADDRESS); if (address4) { this.parsedAddress4 = address4[0]; this.address4 = new ipv4_1.Address4(this.parsedAddress4); for (let i = 0; i < this.address4.groups; i++) { if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) { throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", address.replace(constants4.RE_ADDRESS, this.address4.parsedAddress.map(spanLeadingZeroes4).join('.'))); } } this.v4 = true; groups[groups.length - 1] = this.address4.toGroup6(); address = groups.join(':'); } return address; } // TODO: Make private? parse(address) { address = this.parse4in6(address); const badCharacters = address.match(constants6.RE_BAD_CHARACTERS); if (badCharacters) { throw new address_error_1.AddressError(`Bad character${badCharacters.length > 1 ? 's' : ''} detected in address: ${badCharacters.join('')}`, address.replace(constants6.RE_BAD_CHARACTERS, '$1')); } const badAddress = address.match(constants6.RE_BAD_ADDRESS); if (badAddress) { throw new address_error_1.AddressError(`Address failed regex: ${badAddress.join('')}`, address.replace(constants6.RE_BAD_ADDRESS, '$1')); } let groups = []; const halves = address.split('::'); if (halves.length === 2) { let first = halves[0].split(':'); let last = halves[1].split(':'); if (first.length === 1 && first[0] === '') { first = []; } if (last.length === 1 && last[0] === '') { last = []; } const remaining = this.groups - (first.length + last.length); if (!remaining) { throw new address_error_1.AddressError('Error parsing groups'); } this.elidedGroups = remaining; this.elisionBegin = first.length; this.elisionEnd = first.length + this.elidedGroups; groups = groups.concat(first); for (let i = 0; i < remaining; i++) { groups.push('0'); } groups = groups.concat(last); } else if (halves.length === 1) { groups = address.split(':'); this.elidedGroups = 0; } else { throw new address_error_1.AddressError('Too many :: groups found'); } groups = groups.map((group) => parseInt(group, 16).toString(16)); if (groups.length !== this.groups) { throw new address_error_1.AddressError('Incorrect number of groups found'); } return groups; } /** * Return the canonical form of the address * @memberof Address6 * @instance * @returns {String} */ canonicalForm() { return this.parsedAddress.map(paddedHex).join(':'); } /** * Return the decimal form of the address * @memberof Address6 * @instance * @returns {String} */ decimal() { return this.parsedAddress.map((n) => parseInt(n, 16).toString(10).padStart(5, '0')).join(':'); } /** * Return the address as a BigInt * @memberof Address6 * @instance * @returns {bigint} */ bigInt() { return BigInt(`0x${this.parsedAddress.map(paddedHex).join('')}`); } /** * Return the last two groups of this address as an IPv4 address string * @memberof Address6 * @instance * @returns {Address4} * @example * var address = new Address6('2001:4860:4001::1825:bf11'); * address.to4().correctForm(); // '24.37.191.17' */ to4() { const binary = this.binaryZeroPad().split(''); return ipv4_1.Address4.fromHex(BigInt(`0b${binary.slice(96, 128).join('')}`).toString(16)); } /** * Return the v4-in-v6 form of the address * @memberof Address6 * @instance * @returns {String} */ to4in6() { const address4 = this.to4(); const address6 = new Address6(this.parsedAddress.slice(0, 6).join(':'), 6); const correct = address6.correctForm(); let infix = ''; if (!/:$/.test(correct)) { infix = ':'; } return correct + infix + address4.address; } /** * Return an object containing the Teredo properties of the address * @memberof Address6 * @instance * @returns {Object} */ inspectTeredo() { /* - Bits 0 to 31 are set to the Teredo prefix (normally 2001:0000::/32). - Bits 32 to 63 embed the primary IPv4 address of the Teredo server that is used. - Bits 64 to 79 can be used to define some flags. Currently only the higher order bit is used; it is set to 1 if the Teredo client is located behind a cone NAT, 0 otherwise. For Microsoft's Windows Vista and Windows Server 2008 implementations, more bits are used. In those implementations, the format for these 16 bits is "CRAAAAUG AAAAAAAA", where "C" remains the "Cone" flag. The "R" bit is reserved for future use. The "U" bit is for the Universal/Local flag (set to 0). The "G" bit is Individual/Group flag (set to 0). The A bits are set to a 12-bit randomly generated number chosen by the Teredo client to introduce additional protection for the Teredo node against IPv6-based scanning attacks. - Bits 80 to 95 contains the obfuscated UDP port number. This is the port number that is mapped by the NAT to the Teredo client with all bits inverted. - Bits 96 to 127 contains the obfuscated IPv4 address. This is the public IPv4 address of the NAT with all bits inverted. */ const prefix = this.getBitsBase16(0, 32); const bitsForUdpPort = this.getBits(80, 96); // eslint-disable-next-line no-bitwise const udpPort = (bitsForUdpPort ^ BigInt('0xffff')).toString(); const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64)); const bitsForClient4 = this.getBits(96, 128); // eslint-disable-next-line no-bitwise const client4 = ipv4_1.Address4.fromHex((bitsForClient4 ^ BigInt('0xffffffff')).toString(16)); const flagsBase2 = this.getBitsBase2(64, 80); const coneNat = (0, common_1.testBit)(flagsBase2, 15); const reserved = (0, common_1.testBit)(flagsBase2, 14); const groupIndividual = (0, common_1.testBit)(flagsBase2, 8); const universalLocal = (0, common_1.testBit)(flagsBase2, 9); const nonce = BigInt(`0b${flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16)}`).toString(10); return { prefix: `${prefix.slice(0, 4)}:${prefix.slice(4, 8)}`, server4: server4.address, client4: client4.address, flags: flagsBase2, coneNat, microsoft: { reserved, universalLocal, groupIndividual, nonce, }, udpPort, }; } /** * Return an object containing the 6to4 properties of the address * @memberof Address6 * @instance * @returns {Object} */ inspect6to4() { /* - Bits 0 to 15 are set to the 6to4 prefix (2002::/16). - Bits 16 to 48 embed the IPv4 address of the 6to4 gateway that is used. */ const prefix = this.getBitsBase16(0, 16); const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48)); return { prefix: prefix.slice(0, 4), gateway: gateway.address, }; } /** * Return a v6 6to4 address from a v6 v4inv6 address * @memberof Address6 * @instance * @returns {Address6} */ to6to4() { if (!this.is4()) { return null; } const addr6to4 = [ '2002', this.getBitsBase16(96, 112), this.getBitsBase16(112, 128), '', '/16', ].join(':'); return new Address6(addr6to4); } /** * Return a byte array * @memberof Address6 * @instance * @returns {Array} */ toByteArray() { const valueWithoutPadding = this.bigInt().toString(16); const leadingPad = '0'.repeat(valueWithoutPadding.length % 2); const value = `${leadingPad}${valueWithoutPadding}`; const bytes = []; for (let i = 0, length = value.length; i < length; i += 2) { bytes.push(parseInt(value.substring(i, i + 2), 16)); } return bytes; } /** * Return an unsigned byte array * @memberof Address6 * @instance * @returns {Array} */ toUnsignedByteArray() { return this.toByteArray().map(unsignByte); } /** * Convert a byte array to an Address6 object * @memberof Address6 * @static * @returns {Address6} */ static fromByteArray(bytes) { return this.fromUnsignedByteArray(bytes.map(unsignByte)); } /** * Convert an unsigned byte array to an Address6 object * @memberof Address6 * @static * @returns {Address6} */ static fromUnsignedByteArray(bytes) { const BYTE_MAX = BigInt('256'); let result = BigInt('0'); let multiplier = BigInt('1'); for (let i = bytes.length - 1; i >= 0; i--) { result += multiplier * BigInt(bytes[i].toString(10)); multiplier *= BYTE_MAX; } return Address6.fromBigInt(result); } /** * Returns true if the address is in the canonical form, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isCanonical() { return this.addressMinusSuffix === this.canonicalForm(); } /** * Returns true if the address is a link local address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isLinkLocal() { // Zeroes are required, i.e. we can't check isInSubnet with 'fe80::/10' if (this.getBitsBase2(0, 64) === '1111111010000000000000000000000000000000000000000000000000000000') { return true; } return false; } /** * Returns true if the address is a multicast address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isMulticast() { return this.getType() === 'Multicast'; } /** * Returns true if the address is a v4-in-v6 address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ is4() { return this.v4; } /** * Returns true if the address is a Teredo address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isTeredo() { return this.isInSubnet(new Address6('2001::/32')); } /** * Returns true if the address is a 6to4 address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ is6to4() { return this.isInSubnet(new Address6('2002::/16')); } /** * Returns true if the address is a loopback address, false otherwise * @memberof Address6 * @instance * @returns {boolean} */ isLoopback() { return this.getType() === 'Loopback'; } // #endregion // #region HTML /** * @returns {String} the address in link form with a default port of 80 */ href(optionalPort) { if (optionalPort === undefined) { optionalPort = ''; } else { optionalPort = `:${optionalPort}`; } return `http://[${this.correctForm()}]${optionalPort}/`; } /** * @returns {String} a link suitable for conveying the address via a URL hash */ link(options) { if (!options) { options = {}; } if (options.className === undefined) { options.className = ''; } if (options.prefix === undefined) { options.prefix = '/#address='; } if (options.v4 === undefined) { options.v4 = false; } let formFunction = this.correctForm; if (options.v4) { formFunction = this.to4in6; } const form = formFunction.call(this); if (options.className) { return `${form}`; } return `${form}`; } /** * Groups an address * @returns {String} */ group() { if (this.elidedGroups === 0) { // The simple case return helpers.simpleGroup(this.address).join(':'); } assert(typeof this.elidedGroups === 'number'); assert(typeof this.elisionBegin === 'number'); // The elided case const output = []; const [left, right] = this.address.split('::'); if (left.length) { output.push(...helpers.simpleGroup(left)); } else { output.push(''); } const classes = ['hover-group']; for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { classes.push(`group-${i}`); } output.push(``); if (right.length) { output.push(...helpers.simpleGroup(right, this.elisionEnd)); } else { output.push(''); } if (this.is4()) { assert(this.address4 instanceof ipv4_1.Address4); output.pop(); output.push(this.address4.groupForV6()); } return output.join(':'); } // #endregion // #region Regular expressions /** * Generate a regular expression string that can be used to find or validate * all variations of this address * @memberof Address6 * @instance * @param {boolean} substringSearch * @returns {string} */ regularExpressionString(substringSearch = false) { let output = []; // TODO: revisit why this is necessary const address6 = new Address6(this.correctForm()); if (address6.elidedGroups === 0) { // The simple case output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); } else if (address6.elidedGroups === constants6.GROUPS) { // A completely elided address output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); } else { // A partially elided address const halves = address6.address.split('::'); if (halves[0].length) { output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(':'))); } assert(typeof address6.elidedGroups === 'number'); output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); if (halves[1].length) { output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(':'))); } output = [output.join(':')]; } if (!substringSearch) { output = [ '(?=^|', regular_expressions_1.ADDRESS_BOUNDARY, '|[^\\w\\:])(', ...output, ')(?=[^\\w\\:]|', regular_expressions_1.ADDRESS_BOUNDARY, '|$)', ]; } return output.join(''); } /** * Generate a regular expression that can be used to find or validate all * variations of this address. * @memberof Address6 * @instance * @param {boolean} substringSearch * @returns {RegExp} */ regularExpression(substringSearch = false) { return new RegExp(this.regularExpressionString(substringSearch), 'i'); } } exports.Address6 = Address6; //# sourceMappingURL=ipv6.js.map /***/ }), /***/ 6437: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RE_SUBNET_STRING = exports.RE_ADDRESS = exports.GROUPS = exports.BITS = void 0; exports.BITS = 32; exports.GROUPS = 4; exports.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g; exports.RE_SUBNET_STRING = /\/\d{1,2}$/; //# sourceMappingURL=constants.js.map /***/ }), /***/ 2899: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RE_URL_WITH_PORT = exports.RE_URL = exports.RE_ZONE_STRING = exports.RE_SUBNET_STRING = exports.RE_BAD_ADDRESS = exports.RE_BAD_CHARACTERS = exports.TYPES = exports.SCOPES = exports.GROUPS = exports.BITS = void 0; exports.BITS = 128; exports.GROUPS = 8; /** * Represents IPv6 address scopes * @memberof Address6 * @static */ exports.SCOPES = { 0: 'Reserved', 1: 'Interface local', 2: 'Link local', 4: 'Admin local', 5: 'Site local', 8: 'Organization local', 14: 'Global', 15: 'Reserved', }; /** * Represents IPv6 address types * @memberof Address6 * @static */ exports.TYPES = { 'ff01::1/128': 'Multicast (All nodes on this interface)', 'ff01::2/128': 'Multicast (All routers on this interface)', 'ff02::1/128': 'Multicast (All nodes on this link)', 'ff02::2/128': 'Multicast (All routers on this link)', 'ff05::2/128': 'Multicast (All routers in this site)', 'ff02::5/128': 'Multicast (OSPFv3 AllSPF routers)', 'ff02::6/128': 'Multicast (OSPFv3 AllDR routers)', 'ff02::9/128': 'Multicast (RIP routers)', 'ff02::a/128': 'Multicast (EIGRP routers)', 'ff02::d/128': 'Multicast (PIM routers)', 'ff02::16/128': 'Multicast (MLDv2 reports)', 'ff01::fb/128': 'Multicast (mDNSv6)', 'ff02::fb/128': 'Multicast (mDNSv6)', 'ff05::fb/128': 'Multicast (mDNSv6)', 'ff02::1:2/128': 'Multicast (All DHCP servers and relay agents on this link)', 'ff05::1:2/128': 'Multicast (All DHCP servers and relay agents in this site)', 'ff02::1:3/128': 'Multicast (All DHCP servers on this link)', 'ff05::1:3/128': 'Multicast (All DHCP servers in this site)', '::/128': 'Unspecified', '::1/128': 'Loopback', 'ff00::/8': 'Multicast', 'fe80::/10': 'Link-local unicast', }; /** * A regular expression that matches bad characters in an IPv6 address * @memberof Address6 * @static */ exports.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi; /** * A regular expression that matches an incorrect IPv6 address * @memberof Address6 * @static */ exports.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi; /** * A regular expression that matches an IPv6 subnet * @memberof Address6 * @static */ exports.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/; /** * A regular expression that matches an IPv6 zone * @memberof Address6 * @static */ exports.RE_ZONE_STRING = /%.*$/; exports.RE_URL = /^\[{0,1}([0-9a-f:]+)\]{0,1}/; exports.RE_URL_WITH_PORT = /\[([0-9a-f:]+)\]:([0-9]{1,5})/; //# sourceMappingURL=constants.js.map /***/ }), /***/ 339: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.spanAllZeroes = spanAllZeroes; exports.spanAll = spanAll; exports.spanLeadingZeroes = spanLeadingZeroes; exports.simpleGroup = simpleGroup; /** * @returns {String} the string with all zeroes contained in a */ function spanAllZeroes(s) { return s.replace(/(0+)/g, '$1'); } /** * @returns {String} the string with each character contained in a */ function spanAll(s, offset = 0) { const letters = s.split(''); return letters .map((n, i) => `${spanAllZeroes(n)}`) .join(''); } function spanLeadingZeroesSimple(group) { return group.replace(/^(0+)/, '$1'); } /** * @returns {String} the string with leading zeroes contained in a */ function spanLeadingZeroes(address) { const groups = address.split(':'); return groups.map((g) => spanLeadingZeroesSimple(g)).join(':'); } /** * Groups an address * @returns {String} a grouped address */ function simpleGroup(addressString, offset = 0) { const groups = addressString.split(':'); return groups.map((g, i) => { if (/group-v4/.test(g)) { return g; } return `${spanLeadingZeroesSimple(g)}`; }); } //# sourceMappingURL=helpers.js.map /***/ }), /***/ 2016: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ADDRESS_BOUNDARY = void 0; exports.groupPossibilities = groupPossibilities; exports.padGroup = padGroup; exports.simpleRegularExpression = simpleRegularExpression; exports.possibleElisions = possibleElisions; const v6 = __importStar(__nccwpck_require__(2899)); function groupPossibilities(possibilities) { return `(${possibilities.join('|')})`; } function padGroup(group) { if (group.length < 4) { return `0{0,${4 - group.length}}${group}`; } return group; } exports.ADDRESS_BOUNDARY = '[^A-Fa-f0-9:]'; function simpleRegularExpression(groups) { const zeroIndexes = []; groups.forEach((group, i) => { const groupInteger = parseInt(group, 16); if (groupInteger === 0) { zeroIndexes.push(i); } }); // You can technically elide a single 0, this creates the regular expressions // to match that eventuality const possibilities = zeroIndexes.map((zeroIndex) => groups .map((group, i) => { if (i === zeroIndex) { const elision = i === 0 || i === v6.GROUPS - 1 ? ':' : ''; return groupPossibilities([padGroup(group), elision]); } return padGroup(group); }) .join(':')); // The simplest case possibilities.push(groups.map(padGroup).join(':')); return groupPossibilities(possibilities); } function possibleElisions(elidedGroups, moreLeft, moreRight) { const left = moreLeft ? '' : ':'; const right = moreRight ? '' : ':'; const possibilities = []; // 1. elision of everything (::) if (!moreLeft && !moreRight) { possibilities.push('::'); } // 2. complete elision of the middle if (moreLeft && moreRight) { possibilities.push(''); } if ((moreRight && !moreLeft) || (!moreRight && moreLeft)) { // 3. complete elision of one side possibilities.push(':'); } // 4. elision from the left side possibilities.push(`${left}(:0{1,4}){1,${elidedGroups - 1}}`); // 5. elision from the right side possibilities.push(`(0{1,4}:){1,${elidedGroups - 1}}${right}`); // 6. no elision possibilities.push(`(0{1,4}:){${elidedGroups - 1}}0{1,4}`); // 7. elision (including sloppy elision) from the middle for (let groups = 1; groups < elidedGroups - 1; groups++) { for (let position = 1; position < elidedGroups - groups; position++) { possibilities.push(`(0{1,4}:){${position}}:(0{1,4}:){${elidedGroups - position - groups - 1}}0{1,4}`); } } return groupPossibilities(possibilities); } //# sourceMappingURL=regular-expressions.js.map /***/ }), /***/ 9194: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isRelative = __nccwpck_require__(4991); var isWindows = __nccwpck_require__(8192); /** * Expose `isAbsolute` */ module.exports = isAbsolute; /** * Returns true if a file path is absolute. * * @param {String} `fp` * @return {Boolean} */ function isAbsolute(fp) { if (typeof fp !== 'string') { throw new TypeError('isAbsolute expects a string.'); } return isWindows() ? isAbsolute.win32(fp) : isAbsolute.posix(fp); } /** * Test posix paths. */ isAbsolute.posix = function posixPath(fp) { return fp.charAt(0) === '/'; }; /** * Test windows paths. */ isAbsolute.win32 = function win32(fp) { if (/[a-z]/i.test(fp.charAt(0)) && fp.charAt(1) === ':' && fp.charAt(2) === '\\') { return true; } // Microsoft Azure absolute filepath if (fp.slice(0, 2) === '\\\\') { return true; } return !isRelative(fp); }; /***/ }), /***/ 4097: /***/ ((module) => { /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh * @license MIT */ module.exports = function isBuffer (obj) { return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } /***/ }), /***/ 5540: /***/ ((module) => { /*! * is-extglob * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ module.exports = function isExtglob(str) { if (typeof str !== 'string' || str === '') { return false; } var match; while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { if (match[2]) return true; str = str.slice(match.index + match[0].length); } return false; }; /***/ }), /***/ 1925: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*! * is-glob * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ var isExtglob = __nccwpck_require__(5540); module.exports = function isGlob(str) { if (typeof str !== 'string' || str === '') { return false; } if (isExtglob(str)) return true; var regex = /(\\).|([*?]|\[.*\]|\{.*\}|\(.*\|.*\)|^!)/; var match; while ((match = regex.exec(str))) { if (match[2]) return true; str = str.slice(match.index + match[0].length); } return false; }; /***/ }), /***/ 228: /***/ ((module) => { "use strict"; module.exports = function(pattern) { if (typeof pattern !== 'string') { throw new TypeError('expected a string'); } var glob = { negated: false, pattern: pattern, original: pattern }; if (pattern.charAt(0) === '!' && pattern.charAt(1) !== '(') { glob.negated = true; glob.pattern = pattern.slice(1); } return glob; }; /***/ }), /***/ 4991: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isUncPath = __nccwpck_require__(4675); module.exports = function isRelative(filepath) { if (typeof filepath !== 'string') { throw new TypeError('expected filepath to be a string'); } // Windows UNC paths are always considered to be absolute. return !isUncPath(filepath) && !/^([a-z]:)?[\\\/]/i.test(filepath); }; /***/ }), /***/ 4675: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var regex = __nccwpck_require__(1958)(); module.exports = function(filepath) { if (typeof filepath !== 'string') { throw new TypeError('expected a string'); } return regex.test(filepath); }; /***/ }), /***/ 8192: /***/ ((module, exports) => { /*! * is-windows * * Copyright © 2015-2018, Jon Schlinkert. * Released under the MIT License. */ (function(factory) { if (exports && typeof exports === 'object' && "object" !== 'undefined') { module.exports = factory(); } else if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof window !== 'undefined') { window.isWindows = factory(); } else if (typeof global !== 'undefined') { global.isWindows = factory(); } else if (typeof self !== 'undefined') { self.isWindows = factory(); } else { this.isWindows = factory(); } })(function() { 'use strict'; return function isWindows() { return process && (process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE)); }; }); /***/ }), /***/ 2513: /***/ ((module) => { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }), /***/ 3775: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports.ContainerIterator = exports.Container = exports.Base = void 0; class ContainerIterator { constructor(t = 0) { this.iteratorType = t; } equals(t) { return this.o === t.o; } } exports.ContainerIterator = ContainerIterator; class Base { constructor() { this.i = 0; } get length() { return this.i; } size() { return this.i; } empty() { return this.i === 0; } } exports.Base = Base; class Container extends Base {} exports.Container = Container; //# sourceMappingURL=index.js.map /***/ }), /***/ 8130: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports.HashContainerIterator = exports.HashContainer = void 0; var _ContainerBase = __nccwpck_require__(3775); var _checkObject = _interopRequireDefault(__nccwpck_require__(8943)); var _throwError = __nccwpck_require__(9968); function _interopRequireDefault(t) { return t && t.t ? t : { default: t }; } class HashContainerIterator extends _ContainerBase.ContainerIterator { constructor(t, e, i) { super(i); this.o = t; this.h = e; if (this.iteratorType === 0) { this.pre = function() { if (this.o.L === this.h) { (0, _throwError.throwIteratorAccessError)(); } this.o = this.o.L; return this; }; this.next = function() { if (this.o === this.h) { (0, _throwError.throwIteratorAccessError)(); } this.o = this.o.B; return this; }; } else { this.pre = function() { if (this.o.B === this.h) { (0, _throwError.throwIteratorAccessError)(); } this.o = this.o.B; return this; }; this.next = function() { if (this.o === this.h) { (0, _throwError.throwIteratorAccessError)(); } this.o = this.o.L; return this; }; } } } exports.HashContainerIterator = HashContainerIterator; class HashContainer extends _ContainerBase.Container { constructor() { super(); this.H = []; this.g = {}; this.HASH_TAG = Symbol("@@HASH_TAG"); Object.setPrototypeOf(this.g, null); this.h = {}; this.h.L = this.h.B = this.p = this._ = this.h; } V(t) { const {L: e, B: i} = t; e.B = i; i.L = e; if (t === this.p) { this.p = i; } if (t === this._) { this._ = e; } this.i -= 1; } M(t, e, i) { if (i === undefined) i = (0, _checkObject.default)(t); let s; if (i) { const i = t[this.HASH_TAG]; if (i !== undefined) { this.H[i].l = e; return this.i; } Object.defineProperty(t, this.HASH_TAG, { value: this.H.length, configurable: true }); s = { u: t, l: e, L: this._, B: this.h }; this.H.push(s); } else { const i = this.g[t]; if (i) { i.l = e; return this.i; } s = { u: t, l: e, L: this._, B: this.h }; this.g[t] = s; } if (this.i === 0) { this.p = s; this.h.B = s; } else { this._.B = s; } this._ = s; this.h.L = s; return ++this.i; } I(t, e) { if (e === undefined) e = (0, _checkObject.default)(t); if (e) { const e = t[this.HASH_TAG]; if (e === undefined) return this.h; return this.H[e]; } else { return this.g[t] || this.h; } } clear() { const t = this.HASH_TAG; this.H.forEach((function(e) { delete e.u[t]; })); this.H = []; this.g = {}; Object.setPrototypeOf(this.g, null); this.i = 0; this.p = this._ = this.h.L = this.h.B = this.h; } eraseElementByKey(t, e) { let i; if (e === undefined) e = (0, _checkObject.default)(t); if (e) { const e = t[this.HASH_TAG]; if (e === undefined) return false; delete t[this.HASH_TAG]; i = this.H[e]; delete this.H[e]; } else { i = this.g[t]; if (i === undefined) return false; delete this.g[t]; } this.V(i); return true; } eraseElementByIterator(t) { const e = t.o; if (e === this.h) { (0, _throwError.throwIteratorAccessError)(); } this.V(e); return t.next(); } eraseElementByPos(t) { if (t < 0 || t > this.i - 1) { throw new RangeError; } let e = this.p; while (t--) { e = e.B; } this.V(e); return this.i; } } exports.HashContainer = HashContainer; //# sourceMappingURL=index.js.map /***/ }), /***/ 9152: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = void 0; var _Base = __nccwpck_require__(8130); var _checkObject = _interopRequireDefault(__nccwpck_require__(8943)); var _throwError = __nccwpck_require__(9968); function _interopRequireDefault(t) { return t && t.t ? t : { default: t }; } class HashMapIterator extends _Base.HashContainerIterator { constructor(t, e, r, s) { super(t, e, s); this.container = r; } get pointer() { if (this.o === this.h) { (0, _throwError.throwIteratorAccessError)(); } const t = this; return new Proxy([], { get(e, r) { if (r === "0") return t.o.u; else if (r === "1") return t.o.l; }, set(e, r, s) { if (r !== "1") { throw new TypeError("props must be 1"); } t.o.l = s; return true; } }); } copy() { return new HashMapIterator(this.o, this.h, this.container, this.iteratorType); } } class HashMap extends _Base.HashContainer { constructor(t = []) { super(); const e = this; t.forEach((function(t) { e.setElement(t[0], t[1]); })); } begin() { return new HashMapIterator(this.p, this.h, this); } end() { return new HashMapIterator(this.h, this.h, this); } rBegin() { return new HashMapIterator(this._, this.h, this, 1); } rEnd() { return new HashMapIterator(this.h, this.h, this, 1); } front() { if (this.i === 0) return; return [ this.p.u, this.p.l ]; } back() { if (this.i === 0) return; return [ this._.u, this._.l ]; } setElement(t, e, r) { return this.M(t, e, r); } getElementByKey(t, e) { if (e === undefined) e = (0, _checkObject.default)(t); if (e) { const e = t[this.HASH_TAG]; return e !== undefined ? this.H[e].l : undefined; } const r = this.g[t]; return r ? r.l : undefined; } getElementByPos(t) { if (t < 0 || t > this.i - 1) { throw new RangeError; } let e = this.p; while (t--) { e = e.B; } return [ e.u, e.l ]; } find(t, e) { const r = this.I(t, e); return new HashMapIterator(r, this.h, this); } forEach(t) { let e = 0; let r = this.p; while (r !== this.h) { t([ r.u, r.l ], e++, this); r = r.B; } } [Symbol.iterator]() { return function*() { let t = this.p; while (t !== this.h) { yield [ t.u, t.l ]; t = t.B; } }.bind(this)(); } } var _default = HashMap; exports["default"] = _default; //# sourceMappingURL=HashMap.js.map /***/ }), /***/ 2218: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = void 0; var _Base = __nccwpck_require__(8130); var _throwError = __nccwpck_require__(9968); class HashSetIterator extends _Base.HashContainerIterator { constructor(t, e, r, s) { super(t, e, s); this.container = r; } get pointer() { if (this.o === this.h) { (0, _throwError.throwIteratorAccessError)(); } return this.o.u; } copy() { return new HashSetIterator(this.o, this.h, this.container, this.iteratorType); } } class HashSet extends _Base.HashContainer { constructor(t = []) { super(); const e = this; t.forEach((function(t) { e.insert(t); })); } begin() { return new HashSetIterator(this.p, this.h, this); } end() { return new HashSetIterator(this.h, this.h, this); } rBegin() { return new HashSetIterator(this._, this.h, this, 1); } rEnd() { return new HashSetIterator(this.h, this.h, this, 1); } front() { return this.p.u; } back() { return this._.u; } insert(t, e) { return this.M(t, undefined, e); } getElementByPos(t) { if (t < 0 || t > this.i - 1) { throw new RangeError; } let e = this.p; while (t--) { e = e.B; } return e.u; } find(t, e) { const r = this.I(t, e); return new HashSetIterator(r, this.h, this); } forEach(t) { let e = 0; let r = this.p; while (r !== this.h) { t(r.u, e++, this); r = r.B; } } [Symbol.iterator]() { return function*() { let t = this.p; while (t !== this.h) { yield t.u; t = t.B; } }.bind(this)(); } } var _default = HashSet; exports["default"] = _default; //# sourceMappingURL=HashSet.js.map /***/ }), /***/ 5705: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = void 0; var _ContainerBase = __nccwpck_require__(3775); class PriorityQueue extends _ContainerBase.Base { constructor(t = [], s = function(t, s) { if (t > s) return -1; if (t < s) return 1; return 0; }, i = true) { super(); this.v = s; if (Array.isArray(t)) { this.C = i ? [ ...t ] : t; } else { this.C = []; const s = this; t.forEach((function(t) { s.C.push(t); })); } this.i = this.C.length; const e = this.i >> 1; for (let t = this.i - 1 >> 1; t >= 0; --t) { this.k(t, e); } } m(t) { const s = this.C[t]; while (t > 0) { const i = t - 1 >> 1; const e = this.C[i]; if (this.v(e, s) <= 0) break; this.C[t] = e; t = i; } this.C[t] = s; } k(t, s) { const i = this.C[t]; while (t < s) { let s = t << 1 | 1; const e = s + 1; let h = this.C[s]; if (e < this.i && this.v(h, this.C[e]) > 0) { s = e; h = this.C[e]; } if (this.v(h, i) >= 0) break; this.C[t] = h; t = s; } this.C[t] = i; } clear() { this.i = 0; this.C.length = 0; } push(t) { this.C.push(t); this.m(this.i); this.i += 1; } pop() { if (this.i === 0) return; const t = this.C[0]; const s = this.C.pop(); this.i -= 1; if (this.i) { this.C[0] = s; this.k(0, this.i >> 1); } return t; } top() { return this.C[0]; } find(t) { return this.C.indexOf(t) >= 0; } remove(t) { const s = this.C.indexOf(t); if (s < 0) return false; if (s === 0) { this.pop(); } else if (s === this.i - 1) { this.C.pop(); this.i -= 1; } else { this.C.splice(s, 1, this.C.pop()); this.i -= 1; this.m(s); this.k(s, this.i >> 1); } return true; } updateItem(t) { const s = this.C.indexOf(t); if (s < 0) return false; this.m(s); this.k(s, this.i >> 1); return true; } toArray() { return [ ...this.C ]; } } var _default = PriorityQueue; exports["default"] = _default; //# sourceMappingURL=PriorityQueue.js.map /***/ }), /***/ 8145: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = void 0; var _ContainerBase = __nccwpck_require__(3775); class Queue extends _ContainerBase.Base { constructor(t = []) { super(); this.j = 0; this.q = []; const s = this; t.forEach((function(t) { s.push(t); })); } clear() { this.q = []; this.i = this.j = 0; } push(t) { const s = this.q.length; if (this.j / s > .5 && this.j + this.i >= s && s > 4096) { const s = this.i; for (let t = 0; t < s; ++t) { this.q[t] = this.q[this.j + t]; } this.j = 0; this.q[this.i] = t; } else this.q[this.j + this.i] = t; return ++this.i; } pop() { if (this.i === 0) return; const t = this.q[this.j++]; this.i -= 1; return t; } front() { if (this.i === 0) return; return this.q[this.j]; } } var _default = Queue; exports["default"] = _default; //# sourceMappingURL=Queue.js.map /***/ }), /***/ 9026: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = void 0; var _ContainerBase = __nccwpck_require__(3775); class Stack extends _ContainerBase.Base { constructor(t = []) { super(); this.S = []; const s = this; t.forEach((function(t) { s.push(t); })); } clear() { this.i = 0; this.S = []; } push(t) { this.S.push(t); this.i += 1; return this.i; } pop() { if (this.i === 0) return; this.i -= 1; return this.S.pop(); } top() { return this.S[this.i - 1]; } } var _default = Stack; exports["default"] = _default; //# sourceMappingURL=Stack.js.map /***/ }), /***/ 6404: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports.RandomIterator = void 0; var _ContainerBase = __nccwpck_require__(3775); var _throwError = __nccwpck_require__(9968); class RandomIterator extends _ContainerBase.ContainerIterator { constructor(t, r) { super(r); this.o = t; if (this.iteratorType === 0) { this.pre = function() { if (this.o === 0) { (0, _throwError.throwIteratorAccessError)(); } this.o -= 1; return this; }; this.next = function() { if (this.o === this.container.size()) { (0, _throwError.throwIteratorAccessError)(); } this.o += 1; return this; }; } else { this.pre = function() { if (this.o === this.container.size() - 1) { (0, _throwError.throwIteratorAccessError)(); } this.o += 1; return this; }; this.next = function() { if (this.o === -1) { (0, _throwError.throwIteratorAccessError)(); } this.o -= 1; return this; }; } } get pointer() { return this.container.getElementByPos(this.o); } set pointer(t) { this.container.setElementByPos(this.o, t); } } exports.RandomIterator = RandomIterator; //# sourceMappingURL=RandomIterator.js.map /***/ }), /***/ 5649: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = void 0; var _ContainerBase = __nccwpck_require__(3775); class SequentialContainer extends _ContainerBase.Container {} var _default = SequentialContainer; exports["default"] = _default; //# sourceMappingURL=index.js.map /***/ }), /***/ 1423: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = void 0; var _Base = _interopRequireDefault(__nccwpck_require__(5649)); var _RandomIterator = __nccwpck_require__(6404); function _interopRequireDefault(t) { return t && t.t ? t : { default: t }; } class DequeIterator extends _RandomIterator.RandomIterator { constructor(t, i, s) { super(t, s); this.container = i; } copy() { return new DequeIterator(this.o, this.container, this.iteratorType); } } class Deque extends _Base.default { constructor(t = [], i = 1 << 12) { super(); this.j = 0; this.D = 0; this.R = 0; this.N = 0; this.P = 0; this.A = []; const s = (() => { if (typeof t.length === "number") return t.length; if (typeof t.size === "number") return t.size; if (typeof t.size === "function") return t.size(); throw new TypeError("Cannot get the length or size of the container"); })(); this.F = i; this.P = Math.max(Math.ceil(s / this.F), 1); for (let t = 0; t < this.P; ++t) { this.A.push(new Array(this.F)); } const h = Math.ceil(s / this.F); this.j = this.R = (this.P >> 1) - (h >> 1); this.D = this.N = this.F - s % this.F >> 1; const e = this; t.forEach((function(t) { e.pushBack(t); })); } T() { const t = []; const i = Math.max(this.P >> 1, 1); for (let s = 0; s < i; ++s) { t[s] = new Array(this.F); } for (let i = this.j; i < this.P; ++i) { t[t.length] = this.A[i]; } for (let i = 0; i < this.R; ++i) { t[t.length] = this.A[i]; } t[t.length] = [ ...this.A[this.R] ]; this.j = i; this.R = t.length - 1; for (let s = 0; s < i; ++s) { t[t.length] = new Array(this.F); } this.A = t; this.P = t.length; } O(t) { const i = this.D + t + 1; const s = i % this.F; let h = s - 1; let e = this.j + (i - s) / this.F; if (s === 0) e -= 1; e %= this.P; if (h < 0) h += this.F; return { curNodeBucketIndex: e, curNodePointerIndex: h }; } clear() { this.A = [ new Array(this.F) ]; this.P = 1; this.j = this.R = this.i = 0; this.D = this.N = this.F >> 1; } begin() { return new DequeIterator(0, this); } end() { return new DequeIterator(this.i, this); } rBegin() { return new DequeIterator(this.i - 1, this, 1); } rEnd() { return new DequeIterator(-1, this, 1); } front() { if (this.i === 0) return; return this.A[this.j][this.D]; } back() { if (this.i === 0) return; return this.A[this.R][this.N]; } pushBack(t) { if (this.i) { if (this.N < this.F - 1) { this.N += 1; } else if (this.R < this.P - 1) { this.R += 1; this.N = 0; } else { this.R = 0; this.N = 0; } if (this.R === this.j && this.N === this.D) this.T(); } this.i += 1; this.A[this.R][this.N] = t; return this.i; } popBack() { if (this.i === 0) return; const t = this.A[this.R][this.N]; if (this.i !== 1) { if (this.N > 0) { this.N -= 1; } else if (this.R > 0) { this.R -= 1; this.N = this.F - 1; } else { this.R = this.P - 1; this.N = this.F - 1; } } this.i -= 1; return t; } pushFront(t) { if (this.i) { if (this.D > 0) { this.D -= 1; } else if (this.j > 0) { this.j -= 1; this.D = this.F - 1; } else { this.j = this.P - 1; this.D = this.F - 1; } if (this.j === this.R && this.D === this.N) this.T(); } this.i += 1; this.A[this.j][this.D] = t; return this.i; } popFront() { if (this.i === 0) return; const t = this.A[this.j][this.D]; if (this.i !== 1) { if (this.D < this.F - 1) { this.D += 1; } else if (this.j < this.P - 1) { this.j += 1; this.D = 0; } else { this.j = 0; this.D = 0; } } this.i -= 1; return t; } getElementByPos(t) { if (t < 0 || t > this.i - 1) { throw new RangeError; } const {curNodeBucketIndex: i, curNodePointerIndex: s} = this.O(t); return this.A[i][s]; } setElementByPos(t, i) { if (t < 0 || t > this.i - 1) { throw new RangeError; } const {curNodeBucketIndex: s, curNodePointerIndex: h} = this.O(t); this.A[s][h] = i; } insert(t, i, s = 1) { if (t < 0 || t > this.i) { throw new RangeError; } if (t === 0) { while (s--) this.pushFront(i); } else if (t === this.i) { while (s--) this.pushBack(i); } else { const h = []; for (let i = t; i < this.i; ++i) { h.push(this.getElementByPos(i)); } this.cut(t - 1); for (let t = 0; t < s; ++t) this.pushBack(i); for (let t = 0; t < h.length; ++t) this.pushBack(h[t]); } return this.i; } cut(t) { if (t < 0) { this.clear(); return 0; } const {curNodeBucketIndex: i, curNodePointerIndex: s} = this.O(t); this.R = i; this.N = s; this.i = t + 1; return this.i; } eraseElementByPos(t) { if (t < 0 || t > this.i - 1) { throw new RangeError; } if (t === 0) this.popFront(); else if (t === this.i - 1) this.popBack(); else { const i = []; for (let s = t + 1; s < this.i; ++s) { i.push(this.getElementByPos(s)); } this.cut(t); this.popBack(); const s = this; i.forEach((function(t) { s.pushBack(t); })); } return this.i; } eraseElementByValue(t) { if (this.i === 0) return 0; const i = []; for (let s = 0; s < this.i; ++s) { const h = this.getElementByPos(s); if (h !== t) i.push(h); } const s = i.length; for (let t = 0; t < s; ++t) this.setElementByPos(t, i[t]); return this.cut(s - 1); } eraseElementByIterator(t) { const i = t.o; this.eraseElementByPos(i); t = t.next(); return t; } find(t) { for (let i = 0; i < this.i; ++i) { if (this.getElementByPos(i) === t) { return new DequeIterator(i, this); } } return this.end(); } reverse() { let t = 0; let i = this.i - 1; while (t < i) { const s = this.getElementByPos(t); this.setElementByPos(t, this.getElementByPos(i)); this.setElementByPos(i, s); t += 1; i -= 1; } } unique() { if (this.i <= 1) { return this.i; } let t = 1; let i = this.getElementByPos(0); for (let s = 1; s < this.i; ++s) { const h = this.getElementByPos(s); if (h !== i) { i = h; this.setElementByPos(t++, h); } } while (this.i > t) this.popBack(); return this.i; } sort(t) { const i = []; for (let t = 0; t < this.i; ++t) { i.push(this.getElementByPos(t)); } i.sort(t); for (let t = 0; t < this.i; ++t) this.setElementByPos(t, i[t]); } shrinkToFit() { if (this.i === 0) return; const t = []; this.forEach((function(i) { t.push(i); })); this.P = Math.max(Math.ceil(this.i / this.F), 1); this.i = this.j = this.R = this.D = this.N = 0; this.A = []; for (let t = 0; t < this.P; ++t) { this.A.push(new Array(this.F)); } for (let i = 0; i < t.length; ++i) this.pushBack(t[i]); } forEach(t) { for (let i = 0; i < this.i; ++i) { t(this.getElementByPos(i), i, this); } } [Symbol.iterator]() { return function*() { for (let t = 0; t < this.i; ++t) { yield this.getElementByPos(t); } }.bind(this)(); } } var _default = Deque; exports["default"] = _default; //# sourceMappingURL=Deque.js.map /***/ }), /***/ 4723: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = void 0; var _Base = _interopRequireDefault(__nccwpck_require__(5649)); var _ContainerBase = __nccwpck_require__(3775); var _throwError = __nccwpck_require__(9968); function _interopRequireDefault(t) { return t && t.t ? t : { default: t }; } class LinkListIterator extends _ContainerBase.ContainerIterator { constructor(t, i, s, r) { super(r); this.o = t; this.h = i; this.container = s; if (this.iteratorType === 0) { this.pre = function() { if (this.o.L === this.h) { (0, _throwError.throwIteratorAccessError)(); } this.o = this.o.L; return this; }; this.next = function() { if (this.o === this.h) { (0, _throwError.throwIteratorAccessError)(); } this.o = this.o.B; return this; }; } else { this.pre = function() { if (this.o.B === this.h) { (0, _throwError.throwIteratorAccessError)(); } this.o = this.o.B; return this; }; this.next = function() { if (this.o === this.h) { (0, _throwError.throwIteratorAccessError)(); } this.o = this.o.L; return this; }; } } get pointer() { if (this.o === this.h) { (0, _throwError.throwIteratorAccessError)(); } return this.o.l; } set pointer(t) { if (this.o === this.h) { (0, _throwError.throwIteratorAccessError)(); } this.o.l = t; } copy() { return new LinkListIterator(this.o, this.h, this.container, this.iteratorType); } } class LinkList extends _Base.default { constructor(t = []) { super(); this.h = {}; this.p = this._ = this.h.L = this.h.B = this.h; const i = this; t.forEach((function(t) { i.pushBack(t); })); } V(t) { const {L: i, B: s} = t; i.B = s; s.L = i; if (t === this.p) { this.p = s; } if (t === this._) { this._ = i; } this.i -= 1; } G(t, i) { const s = i.B; const r = { l: t, L: i, B: s }; i.B = r; s.L = r; if (i === this.h) { this.p = r; } if (s === this.h) { this._ = r; } this.i += 1; } clear() { this.i = 0; this.p = this._ = this.h.L = this.h.B = this.h; } begin() { return new LinkListIterator(this.p, this.h, this); } end() { return new LinkListIterator(this.h, this.h, this); } rBegin() { return new LinkListIterator(this._, this.h, this, 1); } rEnd() { return new LinkListIterator(this.h, this.h, this, 1); } front() { return this.p.l; } back() { return this._.l; } getElementByPos(t) { if (t < 0 || t > this.i - 1) { throw new RangeError; } let i = this.p; while (t--) { i = i.B; } return i.l; } eraseElementByPos(t) { if (t < 0 || t > this.i - 1) { throw new RangeError; } let i = this.p; while (t--) { i = i.B; } this.V(i); return this.i; } eraseElementByValue(t) { let i = this.p; while (i !== this.h) { if (i.l === t) { this.V(i); } i = i.B; } return this.i; } eraseElementByIterator(t) { const i = t.o; if (i === this.h) { (0, _throwError.throwIteratorAccessError)(); } t = t.next(); this.V(i); return t; } pushBack(t) { this.G(t, this._); return this.i; } popBack() { if (this.i === 0) return; const t = this._.l; this.V(this._); return t; } pushFront(t) { this.G(t, this.h); return this.i; } popFront() { if (this.i === 0) return; const t = this.p.l; this.V(this.p); return t; } setElementByPos(t, i) { if (t < 0 || t > this.i - 1) { throw new RangeError; } let s = this.p; while (t--) { s = s.B; } s.l = i; } insert(t, i, s = 1) { if (t < 0 || t > this.i) { throw new RangeError; } if (s <= 0) return this.i; if (t === 0) { while (s--) this.pushFront(i); } else if (t === this.i) { while (s--) this.pushBack(i); } else { let r = this.p; for (let i = 1; i < t; ++i) { r = r.B; } const e = r.B; this.i += s; while (s--) { r.B = { l: i, L: r }; r.B.L = r; r = r.B; } r.B = e; e.L = r; } return this.i; } find(t) { let i = this.p; while (i !== this.h) { if (i.l === t) { return new LinkListIterator(i, this.h, this); } i = i.B; } return this.end(); } reverse() { if (this.i <= 1) return; let t = this.p; let i = this._; let s = 0; while (s << 1 < this.i) { const r = t.l; t.l = i.l; i.l = r; t = t.B; i = i.L; s += 1; } } unique() { if (this.i <= 1) { return this.i; } let t = this.p; while (t !== this.h) { let i = t; while (i.B !== this.h && i.l === i.B.l) { i = i.B; this.i -= 1; } t.B = i.B; t.B.L = t; t = t.B; } return this.i; } sort(t) { if (this.i <= 1) return; const i = []; this.forEach((function(t) { i.push(t); })); i.sort(t); let s = this.p; i.forEach((function(t) { s.l = t; s = s.B; })); } merge(t) { const i = this; if (this.i === 0) { t.forEach((function(t) { i.pushBack(t); })); } else { let s = this.p; t.forEach((function(t) { while (s !== i.h && s.l <= t) { s = s.B; } i.G(t, s.L); })); } return this.i; } forEach(t) { let i = this.p; let s = 0; while (i !== this.h) { t(i.l, s++, this); i = i.B; } } [Symbol.iterator]() { return function*() { if (this.i === 0) return; let t = this.p; while (t !== this.h) { yield t.l; t = t.B; } }.bind(this)(); } } var _default = LinkList; exports["default"] = _default; //# sourceMappingURL=LinkList.js.map /***/ }), /***/ 712: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = void 0; var _Base = _interopRequireDefault(__nccwpck_require__(5649)); var _RandomIterator = __nccwpck_require__(6404); function _interopRequireDefault(t) { return t && t.t ? t : { default: t }; } class VectorIterator extends _RandomIterator.RandomIterator { constructor(t, r, e) { super(t, e); this.container = r; } copy() { return new VectorIterator(this.o, this.container, this.iteratorType); } } class Vector extends _Base.default { constructor(t = [], r = true) { super(); if (Array.isArray(t)) { this.J = r ? [ ...t ] : t; this.i = t.length; } else { this.J = []; const r = this; t.forEach((function(t) { r.pushBack(t); })); } } clear() { this.i = 0; this.J.length = 0; } begin() { return new VectorIterator(0, this); } end() { return new VectorIterator(this.i, this); } rBegin() { return new VectorIterator(this.i - 1, this, 1); } rEnd() { return new VectorIterator(-1, this, 1); } front() { return this.J[0]; } back() { return this.J[this.i - 1]; } getElementByPos(t) { if (t < 0 || t > this.i - 1) { throw new RangeError; } return this.J[t]; } eraseElementByPos(t) { if (t < 0 || t > this.i - 1) { throw new RangeError; } this.J.splice(t, 1); this.i -= 1; return this.i; } eraseElementByValue(t) { let r = 0; for (let e = 0; e < this.i; ++e) { if (this.J[e] !== t) { this.J[r++] = this.J[e]; } } this.i = this.J.length = r; return this.i; } eraseElementByIterator(t) { const r = t.o; t = t.next(); this.eraseElementByPos(r); return t; } pushBack(t) { this.J.push(t); this.i += 1; return this.i; } popBack() { if (this.i === 0) return; this.i -= 1; return this.J.pop(); } setElementByPos(t, r) { if (t < 0 || t > this.i - 1) { throw new RangeError; } this.J[t] = r; } insert(t, r, e = 1) { if (t < 0 || t > this.i) { throw new RangeError; } this.J.splice(t, 0, ...new Array(e).fill(r)); this.i += e; return this.i; } find(t) { for (let r = 0; r < this.i; ++r) { if (this.J[r] === t) { return new VectorIterator(r, this); } } return this.end(); } reverse() { this.J.reverse(); } unique() { let t = 1; for (let r = 1; r < this.i; ++r) { if (this.J[r] !== this.J[r - 1]) { this.J[t++] = this.J[r]; } } this.i = this.J.length = t; return this.i; } sort(t) { this.J.sort(t); } forEach(t) { for (let r = 0; r < this.i; ++r) { t(this.J[r], r, this); } } [Symbol.iterator]() { return function*() { yield* this.J; }.bind(this)(); } } var _default = Vector; exports["default"] = _default; //# sourceMappingURL=Vector.js.map /***/ }), /***/ 5498: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = void 0; var _ContainerBase = __nccwpck_require__(3775); var _throwError = __nccwpck_require__(9968); class TreeIterator extends _ContainerBase.ContainerIterator { constructor(t, r, i) { super(i); this.o = t; this.h = r; if (this.iteratorType === 0) { this.pre = function() { if (this.o === this.h.U) { (0, _throwError.throwIteratorAccessError)(); } this.o = this.o.L(); return this; }; this.next = function() { if (this.o === this.h) { (0, _throwError.throwIteratorAccessError)(); } this.o = this.o.B(); return this; }; } else { this.pre = function() { if (this.o === this.h.W) { (0, _throwError.throwIteratorAccessError)(); } this.o = this.o.B(); return this; }; this.next = function() { if (this.o === this.h) { (0, _throwError.throwIteratorAccessError)(); } this.o = this.o.L(); return this; }; } } get index() { let t = this.o; const r = this.h.tt; if (t === this.h) { if (r) { return r.rt - 1; } return 0; } let i = 0; if (t.U) { i += t.U.rt; } while (t !== r) { const r = t.tt; if (t === r.W) { i += 1; if (r.U) { i += r.U.rt; } } t = r; } return i; } } var _default = TreeIterator; exports["default"] = _default; //# sourceMappingURL=TreeIterator.js.map /***/ }), /***/ 9920: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports.TreeNodeEnableIndex = exports.TreeNode = void 0; class TreeNode { constructor(e, t) { this.ee = 1; this.u = undefined; this.l = undefined; this.U = undefined; this.W = undefined; this.tt = undefined; this.u = e; this.l = t; } L() { let e = this; if (e.ee === 1 && e.tt.tt === e) { e = e.W; } else if (e.U) { e = e.U; while (e.W) { e = e.W; } } else { let t = e.tt; while (t.U === e) { e = t; t = e.tt; } e = t; } return e; } B() { let e = this; if (e.W) { e = e.W; while (e.U) { e = e.U; } return e; } else { let t = e.tt; while (t.W === e) { e = t; t = e.tt; } if (e.W !== t) { return t; } else return e; } } te() { const e = this.tt; const t = this.W; const s = t.U; if (e.tt === this) e.tt = t; else if (e.U === this) e.U = t; else e.W = t; t.tt = e; t.U = this; this.tt = t; this.W = s; if (s) s.tt = this; return t; } se() { const e = this.tt; const t = this.U; const s = t.W; if (e.tt === this) e.tt = t; else if (e.U === this) e.U = t; else e.W = t; t.tt = e; t.W = this; this.tt = t; this.U = s; if (s) s.tt = this; return t; } } exports.TreeNode = TreeNode; class TreeNodeEnableIndex extends TreeNode { constructor() { super(...arguments); this.rt = 1; } te() { const e = super.te(); this.ie(); e.ie(); return e; } se() { const e = super.se(); this.ie(); e.ie(); return e; } ie() { this.rt = 1; if (this.U) { this.rt += this.U.rt; } if (this.W) { this.rt += this.W.rt; } } } exports.TreeNodeEnableIndex = TreeNodeEnableIndex; //# sourceMappingURL=TreeNode.js.map /***/ }), /***/ 9286: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = void 0; var _TreeNode = __nccwpck_require__(9920); var _ContainerBase = __nccwpck_require__(3775); var _throwError = __nccwpck_require__(9968); class TreeContainer extends _ContainerBase.Container { constructor(e = function(e, t) { if (e < t) return -1; if (e > t) return 1; return 0; }, t = false) { super(); this.Y = undefined; this.v = e; if (t) { this.re = _TreeNode.TreeNodeEnableIndex; this.M = function(e, t, i) { const s = this.ne(e, t, i); if (s) { let e = s.tt; while (e !== this.h) { e.rt += 1; e = e.tt; } const t = this.he(s); if (t) { const {parentNode: e, grandParent: i, curNode: s} = t; e.ie(); i.ie(); s.ie(); } } return this.i; }; this.V = function(e) { let t = this.fe(e); while (t !== this.h) { t.rt -= 1; t = t.tt; } }; } else { this.re = _TreeNode.TreeNode; this.M = function(e, t, i) { const s = this.ne(e, t, i); if (s) this.he(s); return this.i; }; this.V = this.fe; } this.h = new this.re; } X(e, t) { let i = this.h; while (e) { const s = this.v(e.u, t); if (s < 0) { e = e.W; } else if (s > 0) { i = e; e = e.U; } else return e; } return i; } Z(e, t) { let i = this.h; while (e) { const s = this.v(e.u, t); if (s <= 0) { e = e.W; } else { i = e; e = e.U; } } return i; } $(e, t) { let i = this.h; while (e) { const s = this.v(e.u, t); if (s < 0) { i = e; e = e.W; } else if (s > 0) { e = e.U; } else return e; } return i; } rr(e, t) { let i = this.h; while (e) { const s = this.v(e.u, t); if (s < 0) { i = e; e = e.W; } else { e = e.U; } } return i; } ue(e) { while (true) { const t = e.tt; if (t === this.h) return; if (e.ee === 1) { e.ee = 0; return; } if (e === t.U) { const i = t.W; if (i.ee === 1) { i.ee = 0; t.ee = 1; if (t === this.Y) { this.Y = t.te(); } else t.te(); } else { if (i.W && i.W.ee === 1) { i.ee = t.ee; t.ee = 0; i.W.ee = 0; if (t === this.Y) { this.Y = t.te(); } else t.te(); return; } else if (i.U && i.U.ee === 1) { i.ee = 1; i.U.ee = 0; i.se(); } else { i.ee = 1; e = t; } } } else { const i = t.U; if (i.ee === 1) { i.ee = 0; t.ee = 1; if (t === this.Y) { this.Y = t.se(); } else t.se(); } else { if (i.U && i.U.ee === 1) { i.ee = t.ee; t.ee = 0; i.U.ee = 0; if (t === this.Y) { this.Y = t.se(); } else t.se(); return; } else if (i.W && i.W.ee === 1) { i.ee = 1; i.W.ee = 0; i.te(); } else { i.ee = 1; e = t; } } } } } fe(e) { if (this.i === 1) { this.clear(); return this.h; } let t = e; while (t.U || t.W) { if (t.W) { t = t.W; while (t.U) t = t.U; } else { t = t.U; } [e.u, t.u] = [ t.u, e.u ]; [e.l, t.l] = [ t.l, e.l ]; e = t; } if (this.h.U === t) { this.h.U = t.tt; } else if (this.h.W === t) { this.h.W = t.tt; } this.ue(t); const i = t.tt; if (t === i.U) { i.U = undefined; } else i.W = undefined; this.i -= 1; this.Y.ee = 0; return i; } oe(e, t) { if (e === undefined) return false; const i = this.oe(e.U, t); if (i) return true; if (t(e)) return true; return this.oe(e.W, t); } he(e) { while (true) { const t = e.tt; if (t.ee === 0) return; const i = t.tt; if (t === i.U) { const s = i.W; if (s && s.ee === 1) { s.ee = t.ee = 0; if (i === this.Y) return; i.ee = 1; e = i; continue; } else if (e === t.W) { e.ee = 0; if (e.U) e.U.tt = t; if (e.W) e.W.tt = i; t.W = e.U; i.U = e.W; e.U = t; e.W = i; if (i === this.Y) { this.Y = e; this.h.tt = e; } else { const t = i.tt; if (t.U === i) { t.U = e; } else t.W = e; } e.tt = i.tt; t.tt = e; i.tt = e; i.ee = 1; return { parentNode: t, grandParent: i, curNode: e }; } else { t.ee = 0; if (i === this.Y) { this.Y = i.se(); } else i.se(); i.ee = 1; } } else { const s = i.U; if (s && s.ee === 1) { s.ee = t.ee = 0; if (i === this.Y) return; i.ee = 1; e = i; continue; } else if (e === t.U) { e.ee = 0; if (e.U) e.U.tt = i; if (e.W) e.W.tt = t; i.W = e.U; t.U = e.W; e.U = i; e.W = t; if (i === this.Y) { this.Y = e; this.h.tt = e; } else { const t = i.tt; if (t.U === i) { t.U = e; } else t.W = e; } e.tt = i.tt; t.tt = e; i.tt = e; i.ee = 1; return { parentNode: t, grandParent: i, curNode: e }; } else { t.ee = 0; if (i === this.Y) { this.Y = i.te(); } else i.te(); i.ee = 1; } } return; } } ne(e, t, i) { if (this.Y === undefined) { this.i += 1; this.Y = new this.re(e, t); this.Y.ee = 0; this.Y.tt = this.h; this.h.tt = this.Y; this.h.U = this.Y; this.h.W = this.Y; return; } let s; const r = this.h.U; const n = this.v(r.u, e); if (n === 0) { r.l = t; return; } else if (n > 0) { r.U = new this.re(e, t); r.U.tt = r; s = r.U; this.h.U = s; } else { const r = this.h.W; const n = this.v(r.u, e); if (n === 0) { r.l = t; return; } else if (n < 0) { r.W = new this.re(e, t); r.W.tt = r; s = r.W; this.h.W = s; } else { if (i !== undefined) { const r = i.o; if (r !== this.h) { const i = this.v(r.u, e); if (i === 0) { r.l = t; return; } else if (i > 0) { const i = r.L(); const n = this.v(i.u, e); if (n === 0) { i.l = t; return; } else if (n < 0) { s = new this.re(e, t); if (i.W === undefined) { i.W = s; s.tt = i; } else { r.U = s; s.tt = r; } } } } } if (s === undefined) { s = this.Y; while (true) { const i = this.v(s.u, e); if (i > 0) { if (s.U === undefined) { s.U = new this.re(e, t); s.U.tt = s; s = s.U; break; } s = s.U; } else if (i < 0) { if (s.W === undefined) { s.W = new this.re(e, t); s.W.tt = s; s = s.W; break; } s = s.W; } else { s.l = t; return; } } } } } this.i += 1; return s; } I(e, t) { while (e) { const i = this.v(e.u, t); if (i < 0) { e = e.W; } else if (i > 0) { e = e.U; } else return e; } return e || this.h; } clear() { this.i = 0; this.Y = undefined; this.h.tt = undefined; this.h.U = this.h.W = undefined; } updateKeyByIterator(e, t) { const i = e.o; if (i === this.h) { (0, _throwError.throwIteratorAccessError)(); } if (this.i === 1) { i.u = t; return true; } if (i === this.h.U) { if (this.v(i.B().u, t) > 0) { i.u = t; return true; } return false; } if (i === this.h.W) { if (this.v(i.L().u, t) < 0) { i.u = t; return true; } return false; } const s = i.L().u; if (this.v(s, t) >= 0) return false; const r = i.B().u; if (this.v(r, t) <= 0) return false; i.u = t; return true; } eraseElementByPos(e) { if (e < 0 || e > this.i - 1) { throw new RangeError; } let t = 0; const i = this; this.oe(this.Y, (function(s) { if (e === t) { i.V(s); return true; } t += 1; return false; })); return this.i; } eraseElementByKey(e) { if (this.i === 0) return false; const t = this.I(this.Y, e); if (t === this.h) return false; this.V(t); return true; } eraseElementByIterator(e) { const t = e.o; if (t === this.h) { (0, _throwError.throwIteratorAccessError)(); } const i = t.W === undefined; const s = e.iteratorType === 0; if (s) { if (i) e.next(); } else { if (!i || t.U === undefined) e.next(); } this.V(t); return e; } forEach(e) { let t = 0; for (const i of this) e(i, t++, this); } getElementByPos(e) { if (e < 0 || e > this.i - 1) { throw new RangeError; } let t; let i = 0; for (const s of this) { if (i === e) { t = s; break; } i += 1; } return t; } getHeight() { if (this.i === 0) return 0; const traversal = function(e) { if (!e) return 0; return Math.max(traversal(e.U), traversal(e.W)) + 1; }; return traversal(this.Y); } } var _default = TreeContainer; exports["default"] = _default; //# sourceMappingURL=index.js.map /***/ }), /***/ 3193: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = void 0; var _Base = _interopRequireDefault(__nccwpck_require__(9286)); var _TreeIterator = _interopRequireDefault(__nccwpck_require__(5498)); var _throwError = __nccwpck_require__(9968); function _interopRequireDefault(r) { return r && r.t ? r : { default: r }; } class OrderedMapIterator extends _TreeIterator.default { constructor(r, t, e, s) { super(r, t, s); this.container = e; } get pointer() { if (this.o === this.h) { (0, _throwError.throwIteratorAccessError)(); } const r = this; return new Proxy([], { get(t, e) { if (e === "0") return r.o.u; else if (e === "1") return r.o.l; }, set(t, e, s) { if (e !== "1") { throw new TypeError("props must be 1"); } r.o.l = s; return true; } }); } copy() { return new OrderedMapIterator(this.o, this.h, this.container, this.iteratorType); } } class OrderedMap extends _Base.default { constructor(r = [], t, e) { super(t, e); const s = this; r.forEach((function(r) { s.setElement(r[0], r[1]); })); } * K(r) { if (r === undefined) return; yield* this.K(r.U); yield [ r.u, r.l ]; yield* this.K(r.W); } begin() { return new OrderedMapIterator(this.h.U || this.h, this.h, this); } end() { return new OrderedMapIterator(this.h, this.h, this); } rBegin() { return new OrderedMapIterator(this.h.W || this.h, this.h, this, 1); } rEnd() { return new OrderedMapIterator(this.h, this.h, this, 1); } front() { if (this.i === 0) return; const r = this.h.U; return [ r.u, r.l ]; } back() { if (this.i === 0) return; const r = this.h.W; return [ r.u, r.l ]; } lowerBound(r) { const t = this.X(this.Y, r); return new OrderedMapIterator(t, this.h, this); } upperBound(r) { const t = this.Z(this.Y, r); return new OrderedMapIterator(t, this.h, this); } reverseLowerBound(r) { const t = this.$(this.Y, r); return new OrderedMapIterator(t, this.h, this); } reverseUpperBound(r) { const t = this.rr(this.Y, r); return new OrderedMapIterator(t, this.h, this); } setElement(r, t, e) { return this.M(r, t, e); } find(r) { const t = this.I(this.Y, r); return new OrderedMapIterator(t, this.h, this); } getElementByKey(r) { const t = this.I(this.Y, r); return t.l; } union(r) { const t = this; r.forEach((function(r) { t.setElement(r[0], r[1]); })); return this.i; } [Symbol.iterator]() { return this.K(this.Y); } } var _default = OrderedMap; exports["default"] = _default; //# sourceMappingURL=OrderedMap.js.map /***/ }), /***/ 9615: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = void 0; var _Base = _interopRequireDefault(__nccwpck_require__(9286)); var _TreeIterator = _interopRequireDefault(__nccwpck_require__(5498)); var _throwError = __nccwpck_require__(9968); function _interopRequireDefault(e) { return e && e.t ? e : { default: e }; } class OrderedSetIterator extends _TreeIterator.default { constructor(e, t, r, i) { super(e, t, i); this.container = r; } get pointer() { if (this.o === this.h) { (0, _throwError.throwIteratorAccessError)(); } return this.o.u; } copy() { return new OrderedSetIterator(this.o, this.h, this.container, this.iteratorType); } } class OrderedSet extends _Base.default { constructor(e = [], t, r) { super(t, r); const i = this; e.forEach((function(e) { i.insert(e); })); } * K(e) { if (e === undefined) return; yield* this.K(e.U); yield e.u; yield* this.K(e.W); } begin() { return new OrderedSetIterator(this.h.U || this.h, this.h, this); } end() { return new OrderedSetIterator(this.h, this.h, this); } rBegin() { return new OrderedSetIterator(this.h.W || this.h, this.h, this, 1); } rEnd() { return new OrderedSetIterator(this.h, this.h, this, 1); } front() { return this.h.U ? this.h.U.u : undefined; } back() { return this.h.W ? this.h.W.u : undefined; } insert(e, t) { return this.M(e, undefined, t); } find(e) { const t = this.I(this.Y, e); return new OrderedSetIterator(t, this.h, this); } lowerBound(e) { const t = this.X(this.Y, e); return new OrderedSetIterator(t, this.h, this); } upperBound(e) { const t = this.Z(this.Y, e); return new OrderedSetIterator(t, this.h, this); } reverseLowerBound(e) { const t = this.$(this.Y, e); return new OrderedSetIterator(t, this.h, this); } reverseUpperBound(e) { const t = this.rr(this.Y, e); return new OrderedSetIterator(t, this.h, this); } union(e) { const t = this; e.forEach((function(e) { t.insert(e); })); return this.i; } [Symbol.iterator]() { return this.K(this.Y); } } var _default = OrderedSet; exports["default"] = _default; //# sourceMappingURL=OrderedSet.js.map /***/ }), /***/ 1098: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); __webpack_unused_export__ = ({ enumerable: true, get: function() { return _Deque.default; } }); __webpack_unused_export__ = ({ enumerable: true, get: function() { return _HashMap.default; } }); __webpack_unused_export__ = ({ enumerable: true, get: function() { return _HashSet.default; } }); __webpack_unused_export__ = ({ enumerable: true, get: function() { return _LinkList.default; } }); __webpack_unused_export__ = ({ enumerable: true, get: function() { return _OrderedMap.default; } }); Object.defineProperty(exports, "CD", ({ enumerable: true, get: function() { return _OrderedSet.default; } })); __webpack_unused_export__ = ({ enumerable: true, get: function() { return _PriorityQueue.default; } }); __webpack_unused_export__ = ({ enumerable: true, get: function() { return _Queue.default; } }); __webpack_unused_export__ = ({ enumerable: true, get: function() { return _Stack.default; } }); __webpack_unused_export__ = ({ enumerable: true, get: function() { return _Vector.default; } }); var _Stack = _interopRequireDefault(__nccwpck_require__(9026)); var _Queue = _interopRequireDefault(__nccwpck_require__(8145)); var _PriorityQueue = _interopRequireDefault(__nccwpck_require__(5705)); var _Vector = _interopRequireDefault(__nccwpck_require__(712)); var _LinkList = _interopRequireDefault(__nccwpck_require__(4723)); var _Deque = _interopRequireDefault(__nccwpck_require__(1423)); var _OrderedSet = _interopRequireDefault(__nccwpck_require__(9615)); var _OrderedMap = _interopRequireDefault(__nccwpck_require__(3193)); var _HashSet = _interopRequireDefault(__nccwpck_require__(2218)); var _HashMap = _interopRequireDefault(__nccwpck_require__(9152)); function _interopRequireDefault(e) { return e && e.t ? e : { default: e }; } //# sourceMappingURL=index.js.map /***/ }), /***/ 8943: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports["default"] = checkObject; function checkObject(e) { const t = typeof e; return t === "object" && e !== null || t === "function"; } //# sourceMappingURL=checkObject.js.map /***/ }), /***/ 9968: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "t", ({ value: true })); exports.throwIteratorAccessError = throwIteratorAccessError; function throwIteratorAccessError() { throw new RangeError("Iterator access denied!"); } //# sourceMappingURL=throwError.js.map /***/ }), /***/ 4202: /***/ ((module) => { module.exports = function (obj, opts) { if (!opts) opts = {}; if (typeof opts === 'function') opts = { cmp: opts }; var space = opts.space || ''; if (typeof space === 'number') space = Array(space+1).join(' '); var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; var replacer = opts.replacer || function(key, value) { return value; }; var cmp = opts.cmp && (function (f) { return function (node) { return function (a, b) { var aobj = { key: a, value: node[a] }; var bobj = { key: b, value: node[b] }; return f(aobj, bobj); }; }; })(opts.cmp); var seen = []; return (function stringify (parent, key, node, level) { var indent = space ? ('\n' + new Array(level + 1).join(space)) : ''; var colonSeparator = space ? ': ' : ':'; if (node && node.toJSON && typeof node.toJSON === 'function') { node = node.toJSON(); } node = replacer.call(parent, key, node); if (node === undefined) { return; } if (typeof node !== 'object' || node === null) { return JSON.stringify(node); } if (isArray(node)) { var out = []; for (var i = 0; i < node.length; i++) { var item = stringify(node, i, node[i], level+1) || JSON.stringify(null); out.push(indent + space + item); } return '[' + out.join(',') + indent + ']'; } else { if (seen.indexOf(node) !== -1) { if (cycles) return JSON.stringify('__cycle__'); throw new TypeError('Converting circular structure to JSON'); } else seen.push(node); var keys = objectKeys(node).sort(cmp && cmp(node)); var out = []; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = stringify(node, key, node[key], level+1); if(!value) continue; var keyValue = JSON.stringify(key) + colonSeparator + value; ; out.push(indent + space + keyValue); } seen.splice(seen.indexOf(node), 1); return '{' + out.join(',') + indent + '}'; } })({ '': obj }, '', obj, 0); }; var isArray = Array.isArray || function (x) { return {}.toString.call(x) === '[object Array]'; }; var objectKeys = Object.keys || function (obj) { var has = Object.prototype.hasOwnProperty || function () { return true }; var keys = []; for (var key in obj) { if (has.call(obj, key)) keys.push(key); } return keys; }; /***/ }), /***/ 1444: /***/ ((module) => { "use strict"; /* eslint-disable no-nested-ternary */ var arr = []; var charCodeCache = []; module.exports = function (a, b) { if (a === b) { return 0; } var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the // shortest & which one is the longest if (a.length > b.length) { a = b; b = swap; } var aLen = a.length; var bLen = b.length; if (aLen === 0) { return bLen; } if (bLen === 0) { return aLen; } // Performing suffix trimming: // We can linearly drop suffix common to both strings since they // don't increase distance at all // Note: `~-` is the bitwise way to perform a `- 1` operation while (aLen > 0 && (a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen))) { aLen--; bLen--; } if (aLen === 0) { return bLen; } // Performing prefix trimming // We can linearly drop prefix common to both strings since they // don't increase distance at all var start = 0; while (start < aLen && (a.charCodeAt(start) === b.charCodeAt(start))) { start++; } aLen -= start; bLen -= start; if (aLen === 0) { return bLen; } var bCharCode; var ret; var tmp; var tmp2; var i = 0; var j = 0; while (i < aLen) { charCodeCache[start + i] = a.charCodeAt(start + i); arr[i] = ++i; } while (j < bLen) { bCharCode = b.charCodeAt(start + j); tmp = j++; ret = j; for (i = 0; i < aLen; i++) { tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1; tmp = arr[i]; ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2; } } return ret; }; /***/ }), /***/ 5641: /***/ ((module) => { "use strict"; /** @type {import('./abs')} */ module.exports = Math.abs; /***/ }), /***/ 6171: /***/ ((module) => { "use strict"; /** @type {import('./floor')} */ module.exports = Math.floor; /***/ }), /***/ 7044: /***/ ((module) => { "use strict"; /** @type {import('./isNaN')} */ module.exports = Number.isNaN || function isNaN(a) { return a !== a; }; /***/ }), /***/ 7147: /***/ ((module) => { "use strict"; /** @type {import('./max')} */ module.exports = Math.max; /***/ }), /***/ 1017: /***/ ((module) => { "use strict"; /** @type {import('./min')} */ module.exports = Math.min; /***/ }), /***/ 6947: /***/ ((module) => { "use strict"; /** @type {import('./pow')} */ module.exports = Math.pow; /***/ }), /***/ 2621: /***/ ((module) => { "use strict"; /** @type {import('./round')} */ module.exports = Math.round; /***/ }), /***/ 156: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var $isNaN = __nccwpck_require__(7044); /** @type {import('./sign')} */ module.exports = function sign(number) { if ($isNaN(number) || number === 0) { return number; } return number < 0 ? -1 : +1; }; /***/ }), /***/ 994: /***/ ((module) => { "use strict"; function hasKey(obj, keys) { var o = obj; keys.slice(0, -1).forEach(function (key) { o = o[key] || {}; }); var key = keys[keys.length - 1]; return key in o; } function isNumber(x) { if (typeof x === 'number') { return true; } if ((/^0x[0-9a-f]+$/i).test(x)) { return true; } return (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/).test(x); } function isConstructorOrProto(obj, key) { return (key === 'constructor' && typeof obj[key] === 'function') || key === '__proto__'; } module.exports = function (args, opts) { if (!opts) { opts = {}; } var flags = { bools: {}, strings: {}, unknownFn: null, }; if (typeof opts.unknown === 'function') { flags.unknownFn = opts.unknown; } if (typeof opts.boolean === 'boolean' && opts.boolean) { flags.allBools = true; } else { [].concat(opts.boolean).filter(Boolean).forEach(function (key) { flags.bools[key] = true; }); } var aliases = {}; function aliasIsBoolean(key) { return aliases[key].some(function (x) { return flags.bools[x]; }); } Object.keys(opts.alias || {}).forEach(function (key) { aliases[key] = [].concat(opts.alias[key]); aliases[key].forEach(function (x) { aliases[x] = [key].concat(aliases[key].filter(function (y) { return x !== y; })); }); }); [].concat(opts.string).filter(Boolean).forEach(function (key) { flags.strings[key] = true; if (aliases[key]) { [].concat(aliases[key]).forEach(function (k) { flags.strings[k] = true; }); } }); var defaults = opts.default || {}; var argv = { _: [] }; function argDefined(key, arg) { return (flags.allBools && (/^--[^=]+$/).test(arg)) || flags.strings[key] || flags.bools[key] || aliases[key]; } function setKey(obj, keys, value) { var o = obj; for (var i = 0; i < keys.length - 1; i++) { var key = keys[i]; if (isConstructorOrProto(o, key)) { return; } if (o[key] === undefined) { o[key] = {}; } if ( o[key] === Object.prototype || o[key] === Number.prototype || o[key] === String.prototype ) { o[key] = {}; } if (o[key] === Array.prototype) { o[key] = []; } o = o[key]; } var lastKey = keys[keys.length - 1]; if (isConstructorOrProto(o, lastKey)) { return; } if ( o === Object.prototype || o === Number.prototype || o === String.prototype ) { o = {}; } if (o === Array.prototype) { o = []; } if (o[lastKey] === undefined || flags.bools[lastKey] || typeof o[lastKey] === 'boolean') { o[lastKey] = value; } else if (Array.isArray(o[lastKey])) { o[lastKey].push(value); } else { o[lastKey] = [o[lastKey], value]; } } function setArg(key, val, arg) { if (arg && flags.unknownFn && !argDefined(key, arg)) { if (flags.unknownFn(arg) === false) { return; } } var value = !flags.strings[key] && isNumber(val) ? Number(val) : val; setKey(argv, key.split('.'), value); (aliases[key] || []).forEach(function (x) { setKey(argv, x.split('.'), value); }); } Object.keys(flags.bools).forEach(function (key) { setArg(key, defaults[key] === undefined ? false : defaults[key]); }); var notFlags = []; if (args.indexOf('--') !== -1) { notFlags = args.slice(args.indexOf('--') + 1); args = args.slice(0, args.indexOf('--')); } for (var i = 0; i < args.length; i++) { var arg = args[i]; var key; var next; if ((/^--.+=/).test(arg)) { // Using [\s\S] instead of . because js doesn't support the // 'dotall' regex modifier. See: // http://stackoverflow.com/a/1068308/13216 var m = arg.match(/^--([^=]+)=([\s\S]*)$/); key = m[1]; var value = m[2]; if (flags.bools[key]) { value = value !== 'false'; } setArg(key, value, arg); } else if ((/^--no-.+/).test(arg)) { key = arg.match(/^--no-(.+)/)[1]; setArg(key, false, arg); } else if ((/^--.+/).test(arg)) { key = arg.match(/^--(.+)/)[1]; next = args[i + 1]; if ( next !== undefined && !(/^(-|--)[^-]/).test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true) ) { setArg(key, next, arg); i += 1; } else if ((/^(true|false)$/).test(next)) { setArg(key, next === 'true', arg); i += 1; } else { setArg(key, flags.strings[key] ? '' : true, arg); } } else if ((/^-[^-]+/).test(arg)) { var letters = arg.slice(1, -1).split(''); var broken = false; for (var j = 0; j < letters.length; j++) { next = arg.slice(j + 2); if (next === '-') { setArg(letters[j], next, arg); continue; } if ((/[A-Za-z]/).test(letters[j]) && next[0] === '=') { setArg(letters[j], next.slice(1), arg); broken = true; break; } if ( (/[A-Za-z]/).test(letters[j]) && (/-?\d+(\.\d*)?(e-?\d+)?$/).test(next) ) { setArg(letters[j], next, arg); broken = true; break; } if (letters[j + 1] && letters[j + 1].match(/\W/)) { setArg(letters[j], arg.slice(j + 2), arg); broken = true; break; } else { setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); } } key = arg.slice(-1)[0]; if (!broken && key !== '-') { if ( args[i + 1] && !(/^(-|--)[^-]/).test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true) ) { setArg(key, args[i + 1], arg); i += 1; } else if (args[i + 1] && (/^(true|false)$/).test(args[i + 1])) { setArg(key, args[i + 1] === 'true', arg); i += 1; } else { setArg(key, flags.strings[key] ? '' : true, arg); } } } else { if (!flags.unknownFn || flags.unknownFn(arg) !== false) { argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg)); } if (opts.stopEarly) { argv._.push.apply(argv._, args.slice(i + 1)); break; } } } Object.keys(defaults).forEach(function (k) { if (!hasKey(argv, k.split('.'))) { setKey(argv, k.split('.'), defaults[k]); (aliases[k] || []).forEach(function (x) { setKey(argv, x.split('.'), defaults[k]); }); } }); if (opts['--']) { argv['--'] = notFlags.slice(); } else { notFlags.forEach(function (k) { argv._.push(k); }); } return argv; }; /***/ }), /***/ 8852: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* Protocol - protocol constants */ const protocol = module.exports const { Buffer } = __nccwpck_require__(181) /* Command code => mnemonic */ protocol.types = { 0: 'reserved', 1: 'connect', 2: 'connack', 3: 'publish', 4: 'puback', 5: 'pubrec', 6: 'pubrel', 7: 'pubcomp', 8: 'subscribe', 9: 'suback', 10: 'unsubscribe', 11: 'unsuback', 12: 'pingreq', 13: 'pingresp', 14: 'disconnect', 15: 'auth' } protocol.requiredHeaderFlags = { 1: 0, // 'connect' 2: 0, // 'connack' 4: 0, // 'puback' 5: 0, // 'pubrec' 6: 2, // 'pubrel' 7: 0, // 'pubcomp' 8: 2, // 'subscribe' 9: 0, // 'suback' 10: 2, // 'unsubscribe' 11: 0, // 'unsuback' 12: 0, // 'pingreq' 13: 0, // 'pingresp' 14: 0, // 'disconnect' 15: 0 // 'auth' } protocol.requiredHeaderFlagsErrors = {} for (const k in protocol.requiredHeaderFlags) { const v = protocol.requiredHeaderFlags[k] protocol.requiredHeaderFlagsErrors[k] = 'Invalid header flag bits, must be 0x' + v.toString(16) + ' for ' + protocol.types[k] + ' packet' } /* Mnemonic => Command code */ protocol.codes = {} for (const k in protocol.types) { const v = protocol.types[k] protocol.codes[v] = k } /* Header */ protocol.CMD_SHIFT = 4 protocol.CMD_MASK = 0xF0 protocol.DUP_MASK = 0x08 protocol.QOS_MASK = 0x03 protocol.QOS_SHIFT = 1 protocol.RETAIN_MASK = 0x01 /* Length */ protocol.VARBYTEINT_MASK = 0x7F protocol.VARBYTEINT_FIN_MASK = 0x80 protocol.VARBYTEINT_MAX = 268435455 /* Connack */ protocol.SESSIONPRESENT_MASK = 0x01 protocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK]) protocol.CONNACK_HEADER = Buffer.from([protocol.codes.connack << protocol.CMD_SHIFT]) /* Connect */ protocol.USERNAME_MASK = 0x80 protocol.PASSWORD_MASK = 0x40 protocol.WILL_RETAIN_MASK = 0x20 protocol.WILL_QOS_MASK = 0x18 protocol.WILL_QOS_SHIFT = 3 protocol.WILL_FLAG_MASK = 0x04 protocol.CLEAN_SESSION_MASK = 0x02 protocol.CONNECT_HEADER = Buffer.from([protocol.codes.connect << protocol.CMD_SHIFT]) /* Properties */ protocol.properties = { sessionExpiryInterval: 17, willDelayInterval: 24, receiveMaximum: 33, maximumPacketSize: 39, topicAliasMaximum: 34, requestResponseInformation: 25, requestProblemInformation: 23, userProperties: 38, authenticationMethod: 21, authenticationData: 22, payloadFormatIndicator: 1, messageExpiryInterval: 2, contentType: 3, responseTopic: 8, correlationData: 9, maximumQoS: 36, retainAvailable: 37, assignedClientIdentifier: 18, reasonString: 31, wildcardSubscriptionAvailable: 40, subscriptionIdentifiersAvailable: 41, sharedSubscriptionAvailable: 42, serverKeepAlive: 19, responseInformation: 26, serverReference: 28, topicAlias: 35, subscriptionIdentifier: 11 } protocol.propertiesCodes = {} for (const prop in protocol.properties) { const id = protocol.properties[prop] protocol.propertiesCodes[id] = prop } protocol.propertiesTypes = { sessionExpiryInterval: 'int32', willDelayInterval: 'int32', receiveMaximum: 'int16', maximumPacketSize: 'int32', topicAliasMaximum: 'int16', requestResponseInformation: 'byte', requestProblemInformation: 'byte', userProperties: 'pair', authenticationMethod: 'string', authenticationData: 'binary', payloadFormatIndicator: 'byte', messageExpiryInterval: 'int32', contentType: 'string', responseTopic: 'string', correlationData: 'binary', maximumQoS: 'int8', retainAvailable: 'byte', assignedClientIdentifier: 'string', reasonString: 'string', wildcardSubscriptionAvailable: 'byte', subscriptionIdentifiersAvailable: 'byte', sharedSubscriptionAvailable: 'byte', serverKeepAlive: 'int16', responseInformation: 'string', serverReference: 'string', topicAlias: 'int16', subscriptionIdentifier: 'var' } function genHeader (type) { return [0, 1, 2].map(qos => { return [0, 1].map(dup => { return [0, 1].map(retain => { const buf = Buffer.alloc(1) buf.writeUInt8( protocol.codes[type] << protocol.CMD_SHIFT | (dup ? protocol.DUP_MASK : 0) | qos << protocol.QOS_SHIFT | retain, 0, true) return buf }) }) }) } /* Publish */ protocol.PUBLISH_HEADER = genHeader('publish') /* Subscribe */ protocol.SUBSCRIBE_HEADER = genHeader('subscribe') protocol.SUBSCRIBE_OPTIONS_QOS_MASK = 0x03 protocol.SUBSCRIBE_OPTIONS_NL_MASK = 0x01 protocol.SUBSCRIBE_OPTIONS_NL_SHIFT = 2 protocol.SUBSCRIBE_OPTIONS_RAP_MASK = 0x01 protocol.SUBSCRIBE_OPTIONS_RAP_SHIFT = 3 protocol.SUBSCRIBE_OPTIONS_RH_MASK = 0x03 protocol.SUBSCRIBE_OPTIONS_RH_SHIFT = 4 protocol.SUBSCRIBE_OPTIONS_RH = [0x00, 0x10, 0x20] protocol.SUBSCRIBE_OPTIONS_NL = 0x04 protocol.SUBSCRIBE_OPTIONS_RAP = 0x08 protocol.SUBSCRIBE_OPTIONS_QOS = [0x00, 0x01, 0x02] /* Unsubscribe */ protocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe') /* Confirmations */ protocol.ACKS = { unsuback: genHeader('unsuback'), puback: genHeader('puback'), pubcomp: genHeader('pubcomp'), pubrel: genHeader('pubrel'), pubrec: genHeader('pubrec') } protocol.SUBACK_HEADER = Buffer.from([protocol.codes.suback << protocol.CMD_SHIFT]) /* Protocol versions */ protocol.VERSION3 = Buffer.from([3]) protocol.VERSION4 = Buffer.from([4]) protocol.VERSION5 = Buffer.from([5]) protocol.VERSION131 = Buffer.from([131]) protocol.VERSION132 = Buffer.from([132]) /* QoS */ protocol.QOS = [0, 1, 2].map(qos => { return Buffer.from([qos]) }) /* Empty packets */ protocol.EMPTY = { pingreq: Buffer.from([protocol.codes.pingreq << 4, 0]), pingresp: Buffer.from([protocol.codes.pingresp << 4, 0]), disconnect: Buffer.from([protocol.codes.disconnect << 4, 0]) } protocol.MQTT5_PUBACK_PUBREC_CODES = { 0x00: 'Success', 0x10: 'No matching subscribers', 0x80: 'Unspecified error', 0x83: 'Implementation specific error', 0x87: 'Not authorized', 0x90: 'Topic Name invalid', 0x91: 'Packet identifier in use', 0x97: 'Quota exceeded', 0x99: 'Payload format invalid' } protocol.MQTT5_PUBREL_PUBCOMP_CODES = { 0x00: 'Success', 0x92: 'Packet Identifier not found' } protocol.MQTT5_SUBACK_CODES = { 0x00: 'Granted QoS 0', 0x01: 'Granted QoS 1', 0x02: 'Granted QoS 2', 0x80: 'Unspecified error', 0x83: 'Implementation specific error', 0x87: 'Not authorized', 0x8F: 'Topic Filter invalid', 0x91: 'Packet Identifier in use', 0x97: 'Quota exceeded', 0x9E: 'Shared Subscriptions not supported', 0xA1: 'Subscription Identifiers not supported', 0xA2: 'Wildcard Subscriptions not supported' } protocol.MQTT5_UNSUBACK_CODES = { 0x00: 'Success', 0x11: 'No subscription existed', 0x80: 'Unspecified error', 0x83: 'Implementation specific error', 0x87: 'Not authorized', 0x8F: 'Topic Filter invalid', 0x91: 'Packet Identifier in use' } protocol.MQTT5_DISCONNECT_CODES = { 0x00: 'Normal disconnection', 0x04: 'Disconnect with Will Message', 0x80: 'Unspecified error', 0x81: 'Malformed Packet', 0x82: 'Protocol Error', 0x83: 'Implementation specific error', 0x87: 'Not authorized', 0x89: 'Server busy', 0x8B: 'Server shutting down', 0x8D: 'Keep Alive timeout', 0x8E: 'Session taken over', 0x8F: 'Topic Filter invalid', 0x90: 'Topic Name invalid', 0x93: 'Receive Maximum exceeded', 0x94: 'Topic Alias invalid', 0x95: 'Packet too large', 0x96: 'Message rate too high', 0x97: 'Quota exceeded', 0x98: 'Administrative action', 0x99: 'Payload format invalid', 0x9A: 'Retain not supported', 0x9B: 'QoS not supported', 0x9C: 'Use another server', 0x9D: 'Server moved', 0x9E: 'Shared Subscriptions not supported', 0x9F: 'Connection rate exceeded', 0xA0: 'Maximum connect time', 0xA1: 'Subscription Identifiers not supported', 0xA2: 'Wildcard Subscriptions not supported' } protocol.MQTT5_AUTH_CODES = { 0x00: 'Success', 0x18: 'Continue authentication', 0x19: 'Re-authenticate' } /***/ }), /***/ 1666: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const writeToStream = __nccwpck_require__(7863) const { EventEmitter } = __nccwpck_require__(4434) const { Buffer } = __nccwpck_require__(181) function generate (packet, opts) { const stream = new Accumulator() writeToStream(packet, stream, opts) return stream.concat() } class Accumulator extends EventEmitter { constructor () { super() this._array = new Array(20) this._i = 0 } write (chunk) { this._array[this._i++] = chunk return true } concat () { let length = 0 const lengths = new Array(this._array.length) const list = this._array let pos = 0 let i for (i = 0; i < list.length && list[i] !== undefined; i++) { if (typeof list[i] !== 'string') lengths[i] = list[i].length else lengths[i] = Buffer.byteLength(list[i]) length += lengths[i] } const result = Buffer.allocUnsafe(length) for (i = 0; i < list.length && list[i] !== undefined; i++) { if (typeof list[i] !== 'string') { list[i].copy(result, pos) pos += lengths[i] } else { result.write(list[i], pos) pos += lengths[i] } } return result } destroy (err) { if (err) this.emit('error', err) } } module.exports = generate /***/ }), /***/ 4895: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { exports.parser = __nccwpck_require__(3650).parser exports.generate = __nccwpck_require__(1666) exports.writeToStream = __nccwpck_require__(7863) /***/ }), /***/ 9463: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { Buffer } = __nccwpck_require__(181) const max = 65536 const cache = {} // in node 6 Buffer.subarray returns a Uint8Array instead of a Buffer // later versions return a Buffer // alternative is Buffer.slice but that creates a new buffer // creating new buffers takes time // SubOk is only false on node < 8 const SubOk = Buffer.isBuffer(Buffer.from([1, 2]).subarray(0, 1)) function generateBuffer (i) { const buffer = Buffer.allocUnsafe(2) buffer.writeUInt8(i >> 8, 0) buffer.writeUInt8(i & 0x00FF, 0 + 1) return buffer } function generateCache () { for (let i = 0; i < max; i++) { cache[i] = generateBuffer(i) } } function genBufVariableByteInt (num) { const maxLength = 4 // max 4 bytes let digit = 0 let pos = 0 const buffer = Buffer.allocUnsafe(maxLength) do { digit = num % 128 | 0 num = num / 128 | 0 if (num > 0) digit = digit | 0x80 buffer.writeUInt8(digit, pos++) } while (num > 0 && pos < maxLength) if (num > 0) { pos = 0 } return SubOk ? buffer.subarray(0, pos) : buffer.slice(0, pos) } function generate4ByteBuffer (num) { const buffer = Buffer.allocUnsafe(4) buffer.writeUInt32BE(num, 0) return buffer } module.exports = { cache, generateCache, generateNumber: generateBuffer, genBufVariableByteInt, generate4ByteBuffer } /***/ }), /***/ 7481: /***/ ((module) => { class Packet { constructor () { this.cmd = null this.retain = false this.qos = 0 this.dup = false this.length = -1 this.topic = null this.payload = null } } module.exports = Packet /***/ }), /***/ 3650: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const bl = __nccwpck_require__(794) const { EventEmitter } = __nccwpck_require__(4434) const Packet = __nccwpck_require__(7481) const constants = __nccwpck_require__(8852) const debug = __nccwpck_require__(2830)('mqtt-packet:parser') class Parser extends EventEmitter { constructor () { super() this.parser = this.constructor.parser } static parser (opt) { if (!(this instanceof Parser)) return (new Parser()).parser(opt) this.settings = opt || {} this._states = [ '_parseHeader', '_parseLength', '_parsePayload', '_newPacket' ] this._resetState() return this } _resetState () { debug('_resetState: resetting packet, error, _list, and _stateCounter') this.packet = new Packet() this.error = null this._list = bl() this._stateCounter = 0 } parse (buf) { if (this.error) this._resetState() this._list.append(buf) debug('parse: current state: %s', this._states[this._stateCounter]) while ((this.packet.length !== -1 || this._list.length > 0) && this[this._states[this._stateCounter]]() && !this.error) { this._stateCounter++ debug('parse: state complete. _stateCounter is now: %d', this._stateCounter) debug('parse: packet.length: %d, buffer list length: %d', this.packet.length, this._list.length) if (this._stateCounter >= this._states.length) this._stateCounter = 0 } debug('parse: exited while loop. packet: %d, buffer list length: %d', this.packet.length, this._list.length) return this._list.length } _parseHeader () { // There is at least one byte in the buffer const zero = this._list.readUInt8(0) const cmdIndex = zero >> constants.CMD_SHIFT this.packet.cmd = constants.types[cmdIndex] const headerFlags = zero & 0xf const requiredHeaderFlags = constants.requiredHeaderFlags[cmdIndex] if (requiredHeaderFlags != null && headerFlags !== requiredHeaderFlags) { // Where a flag bit is marked as “Reserved” in Table 2.2 - Flag Bits, it is reserved for future use and MUST be set to the value listed in that table [MQTT-2.2.2-1]. If invalid flags are received, the receiver MUST close the Network Connection [MQTT-2.2.2-2] return this._emitError(new Error(constants.requiredHeaderFlagsErrors[cmdIndex])) } this.packet.retain = (zero & constants.RETAIN_MASK) !== 0 this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK if (this.packet.qos > 2) { return this._emitError(new Error('Packet must not have both QoS bits set to 1')) } this.packet.dup = (zero & constants.DUP_MASK) !== 0 debug('_parseHeader: packet: %o', this.packet) this._list.consume(1) return true } _parseLength () { // There is at least one byte in the list const result = this._parseVarByteNum(true) if (result) { this.packet.length = result.value this._list.consume(result.bytes) } debug('_parseLength %d', result.value) return !!result } _parsePayload () { debug('_parsePayload: payload %O', this._list) let result = false // Do we have a payload? Do we have enough data to complete the payload? // PINGs have no payload if (this.packet.length === 0 || this._list.length >= this.packet.length) { this._pos = 0 switch (this.packet.cmd) { case 'connect': this._parseConnect() break case 'connack': this._parseConnack() break case 'publish': this._parsePublish() break case 'puback': case 'pubrec': case 'pubrel': case 'pubcomp': this._parseConfirmation() break case 'subscribe': this._parseSubscribe() break case 'suback': this._parseSuback() break case 'unsubscribe': this._parseUnsubscribe() break case 'unsuback': this._parseUnsuback() break case 'pingreq': case 'pingresp': // These are empty, nothing to do break case 'disconnect': this._parseDisconnect() break case 'auth': this._parseAuth() break default: this._emitError(new Error('Not supported')) } result = true } debug('_parsePayload complete result: %s', result) return result } _parseConnect () { debug('_parseConnect') let topic // Will topic let payload // Will payload let password // Password let username // Username const flags = {} const packet = this.packet // Parse protocolId const protocolId = this._parseString() if (protocolId === null) return this._emitError(new Error('Cannot parse protocolId')) if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') { return this._emitError(new Error('Invalid protocolId')) } packet.protocolId = protocolId // Parse constants version number if (this._pos >= this._list.length) return this._emitError(new Error('Packet too short')) packet.protocolVersion = this._list.readUInt8(this._pos) if (packet.protocolVersion >= 128) { packet.bridgeMode = true packet.protocolVersion = packet.protocolVersion - 128 } if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4 && packet.protocolVersion !== 5) { return this._emitError(new Error('Invalid protocol version')) } this._pos++ if (this._pos >= this._list.length) { return this._emitError(new Error('Packet too short')) } if (this._list.readUInt8(this._pos) & 0x1) { // The Server MUST validate that the reserved flag in the CONNECT Control Packet is set to zero and disconnect the Client if it is not zero [MQTT-3.1.2-3] return this._emitError(new Error('Connect flag bit 0 must be 0, but got 1')) } // Parse connect flags flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK) flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK) flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK) const willRetain = !!(this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) const willQos = (this._list.readUInt8(this._pos) & constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT if (flags.will) { packet.will = {} packet.will.retain = willRetain packet.will.qos = willQos } else { if (willRetain) { return this._emitError(new Error('Will Retain Flag must be set to zero when Will Flag is set to 0')) } if (willQos) { return this._emitError(new Error('Will QoS must be set to zero when Will Flag is set to 0')) } } packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0 this._pos++ // Parse keepalive packet.keepalive = this._parseNum() if (packet.keepalive === -1) return this._emitError(new Error('Packet too short')) // parse properties if (packet.protocolVersion === 5) { const properties = this._parseProperties() if (Object.getOwnPropertyNames(properties).length) { packet.properties = properties } } // Parse clientId const clientId = this._parseString() if (clientId === null) return this._emitError(new Error('Packet too short')) packet.clientId = clientId debug('_parseConnect: packet.clientId: %s', packet.clientId) if (flags.will) { if (packet.protocolVersion === 5) { const willProperties = this._parseProperties() if (Object.getOwnPropertyNames(willProperties).length) { packet.will.properties = willProperties } } // Parse will topic topic = this._parseString() if (topic === null) return this._emitError(new Error('Cannot parse will topic')) packet.will.topic = topic debug('_parseConnect: packet.will.topic: %s', packet.will.topic) // Parse will payload payload = this._parseBuffer() if (payload === null) return this._emitError(new Error('Cannot parse will payload')) packet.will.payload = payload debug('_parseConnect: packet.will.paylaod: %s', packet.will.payload) } // Parse username if (flags.username) { username = this._parseString() if (username === null) return this._emitError(new Error('Cannot parse username')) packet.username = username debug('_parseConnect: packet.username: %s', packet.username) } // Parse password if (flags.password) { password = this._parseBuffer() if (password === null) return this._emitError(new Error('Cannot parse password')) packet.password = password } // need for right parse auth packet and self set up this.settings = packet debug('_parseConnect: complete') return packet } _parseConnack () { debug('_parseConnack') const packet = this.packet if (this._list.length < 1) return null const flags = this._list.readUInt8(this._pos++) if (flags > 1) { return this._emitError(new Error('Invalid connack flags, bits 7-1 must be set to 0')) } packet.sessionPresent = !!(flags & constants.SESSIONPRESENT_MASK) if (this.settings.protocolVersion === 5) { if (this._list.length >= 2) { packet.reasonCode = this._list.readUInt8(this._pos++) } else { packet.reasonCode = 0 } } else { if (this._list.length < 2) return null packet.returnCode = this._list.readUInt8(this._pos++) } if (packet.returnCode === -1 || packet.reasonCode === -1) return this._emitError(new Error('Cannot parse return code')) // mqtt 5 properties if (this.settings.protocolVersion === 5) { const properties = this._parseProperties() if (Object.getOwnPropertyNames(properties).length) { packet.properties = properties } } debug('_parseConnack: complete') } _parsePublish () { debug('_parsePublish') const packet = this.packet packet.topic = this._parseString() if (packet.topic === null) return this._emitError(new Error('Cannot parse topic')) // Parse messageId if (packet.qos > 0) if (!this._parseMessageId()) { return } // Properties mqtt 5 if (this.settings.protocolVersion === 5) { const properties = this._parseProperties() if (Object.getOwnPropertyNames(properties).length) { packet.properties = properties } } packet.payload = this._list.slice(this._pos, packet.length) debug('_parsePublish: payload from buffer list: %o', packet.payload) } _parseSubscribe () { debug('_parseSubscribe') const packet = this.packet let topic let options let qos let rh let rap let nl let subscription packet.subscriptions = [] if (!this._parseMessageId()) { return } // Properties mqtt 5 if (this.settings.protocolVersion === 5) { const properties = this._parseProperties() if (Object.getOwnPropertyNames(properties).length) { packet.properties = properties } } if (packet.length <= 0) { return this._emitError(new Error('Malformed subscribe, no payload specified')) } while (this._pos < packet.length) { // Parse topic topic = this._parseString() if (topic === null) return this._emitError(new Error('Cannot parse topic')) if (this._pos >= packet.length) return this._emitError(new Error('Malformed Subscribe Payload')) options = this._parseByte() if (this.settings.protocolVersion === 5) { if (options & 0xc0) { return this._emitError(new Error('Invalid subscribe topic flag bits, bits 7-6 must be 0')) } } else { if (options & 0xfc) { return this._emitError(new Error('Invalid subscribe topic flag bits, bits 7-2 must be 0')) } } qos = options & constants.SUBSCRIBE_OPTIONS_QOS_MASK if (qos > 2) { return this._emitError(new Error('Invalid subscribe QoS, must be <= 2')) } nl = ((options >> constants.SUBSCRIBE_OPTIONS_NL_SHIFT) & constants.SUBSCRIBE_OPTIONS_NL_MASK) !== 0 rap = ((options >> constants.SUBSCRIBE_OPTIONS_RAP_SHIFT) & constants.SUBSCRIBE_OPTIONS_RAP_MASK) !== 0 rh = (options >> constants.SUBSCRIBE_OPTIONS_RH_SHIFT) & constants.SUBSCRIBE_OPTIONS_RH_MASK if (rh > 2) { return this._emitError(new Error('Invalid retain handling, must be <= 2')) } subscription = { topic, qos } // mqtt 5 options if (this.settings.protocolVersion === 5) { subscription.nl = nl subscription.rap = rap subscription.rh = rh } else if (this.settings.bridgeMode) { subscription.rh = 0 subscription.rap = true subscription.nl = true } // Push pair to subscriptions debug('_parseSubscribe: push subscription `%s` to subscription', subscription) packet.subscriptions.push(subscription) } } _parseSuback () { debug('_parseSuback') const packet = this.packet this.packet.granted = [] if (!this._parseMessageId()) { return } // Properties mqtt 5 if (this.settings.protocolVersion === 5) { const properties = this._parseProperties() if (Object.getOwnPropertyNames(properties).length) { packet.properties = properties } } if (packet.length <= 0) { return this._emitError(new Error('Malformed suback, no payload specified')) } // Parse granted QoSes while (this._pos < this.packet.length) { const code = this._list.readUInt8(this._pos++) if (this.settings.protocolVersion === 5) { if (!constants.MQTT5_SUBACK_CODES[code]) { return this._emitError(new Error('Invalid suback code')) } } else { if (code > 2 && code !== 0x80) { return this._emitError(new Error('Invalid suback QoS, must be 0, 1, 2 or 128')) } } this.packet.granted.push(code) } } _parseUnsubscribe () { debug('_parseUnsubscribe') const packet = this.packet packet.unsubscriptions = [] // Parse messageId if (!this._parseMessageId()) { return } // Properties mqtt 5 if (this.settings.protocolVersion === 5) { const properties = this._parseProperties() if (Object.getOwnPropertyNames(properties).length) { packet.properties = properties } } if (packet.length <= 0) { return this._emitError(new Error('Malformed unsubscribe, no payload specified')) } while (this._pos < packet.length) { // Parse topic const topic = this._parseString() if (topic === null) return this._emitError(new Error('Cannot parse topic')) // Push topic to unsubscriptions debug('_parseUnsubscribe: push topic `%s` to unsubscriptions', topic) packet.unsubscriptions.push(topic) } } _parseUnsuback () { debug('_parseUnsuback') const packet = this.packet if (!this._parseMessageId()) return this._emitError(new Error('Cannot parse messageId')) if ((this.settings.protocolVersion === 3 || this.settings.protocolVersion === 4) && packet.length !== 2) { return this._emitError(new Error('Malformed unsuback, payload length must be 2')) } if (packet.length <= 0) { return this._emitError(new Error('Malformed unsuback, no payload specified')) } // Properties mqtt 5 if (this.settings.protocolVersion === 5) { const properties = this._parseProperties() if (Object.getOwnPropertyNames(properties).length) { packet.properties = properties } // Parse granted QoSes packet.granted = [] while (this._pos < this.packet.length) { const code = this._list.readUInt8(this._pos++) if (!constants.MQTT5_UNSUBACK_CODES[code]) { return this._emitError(new Error('Invalid unsuback code')) } this.packet.granted.push(code) } } } // parse packets like puback, pubrec, pubrel, pubcomp _parseConfirmation () { debug('_parseConfirmation: packet.cmd: `%s`', this.packet.cmd) const packet = this.packet this._parseMessageId() if (this.settings.protocolVersion === 5) { if (packet.length > 2) { // response code packet.reasonCode = this._parseByte() switch (this.packet.cmd) { case 'puback': case 'pubrec': if (!constants.MQTT5_PUBACK_PUBREC_CODES[packet.reasonCode]) { return this._emitError(new Error('Invalid ' + this.packet.cmd + ' reason code')) } break case 'pubrel': case 'pubcomp': if (!constants.MQTT5_PUBREL_PUBCOMP_CODES[packet.reasonCode]) { return this._emitError(new Error('Invalid ' + this.packet.cmd + ' reason code')) } break } debug('_parseConfirmation: packet.reasonCode `%d`', packet.reasonCode) } else { packet.reasonCode = 0 } if (packet.length > 3) { // properies mqtt 5 const properties = this._parseProperties() if (Object.getOwnPropertyNames(properties).length) { packet.properties = properties } } } return true } // parse disconnect packet _parseDisconnect () { const packet = this.packet debug('_parseDisconnect') if (this.settings.protocolVersion === 5) { // response code if (this._list.length > 0) { packet.reasonCode = this._parseByte() if (!constants.MQTT5_DISCONNECT_CODES[packet.reasonCode]) { this._emitError(new Error('Invalid disconnect reason code')) } } else { packet.reasonCode = 0 } // properies mqtt 5 const properties = this._parseProperties() if (Object.getOwnPropertyNames(properties).length) { packet.properties = properties } } debug('_parseDisconnect result: true') return true } // parse auth packet _parseAuth () { debug('_parseAuth') const packet = this.packet if (this.settings.protocolVersion !== 5) { return this._emitError(new Error('Not supported auth packet for this version MQTT')) } // response code packet.reasonCode = this._parseByte() if (!constants.MQTT5_AUTH_CODES[packet.reasonCode]) { return this._emitError(new Error('Invalid auth reason code')) } // properies mqtt 5 const properties = this._parseProperties() if (Object.getOwnPropertyNames(properties).length) { packet.properties = properties } debug('_parseAuth: result: true') return true } _parseMessageId () { const packet = this.packet packet.messageId = this._parseNum() if (packet.messageId === null) { this._emitError(new Error('Cannot parse messageId')) return false } debug('_parseMessageId: packet.messageId %d', packet.messageId) return true } _parseString (maybeBuffer) { const length = this._parseNum() const end = length + this._pos if (length === -1 || end > this._list.length || end > this.packet.length) return null const result = this._list.toString('utf8', this._pos, end) this._pos += length debug('_parseString: result: %s', result) return result } _parseStringPair () { debug('_parseStringPair') return { name: this._parseString(), value: this._parseString() } } _parseBuffer () { const length = this._parseNum() const end = length + this._pos if (length === -1 || end > this._list.length || end > this.packet.length) return null const result = this._list.slice(this._pos, end) this._pos += length debug('_parseBuffer: result: %o', result) return result } _parseNum () { if (this._list.length - this._pos < 2) return -1 const result = this._list.readUInt16BE(this._pos) this._pos += 2 debug('_parseNum: result: %s', result) return result } _parse4ByteNum () { if (this._list.length - this._pos < 4) return -1 const result = this._list.readUInt32BE(this._pos) this._pos += 4 debug('_parse4ByteNum: result: %s', result) return result } _parseVarByteNum (fullInfoFlag) { debug('_parseVarByteNum') const maxBytes = 4 let bytes = 0 let mul = 1 let value = 0 let result = false let current const padding = this._pos ? this._pos : 0 while (bytes < maxBytes && (padding + bytes) < this._list.length) { current = this._list.readUInt8(padding + bytes++) value += mul * (current & constants.VARBYTEINT_MASK) mul *= 0x80 if ((current & constants.VARBYTEINT_FIN_MASK) === 0) { result = true break } if (this._list.length <= bytes) { break } } if (!result && bytes === maxBytes && this._list.length >= bytes) { this._emitError(new Error('Invalid variable byte integer')) } if (padding) { this._pos += bytes } if (result) { if (fullInfoFlag) { result = { bytes, value } } else { result = value } } else { result = false } debug('_parseVarByteNum: result: %o', result) return result } _parseByte () { let result if (this._pos < this._list.length) { result = this._list.readUInt8(this._pos) this._pos++ } debug('_parseByte: result: %o', result) return result } _parseByType (type) { debug('_parseByType: type: %s', type) switch (type) { case 'byte': { return this._parseByte() !== 0 } case 'int8': { return this._parseByte() } case 'int16': { return this._parseNum() } case 'int32': { return this._parse4ByteNum() } case 'var': { return this._parseVarByteNum() } case 'string': { return this._parseString() } case 'pair': { return this._parseStringPair() } case 'binary': { return this._parseBuffer() } } } _parseProperties () { debug('_parseProperties') const length = this._parseVarByteNum() const start = this._pos const end = start + length const result = {} while (this._pos < end) { const type = this._parseByte() if (!type) { this._emitError(new Error('Cannot parse property code type')) return false } const name = constants.propertiesCodes[type] if (!name) { this._emitError(new Error('Unknown property')) return false } // user properties process if (name === 'userProperties') { if (!result[name]) { result[name] = Object.create(null) } const currentUserProperty = this._parseByType(constants.propertiesTypes[name]) if (result[name][currentUserProperty.name]) { if (Array.isArray(result[name][currentUserProperty.name])) { result[name][currentUserProperty.name].push(currentUserProperty.value) } else { const currentValue = result[name][currentUserProperty.name] result[name][currentUserProperty.name] = [currentValue] result[name][currentUserProperty.name].push(currentUserProperty.value) } } else { result[name][currentUserProperty.name] = currentUserProperty.value } continue } if (result[name]) { if (Array.isArray(result[name])) { result[name].push(this._parseByType(constants.propertiesTypes[name])) } else { result[name] = [result[name]] result[name].push(this._parseByType(constants.propertiesTypes[name])) } } else { result[name] = this._parseByType(constants.propertiesTypes[name]) } } return result } _newPacket () { debug('_newPacket') if (this.packet) { this._list.consume(this.packet.length) debug('_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d', this.packet.cmd, this.packet.payload, this.packet.length) this.emit('packet', this.packet) } debug('_newPacket: new packet') this.packet = new Packet() this._pos = 0 return true } _emitError (err) { debug('_emitError', err) this.error = err this.emit('error', err) } } module.exports = Parser /***/ }), /***/ 7863: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const protocol = __nccwpck_require__(8852) const { Buffer } = __nccwpck_require__(181) const empty = Buffer.allocUnsafe(0) const zeroBuf = Buffer.from([0]) const numbers = __nccwpck_require__(9463) const nextTick = (__nccwpck_require__(1564).nextTick) const debug = __nccwpck_require__(2830)('mqtt-packet:writeToStream') const numCache = numbers.cache const generateNumber = numbers.generateNumber const generateCache = numbers.generateCache const genBufVariableByteInt = numbers.genBufVariableByteInt const generate4ByteBuffer = numbers.generate4ByteBuffer let writeNumber = writeNumberCached let toGenerate = true function generate (packet, stream, opts) { debug('generate called') if (stream.cork) { stream.cork() nextTick(uncork, stream) } if (toGenerate) { toGenerate = false generateCache() } debug('generate: packet.cmd: %s', packet.cmd) switch (packet.cmd) { case 'connect': return connect(packet, stream, opts) case 'connack': return connack(packet, stream, opts) case 'publish': return publish(packet, stream, opts) case 'puback': case 'pubrec': case 'pubrel': case 'pubcomp': return confirmation(packet, stream, opts) case 'subscribe': return subscribe(packet, stream, opts) case 'suback': return suback(packet, stream, opts) case 'unsubscribe': return unsubscribe(packet, stream, opts) case 'unsuback': return unsuback(packet, stream, opts) case 'pingreq': case 'pingresp': return emptyPacket(packet, stream, opts) case 'disconnect': return disconnect(packet, stream, opts) case 'auth': return auth(packet, stream, opts) default: stream.destroy(new Error('Unknown command')) return false } } /** * Controls numbers cache. * Set to "false" to allocate buffers on-the-flight instead of pre-generated cache */ Object.defineProperty(generate, 'cacheNumbers', { get () { return writeNumber === writeNumberCached }, set (value) { if (value) { if (!numCache || Object.keys(numCache).length === 0) toGenerate = true writeNumber = writeNumberCached } else { toGenerate = false writeNumber = writeNumberGenerated } } }) function uncork (stream) { stream.uncork() } function connect (packet, stream, opts) { const settings = packet || {} const protocolId = settings.protocolId || 'MQTT' let protocolVersion = settings.protocolVersion || 4 const will = settings.will let clean = settings.clean const keepalive = settings.keepalive || 0 const clientId = settings.clientId || '' const username = settings.username const password = settings.password /* mqtt5 new oprions */ const properties = settings.properties if (clean === undefined) clean = true let length = 0 // Must be a string and non-falsy if (!protocolId || (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) { stream.destroy(new Error('Invalid protocolId')) return false } else length += protocolId.length + 2 // Must be 3 or 4 or 5 if (protocolVersion !== 3 && protocolVersion !== 4 && protocolVersion !== 5) { stream.destroy(new Error('Invalid protocol version')) return false } else length += 1 // ClientId might be omitted in 3.1.1 and 5, but only if cleanSession is set to 1 if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) && (clientId || protocolVersion >= 4) && (clientId || clean)) { length += Buffer.byteLength(clientId) + 2 } else { if (protocolVersion < 4) { stream.destroy(new Error('clientId must be supplied before 3.1.1')) return false } if ((clean * 1) === 0) { stream.destroy(new Error('clientId must be given if cleanSession set to 0')) return false } } // Must be a two byte number if (typeof keepalive !== 'number' || keepalive < 0 || keepalive > 65535 || keepalive % 1 !== 0) { stream.destroy(new Error('Invalid keepalive')) return false } else length += 2 // Connect flags length += 1 let propertiesData let willProperties // Properties if (protocolVersion === 5) { propertiesData = getProperties(stream, properties) if (!propertiesData) { return false } length += propertiesData.length } // If will exists... if (will) { // It must be an object if (typeof will !== 'object') { stream.destroy(new Error('Invalid will')) return false } // It must have topic typeof string if (!will.topic || typeof will.topic !== 'string') { stream.destroy(new Error('Invalid will topic')) return false } else { length += Buffer.byteLength(will.topic) + 2 } // Payload length += 2 // payload length if (will.payload) { if (will.payload.length >= 0) { if (typeof will.payload === 'string') { length += Buffer.byteLength(will.payload) } else { length += will.payload.length } } else { stream.destroy(new Error('Invalid will payload')) return false } } // will properties willProperties = {} if (protocolVersion === 5) { willProperties = getProperties(stream, will.properties) if (!willProperties) { return false } length += willProperties.length } } // Username let providedUsername = false if (username != null) { if (isStringOrBuffer(username)) { providedUsername = true length += Buffer.byteLength(username) + 2 } else { stream.destroy(new Error('Invalid username')) return false } } // Password if (password != null) { if (!providedUsername) { stream.destroy(new Error('Username is required to use password')) return false } if (isStringOrBuffer(password)) { length += byteLength(password) + 2 } else { stream.destroy(new Error('Invalid password')) return false } } // Generate header stream.write(protocol.CONNECT_HEADER) // Generate length writeVarByteInt(stream, length) // Generate protocol ID writeStringOrBuffer(stream, protocolId) if (settings.bridgeMode) { protocolVersion += 128 } stream.write( protocolVersion === 131 ? protocol.VERSION131 : protocolVersion === 132 ? protocol.VERSION132 : protocolVersion === 4 ? protocol.VERSION4 : protocolVersion === 5 ? protocol.VERSION5 : protocol.VERSION3 ) // Connect flags let flags = 0 flags |= (username != null) ? protocol.USERNAME_MASK : 0 flags |= (password != null) ? protocol.PASSWORD_MASK : 0 flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0 flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0 flags |= will ? protocol.WILL_FLAG_MASK : 0 flags |= clean ? protocol.CLEAN_SESSION_MASK : 0 stream.write(Buffer.from([flags])) // Keepalive writeNumber(stream, keepalive) // Properties if (protocolVersion === 5) { propertiesData.write() } // Client ID writeStringOrBuffer(stream, clientId) // Will if (will) { if (protocolVersion === 5) { willProperties.write() } writeString(stream, will.topic) writeStringOrBuffer(stream, will.payload) } // Username and password if (username != null) { writeStringOrBuffer(stream, username) } if (password != null) { writeStringOrBuffer(stream, password) } // This is a small packet that happens only once on a stream // We assume the stream is always free to receive more data after this return true } function connack (packet, stream, opts) { const version = opts ? opts.protocolVersion : 4 const settings = packet || {} const rc = version === 5 ? settings.reasonCode : settings.returnCode const properties = settings.properties let length = 2 // length of rc and sessionHeader // Check return code if (typeof rc !== 'number') { stream.destroy(new Error('Invalid return code')) return false } // mqtt5 properties let propertiesData = null if (version === 5) { propertiesData = getProperties(stream, properties) if (!propertiesData) { return false } length += propertiesData.length } stream.write(protocol.CONNACK_HEADER) // length writeVarByteInt(stream, length) stream.write(settings.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf) stream.write(Buffer.from([rc])) if (propertiesData != null) { propertiesData.write() } return true } function publish (packet, stream, opts) { debug('publish: packet: %o', packet) const version = opts ? opts.protocolVersion : 4 const settings = packet || {} const qos = settings.qos || 0 const retain = settings.retain ? protocol.RETAIN_MASK : 0 const topic = settings.topic const payload = settings.payload || empty const id = settings.messageId const properties = settings.properties let length = 0 // Topic must be a non-empty string or Buffer if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2 else if (Buffer.isBuffer(topic)) length += topic.length + 2 else { stream.destroy(new Error('Invalid topic')) return false } // Get the payload length if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload) else length += payload.length // Message ID must a number if qos > 0 if (qos && typeof id !== 'number') { stream.destroy(new Error('Invalid messageId')) return false } else if (qos) length += 2 // mqtt5 properties let propertiesData = null if (version === 5) { propertiesData = getProperties(stream, properties) if (!propertiesData) { return false } length += propertiesData.length } // Header stream.write(protocol.PUBLISH_HEADER[qos][settings.dup ? 1 : 0][retain ? 1 : 0]) // Remaining length writeVarByteInt(stream, length) // Topic writeNumber(stream, byteLength(topic)) stream.write(topic) // Message ID if (qos > 0) writeNumber(stream, id) // Properties if (propertiesData != null) { propertiesData.write() } // Payload debug('publish: payload: %o', payload) return stream.write(payload) } /* Puback, pubrec, pubrel and pubcomp */ function confirmation (packet, stream, opts) { const version = opts ? opts.protocolVersion : 4 const settings = packet || {} const type = settings.cmd || 'puback' const id = settings.messageId const dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0 let qos = 0 const reasonCode = settings.reasonCode const properties = settings.properties let length = version === 5 ? 3 : 2 if (type === 'pubrel') qos = 1 // Check message ID if (typeof id !== 'number') { stream.destroy(new Error('Invalid messageId')) return false } // properies mqtt 5 let propertiesData = null if (version === 5) { // Confirm should not add empty property length with no properties (rfc 3.4.2.2.1) if (typeof properties === 'object') { propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length) if (!propertiesData) { return false } length += propertiesData.length } } // Header stream.write(protocol.ACKS[type][qos][dup][0]) // Length === 3 is only true of version === 5 and no properties; therefore if reasonCode === 0 we are allowed to skip both bytes - but if we write the reason code we also have to write property length [MQTT-3.4.2-1]. if (length === 3) length += reasonCode !== 0 ? 1 : -1 writeVarByteInt(stream, length) // Message ID writeNumber(stream, id) // reason code in header - but only if it couldn't be omitted - indicated by length !== 2. if (version === 5 && length !== 2) { stream.write(Buffer.from([reasonCode])) } // properties mqtt 5 if (propertiesData !== null) { propertiesData.write() } else { if (length === 4) { // we have no properties but have written a reason code - so we need to indicate empty properties by filling in a zero. stream.write(Buffer.from([0])) } } return true } function subscribe (packet, stream, opts) { debug('subscribe: packet: ') const version = opts ? opts.protocolVersion : 4 const settings = packet || {} const dup = settings.dup ? protocol.DUP_MASK : 0 const id = settings.messageId const subs = settings.subscriptions const properties = settings.properties let length = 0 // Check message ID if (typeof id !== 'number') { stream.destroy(new Error('Invalid messageId')) return false } else length += 2 // properies mqtt 5 let propertiesData = null if (version === 5) { propertiesData = getProperties(stream, properties) if (!propertiesData) { return false } length += propertiesData.length } // Check subscriptions if (typeof subs === 'object' && subs.length) { for (let i = 0; i < subs.length; i += 1) { const itopic = subs[i].topic const iqos = subs[i].qos if (typeof itopic !== 'string') { stream.destroy(new Error('Invalid subscriptions - invalid topic')) return false } if (typeof iqos !== 'number') { stream.destroy(new Error('Invalid subscriptions - invalid qos')) return false } if (version === 5) { const nl = subs[i].nl || false if (typeof nl !== 'boolean') { stream.destroy(new Error('Invalid subscriptions - invalid No Local')) return false } const rap = subs[i].rap || false if (typeof rap !== 'boolean') { stream.destroy(new Error('Invalid subscriptions - invalid Retain as Published')) return false } const rh = subs[i].rh || 0 if (typeof rh !== 'number' || rh > 2) { stream.destroy(new Error('Invalid subscriptions - invalid Retain Handling')) return false } } length += Buffer.byteLength(itopic) + 2 + 1 } } else { stream.destroy(new Error('Invalid subscriptions')) return false } // Generate header debug('subscribe: writing to stream: %o', protocol.SUBSCRIBE_HEADER) stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0]) // Generate length writeVarByteInt(stream, length) // Generate message ID writeNumber(stream, id) // properies mqtt 5 if (propertiesData !== null) { propertiesData.write() } let result = true // Generate subs for (const sub of subs) { const jtopic = sub.topic const jqos = sub.qos const jnl = +sub.nl const jrap = +sub.rap const jrh = sub.rh let joptions // Write topic string writeString(stream, jtopic) // options process joptions = protocol.SUBSCRIBE_OPTIONS_QOS[jqos] if (version === 5) { joptions |= jnl ? protocol.SUBSCRIBE_OPTIONS_NL : 0 joptions |= jrap ? protocol.SUBSCRIBE_OPTIONS_RAP : 0 joptions |= jrh ? protocol.SUBSCRIBE_OPTIONS_RH[jrh] : 0 } // Write options result = stream.write(Buffer.from([joptions])) } return result } function suback (packet, stream, opts) { const version = opts ? opts.protocolVersion : 4 const settings = packet || {} const id = settings.messageId const granted = settings.granted const properties = settings.properties let length = 0 // Check message ID if (typeof id !== 'number') { stream.destroy(new Error('Invalid messageId')) return false } else length += 2 // Check granted qos vector if (typeof granted === 'object' && granted.length) { for (let i = 0; i < granted.length; i += 1) { if (typeof granted[i] !== 'number') { stream.destroy(new Error('Invalid qos vector')) return false } length += 1 } } else { stream.destroy(new Error('Invalid qos vector')) return false } // properies mqtt 5 let propertiesData = null if (version === 5) { propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length) if (!propertiesData) { return false } length += propertiesData.length } // header stream.write(protocol.SUBACK_HEADER) // Length writeVarByteInt(stream, length) // Message ID writeNumber(stream, id) // properies mqtt 5 if (propertiesData !== null) { propertiesData.write() } return stream.write(Buffer.from(granted)) } function unsubscribe (packet, stream, opts) { const version = opts ? opts.protocolVersion : 4 const settings = packet || {} const id = settings.messageId const dup = settings.dup ? protocol.DUP_MASK : 0 const unsubs = settings.unsubscriptions const properties = settings.properties let length = 0 // Check message ID if (typeof id !== 'number') { stream.destroy(new Error('Invalid messageId')) return false } else { length += 2 } // Check unsubs if (typeof unsubs === 'object' && unsubs.length) { for (let i = 0; i < unsubs.length; i += 1) { if (typeof unsubs[i] !== 'string') { stream.destroy(new Error('Invalid unsubscriptions')) return false } length += Buffer.byteLength(unsubs[i]) + 2 } } else { stream.destroy(new Error('Invalid unsubscriptions')) return false } // properies mqtt 5 let propertiesData = null if (version === 5) { propertiesData = getProperties(stream, properties) if (!propertiesData) { return false } length += propertiesData.length } // Header stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0]) // Length writeVarByteInt(stream, length) // Message ID writeNumber(stream, id) // properies mqtt 5 if (propertiesData !== null) { propertiesData.write() } // Unsubs let result = true for (let j = 0; j < unsubs.length; j++) { result = writeString(stream, unsubs[j]) } return result } function unsuback (packet, stream, opts) { const version = opts ? opts.protocolVersion : 4 const settings = packet || {} const id = settings.messageId const dup = settings.dup ? protocol.DUP_MASK : 0 const granted = settings.granted const properties = settings.properties const type = settings.cmd const qos = 0 let length = 2 // Check message ID if (typeof id !== 'number') { stream.destroy(new Error('Invalid messageId')) return false } // Check granted if (version === 5) { if (typeof granted === 'object' && granted.length) { for (let i = 0; i < granted.length; i += 1) { if (typeof granted[i] !== 'number') { stream.destroy(new Error('Invalid qos vector')) return false } length += 1 } } else { stream.destroy(new Error('Invalid qos vector')) return false } } // properies mqtt 5 let propertiesData = null if (version === 5) { propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length) if (!propertiesData) { return false } length += propertiesData.length } // Header stream.write(protocol.ACKS[type][qos][dup][0]) // Length writeVarByteInt(stream, length) // Message ID writeNumber(stream, id) // properies mqtt 5 if (propertiesData !== null) { propertiesData.write() } // payload if (version === 5) { stream.write(Buffer.from(granted)) } return true } function emptyPacket (packet, stream, opts) { return stream.write(protocol.EMPTY[packet.cmd]) } function disconnect (packet, stream, opts) { const version = opts ? opts.protocolVersion : 4 const settings = packet || {} const reasonCode = settings.reasonCode const properties = settings.properties let length = version === 5 ? 1 : 0 // properies mqtt 5 let propertiesData = null if (version === 5) { propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length) if (!propertiesData) { return false } length += propertiesData.length } // Header stream.write(Buffer.from([protocol.codes.disconnect << 4])) // Length writeVarByteInt(stream, length) // reason code in header if (version === 5) { stream.write(Buffer.from([reasonCode])) } // properies mqtt 5 if (propertiesData !== null) { propertiesData.write() } return true } function auth (packet, stream, opts) { const version = opts ? opts.protocolVersion : 4 const settings = packet || {} const reasonCode = settings.reasonCode const properties = settings.properties let length = version === 5 ? 1 : 0 if (version !== 5) stream.destroy(new Error('Invalid mqtt version for auth packet')) // properies mqtt 5 const propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length) if (!propertiesData) { return false } length += propertiesData.length // Header stream.write(Buffer.from([protocol.codes.auth << 4])) // Length writeVarByteInt(stream, length) // reason code in header stream.write(Buffer.from([reasonCode])) // properies mqtt 5 if (propertiesData !== null) { propertiesData.write() } return true } /** * writeVarByteInt - write an MQTT style variable byte integer to the buffer * * @param buffer - destination * @param pos - offset * @param length - length (>0) * @returns number of bytes written * * @api private */ const varByteIntCache = {} function writeVarByteInt (stream, num) { if (num > protocol.VARBYTEINT_MAX) { stream.destroy(new Error(`Invalid variable byte integer: ${num}`)) return false } let buffer = varByteIntCache[num] if (!buffer) { buffer = genBufVariableByteInt(num) if (num < 16384) varByteIntCache[num] = buffer } debug('writeVarByteInt: writing to stream: %o', buffer) return stream.write(buffer) } /** * writeString - write a utf8 string to the buffer * * @param buffer - destination * @param pos - offset * @param string - string to write * @return number of bytes written * * @api private */ function writeString (stream, string) { const strlen = Buffer.byteLength(string) writeNumber(stream, strlen) debug('writeString: %s', string) return stream.write(string, 'utf8') } /** * writeStringPair - write a utf8 string pairs to the buffer * * @param buffer - destination * @param name - string name to write * @param value - string value to write * @return number of bytes written * * @api private */ function writeStringPair (stream, name, value) { writeString(stream, name) writeString(stream, value) } /** * writeNumber - write a two byte number to the buffer * * @param buffer - destination * @param pos - offset * @param number - number to write * @return number of bytes written * * @api private */ function writeNumberCached (stream, number) { debug('writeNumberCached: number: %d', number) debug('writeNumberCached: %o', numCache[number]) return stream.write(numCache[number]) } function writeNumberGenerated (stream, number) { const generatedNumber = generateNumber(number) debug('writeNumberGenerated: %o', generatedNumber) return stream.write(generatedNumber) } function write4ByteNumber (stream, number) { const generated4ByteBuffer = generate4ByteBuffer(number) debug('write4ByteNumber: %o', generated4ByteBuffer) return stream.write(generated4ByteBuffer) } /** * writeStringOrBuffer - write a String or Buffer with the its length prefix * * @param buffer - destination * @param pos - offset * @param toWrite - String or Buffer * @return number of bytes written */ function writeStringOrBuffer (stream, toWrite) { if (typeof toWrite === 'string') { writeString(stream, toWrite) } else if (toWrite) { writeNumber(stream, toWrite.length) stream.write(toWrite) } else writeNumber(stream, 0) } function getProperties (stream, properties) { /* connect properties */ if (typeof properties !== 'object' || properties.length != null) { return { length: 1, write () { writeProperties(stream, {}, 0) } } } let propertiesLength = 0 function getLengthProperty (name, value) { const type = protocol.propertiesTypes[name] let length = 0 switch (type) { case 'byte': { if (typeof value !== 'boolean') { stream.destroy(new Error(`Invalid ${name}: ${value}`)) return false } length += 1 + 1 break } case 'int8': { if (typeof value !== 'number' || value < 0 || value > 0xff) { stream.destroy(new Error(`Invalid ${name}: ${value}`)) return false } length += 1 + 1 break } case 'binary': { if (value && value === null) { stream.destroy(new Error(`Invalid ${name}: ${value}`)) return false } length += 1 + Buffer.byteLength(value) + 2 break } case 'int16': { if (typeof value !== 'number' || value < 0 || value > 0xffff) { stream.destroy(new Error(`Invalid ${name}: ${value}`)) return false } length += 1 + 2 break } case 'int32': { if (typeof value !== 'number' || value < 0 || value > 0xffffffff) { stream.destroy(new Error(`Invalid ${name}: ${value}`)) return false } length += 1 + 4 break } case 'var': { // var byte integer is max 24 bits packed in 32 bits if (typeof value !== 'number' || value < 0 || value > 0x0fffffff) { stream.destroy(new Error(`Invalid ${name}: ${value}`)) return false } length += 1 + Buffer.byteLength(genBufVariableByteInt(value)) break } case 'string': { if (typeof value !== 'string') { stream.destroy(new Error(`Invalid ${name}: ${value}`)) return false } length += 1 + 2 + Buffer.byteLength(value.toString()) break } case 'pair': { if (typeof value !== 'object') { stream.destroy(new Error(`Invalid ${name}: ${value}`)) return false } length += Object.getOwnPropertyNames(value).reduce((result, name) => { const currentValue = value[name] if (Array.isArray(currentValue)) { result += currentValue.reduce((currentLength, value) => { currentLength += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value.toString()) return currentLength }, 0) } else { result += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value[name].toString()) } return result }, 0) break } default: { stream.destroy(new Error(`Invalid property ${name}: ${value}`)) return false } } return length } if (properties) { for (const propName in properties) { let propLength = 0 let propValueLength = 0 const propValue = properties[propName] if (propValue === undefined) { continue } else if (Array.isArray(propValue)) { for (let valueIndex = 0; valueIndex < propValue.length; valueIndex++) { propValueLength = getLengthProperty(propName, propValue[valueIndex]) if (!propValueLength) { return false } propLength += propValueLength } } else { propValueLength = getLengthProperty(propName, propValue) if (!propValueLength) { return false } propLength = propValueLength } if (!propLength) return false propertiesLength += propLength } } const propertiesLengthLength = Buffer.byteLength(genBufVariableByteInt(propertiesLength)) return { length: propertiesLengthLength + propertiesLength, write () { writeProperties(stream, properties, propertiesLength) } } } function getPropertiesByMaximumPacketSize (stream, properties, opts, length) { const mayEmptyProps = ['reasonString', 'userProperties'] const maximumPacketSize = opts && opts.properties && opts.properties.maximumPacketSize ? opts.properties.maximumPacketSize : 0 let propertiesData = getProperties(stream, properties) if (maximumPacketSize) { while (length + propertiesData.length > maximumPacketSize) { const currentMayEmptyProp = mayEmptyProps.shift() if (currentMayEmptyProp && properties[currentMayEmptyProp]) { delete properties[currentMayEmptyProp] propertiesData = getProperties(stream, properties) } else { return false } } } return propertiesData } function writeProperty (stream, propName, value) { const type = protocol.propertiesTypes[propName] switch (type) { case 'byte': { stream.write(Buffer.from([protocol.properties[propName]])) stream.write(Buffer.from([+value])) break } case 'int8': { stream.write(Buffer.from([protocol.properties[propName]])) stream.write(Buffer.from([value])) break } case 'binary': { stream.write(Buffer.from([protocol.properties[propName]])) writeStringOrBuffer(stream, value) break } case 'int16': { stream.write(Buffer.from([protocol.properties[propName]])) writeNumber(stream, value) break } case 'int32': { stream.write(Buffer.from([protocol.properties[propName]])) write4ByteNumber(stream, value) break } case 'var': { stream.write(Buffer.from([protocol.properties[propName]])) writeVarByteInt(stream, value) break } case 'string': { stream.write(Buffer.from([protocol.properties[propName]])) writeString(stream, value) break } case 'pair': { Object.getOwnPropertyNames(value).forEach(name => { const currentValue = value[name] if (Array.isArray(currentValue)) { currentValue.forEach(value => { stream.write(Buffer.from([protocol.properties[propName]])) writeStringPair(stream, name.toString(), value.toString()) }) } else { stream.write(Buffer.from([protocol.properties[propName]])) writeStringPair(stream, name.toString(), currentValue.toString()) } }) break } default: { stream.destroy(new Error(`Invalid property ${propName} value: ${value}`)) return false } } } function writeProperties (stream, properties, propertiesLength) { /* write properties to stream */ writeVarByteInt(stream, propertiesLength) for (const propName in properties) { if (Object.prototype.hasOwnProperty.call(properties, propName) && properties[propName] != null) { const value = properties[propName] if (Array.isArray(value)) { for (let valueIndex = 0; valueIndex < value.length; valueIndex++) { writeProperty(stream, propName, value[valueIndex]) } } else { writeProperty(stream, propName, value) } } } } function byteLength (bufOrString) { if (!bufOrString) return 0 else if (bufOrString instanceof Buffer) return bufOrString.length else return Buffer.byteLength(bufOrString) } function isStringOrBuffer (field) { return typeof field === 'string' || field instanceof Buffer } module.exports = generate /***/ }), /***/ 4825: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); const mqtt = __importStar(__nccwpck_require__(8867)); exports["default"] = mqtt; __exportStar(__nccwpck_require__(8867), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 920: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BufferedDuplex = void 0; exports.writev = writev; const readable_stream_1 = __nccwpck_require__(1657); const buffer_1 = __nccwpck_require__(181); function writev(chunks, cb) { const buffers = new Array(chunks.length); for (let i = 0; i < chunks.length; i++) { if (typeof chunks[i].chunk === 'string') { buffers[i] = buffer_1.Buffer.from(chunks[i].chunk, 'utf8'); } else { buffers[i] = chunks[i].chunk; } } this._write(buffer_1.Buffer.concat(buffers), 'binary', cb); } class BufferedDuplex extends readable_stream_1.Duplex { socket; proxy; isSocketOpen; writeQueue; constructor(opts, proxy, socket) { super({ objectMode: true, }); this.proxy = proxy; this.socket = socket; this.writeQueue = []; if (!opts.objectMode) { this._writev = writev.bind(this); } this.isSocketOpen = false; this.proxy.on('data', (chunk) => { if (!this.destroyed && this.readable) { this.push(chunk); } }); } _read(size) { this.proxy.read(size); } _write(chunk, encoding, cb) { if (!this.isSocketOpen) { this.writeQueue.push({ chunk, encoding, cb }); } else { this.writeToProxy(chunk, encoding, cb); } } _final(callback) { this.writeQueue = []; this.proxy.end(callback); } _destroy(err, callback) { this.writeQueue = []; this.proxy.destroy(); callback(err); } socketReady() { this.emit('connect'); this.isSocketOpen = true; this.processWriteQueue(); } writeToProxy(chunk, encoding, cb) { if (this.proxy.write(chunk, encoding) === false) { this.proxy.once('drain', cb); } else { cb(); } } processWriteQueue() { while (this.writeQueue.length > 0) { const { chunk, encoding, cb } = this.writeQueue.shift(); this.writeToProxy(chunk, encoding, cb); } } } exports.BufferedDuplex = BufferedDuplex; //# sourceMappingURL=BufferedDuplex.js.map /***/ }), /***/ 460: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const get_timer_1 = __importDefault(__nccwpck_require__(1617)); class KeepaliveManager { _keepalive; timerId; timer; destroyed = false; counter; client; _keepaliveTimeoutTimestamp; _intervalEvery; get keepaliveTimeoutTimestamp() { return this._keepaliveTimeoutTimestamp; } get intervalEvery() { return this._intervalEvery; } get keepalive() { return this._keepalive; } constructor(client, variant) { this.client = client; this.timer = typeof variant === 'object' && 'set' in variant && 'clear' in variant ? variant : (0, get_timer_1.default)(variant); this.setKeepalive(client.options.keepalive); } clear() { if (this.timerId) { this.timer.clear(this.timerId); this.timerId = null; } } setKeepalive(value) { value *= 1000; if (isNaN(value) || value <= 0 || value > 2147483647) { throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${value}`); } this._keepalive = value; this.reschedule(); this.client['log'](`KeepaliveManager: set keepalive to ${value}ms`); } destroy() { this.clear(); this.destroyed = true; } reschedule() { if (this.destroyed) { return; } this.clear(); this.counter = 0; const keepAliveTimeout = Math.ceil(this._keepalive * 1.5); this._keepaliveTimeoutTimestamp = Date.now() + keepAliveTimeout; this._intervalEvery = Math.ceil(this._keepalive / 2); this.timerId = this.timer.set(() => { if (this.destroyed) { return; } this.counter += 1; if (this.counter === 2) { this.client.sendPing(); } else if (this.counter > 2) { this.client.onKeepaliveTimeout(); } }, this._intervalEvery); } } exports["default"] = KeepaliveManager; //# sourceMappingURL=KeepaliveManager.js.map /***/ }), /***/ 2239: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TypedEventEmitter = void 0; const events_1 = __importDefault(__nccwpck_require__(4434)); const shared_1 = __nccwpck_require__(2324); class TypedEventEmitter { } exports.TypedEventEmitter = TypedEventEmitter; (0, shared_1.applyMixin)(TypedEventEmitter, events_1.default); //# sourceMappingURL=TypedEmitter.js.map /***/ }), /***/ 5946: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const mqtt_packet_1 = __importDefault(__nccwpck_require__(4895)); const readable_stream_1 = __nccwpck_require__(1657); const default_1 = __importDefault(__nccwpck_require__(6748)); const debug_1 = __importDefault(__nccwpck_require__(4496)); const validations = __importStar(__nccwpck_require__(6105)); const store_1 = __importDefault(__nccwpck_require__(6248)); const handlers_1 = __importDefault(__nccwpck_require__(4919)); const default_message_id_provider_1 = __importDefault(__nccwpck_require__(8718)); const topic_alias_recv_1 = __importDefault(__nccwpck_require__(700)); const shared_1 = __nccwpck_require__(2324); const TypedEmitter_1 = __nccwpck_require__(2239); const KeepaliveManager_1 = __importDefault(__nccwpck_require__(460)); const is_browser_1 = __importStar(__nccwpck_require__(0)); const setImmediate = globalThis.setImmediate || ((...args) => { const callback = args.shift(); (0, shared_1.nextTick)(() => { callback(...args); }); }); const defaultConnectOptions = { keepalive: 60, reschedulePings: true, protocolId: 'MQTT', protocolVersion: 4, reconnectPeriod: 1000, connectTimeout: 30 * 1000, clean: true, resubscribe: true, subscribeBatchSize: null, writeCache: true, timerVariant: 'auto', }; class MqttClient extends TypedEmitter_1.TypedEventEmitter { static VERSION = shared_1.MQTTJS_VERSION; connected; disconnecting; disconnected; reconnecting; incomingStore; outgoingStore; options; queueQoSZero; _reconnectCount; log; messageIdProvider; outgoing; messageIdToTopic; noop; keepaliveManager; stream; queue; streamBuilder; _resubscribeTopics; connackTimer; reconnectTimer; _storeProcessing; _packetIdsDuringStoreProcessing; _storeProcessingQueue; _firstConnection; topicAliasRecv; topicAliasSend; _deferredReconnect; connackPacket; static defaultId() { return `mqttjs_${Math.random().toString(16).substr(2, 8)}`; } constructor(streamBuilder, options) { super(); this.options = options || {}; for (const k in defaultConnectOptions) { if (typeof this.options[k] === 'undefined') { this.options[k] = defaultConnectOptions[k]; } else { this.options[k] = options[k]; } } this.log = this.options.log || (0, debug_1.default)('mqttjs:client'); this.noop = this._noop.bind(this); this.log('MqttClient :: version:', MqttClient.VERSION); if (is_browser_1.isWebWorker) { this.log('MqttClient :: environment', 'webworker'); } else { this.log('MqttClient :: environment', is_browser_1.default ? 'browser' : 'node'); } this.log('MqttClient :: options.protocol', options.protocol); this.log('MqttClient :: options.protocolVersion', options.protocolVersion); this.log('MqttClient :: options.username', options.username); this.log('MqttClient :: options.keepalive', options.keepalive); this.log('MqttClient :: options.reconnectPeriod', options.reconnectPeriod); this.log('MqttClient :: options.rejectUnauthorized', options.rejectUnauthorized); this.log('MqttClient :: options.properties.topicAliasMaximum', options.properties ? options.properties.topicAliasMaximum : undefined); this.options.clientId = typeof options.clientId === 'string' ? options.clientId : MqttClient.defaultId(); this.log('MqttClient :: clientId', this.options.clientId); this.options.customHandleAcks = options.protocolVersion === 5 && options.customHandleAcks ? options.customHandleAcks : (...args) => { args[3](null, 0); }; if (!this.options.writeCache) { mqtt_packet_1.default.writeToStream.cacheNumbers = false; } this.streamBuilder = streamBuilder; this.messageIdProvider = typeof this.options.messageIdProvider === 'undefined' ? new default_message_id_provider_1.default() : this.options.messageIdProvider; this.outgoingStore = options.outgoingStore || new store_1.default(); this.incomingStore = options.incomingStore || new store_1.default(); this.queueQoSZero = options.queueQoSZero === undefined ? true : options.queueQoSZero; this._resubscribeTopics = {}; this.messageIdToTopic = {}; this.keepaliveManager = null; this.connected = false; this.disconnecting = false; this.reconnecting = false; this.queue = []; this.connackTimer = null; this.reconnectTimer = null; this._storeProcessing = false; this._packetIdsDuringStoreProcessing = {}; this._storeProcessingQueue = []; this.outgoing = {}; this._firstConnection = true; if (options.properties && options.properties.topicAliasMaximum > 0) { if (options.properties.topicAliasMaximum > 0xffff) { this.log('MqttClient :: options.properties.topicAliasMaximum is out of range'); } else { this.topicAliasRecv = new topic_alias_recv_1.default(options.properties.topicAliasMaximum); } } this.on('connect', () => { const { queue } = this; const deliver = () => { const entry = queue.shift(); this.log('deliver :: entry %o', entry); let packet = null; if (!entry) { this._resubscribe(); return; } packet = entry.packet; this.log('deliver :: call _sendPacket for %o', packet); let send = true; if (packet.messageId && packet.messageId !== 0) { if (!this.messageIdProvider.register(packet.messageId)) { send = false; } } if (send) { this._sendPacket(packet, (err) => { if (entry.cb) { entry.cb(err); } deliver(); }); } else { this.log('messageId: %d has already used. The message is skipped and removed.', packet.messageId); deliver(); } }; this.log('connect :: sending queued packets'); deliver(); }); this.on('close', () => { this.log('close :: connected set to `false`'); this.connected = false; this.log('close :: clearing connackTimer'); clearTimeout(this.connackTimer); this._destroyKeepaliveManager(); if (this.topicAliasRecv) { this.topicAliasRecv.clear(); } this.log('close :: calling _setupReconnect'); this._setupReconnect(); }); if (!this.options.manualConnect) { this.log('MqttClient :: setting up stream'); this.connect(); } } handleAuth(packet, callback) { callback(); } handleMessage(packet, callback) { callback(); } _nextId() { return this.messageIdProvider.allocate(); } getLastMessageId() { return this.messageIdProvider.getLastAllocated(); } connect() { const writable = new readable_stream_1.Writable(); const parser = mqtt_packet_1.default.parser(this.options); let completeParse = null; const packets = []; this.log('connect :: calling method to clear reconnect'); this._clearReconnect(); if (this.disconnected && !this.reconnecting) { this.incomingStore = this.options.incomingStore || new store_1.default(); this.outgoingStore = this.options.outgoingStore || new store_1.default(); this.disconnecting = false; this.disconnected = false; } this.log('connect :: using streamBuilder provided to client to create stream'); this.stream = this.streamBuilder(this); parser.on('packet', (packet) => { this.log('parser :: on packet push to packets array.'); packets.push(packet); }); const work = () => { this.log('work :: getting next packet in queue'); const packet = packets.shift(); if (packet) { this.log('work :: packet pulled from queue'); (0, handlers_1.default)(this, packet, nextTickWork); } else { this.log('work :: no packets in queue'); const done = completeParse; completeParse = null; this.log('work :: done flag is %s', !!done); if (done) done(); } }; const nextTickWork = () => { if (packets.length) { (0, shared_1.nextTick)(work); } else { const done = completeParse; completeParse = null; done(); } }; writable._write = (buf, enc, done) => { completeParse = done; this.log('writable stream :: parsing buffer'); parser.parse(buf); work(); }; const streamErrorHandler = (error) => { this.log('streamErrorHandler :: error', error.message); if (error.code) { this.log('streamErrorHandler :: emitting error'); this.emit('error', error); } else { this.noop(error); } }; this.log('connect :: pipe stream to writable stream'); this.stream.pipe(writable); this.stream.on('error', streamErrorHandler); this.stream.on('close', () => { this.log('(%s)stream :: on close', this.options.clientId); this._flushVolatile(); this.log('stream: emit close to MqttClient'); this.emit('close'); }); this.log('connect: sending packet `connect`'); const connectPacket = { cmd: 'connect', protocolId: this.options.protocolId, protocolVersion: this.options.protocolVersion, clean: this.options.clean, clientId: this.options.clientId, keepalive: this.options.keepalive, username: this.options.username, password: this.options.password, properties: this.options.properties, }; if (this.options.will) { connectPacket.will = { ...this.options.will, payload: this.options.will?.payload, }; } if (this.topicAliasRecv) { if (!connectPacket.properties) { connectPacket.properties = {}; } if (this.topicAliasRecv) { connectPacket.properties.topicAliasMaximum = this.topicAliasRecv.max; } } this._writePacket(connectPacket); parser.on('error', this.emit.bind(this, 'error')); if (this.options.properties) { if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData) { this.end(() => this.emit('error', new Error('Packet has no Authentication Method'))); return this; } if (this.options.properties.authenticationMethod && this.options.authPacket && typeof this.options.authPacket === 'object') { const authPacket = { cmd: 'auth', reasonCode: 0, ...this.options.authPacket, }; this._writePacket(authPacket); } } this.stream.setMaxListeners(1000); clearTimeout(this.connackTimer); this.connackTimer = setTimeout(() => { this.log('!!connectTimeout hit!! Calling _cleanUp with force `true`'); this.emit('error', new Error('connack timeout')); this._cleanUp(true); }, this.options.connectTimeout); return this; } publish(topic, message, opts, callback) { this.log('publish :: message `%s` to topic `%s`', message, topic); const { options } = this; if (typeof opts === 'function') { callback = opts; opts = null; } opts = opts || {}; const defaultOpts = { qos: 0, retain: false, dup: false, }; opts = { ...defaultOpts, ...opts }; const { qos, retain, dup, properties, cbStorePut } = opts; if (this._checkDisconnecting(callback)) { return this; } const publishProc = () => { let messageId = 0; if (qos === 1 || qos === 2) { messageId = this._nextId(); if (messageId === null) { this.log('No messageId left'); return false; } } const packet = { cmd: 'publish', topic, payload: message, qos, retain, messageId, dup, }; if (options.protocolVersion === 5) { packet.properties = properties; } this.log('publish :: qos', qos); switch (qos) { case 1: case 2: this.outgoing[packet.messageId] = { volatile: false, cb: callback || this.noop, }; this.log('MqttClient:publish: packet cmd: %s', packet.cmd); this._sendPacket(packet, undefined, cbStorePut); break; default: this.log('MqttClient:publish: packet cmd: %s', packet.cmd); this._sendPacket(packet, callback, cbStorePut); break; } return true; }; if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !publishProc()) { this._storeProcessingQueue.push({ invoke: publishProc, cbStorePut: opts.cbStorePut, callback, }); } return this; } publishAsync(topic, message, opts) { return new Promise((resolve, reject) => { this.publish(topic, message, opts, (err, packet) => { if (err) { reject(err); } else { resolve(packet); } }); }); } subscribe(topicObject, opts, callback) { const version = this.options.protocolVersion; if (typeof opts === 'function') { callback = opts; } callback = callback || this.noop; let resubscribe = false; let topicsList = []; if (typeof topicObject === 'string') { topicObject = [topicObject]; topicsList = topicObject; } else if (Array.isArray(topicObject)) { topicsList = topicObject; } else if (typeof topicObject === 'object') { resubscribe = topicObject.resubscribe; delete topicObject.resubscribe; topicsList = Object.keys(topicObject); } const invalidTopic = validations.validateTopics(topicsList); if (invalidTopic !== null) { setImmediate(callback, new Error(`Invalid topic ${invalidTopic}`)); return this; } if (this._checkDisconnecting(callback)) { this.log('subscribe: discconecting true'); return this; } const defaultOpts = { qos: 0, }; if (version === 5) { defaultOpts.nl = false; defaultOpts.rap = false; defaultOpts.rh = 0; } opts = { ...defaultOpts, ...opts }; const { properties } = opts; const subs = []; const parseSub = (topic, subOptions) => { subOptions = (subOptions || opts); if (!Object.prototype.hasOwnProperty.call(this._resubscribeTopics, topic) || this._resubscribeTopics[topic].qos < subOptions.qos || resubscribe) { const currentOpts = { topic, qos: subOptions.qos, }; if (version === 5) { currentOpts.nl = subOptions.nl; currentOpts.rap = subOptions.rap; currentOpts.rh = subOptions.rh; currentOpts.properties = properties; } this.log('subscribe: pushing topic `%s` and qos `%s` to subs list', currentOpts.topic, currentOpts.qos); subs.push(currentOpts); } }; if (Array.isArray(topicObject)) { topicObject.forEach((topic) => { this.log('subscribe: array topic %s', topic); parseSub(topic); }); } else { Object.keys(topicObject).forEach((topic) => { this.log('subscribe: object topic %s, %o', topic, topicObject[topic]); parseSub(topic, topicObject[topic]); }); } if (!subs.length) { callback(null, []); return this; } const subscribeChunkedSubs = (chunkedSubs, messageId) => { const packet = { cmd: 'subscribe', subscriptions: chunkedSubs, messageId, }; if (properties) { packet.properties = properties; } if (this.options.resubscribe) { this.log('subscribe :: resubscribe true'); const topics = []; chunkedSubs.forEach((sub) => { if (this.options.reconnectPeriod > 0) { const topic = { qos: sub.qos }; if (version === 5) { topic.nl = sub.nl || false; topic.rap = sub.rap || false; topic.rh = sub.rh || 0; topic.properties = sub.properties; } this._resubscribeTopics[sub.topic] = topic; topics.push(sub.topic); } }); this.messageIdToTopic[packet.messageId] = topics; } const promise = new Promise((resolve, reject) => { this.outgoing[packet.messageId] = { volatile: true, cb(err, packet2) { if (!err) { const { granted } = packet2; for (let grantedI = 0; grantedI < granted.length; grantedI += 1) { chunkedSubs[grantedI].qos = granted[grantedI]; } } if (!err) { resolve(packet2); } else { reject(new shared_1.ErrorWithSubackPacket(err.message, packet2)); } }, }; }); this.log('subscribe :: call _sendPacket'); this._sendPacket(packet); return promise; }; const subscribeProc = () => { const batchSize = this.options.subscribeBatchSize ?? subs.length; const subscribePromises = []; for (let i = 0; i < subs.length; i += batchSize) { const chunkedSubs = subs.slice(i, i + batchSize); const messageId = this._nextId(); if (messageId === null) { this.log('No messageId left'); return false; } subscribePromises.push(subscribeChunkedSubs(chunkedSubs, messageId)); } Promise.all(subscribePromises) .then((packets) => { callback(null, subs, packets.at(-1)); }) .catch((err) => { callback(err, subs, err.packet); }); return true; }; if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !subscribeProc()) { this._storeProcessingQueue.push({ invoke: subscribeProc, callback, }); } return this; } subscribeAsync(topicObject, opts) { return new Promise((resolve, reject) => { this.subscribe(topicObject, opts, (err, granted) => { if (err) { reject(err); } else { resolve(granted); } }); }); } unsubscribe(topic, opts, callback) { if (typeof topic === 'string') { topic = [topic]; } if (typeof opts === 'function') { callback = opts; } callback = callback || this.noop; const invalidTopic = validations.validateTopics(topic); if (invalidTopic !== null) { setImmediate(callback, new Error(`Invalid topic ${invalidTopic}`)); return this; } if (this._checkDisconnecting(callback)) { return this; } const unsubscribeProc = () => { const messageId = this._nextId(); if (messageId === null) { this.log('No messageId left'); return false; } const packet = { cmd: 'unsubscribe', messageId, unsubscriptions: [], }; if (typeof topic === 'string') { packet.unsubscriptions = [topic]; } else if (Array.isArray(topic)) { packet.unsubscriptions = topic; } if (this.options.resubscribe) { packet.unsubscriptions.forEach((topic2) => { delete this._resubscribeTopics[topic2]; }); } if (typeof opts === 'object' && opts.properties) { packet.properties = opts.properties; } this.outgoing[packet.messageId] = { volatile: true, cb: callback, }; this.log('unsubscribe: call _sendPacket'); this._sendPacket(packet); return true; }; if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !unsubscribeProc()) { this._storeProcessingQueue.push({ invoke: unsubscribeProc, callback, }); } return this; } unsubscribeAsync(topic, opts) { return new Promise((resolve, reject) => { this.unsubscribe(topic, opts, (err, packet) => { if (err) { reject(err); } else { resolve(packet); } }); }); } end(force, opts, cb) { this.log('end :: (%s)', this.options.clientId); if (force == null || typeof force !== 'boolean') { cb = cb || opts; opts = force; force = false; } if (typeof opts !== 'object') { cb = cb || opts; opts = null; } this.log('end :: cb? %s', !!cb); if (!cb || typeof cb !== 'function') { cb = this.noop; } const closeStores = () => { this.log('end :: closeStores: closing incoming and outgoing stores'); this.disconnected = true; this.incomingStore.close((e1) => { this.outgoingStore.close((e2) => { this.log('end :: closeStores: emitting end'); this.emit('end'); if (cb) { const err = e1 || e2; this.log('end :: closeStores: invoking callback with args'); cb(err); } }); }); if (this._deferredReconnect) { this._deferredReconnect(); } else if (this.options.reconnectPeriod === 0 || this.options.manualConnect) { this.disconnecting = false; } }; const finish = () => { this.log('end :: (%s) :: finish :: calling _cleanUp with force %s', this.options.clientId, force); this._cleanUp(force, () => { this.log('end :: finish :: calling process.nextTick on closeStores'); (0, shared_1.nextTick)(closeStores); }, opts); }; if (this.disconnecting) { cb(); return this; } this._clearReconnect(); this.disconnecting = true; if (!force && Object.keys(this.outgoing).length > 0) { this.log('end :: (%s) :: calling finish in 10ms once outgoing is empty', this.options.clientId); this.once('outgoingEmpty', setTimeout.bind(null, finish, 10)); } else { this.log('end :: (%s) :: immediately calling finish', this.options.clientId); finish(); } return this; } endAsync(force, opts) { return new Promise((resolve, reject) => { this.end(force, opts, (err) => { if (err) { reject(err); } else { resolve(); } }); }); } removeOutgoingMessage(messageId) { if (this.outgoing[messageId]) { const { cb } = this.outgoing[messageId]; this._removeOutgoingAndStoreMessage(messageId, () => { cb(new Error('Message removed')); }); } return this; } reconnect(opts) { this.log('client reconnect'); const f = () => { if (opts) { this.options.incomingStore = opts.incomingStore; this.options.outgoingStore = opts.outgoingStore; } else { this.options.incomingStore = null; this.options.outgoingStore = null; } this.incomingStore = this.options.incomingStore || new store_1.default(); this.outgoingStore = this.options.outgoingStore || new store_1.default(); this.disconnecting = false; this.disconnected = false; this._deferredReconnect = null; this._reconnect(); }; if (this.disconnecting && !this.disconnected) { this._deferredReconnect = f; } else { f(); } return this; } _flushVolatile() { if (this.outgoing) { this.log('_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function'); Object.keys(this.outgoing).forEach((messageId) => { if (this.outgoing[messageId].volatile && typeof this.outgoing[messageId].cb === 'function') { this.outgoing[messageId].cb(new Error('Connection closed')); delete this.outgoing[messageId]; } }); } } _flush() { if (this.outgoing) { this.log('_flush: queue exists? %b', !!this.outgoing); Object.keys(this.outgoing).forEach((messageId) => { if (typeof this.outgoing[messageId].cb === 'function') { this.outgoing[messageId].cb(new Error('Connection closed')); delete this.outgoing[messageId]; } }); } } _removeTopicAliasAndRecoverTopicName(packet) { let alias; if (packet.properties) { alias = packet.properties.topicAlias; } let topic = packet.topic.toString(); this.log('_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o', alias, topic); if (topic.length === 0) { if (typeof alias === 'undefined') { return new Error('Unregistered Topic Alias'); } topic = this.topicAliasSend.getTopicByAlias(alias); if (typeof topic === 'undefined') { return new Error('Unregistered Topic Alias'); } packet.topic = topic; } if (alias) { delete packet.properties.topicAlias; } } _checkDisconnecting(callback) { if (this.disconnecting) { if (callback && callback !== this.noop) { callback(new Error('client disconnecting')); } else { this.emit('error', new Error('client disconnecting')); } } return this.disconnecting; } _reconnect() { this.log('_reconnect: emitting reconnect to client'); this.emit('reconnect'); if (this.connected) { this.end(() => { this.connect(); }); this.log('client already connected. disconnecting first.'); } else { this.log('_reconnect: calling connect'); this.connect(); } } _setupReconnect() { if (!this.disconnecting && !this.reconnectTimer && this.options.reconnectPeriod > 0) { if (!this.reconnecting) { this.log('_setupReconnect :: emit `offline` state'); this.emit('offline'); this.log('_setupReconnect :: set `reconnecting` to `true`'); this.reconnecting = true; } this.log('_setupReconnect :: setting reconnectTimer for %d ms', this.options.reconnectPeriod); this.reconnectTimer = setInterval(() => { this.log('reconnectTimer :: reconnect triggered!'); this._reconnect(); }, this.options.reconnectPeriod); } else { this.log('_setupReconnect :: doing nothing...'); } } _clearReconnect() { this.log('_clearReconnect : clearing reconnect timer'); if (this.reconnectTimer) { clearInterval(this.reconnectTimer); this.reconnectTimer = null; } } _cleanUp(forced, done, opts = {}) { if (done) { this.log('_cleanUp :: done callback provided for on stream close'); this.stream.on('close', done); } this.log('_cleanUp :: forced? %s', forced); if (forced) { if (this.options.reconnectPeriod === 0 && this.options.clean) { this._flush(); } this.log('_cleanUp :: (%s) :: destroying stream', this.options.clientId); this.stream.destroy(); } else { const packet = { cmd: 'disconnect', ...opts }; this.log('_cleanUp :: (%s) :: call _sendPacket with disconnect packet', this.options.clientId); this._sendPacket(packet, () => { this.log('_cleanUp :: (%s) :: destroying stream', this.options.clientId); setImmediate(() => { this.stream.end(() => { this.log('_cleanUp :: (%s) :: stream destroyed', this.options.clientId); }); }); }); } if (!this.disconnecting && !this.reconnecting) { this.log('_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect.'); this._clearReconnect(); this._setupReconnect(); } this._destroyKeepaliveManager(); if (done && !this.connected) { this.log('_cleanUp :: (%s) :: removing stream `done` callback `close` listener', this.options.clientId); this.stream.removeListener('close', done); done(); } } _storeAndSend(packet, cb, cbStorePut) { this.log('storeAndSend :: store packet with cmd %s to outgoingStore', packet.cmd); let storePacket = packet; let err; if (storePacket.cmd === 'publish') { storePacket = (0, default_1.default)(packet); err = this._removeTopicAliasAndRecoverTopicName(storePacket); if (err) { return cb && cb(err); } } this.outgoingStore.put(storePacket, (err2) => { if (err2) { return cb && cb(err2); } cbStorePut(); this._writePacket(packet, cb); }); } _applyTopicAlias(packet) { if (this.options.protocolVersion === 5) { if (packet.cmd === 'publish') { let alias; if (packet.properties) { alias = packet.properties.topicAlias; } const topic = packet.topic.toString(); if (this.topicAliasSend) { if (alias) { if (topic.length !== 0) { this.log('applyTopicAlias :: register topic: %s - alias: %d', topic, alias); if (!this.topicAliasSend.put(topic, alias)) { this.log('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias); return new Error('Sending Topic Alias out of range'); } } } else if (topic.length !== 0) { if (this.options.autoAssignTopicAlias) { alias = this.topicAliasSend.getAliasByTopic(topic); if (alias) { packet.topic = ''; packet.properties = { ...packet.properties, topicAlias: alias, }; this.log('applyTopicAlias :: auto assign(use) topic: %s - alias: %d', topic, alias); } else { alias = this.topicAliasSend.getLruAlias(); this.topicAliasSend.put(topic, alias); packet.properties = { ...packet.properties, topicAlias: alias, }; this.log('applyTopicAlias :: auto assign topic: %s - alias: %d', topic, alias); } } else if (this.options.autoUseTopicAlias) { alias = this.topicAliasSend.getAliasByTopic(topic); if (alias) { packet.topic = ''; packet.properties = { ...packet.properties, topicAlias: alias, }; this.log('applyTopicAlias :: auto use topic: %s - alias: %d', topic, alias); } } } } else if (alias) { this.log('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias); return new Error('Sending Topic Alias out of range'); } } } } _noop(err) { this.log('noop ::', err); } _writePacket(packet, cb) { this.log('_writePacket :: packet: %O', packet); this.log('_writePacket :: emitting `packetsend`'); this.emit('packetsend', packet); this.log('_writePacket :: writing to stream'); const result = mqtt_packet_1.default.writeToStream(packet, this.stream, this.options); this.log('_writePacket :: writeToStream result %s', result); if (!result && cb && cb !== this.noop) { this.log('_writePacket :: handle events on `drain` once through callback.'); this.stream.once('drain', cb); } else if (cb) { this.log('_writePacket :: invoking cb'); cb(); } } _sendPacket(packet, cb, cbStorePut, noStore) { this.log('_sendPacket :: (%s) :: start', this.options.clientId); cbStorePut = cbStorePut || this.noop; cb = cb || this.noop; const err = this._applyTopicAlias(packet); if (err) { cb(err); return; } if (!this.connected) { if (packet.cmd === 'auth') { this._writePacket(packet, cb); return; } this.log('_sendPacket :: client not connected. Storing packet offline.'); this._storePacket(packet, cb, cbStorePut); return; } if (noStore) { this._writePacket(packet, cb); return; } switch (packet.cmd) { case 'publish': break; case 'pubrel': this._storeAndSend(packet, cb, cbStorePut); return; default: this._writePacket(packet, cb); return; } switch (packet.qos) { case 2: case 1: this._storeAndSend(packet, cb, cbStorePut); break; case 0: default: this._writePacket(packet, cb); break; } this.log('_sendPacket :: (%s) :: end', this.options.clientId); } _storePacket(packet, cb, cbStorePut) { this.log('_storePacket :: packet: %o', packet); this.log('_storePacket :: cb? %s', !!cb); cbStorePut = cbStorePut || this.noop; let storePacket = packet; if (storePacket.cmd === 'publish') { storePacket = (0, default_1.default)(packet); const err = this._removeTopicAliasAndRecoverTopicName(storePacket); if (err) { return cb && cb(err); } } const qos = storePacket.qos || 0; if ((qos === 0 && this.queueQoSZero) || storePacket.cmd !== 'publish') { this.queue.push({ packet: storePacket, cb }); } else if (qos > 0) { cb = this.outgoing[storePacket.messageId] ? this.outgoing[storePacket.messageId].cb : null; this.outgoingStore.put(storePacket, (err) => { if (err) { return cb && cb(err); } cbStorePut(); }); } else if (cb) { cb(new Error('No connection to broker')); } } _setupKeepaliveManager() { this.log('_setupKeepaliveManager :: keepalive %d (seconds)', this.options.keepalive); if (!this.keepaliveManager && this.options.keepalive) { this.keepaliveManager = new KeepaliveManager_1.default(this, this.options.timerVariant); } } _destroyKeepaliveManager() { if (this.keepaliveManager) { this.log('_destroyKeepaliveManager :: destroying keepalive manager'); this.keepaliveManager.destroy(); this.keepaliveManager = null; } } reschedulePing(force = false) { if (this.keepaliveManager && this.options.keepalive && (force || this.options.reschedulePings)) { this._reschedulePing(); } } _reschedulePing() { this.log('_reschedulePing :: rescheduling ping'); this.keepaliveManager.reschedule(); } sendPing() { this.log('_sendPing :: sending pingreq'); this._sendPacket({ cmd: 'pingreq' }); } onKeepaliveTimeout() { this.emit('error', new Error('Keepalive timeout')); this.log('onKeepaliveTimeout :: calling _cleanUp with force true'); this._cleanUp(true); } _resubscribe() { this.log('_resubscribe'); const _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics); if (!this._firstConnection && (this.options.clean || (this.options.protocolVersion >= 4 && !this.connackPacket.sessionPresent)) && _resubscribeTopicsKeys.length > 0) { if (this.options.resubscribe) { if (this.options.protocolVersion === 5) { this.log('_resubscribe: protocolVersion 5'); for (let topicI = 0; topicI < _resubscribeTopicsKeys.length; topicI++) { const resubscribeTopic = {}; resubscribeTopic[_resubscribeTopicsKeys[topicI]] = this._resubscribeTopics[_resubscribeTopicsKeys[topicI]]; resubscribeTopic.resubscribe = true; this.subscribe(resubscribeTopic, { properties: resubscribeTopic[_resubscribeTopicsKeys[topicI]] .properties, }); } } else { this._resubscribeTopics.resubscribe = true; this.subscribe(this._resubscribeTopics); } } else { this._resubscribeTopics = {}; } } this._firstConnection = false; } _onConnect(packet) { if (this.disconnected) { this.emit('connect', packet); return; } this.connackPacket = packet; this.messageIdProvider.clear(); this._setupKeepaliveManager(); this.connected = true; const startStreamProcess = () => { let outStore = this.outgoingStore.createStream(); const remove = () => { outStore.destroy(); outStore = null; this._flushStoreProcessingQueue(); clearStoreProcessing(); }; const clearStoreProcessing = () => { this._storeProcessing = false; this._packetIdsDuringStoreProcessing = {}; }; this.once('close', remove); outStore.on('error', (err) => { clearStoreProcessing(); this._flushStoreProcessingQueue(); this.removeListener('close', remove); this.emit('error', err); }); const storeDeliver = () => { if (!outStore) { return; } const packet2 = outStore.read(1); let cb; if (!packet2) { outStore.once('readable', storeDeliver); return; } this._storeProcessing = true; if (this._packetIdsDuringStoreProcessing[packet2.messageId]) { storeDeliver(); return; } if (!this.disconnecting && !this.reconnectTimer) { cb = this.outgoing[packet2.messageId] ? this.outgoing[packet2.messageId].cb : null; this.outgoing[packet2.messageId] = { volatile: false, cb(err, status) { if (cb) { cb(err, status); } storeDeliver(); }, }; this._packetIdsDuringStoreProcessing[packet2.messageId] = true; if (this.messageIdProvider.register(packet2.messageId)) { this._sendPacket(packet2, undefined, undefined, true); } else { this.log('messageId: %d has already used.', packet2.messageId); } } else if (outStore.destroy) { outStore.destroy(); } }; outStore.on('end', () => { let allProcessed = true; for (const id in this._packetIdsDuringStoreProcessing) { if (!this._packetIdsDuringStoreProcessing[id]) { allProcessed = false; break; } } this.removeListener('close', remove); if (allProcessed) { clearStoreProcessing(); this._invokeAllStoreProcessingQueue(); this.emit('connect', packet); } else { startStreamProcess(); } }); storeDeliver(); }; startStreamProcess(); } _invokeStoreProcessingQueue() { if (!this._storeProcessing && this._storeProcessingQueue.length > 0) { const f = this._storeProcessingQueue[0]; if (f && f.invoke()) { this._storeProcessingQueue.shift(); return true; } } return false; } _invokeAllStoreProcessingQueue() { while (this._invokeStoreProcessingQueue()) { } } _flushStoreProcessingQueue() { for (const f of this._storeProcessingQueue) { if (f.cbStorePut) f.cbStorePut(new Error('Connection closed')); if (f.callback) f.callback(new Error('Connection closed')); } this._storeProcessingQueue.splice(0); } _removeOutgoingAndStoreMessage(messageId, cb) { delete this.outgoing[messageId]; this.outgoingStore.del({ messageId }, (err, packet) => { cb(err, packet); this.messageIdProvider.deallocate(messageId); this._invokeStoreProcessingQueue(); }); } } exports["default"] = MqttClient; //# sourceMappingURL=client.js.map /***/ }), /***/ 3880: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const buffer_1 = __nccwpck_require__(181); const readable_stream_1 = __nccwpck_require__(1657); const BufferedDuplex_1 = __nccwpck_require__(920); let my; let proxy; let stream; let isInitialized = false; function buildProxy() { const _proxy = new readable_stream_1.Transform(); _proxy._write = (chunk, encoding, next) => { my.sendSocketMessage({ data: chunk.buffer, success() { next(); }, fail() { next(new Error()); }, }); }; _proxy._flush = (done) => { my.closeSocket({ success() { done(); }, }); }; return _proxy; } function setDefaultOpts(opts) { if (!opts.hostname) { opts.hostname = 'localhost'; } if (!opts.path) { opts.path = '/'; } if (!opts.wsOptions) { opts.wsOptions = {}; } } function buildUrl(opts, client) { const protocol = opts.protocol === 'alis' ? 'wss' : 'ws'; let url = `${protocol}://${opts.hostname}${opts.path}`; if (opts.port && opts.port !== 80 && opts.port !== 443) { url = `${protocol}://${opts.hostname}:${opts.port}${opts.path}`; } if (typeof opts.transformWsUrl === 'function') { url = opts.transformWsUrl(url, opts, client); } return url; } function bindEventHandler() { if (isInitialized) return; isInitialized = true; my.onSocketOpen(() => { stream.socketReady(); }); my.onSocketMessage((res) => { if (typeof res.data === 'string') { const buffer = buffer_1.Buffer.from(res.data, 'base64'); proxy.push(buffer); } else { const reader = new FileReader(); reader.addEventListener('load', () => { if (reader.result instanceof ArrayBuffer) { proxy.push(buffer_1.Buffer.from(reader.result)); return; } proxy.push(buffer_1.Buffer.from(reader.result, 'utf-8')); }); reader.readAsArrayBuffer(res.data); } }); my.onSocketClose(() => { stream.end(); stream.destroy(); }); my.onSocketError((err) => { stream.destroy(err); }); } const buildStream = (client, opts) => { opts.hostname = opts.hostname || opts.host; if (!opts.hostname) { throw new Error('Could not determine host. Specify host manually.'); } const websocketSubProtocol = opts.protocolId === 'MQIsdp' && opts.protocolVersion === 3 ? 'mqttv3.1' : 'mqtt'; setDefaultOpts(opts); const url = buildUrl(opts, client); my = opts.my; my.connectSocket({ url, protocols: websocketSubProtocol, }); proxy = buildProxy(); stream = new BufferedDuplex_1.BufferedDuplex(opts, proxy, my); bindEventHandler(); return stream; }; exports.A = buildStream; //# sourceMappingURL=ali.js.map /***/ }), /***/ 936: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.connectAsync = connectAsync; const debug_1 = __importDefault(__nccwpck_require__(4496)); const url_1 = __importDefault(__nccwpck_require__(7016)); const client_1 = __importDefault(__nccwpck_require__(5946)); const is_browser_1 = __importDefault(__nccwpck_require__(0)); if (typeof process?.nextTick !== 'function') { process.nextTick = setImmediate; } const debug = (0, debug_1.default)('mqttjs'); let protocols = null; function parseAuthOptions(opts) { let matches; if (opts.auth) { matches = opts.auth.match(/^(.+):(.+)$/); if (matches) { const [, username, password] = matches; opts.username = username; opts.password = password; } else { opts.username = opts.auth; } } } function connect(brokerUrl, opts) { debug('connecting to an MQTT broker...'); if (typeof brokerUrl === 'object' && !opts) { opts = brokerUrl; brokerUrl = ''; } opts = opts || {}; if (brokerUrl && typeof brokerUrl === 'string') { const parsedUrl = url_1.default.parse(brokerUrl, true); const parsedOptions = {}; if (parsedUrl.port != null) { parsedOptions.port = Number(parsedUrl.port); } parsedOptions.host = parsedUrl.hostname; parsedOptions.query = parsedUrl.query; parsedOptions.auth = parsedUrl.auth; parsedOptions.protocol = parsedUrl.protocol; parsedOptions.path = parsedUrl.path; opts = { ...parsedOptions, ...opts }; if (!opts.protocol) { throw new Error('Missing protocol'); } opts.protocol = opts.protocol.replace(/:$/, ''); } opts.unixSocket = opts.unixSocket || opts.protocol?.includes('+unix'); if (opts.unixSocket) { opts.protocol = opts.protocol.replace('+unix', ''); } else if (!opts.protocol?.startsWith('ws') && !opts.protocol?.startsWith('wx')) { delete opts.path; } parseAuthOptions(opts); if (opts.query && typeof opts.query.clientId === 'string') { opts.clientId = opts.query.clientId; } if (is_browser_1.default || opts.unixSocket) { opts.socksProxy = undefined; } else if (opts.socksProxy === undefined && typeof process !== 'undefined') { opts.socksProxy = process.env['MQTTJS_SOCKS_PROXY']; } if (opts.cert && opts.key) { if (opts.protocol) { if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) { switch (opts.protocol) { case 'mqtt': opts.protocol = 'mqtts'; break; case 'ws': opts.protocol = 'wss'; break; case 'wx': opts.protocol = 'wxs'; break; case 'ali': opts.protocol = 'alis'; break; default: throw new Error(`Unknown protocol for secure connection: "${opts.protocol}"!`); } } } else { throw new Error('Missing secure protocol key'); } } if (!protocols) { protocols = {}; if (!is_browser_1.default && !opts.forceNativeWebSocket) { protocols.ws = (__nccwpck_require__(5852).streamBuilder); protocols.wss = (__nccwpck_require__(5852).streamBuilder); protocols.mqtt = (__nccwpck_require__(5335)["default"]); protocols.tcp = (__nccwpck_require__(5335)["default"]); protocols.ssl = (__nccwpck_require__(8541)["default"]); protocols.tls = protocols.ssl; protocols.mqtts = (__nccwpck_require__(8541)["default"]); } else { protocols.ws = (__nccwpck_require__(5852).browserStreamBuilder); protocols.wss = (__nccwpck_require__(5852).browserStreamBuilder); protocols.wx = (__nccwpck_require__(6829)/* ["default"] */ .A); protocols.wxs = (__nccwpck_require__(6829)/* ["default"] */ .A); protocols.ali = (__nccwpck_require__(3880)/* ["default"] */ .A); protocols.alis = (__nccwpck_require__(3880)/* ["default"] */ .A); } } if (!protocols[opts.protocol]) { const isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1; opts.protocol = [ 'mqtt', 'mqtts', 'ws', 'wss', 'wx', 'wxs', 'ali', 'alis', ].filter((key, index) => { if (isSecure && index % 2 === 0) { return false; } return typeof protocols[key] === 'function'; })[0]; } if (opts.clean === false && !opts.clientId) { throw new Error('Missing clientId for unclean clients'); } if (opts.protocol) { opts.defaultProtocol = opts.protocol; } function wrapper(client) { if (opts.servers) { if (!client._reconnectCount || client._reconnectCount === opts.servers.length) { client._reconnectCount = 0; } opts.host = opts.servers[client._reconnectCount].host; opts.port = opts.servers[client._reconnectCount].port; opts.protocol = !opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol; opts.hostname = opts.host; client._reconnectCount++; } debug('calling streambuilder for', opts.protocol); return protocols[opts.protocol](client, opts); } const client = new client_1.default(wrapper, opts); client.on('error', () => { }); return client; } function connectAsync(brokerUrl, opts, allowRetries = true) { return new Promise((resolve, reject) => { const client = connect(brokerUrl, opts); const promiseResolutionListeners = { connect: (connack) => { removePromiseResolutionListeners(); resolve(client); }, end: () => { removePromiseResolutionListeners(); resolve(client); }, error: (err) => { removePromiseResolutionListeners(); client.end(); reject(err); }, }; if (allowRetries === false) { promiseResolutionListeners.close = () => { promiseResolutionListeners.error(new Error("Couldn't connect to server")); }; } function removePromiseResolutionListeners() { Object.keys(promiseResolutionListeners).forEach((eventName) => { client.off(eventName, promiseResolutionListeners[eventName]); }); } Object.keys(promiseResolutionListeners).forEach((eventName) => { client.on(eventName, promiseResolutionListeners[eventName]); }); }); } exports["default"] = connect; //# sourceMappingURL=index.js.map /***/ }), /***/ 6141: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = openSocks; const debug_1 = __importDefault(__nccwpck_require__(4496)); const stream_1 = __nccwpck_require__(2203); const socks_1 = __nccwpck_require__(2474); const dns = __importStar(__nccwpck_require__(2250)); const util_1 = __nccwpck_require__(9023); const assert_1 = __importDefault(__nccwpck_require__(2613)); const debug = (0, debug_1.default)('mqttjs:socks'); class ProxyStream extends stream_1.Duplex { _flowing = false; _socket; constructor() { super({ autoDestroy: false }); this.cork(); } _start(socket) { debug('proxy stream started'); (0, assert_1.default)(!this._socket); if (this.destroyed) { socket.destroy(this.errored); return; } this._socket = socket; if (!this._flowing) socket.pause(); socket.on('data', this._onData); socket.on('end', this._onEnd); socket.on('error', this._onError); socket.on('close', this._onClose); socket.emit('connect'); this.uncork(); } _write(chunk, encoding, callback) { (0, assert_1.default)(this._socket); this._socket.write(chunk, callback); } _read(size) { this._flowing = true; this._socket?.resume?.(); } _destroy(error, callback) { this._socket?.destroy?.(error); callback(error); } _onData = (chunk) => { (0, assert_1.default)(this._socket); this._flowing = this.push(chunk); if (!this._flowing) this._socket.pause(); }; _onEnd = () => { debug('proxy stream received EOF'); this.push(null); }; _onClose = () => { debug('proxy stream closed'); this.destroy(); }; _onError = (err) => { debug('proxy stream died with error %s', err); this.destroy(err); }; } function fatal(e) { try { if (e.code === undefined) e.code = 'SOCKS'; return e; } catch { return e; } } function typeFromProtocol(proto) { switch (proto) { case 'socks5h:': return [5, true]; case 'socks4a:': return [4, true]; case 'socks5:': return [5, false]; case 'socks4:': return [4, false]; default: return [undefined, false]; } } function parseSocksUrl(url) { const parsedUrl = new URL(url); if (parsedUrl.pathname || parsedUrl.hash || parsedUrl.search) { throw fatal(new Error('bad SOCKS URL')); } const [type, resolveThroughProxy] = typeFromProtocol(parsedUrl.protocol); if (!type) { throw fatal(new Error('bad SOCKS URL: invalid protocol')); } const port = parseInt(parsedUrl.port, 10); if (Number.isNaN(port)) { throw fatal(new Error('bad SOCKS URL: invalid port')); } const proxy = { host: parsedUrl.hostname, port, type, }; return [proxy, resolveThroughProxy]; } async function connectSocks(destinationHost, destinationPort, socksUrl, stream, options = {}) { const lookup = options.lookup ?? (0, util_1.promisify)(dns.lookup); const [proxy, resolveThroughProxy] = parseSocksUrl(socksUrl); if (!resolveThroughProxy) { debug('resolving %s locally', destinationHost); destinationHost = (await lookup(destinationHost, { family: proxy.type === 4 ? 4 : 0, })).address; } debug('establishing SOCKS%d connection to %s:%d via %s:%d', proxy.type, destinationHost, destinationPort, proxy.host, proxy.port); const socksClient = new socks_1.SocksClient({ command: 'connect', destination: { host: destinationHost, port: destinationPort, }, proxy: { ...proxy }, timeout: options.timeout, }); socksClient.connect(); socksClient.on('established', ({ socket }) => stream._start(socket)); socksClient.on('error', (e) => { debug('SOCKS failed: %s', e); stream.destroy(fatal(e)); }); } function openSocks(destinationHost, destinationPort, socksUrl, options) { debug('SOCKS connection to %s:%d via %s', destinationHost, destinationPort, socksUrl); const stream = new ProxyStream(); connectSocks(destinationHost, destinationPort, socksUrl, stream, options).catch((e) => { debug('SOCKS failed: %s', e); stream.destroy(e); }); return stream; } //# sourceMappingURL=socks.js.map /***/ }), /***/ 5335: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const net_1 = __importDefault(__nccwpck_require__(9278)); const debug_1 = __importDefault(__nccwpck_require__(4496)); const socks_1 = __importDefault(__nccwpck_require__(6141)); const debug = (0, debug_1.default)('mqttjs:tcp'); const buildStream = (client, opts) => { opts.port = opts.port || 1883; opts.hostname = opts.hostname || opts.host || 'localhost'; if (opts.socksProxy) { return (0, socks_1.default)(opts.hostname, opts.port, opts.socksProxy, { timeout: opts.socksTimeout, }); } const { port, path } = opts; const host = opts.hostname; debug('port %d and host %s', port, host); return net_1.default.createConnection({ port, host, path }); }; exports["default"] = buildStream; //# sourceMappingURL=tcp.js.map /***/ }), /***/ 8541: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const tls_1 = __nccwpck_require__(4756); const net_1 = __importDefault(__nccwpck_require__(9278)); const debug_1 = __importDefault(__nccwpck_require__(4496)); const socks_1 = __importDefault(__nccwpck_require__(6141)); const debug = (0, debug_1.default)('mqttjs:tls'); function connect(opts) { const { host, port, socksProxy, ...rest } = opts; if (socksProxy !== undefined) { const socket = (0, socks_1.default)(host, port, socksProxy, { timeout: opts.socksTimeout, }); return (0, tls_1.connect)({ ...rest, socket, }); } return (0, tls_1.connect)(opts); } const buildStream = (client, opts) => { opts.port = opts.port || 8883; opts.host = opts.hostname || opts.host || 'localhost'; if (net_1.default.isIP(opts.host) === 0) { opts.servername = opts.host; } opts.rejectUnauthorized = opts.rejectUnauthorized !== false; delete opts.path; debug('port %d host %s rejectUnauthorized %b', opts.port, opts.host, opts.rejectUnauthorized); const connection = connect(opts); connection.on('secureConnect', () => { if (opts.rejectUnauthorized && !connection.authorized) { connection.emit('error', new Error('TLS not authorized')); } else { connection.removeListener('error', handleTLSerrors); } }); function handleTLSerrors(err) { if (opts.rejectUnauthorized) { client.emit('error', err); } connection.end(); } connection.on('error', handleTLSerrors); return connection; }; exports["default"] = buildStream; //# sourceMappingURL=tls.js.map /***/ }), /***/ 5852: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.streamBuilder = exports.browserStreamBuilder = void 0; const buffer_1 = __nccwpck_require__(181); const ws_1 = __importDefault(__nccwpck_require__(1354)); const debug_1 = __importDefault(__nccwpck_require__(4496)); const readable_stream_1 = __nccwpck_require__(1657); const is_browser_1 = __importDefault(__nccwpck_require__(0)); const BufferedDuplex_1 = __nccwpck_require__(920); const debug = (0, debug_1.default)('mqttjs:ws'); const WSS_OPTIONS = [ 'rejectUnauthorized', 'ca', 'cert', 'key', 'pfx', 'passphrase', ]; function buildUrl(opts, client) { let url = `${opts.protocol}://${opts.hostname}:${opts.port}${opts.path}`; if (typeof opts.transformWsUrl === 'function') { url = opts.transformWsUrl(url, opts, client); } return url; } function setDefaultOpts(opts) { const options = opts; if (!opts.port) { if (opts.protocol === 'wss') { options.port = 443; } else { options.port = 80; } } if (!opts.path) { options.path = '/'; } if (!opts.wsOptions) { options.wsOptions = {}; } if (!is_browser_1.default && !opts.forceNativeWebSocket && opts.protocol === 'wss') { WSS_OPTIONS.forEach((prop) => { if (Object.prototype.hasOwnProperty.call(opts, prop) && !Object.prototype.hasOwnProperty.call(opts.wsOptions, prop)) { options.wsOptions[prop] = opts[prop]; } }); } return options; } function setDefaultBrowserOpts(opts) { const options = setDefaultOpts(opts); if (!options.hostname) { options.hostname = options.host; } if (!options.hostname) { if (typeof document === 'undefined') { throw new Error('Could not determine host. Specify host manually.'); } const parsed = new URL(document.URL); options.hostname = parsed.hostname; if (!options.port) { options.port = Number(parsed.port); } } if (options.objectMode === undefined) { options.objectMode = !(options.binary === true || options.binary === undefined); } return options; } function createWebSocket(client, url, opts) { debug('createWebSocket'); debug(`protocol: ${opts.protocolId} ${opts.protocolVersion}`); const websocketSubProtocol = opts.protocolId === 'MQIsdp' && opts.protocolVersion === 3 ? 'mqttv3.1' : 'mqtt'; debug(`creating new Websocket for url: ${url} and protocol: ${websocketSubProtocol}`); let socket; if (opts.createWebsocket) { socket = opts.createWebsocket(url, [websocketSubProtocol], opts); } else { socket = new ws_1.default(url, [websocketSubProtocol], opts.wsOptions); } return socket; } function createBrowserWebSocket(client, opts) { const websocketSubProtocol = opts.protocolId === 'MQIsdp' && opts.protocolVersion === 3 ? 'mqttv3.1' : 'mqtt'; const url = buildUrl(opts, client); let socket; if (opts.createWebsocket) { socket = opts.createWebsocket(url, [websocketSubProtocol], opts); } else { socket = new WebSocket(url, [websocketSubProtocol]); } socket.binaryType = 'arraybuffer'; return socket; } const streamBuilder = (client, opts) => { debug('streamBuilder'); const options = setDefaultOpts(opts); options.hostname = options.hostname || options.host || 'localhost'; const url = buildUrl(options, client); const socket = createWebSocket(client, url, options); const webSocketStream = ws_1.default.createWebSocketStream(socket, options.wsOptions); webSocketStream['url'] = url; socket.on('close', () => { webSocketStream.destroy(); }); return webSocketStream; }; exports.streamBuilder = streamBuilder; const browserStreamBuilder = (client, opts) => { debug('browserStreamBuilder'); let stream; const options = setDefaultBrowserOpts(opts); const bufferSize = options.browserBufferSize || 1024 * 512; const bufferTimeout = opts.browserBufferTimeout || 1000; const coerceToBuffer = !opts.objectMode; const socket = createBrowserWebSocket(client, opts); const proxy = buildProxy(opts, socketWriteBrowser, socketEndBrowser); if (!opts.objectMode) { proxy._writev = BufferedDuplex_1.writev.bind(proxy); } proxy.on('close', () => { socket.close(); }); const eventListenerSupport = typeof socket.addEventListener !== 'undefined'; if (socket.readyState === socket.OPEN) { stream = proxy; stream.socket = socket; } else { stream = new BufferedDuplex_1.BufferedDuplex(opts, proxy, socket); if (eventListenerSupport) { socket.addEventListener('open', onOpen); } else { socket.onopen = onOpen; } } if (eventListenerSupport) { socket.addEventListener('close', onClose); socket.addEventListener('error', onError); socket.addEventListener('message', onMessage); } else { socket.onclose = onClose; socket.onerror = onError; socket.onmessage = onMessage; } function buildProxy(pOptions, socketWrite, socketEnd) { const _proxy = new readable_stream_1.Transform({ objectMode: pOptions.objectMode, }); _proxy._write = socketWrite; _proxy._flush = socketEnd; return _proxy; } function onOpen() { debug('WebSocket onOpen'); if (stream instanceof BufferedDuplex_1.BufferedDuplex) { stream.socketReady(); } } function onClose(event) { debug('WebSocket onClose', event); stream.end(); stream.destroy(); } function onError(err) { debug('WebSocket onError', err); const error = new Error('WebSocket error'); error['event'] = err; stream.destroy(error); } async function onMessage(event) { if (!proxy || !proxy.readable || !proxy.writable) { return; } let { data } = event; if (data instanceof ArrayBuffer) data = buffer_1.Buffer.from(data); else if (data instanceof Blob) data = buffer_1.Buffer.from(await new Response(data).arrayBuffer()); else data = buffer_1.Buffer.from(data, 'utf8'); proxy.push(data); } function socketWriteBrowser(chunk, enc, next) { if (socket.bufferedAmount > bufferSize) { setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next); return; } if (coerceToBuffer && typeof chunk === 'string') { chunk = buffer_1.Buffer.from(chunk, 'utf8'); } try { socket.send(chunk); } catch (err) { return next(err); } next(); } function socketEndBrowser(done) { socket.close(); done(); } return stream; }; exports.browserStreamBuilder = browserStreamBuilder; //# sourceMappingURL=ws.js.map /***/ }), /***/ 6829: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); const buffer_1 = __nccwpck_require__(181); const readable_stream_1 = __nccwpck_require__(1657); const BufferedDuplex_1 = __nccwpck_require__(920); let socketTask; let proxy; let stream; function buildProxy() { const _proxy = new readable_stream_1.Transform(); _proxy._write = (chunk, encoding, next) => { socketTask.send({ data: chunk.buffer, success() { next(); }, fail(errMsg) { next(new Error(errMsg)); }, }); }; _proxy._flush = (done) => { socketTask.close({ success() { done(); }, }); }; return _proxy; } function setDefaultOpts(opts) { if (!opts.hostname) { opts.hostname = 'localhost'; } if (!opts.path) { opts.path = '/'; } if (!opts.wsOptions) { opts.wsOptions = {}; } } function buildUrl(opts, client) { const protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'; let url = `${protocol}://${opts.hostname}${opts.path}`; if (opts.port && opts.port !== 80 && opts.port !== 443) { url = `${protocol}://${opts.hostname}:${opts.port}${opts.path}`; } if (typeof opts.transformWsUrl === 'function') { url = opts.transformWsUrl(url, opts, client); } return url; } function bindEventHandler() { socketTask.onOpen(() => { stream.socketReady(); }); socketTask.onMessage((res) => { let { data } = res; if (data instanceof ArrayBuffer) data = buffer_1.Buffer.from(data); else data = buffer_1.Buffer.from(data, 'utf8'); proxy.push(data); }); socketTask.onClose(() => { stream.emit('close'); stream.end(); stream.destroy(); }); socketTask.onError((error) => { const err = new Error(error.errMsg); stream.destroy(err); }); } const buildStream = (client, opts) => { opts.hostname = opts.hostname || opts.host; if (!opts.hostname) { throw new Error('Could not determine host. Specify host manually.'); } const websocketSubProtocol = opts.protocolId === 'MQIsdp' && opts.protocolVersion === 3 ? 'mqttv3.1' : 'mqtt'; setDefaultOpts(opts); const url = buildUrl(opts, client); socketTask = wx.connectSocket({ url, protocols: [websocketSubProtocol], }); proxy = buildProxy(); stream = new BufferedDuplex_1.BufferedDuplex(opts, proxy, socketTask); stream._destroy = (err, cb) => { socketTask.close({ success() { if (cb) cb(err); }, }); }; const destroyRef = stream.destroy; stream.destroy = (err, cb) => { stream.destroy = destroyRef; setTimeout(() => { socketTask.close({ fail() { stream._destroy(err, cb); }, }); }, 0); return stream; }; bindEventHandler(); return stream; }; exports.A = buildStream; //# sourceMappingURL=wx.js.map /***/ }), /***/ 8718: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class DefaultMessageIdProvider { nextId; constructor() { this.nextId = Math.max(1, Math.floor(Math.random() * 65535)); } allocate() { const id = this.nextId++; if (this.nextId === 65536) { this.nextId = 1; } return id; } getLastAllocated() { return this.nextId === 1 ? 65535 : this.nextId - 1; } register(messageId) { return true; } deallocate(messageId) { } clear() { } } exports["default"] = DefaultMessageIdProvider; //# sourceMappingURL=default-message-id-provider.js.map /***/ }), /***/ 1617: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", ({ value: true })); const worker_timers_1 = __nccwpck_require__(4886); const is_browser_1 = __importStar(__nccwpck_require__(0)); const workerTimer = { set: worker_timers_1.setInterval, clear: worker_timers_1.clearInterval, }; const nativeTimer = { set: (func, time) => setInterval(func, time), clear: (timerId) => clearInterval(timerId), }; const getTimer = (variant) => { switch (variant) { case 'native': { return nativeTimer; } case 'worker': { return workerTimer; } case 'auto': default: { return is_browser_1.default && !is_browser_1.isWebWorker && !is_browser_1.isReactNativeBrowser ? workerTimer : nativeTimer; } } }; exports["default"] = getTimer; //# sourceMappingURL=get-timer.js.map /***/ }), /***/ 2686: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReasonCodes = void 0; const shared_1 = __nccwpck_require__(2324); exports.ReasonCodes = { 0: '', 1: 'Unacceptable protocol version', 2: 'Identifier rejected', 3: 'Server unavailable', 4: 'Bad username or password', 5: 'Not authorized', 16: 'No matching subscribers', 17: 'No subscription existed', 128: 'Unspecified error', 129: 'Malformed Packet', 130: 'Protocol Error', 131: 'Implementation specific error', 132: 'Unsupported Protocol Version', 133: 'Client Identifier not valid', 134: 'Bad User Name or Password', 135: 'Not authorized', 136: 'Server unavailable', 137: 'Server busy', 138: 'Banned', 139: 'Server shutting down', 140: 'Bad authentication method', 141: 'Keep Alive timeout', 142: 'Session taken over', 143: 'Topic Filter invalid', 144: 'Topic Name invalid', 145: 'Packet identifier in use', 146: 'Packet Identifier not found', 147: 'Receive Maximum exceeded', 148: 'Topic Alias invalid', 149: 'Packet too large', 150: 'Message rate too high', 151: 'Quota exceeded', 152: 'Administrative action', 153: 'Payload format invalid', 154: 'Retain not supported', 155: 'QoS not supported', 156: 'Use another server', 157: 'Server moved', 158: 'Shared Subscriptions not supported', 159: 'Connection rate exceeded', 160: 'Maximum connect time', 161: 'Subscription Identifiers not supported', 162: 'Wildcard Subscriptions not supported', }; const handleAck = (client, packet) => { const { messageId } = packet; const type = packet.cmd; let response = null; const cb = client.outgoing[messageId] ? client.outgoing[messageId].cb : null; let err = null; if (!cb) { client.log('_handleAck :: Server sent an ack in error. Ignoring.'); return; } client.log('_handleAck :: packet type', type); switch (type) { case 'pubcomp': case 'puback': { const pubackRC = packet.reasonCode; if (pubackRC && pubackRC > 0 && pubackRC !== 16) { err = new shared_1.ErrorWithReasonCode(`Publish error: ${exports.ReasonCodes[pubackRC]}`, pubackRC); client['_removeOutgoingAndStoreMessage'](messageId, () => { cb(err, packet); }); } else { client['_removeOutgoingAndStoreMessage'](messageId, cb); } break; } case 'pubrec': { response = { cmd: 'pubrel', qos: 2, messageId, }; const pubrecRC = packet.reasonCode; if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) { err = new shared_1.ErrorWithReasonCode(`Publish error: ${exports.ReasonCodes[pubrecRC]}`, pubrecRC); client['_removeOutgoingAndStoreMessage'](messageId, () => { cb(err, packet); }); } else { client['_sendPacket'](response); } break; } case 'suback': { delete client.outgoing[messageId]; client.messageIdProvider.deallocate(messageId); const granted = packet.granted; for (let grantedI = 0; grantedI < granted.length; grantedI++) { const subackRC = granted[grantedI]; if ((subackRC & 0x80) !== 0) { err = new Error(`Subscribe error: ${exports.ReasonCodes[subackRC]}`); err.code = subackRC; const topics = client.messageIdToTopic[messageId]; if (topics) { topics.forEach((topic) => { delete client['_resubscribeTopics'][topic]; }); } } } delete client.messageIdToTopic[messageId]; client['_invokeStoreProcessingQueue'](); cb(err, packet); break; } case 'unsuback': { delete client.outgoing[messageId]; client.messageIdProvider.deallocate(messageId); client['_invokeStoreProcessingQueue'](); cb(null, packet); break; } default: client.emit('error', new Error('unrecognized packet type')); } if (client.disconnecting && Object.keys(client.outgoing).length === 0) { client.emit('outgoingEmpty'); } }; exports["default"] = handleAck; //# sourceMappingURL=ack.js.map /***/ }), /***/ 3549: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const shared_1 = __nccwpck_require__(2324); const ack_1 = __nccwpck_require__(2686); const handleAuth = (client, packet) => { const { options } = client; const version = options.protocolVersion; const rc = version === 5 ? packet.reasonCode : packet.returnCode; if (version !== 5) { const err = new shared_1.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${version}`, rc); client.emit('error', err); return; } client.handleAuth(packet, (err, packet2) => { if (err) { client.emit('error', err); return; } if (rc === 24) { client.reconnecting = false; client['_sendPacket'](packet2); } else { const error = new shared_1.ErrorWithReasonCode(`Connection refused: ${ack_1.ReasonCodes[rc]}`, rc); client.emit('error', error); } }); }; exports["default"] = handleAuth; //# sourceMappingURL=auth.js.map /***/ }), /***/ 9772: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const ack_1 = __nccwpck_require__(2686); const topic_alias_send_1 = __importDefault(__nccwpck_require__(222)); const shared_1 = __nccwpck_require__(2324); const handleConnack = (client, packet) => { client.log('_handleConnack'); const { options } = client; const version = options.protocolVersion; const rc = version === 5 ? packet.reasonCode : packet.returnCode; clearTimeout(client['connackTimer']); delete client['topicAliasSend']; if (packet.properties) { if (packet.properties.topicAliasMaximum) { if (packet.properties.topicAliasMaximum > 0xffff) { client.emit('error', new Error('topicAliasMaximum from broker is out of range')); return; } if (packet.properties.topicAliasMaximum > 0) { client['topicAliasSend'] = new topic_alias_send_1.default(packet.properties.topicAliasMaximum); } } if (packet.properties.serverKeepAlive && options.keepalive) { options.keepalive = packet.properties.serverKeepAlive; } if (packet.properties.maximumPacketSize) { if (!options.properties) { options.properties = {}; } options.properties.maximumPacketSize = packet.properties.maximumPacketSize; } } if (rc === 0) { client.reconnecting = false; client['_onConnect'](packet); } else if (rc > 0) { const err = new shared_1.ErrorWithReasonCode(`Connection refused: ${ack_1.ReasonCodes[rc]}`, rc); client.emit('error', err); if (client.options.reconnectOnConnackError) { client['_cleanUp'](true); } } }; exports["default"] = handleConnack; //# sourceMappingURL=connack.js.map /***/ }), /***/ 4919: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const publish_1 = __importDefault(__nccwpck_require__(1460)); const auth_1 = __importDefault(__nccwpck_require__(3549)); const connack_1 = __importDefault(__nccwpck_require__(9772)); const ack_1 = __importDefault(__nccwpck_require__(2686)); const pubrel_1 = __importDefault(__nccwpck_require__(8181)); const handle = (client, packet, done) => { const { options } = client; if (options.protocolVersion === 5 && options.properties && options.properties.maximumPacketSize && options.properties.maximumPacketSize < packet.length) { client.emit('error', new Error(`exceeding packets size ${packet.cmd}`)); client.end({ reasonCode: 149, properties: { reasonString: 'Maximum packet size was exceeded' }, }); return client; } client.log('_handlePacket :: emitting packetreceive'); client.emit('packetreceive', packet); switch (packet.cmd) { case 'publish': (0, publish_1.default)(client, packet, done); break; case 'puback': case 'pubrec': case 'pubcomp': case 'suback': case 'unsuback': client.reschedulePing(); (0, ack_1.default)(client, packet); done(); break; case 'pubrel': client.reschedulePing(); (0, pubrel_1.default)(client, packet, done); break; case 'connack': (0, connack_1.default)(client, packet); done(); break; case 'auth': client.reschedulePing(); (0, auth_1.default)(client, packet); done(); break; case 'pingresp': client.log('_handlePacket :: received pingresp'); client.reschedulePing(true); done(); break; case 'disconnect': client.emit('disconnect', packet); done(); break; default: client.log('_handlePacket :: unknown command'); done(); break; } }; exports["default"] = handle; //# sourceMappingURL=index.js.map /***/ }), /***/ 1460: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]; const handlePublish = (client, packet, done) => { client.log('handlePublish: packet %o', packet); done = typeof done !== 'undefined' ? done : client.noop; let topic = packet.topic.toString(); const message = packet.payload; const { qos } = packet; const { messageId } = packet; const { options } = client; if (client.options.protocolVersion === 5) { let alias; if (packet.properties) { alias = packet.properties.topicAlias; } if (typeof alias !== 'undefined') { if (topic.length === 0) { if (alias > 0 && alias <= 0xffff) { const gotTopic = client['topicAliasRecv'].getTopicByAlias(alias); if (gotTopic) { topic = gotTopic; client.log('handlePublish :: topic complemented by alias. topic: %s - alias: %d', topic, alias); } else { client.log('handlePublish :: unregistered topic alias. alias: %d', alias); client.emit('error', new Error('Received unregistered Topic Alias')); return; } } else { client.log('handlePublish :: topic alias out of range. alias: %d', alias); client.emit('error', new Error('Received Topic Alias is out of range')); return; } } else if (client['topicAliasRecv'].put(topic, alias)) { client.log('handlePublish :: registered topic: %s - alias: %d', topic, alias); } else { client.log('handlePublish :: topic alias out of range. alias: %d', alias); client.emit('error', new Error('Received Topic Alias is out of range')); return; } } } client.log('handlePublish: qos %d', qos); switch (qos) { case 2: { options.customHandleAcks(topic, message, packet, (error, code) => { if (typeof error === 'number') { code = error; error = null; } if (error) { return client.emit('error', error); } if (validReasonCodes.indexOf(code) === -1) { return client.emit('error', new Error('Wrong reason code for pubrec')); } if (code) { client['_sendPacket']({ cmd: 'pubrec', messageId, reasonCode: code }, done); } else { client.incomingStore.put(packet, () => { client['_sendPacket']({ cmd: 'pubrec', messageId }, done); }); } }); break; } case 1: { options.customHandleAcks(topic, message, packet, (error, code) => { if (typeof error === 'number') { code = error; error = null; } if (error) { return client.emit('error', error); } if (validReasonCodes.indexOf(code) === -1) { return client.emit('error', new Error('Wrong reason code for puback')); } if (!code) { client.emit('message', topic, message, packet); } client.handleMessage(packet, (err) => { if (err) { return done && done(err); } client['_sendPacket']({ cmd: 'puback', messageId, reasonCode: code }, done); }); }); break; } case 0: client.emit('message', topic, message, packet); client.handleMessage(packet, done); break; default: client.log('handlePublish: unknown QoS. Doing nothing.'); break; } }; exports["default"] = handlePublish; //# sourceMappingURL=publish.js.map /***/ }), /***/ 8181: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const handlePubrel = (client, packet, done) => { client.log('handling pubrel packet'); const callback = typeof done !== 'undefined' ? done : client.noop; const { messageId } = packet; const comp = { cmd: 'pubcomp', messageId }; client.incomingStore.get(packet, (err, pub) => { if (!err) { client.emit('message', pub.topic, pub.payload, pub); client.handleMessage(pub, (err2) => { if (err2) { return callback(err2); } client.incomingStore.del(pub, client.noop); client['_sendPacket'](comp, callback); }); } else { client['_sendPacket'](comp, callback); } }); }; exports["default"] = handlePubrel; //# sourceMappingURL=pubrel.js.map /***/ }), /***/ 0: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isReactNativeBrowser = exports.isWebWorker = void 0; const isStandardBrowserEnv = () => { if (typeof window !== 'undefined') { const electronRenderCheck = typeof navigator !== 'undefined' && navigator.userAgent?.toLowerCase().indexOf(' electron/') > -1; if (electronRenderCheck && process?.versions) { const electronMainCheck = Object.prototype.hasOwnProperty.call(process.versions, 'electron'); return !electronMainCheck; } return typeof window.document !== 'undefined'; } return false; }; const isWebWorkerEnv = () => Boolean(typeof self === 'object' && self?.constructor?.name?.includes('WorkerGlobalScope') && typeof Deno === 'undefined'); const isReactNativeEnv = () => typeof navigator !== 'undefined' && navigator.product === 'ReactNative'; const isBrowser = isStandardBrowserEnv() || isWebWorkerEnv() || isReactNativeEnv(); exports.isWebWorker = isWebWorkerEnv(); exports.isReactNativeBrowser = isReactNativeEnv(); exports["default"] = isBrowser; //# sourceMappingURL=is-browser.js.map /***/ }), /***/ 2324: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MQTTJS_VERSION = exports.nextTick = exports.ErrorWithSubackPacket = exports.ErrorWithReasonCode = void 0; exports.applyMixin = applyMixin; class ErrorWithReasonCode extends Error { code; constructor(message, code) { super(message); this.code = code; Object.setPrototypeOf(this, ErrorWithReasonCode.prototype); Object.getPrototypeOf(this).name = 'ErrorWithReasonCode'; } } exports.ErrorWithReasonCode = ErrorWithReasonCode; class ErrorWithSubackPacket extends Error { packet; constructor(message, packet) { super(message); this.packet = packet; Object.setPrototypeOf(this, ErrorWithSubackPacket.prototype); Object.getPrototypeOf(this).name = 'ErrorWithSubackPacket'; } } exports.ErrorWithSubackPacket = ErrorWithSubackPacket; function applyMixin(target, mixin, includeConstructor = false) { const inheritanceChain = [mixin]; while (true) { const current = inheritanceChain[0]; const base = Object.getPrototypeOf(current); if (base?.prototype) { inheritanceChain.unshift(base); } else { break; } } for (const ctor of inheritanceChain) { for (const prop of Object.getOwnPropertyNames(ctor.prototype)) { if (includeConstructor || prop !== 'constructor') { Object.defineProperty(target.prototype, prop, Object.getOwnPropertyDescriptor(ctor.prototype, prop) ?? Object.create(null)); } } } } exports.nextTick = typeof process?.nextTick === 'function' ? process.nextTick : (callback) => { setTimeout(callback, 0); }; exports.MQTTJS_VERSION = __nccwpck_require__(2860).version; //# sourceMappingURL=shared.js.map /***/ }), /***/ 6248: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const readable_stream_1 = __nccwpck_require__(1657); const streamsOpts = { objectMode: true }; const defaultStoreOptions = { clean: true, }; class Store { options; _inflights; constructor(options) { this.options = options || {}; this.options = { ...defaultStoreOptions, ...options }; this._inflights = new Map(); } put(packet, cb) { this._inflights.set(packet.messageId, packet); if (cb) { cb(); } return this; } createStream() { const stream = new readable_stream_1.Readable(streamsOpts); const values = []; let destroyed = false; let i = 0; this._inflights.forEach((value, key) => { values.push(value); }); stream._read = () => { if (!destroyed && i < values.length) { stream.push(values[i++]); } else { stream.push(null); } }; stream.destroy = (err) => { if (destroyed) { return; } destroyed = true; setTimeout(() => { stream.emit('close'); }, 0); return stream; }; return stream; } del(packet, cb) { const toDelete = this._inflights.get(packet.messageId); if (toDelete) { this._inflights.delete(packet.messageId); cb(null, toDelete); } else if (cb) { cb(new Error('missing packet')); } return this; } get(packet, cb) { const storedPacket = this._inflights.get(packet.messageId); if (storedPacket) { cb(null, storedPacket); } else if (cb) { cb(new Error('missing packet')); } return this; } close(cb) { if (this.options.clean) { this._inflights = null; } if (cb) { cb(); } } } exports["default"] = Store; //# sourceMappingURL=store.js.map /***/ }), /***/ 700: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class TopicAliasRecv { aliasToTopic; max; length; constructor(max) { this.aliasToTopic = {}; this.max = max; } put(topic, alias) { if (alias === 0 || alias > this.max) { return false; } this.aliasToTopic[alias] = topic; this.length = Object.keys(this.aliasToTopic).length; return true; } getTopicByAlias(alias) { return this.aliasToTopic[alias]; } clear() { this.aliasToTopic = {}; } } exports["default"] = TopicAliasRecv; //# sourceMappingURL=topic-alias-recv.js.map /***/ }), /***/ 222: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const lru_cache_1 = __nccwpck_require__(2477); const number_allocator_1 = __nccwpck_require__(6733); class TopicAliasSend { aliasToTopic; topicToAlias; max; numberAllocator; length; constructor(max) { if (max > 0) { this.aliasToTopic = new lru_cache_1.LRUCache({ max }); this.topicToAlias = {}; this.numberAllocator = new number_allocator_1.NumberAllocator(1, max); this.max = max; this.length = 0; } } put(topic, alias) { if (alias === 0 || alias > this.max) { return false; } const entry = this.aliasToTopic.get(alias); if (entry) { delete this.topicToAlias[entry]; } this.aliasToTopic.set(alias, topic); this.topicToAlias[topic] = alias; this.numberAllocator.use(alias); this.length = this.aliasToTopic.size; return true; } getTopicByAlias(alias) { return this.aliasToTopic.get(alias); } getAliasByTopic(topic) { const alias = this.topicToAlias[topic]; if (typeof alias !== 'undefined') { this.aliasToTopic.get(alias); } return alias; } clear() { this.aliasToTopic.clear(); this.topicToAlias = {}; this.numberAllocator.clear(); this.length = 0; } getLruAlias() { const alias = this.numberAllocator.firstVacant(); if (alias) return alias; return [...this.aliasToTopic.keys()][this.aliasToTopic.size - 1]; } } exports["default"] = TopicAliasSend; //# sourceMappingURL=topic-alias-send.js.map /***/ }), /***/ 1236: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const number_allocator_1 = __nccwpck_require__(6733); class UniqueMessageIdProvider { numberAllocator; lastId; constructor() { this.numberAllocator = new number_allocator_1.NumberAllocator(1, 65535); } allocate() { this.lastId = this.numberAllocator.alloc(); return this.lastId; } getLastAllocated() { return this.lastId; } register(messageId) { return this.numberAllocator.use(messageId); } deallocate(messageId) { this.numberAllocator.free(messageId); } clear() { this.numberAllocator.clear(); } } exports["default"] = UniqueMessageIdProvider; //# sourceMappingURL=unique-message-id-provider.js.map /***/ }), /***/ 6105: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.validateTopic = validateTopic; exports.validateTopics = validateTopics; function validateTopic(topic) { const parts = topic.split('/'); for (let i = 0; i < parts.length; i++) { if (parts[i] === '+') { continue; } if (parts[i] === '#') { return i === parts.length - 1; } if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) { return false; } } return true; } function validateTopics(topics) { if (topics.length === 0) { return 'empty_topic_list'; } for (let i = 0; i < topics.length; i++) { if (!validateTopic(topics[i])) { return topics[i]; } } return null; } //# sourceMappingURL=validations.js.map /***/ }), /***/ 8867: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReasonCodes = exports.KeepaliveManager = exports.UniqueMessageIdProvider = exports.DefaultMessageIdProvider = exports.Store = exports.MqttClient = exports.connectAsync = exports.connect = exports.Client = void 0; const client_1 = __importDefault(__nccwpck_require__(5946)); exports.MqttClient = client_1.default; const default_message_id_provider_1 = __importDefault(__nccwpck_require__(8718)); exports.DefaultMessageIdProvider = default_message_id_provider_1.default; const unique_message_id_provider_1 = __importDefault(__nccwpck_require__(1236)); exports.UniqueMessageIdProvider = unique_message_id_provider_1.default; const store_1 = __importDefault(__nccwpck_require__(6248)); exports.Store = store_1.default; const connect_1 = __importStar(__nccwpck_require__(936)); exports.connect = connect_1.default; Object.defineProperty(exports, "connectAsync", ({ enumerable: true, get: function () { return connect_1.connectAsync; } })); const KeepaliveManager_1 = __importDefault(__nccwpck_require__(460)); exports.KeepaliveManager = KeepaliveManager_1.default; exports.Client = client_1.default; __exportStar(__nccwpck_require__(5946), exports); __exportStar(__nccwpck_require__(2324), exports); __exportStar(__nccwpck_require__(6105), exports); var ack_1 = __nccwpck_require__(2686); Object.defineProperty(exports, "ReasonCodes", ({ enumerable: true, get: function () { return ack_1.ReasonCodes; } })); //# sourceMappingURL=mqtt.js.map /***/ }), /***/ 3596: /***/ ((module, exports, __nccwpck_require__) => { /* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } let m; // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 // eslint-disable-next-line no-return-assign return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = __nccwpck_require__(8643)(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; /***/ }), /***/ 8643: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = __nccwpck_require__(744); createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } if (namespacesCache !== createDebug.namespaces) { namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; const split = (typeof namespaces === 'string' ? namespaces : '') .trim() .replace(/\s+/g, ',') .split(',') .filter(Boolean); for (const ns of split) { if (ns[0] === '-') { createDebug.skips.push(ns.slice(1)); } else { createDebug.names.push(ns); } } } /** * Checks if the given string matches a namespace template, honoring * asterisks as wildcards. * * @param {String} search * @param {String} template * @return {Boolean} */ function matchesTemplate(search, template) { let searchIndex = 0; let templateIndex = 0; let starIndex = -1; let matchIndex = 0; while (searchIndex < search.length) { if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { // Match character or proceed with wildcard if (template[templateIndex] === '*') { starIndex = templateIndex; matchIndex = searchIndex; templateIndex++; // Skip the '*' } else { searchIndex++; templateIndex++; } } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition // Backtrack to the last '*' and try to match more characters templateIndex = starIndex + 1; matchIndex++; searchIndex = matchIndex; } else { return false; // No match } } // Handle trailing '*' in template while (templateIndex < template.length && template[templateIndex] === '*') { templateIndex++; } return templateIndex === template.length; } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names, ...createDebug.skips.map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { for (const skip of createDebug.skips) { if (matchesTemplate(name, skip)) { return false; } } for (const ns of createDebug.names) { if (matchesTemplate(name, ns)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } module.exports = setup; /***/ }), /***/ 4496: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { module.exports = __nccwpck_require__(3596); } else { module.exports = __nccwpck_require__(7710); } /***/ }), /***/ 7710: /***/ ((module, exports, __nccwpck_require__) => { /** * Module dependencies. */ const tty = __nccwpck_require__(2018); const util = __nccwpck_require__(9023); /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = __nccwpck_require__(1450); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = __nccwpck_require__(8643)(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util.inspect(v, this.inspectOpts); }; /***/ }), /***/ 9018: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { SymbolDispose } = __nccwpck_require__(2177) const { AbortError, codes } = __nccwpck_require__(5358) const { isNodeStream, isWebStream, kControllerErrorFunction } = __nccwpck_require__(5848) const eos = __nccwpck_require__(741) const { ERR_INVALID_ARG_TYPE } = codes let addAbortListener // This method is inlined here for readable-stream // It also does not allow for signal to not exist on the stream // https://github.com/nodejs/node/pull/36061#discussion_r533718029 const validateAbortSignal = (signal, name) => { if (typeof signal !== 'object' || !('aborted' in signal)) { throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) } } module.exports.addAbortSignal = function addAbortSignal(signal, stream) { validateAbortSignal(signal, 'signal') if (!isNodeStream(stream) && !isWebStream(stream)) { throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) } return module.exports.addAbortSignalNoValidate(signal, stream) } module.exports.addAbortSignalNoValidate = function (signal, stream) { if (typeof signal !== 'object' || !('aborted' in signal)) { return stream } const onAbort = isNodeStream(stream) ? () => { stream.destroy( new AbortError(undefined, { cause: signal.reason }) ) } : () => { stream[kControllerErrorFunction]( new AbortError(undefined, { cause: signal.reason }) ) } if (signal.aborted) { onAbort() } else { addAbortListener = addAbortListener || (__nccwpck_require__(1953).addAbortListener) const disposable = addAbortListener(signal, onAbort) eos(stream, disposable[SymbolDispose]) } return stream } /***/ }), /***/ 9794: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array } = __nccwpck_require__(2177) const { Buffer } = __nccwpck_require__(181) const { inspect } = __nccwpck_require__(1953) module.exports = class BufferList { constructor() { this.head = null this.tail = null this.length = 0 } push(v) { const entry = { data: v, next: null } if (this.length > 0) this.tail.next = entry else this.head = entry this.tail = entry ++this.length } unshift(v) { const entry = { data: v, next: this.head } if (this.length === 0) this.tail = entry this.head = entry ++this.length } shift() { if (this.length === 0) return const ret = this.head.data if (this.length === 1) this.head = this.tail = null else this.head = this.head.next --this.length return ret } clear() { this.head = this.tail = null this.length = 0 } join(s) { if (this.length === 0) return '' let p = this.head let ret = '' + p.data while ((p = p.next) !== null) ret += s + p.data return ret } concat(n) { if (this.length === 0) return Buffer.alloc(0) const ret = Buffer.allocUnsafe(n >>> 0) let p = this.head let i = 0 while (p) { TypedArrayPrototypeSet(ret, p.data, i) i += p.data.length p = p.next } return ret } // Consumes a specified amount of bytes or characters from the buffered data. consume(n, hasStrings) { const data = this.head.data if (n < data.length) { // `slice` is the same for buffers and strings. const slice = data.slice(0, n) this.head.data = data.slice(n) return slice } if (n === data.length) { // First chunk is a perfect match. return this.shift() } // Result spans more than one buffer. return hasStrings ? this._getString(n) : this._getBuffer(n) } first() { return this.head.data } *[SymbolIterator]() { for (let p = this.head; p; p = p.next) { yield p.data } } // Consumes a specified amount of characters from the buffered data. _getString(n) { let ret = '' let p = this.head let c = 0 do { const str = p.data if (n > str.length) { ret += str n -= str.length } else { if (n === str.length) { ret += str ++c if (p.next) this.head = p.next else this.head = this.tail = null } else { ret += StringPrototypeSlice(str, 0, n) this.head = p p.data = StringPrototypeSlice(str, n) } break } ++c } while ((p = p.next) !== null) this.length -= c return ret } // Consumes a specified amount of bytes from the buffered data. _getBuffer(n) { const ret = Buffer.allocUnsafe(n) const retLen = n let p = this.head let c = 0 do { const buf = p.data if (n > buf.length) { TypedArrayPrototypeSet(ret, buf, retLen - n) n -= buf.length } else { if (n === buf.length) { TypedArrayPrototypeSet(ret, buf, retLen - n) ++c if (p.next) this.head = p.next else this.head = this.tail = null } else { TypedArrayPrototypeSet(ret, new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n) this.head = p p.data = buf.slice(n) } break } ++c } while ((p = p.next) !== null) this.length -= c return ret } // Make sure the linked list only shows the minimal necessary information. [Symbol.for('nodejs.util.inspect.custom')](_, options) { return inspect(this, { ...options, // Only inspect one level. depth: 0, // It should not recurse. customInspect: false }) } } /***/ }), /***/ 3177: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { pipeline } = __nccwpck_require__(4687) const Duplex = __nccwpck_require__(2327) const { destroyer } = __nccwpck_require__(6127) const { isNodeStream, isReadable, isWritable, isWebStream, isTransformStream, isWritableStream, isReadableStream } = __nccwpck_require__(5848) const { AbortError, codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS } } = __nccwpck_require__(5358) const eos = __nccwpck_require__(741) module.exports = function compose(...streams) { if (streams.length === 0) { throw new ERR_MISSING_ARGS('streams') } if (streams.length === 1) { return Duplex.from(streams[0]) } const orgStreams = [...streams] if (typeof streams[0] === 'function') { streams[0] = Duplex.from(streams[0]) } if (typeof streams[streams.length - 1] === 'function') { const idx = streams.length - 1 streams[idx] = Duplex.from(streams[idx]) } for (let n = 0; n < streams.length; ++n) { if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) { // TODO(ronag): Add checks for non streams. continue } if ( n < streams.length - 1 && !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n])) ) { throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be readable') } if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) { throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be writable') } } let ondrain let onfinish let onreadable let onclose let d function onfinished(err) { const cb = onclose onclose = null if (cb) { cb(err) } else if (err) { d.destroy(err) } else if (!readable && !writable) { d.destroy() } } const head = streams[0] const tail = pipeline(streams, onfinished) const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head)) const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail)) // TODO(ronag): Avoid double buffering. // Implement Writable/Readable/Duplex traits. // See, https://github.com/nodejs/node/pull/33515. d = new Duplex({ // TODO (ronag): highWaterMark? writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode), readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode), writable, readable }) if (writable) { if (isNodeStream(head)) { d._write = function (chunk, encoding, callback) { if (head.write(chunk, encoding)) { callback() } else { ondrain = callback } } d._final = function (callback) { head.end() onfinish = callback } head.on('drain', function () { if (ondrain) { const cb = ondrain ondrain = null cb() } }) } else if (isWebStream(head)) { const writable = isTransformStream(head) ? head.writable : head const writer = writable.getWriter() d._write = async function (chunk, encoding, callback) { try { await writer.ready writer.write(chunk).catch(() => {}) callback() } catch (err) { callback(err) } } d._final = async function (callback) { try { await writer.ready writer.close().catch(() => {}) onfinish = callback } catch (err) { callback(err) } } } const toRead = isTransformStream(tail) ? tail.readable : tail eos(toRead, () => { if (onfinish) { const cb = onfinish onfinish = null cb() } }) } if (readable) { if (isNodeStream(tail)) { tail.on('readable', function () { if (onreadable) { const cb = onreadable onreadable = null cb() } }) tail.on('end', function () { d.push(null) }) d._read = function () { while (true) { const buf = tail.read() if (buf === null) { onreadable = d._read return } if (!d.push(buf)) { return } } } } else if (isWebStream(tail)) { const readable = isTransformStream(tail) ? tail.readable : tail const reader = readable.getReader() d._read = async function () { while (true) { try { const { value, done } = await reader.read() if (!d.push(value)) { return } if (done) { d.push(null) return } } catch { return } } } } } d._destroy = function (err, callback) { if (!err && onclose !== null) { err = new AbortError() } onreadable = null ondrain = null onfinish = null if (onclose === null) { callback(err) } else { onclose = callback if (isNodeStream(tail)) { destroyer(tail, err) } } } return d } /***/ }), /***/ 6127: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ const { aggregateTwoErrors, codes: { ERR_MULTIPLE_CALLBACK }, AbortError } = __nccwpck_require__(5358) const { Symbol } = __nccwpck_require__(2177) const { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = __nccwpck_require__(5848) const kDestroy = Symbol('kDestroy') const kConstruct = Symbol('kConstruct') function checkError(err, w, r) { if (err) { // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 err.stack // eslint-disable-line no-unused-expressions if (w && !w.errored) { w.errored = err } if (r && !r.errored) { r.errored = err } } } // Backwards compat. cb() is undocumented and unused in core but // unfortunately might be used by modules. function destroy(err, cb) { const r = this._readableState const w = this._writableState // With duplex streams we use the writable side for state. const s = w || r if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { if (typeof cb === 'function') { cb() } return this } // We set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks checkError(err, w, r) if (w) { w.destroyed = true } if (r) { r.destroyed = true } // If still constructing then defer calling _destroy. if (!s.constructed) { this.once(kDestroy, function (er) { _destroy(this, aggregateTwoErrors(er, err), cb) }) } else { _destroy(this, err, cb) } return this } function _destroy(self, err, cb) { let called = false function onDestroy(err) { if (called) { return } called = true const r = self._readableState const w = self._writableState checkError(err, w, r) if (w) { w.closed = true } if (r) { r.closed = true } if (typeof cb === 'function') { cb(err) } if (err) { process.nextTick(emitErrorCloseNT, self, err) } else { process.nextTick(emitCloseNT, self) } } try { self._destroy(err || null, onDestroy) } catch (err) { onDestroy(err) } } function emitErrorCloseNT(self, err) { emitErrorNT(self, err) emitCloseNT(self) } function emitCloseNT(self) { const r = self._readableState const w = self._writableState if (w) { w.closeEmitted = true } if (r) { r.closeEmitted = true } if ((w !== null && w !== undefined && w.emitClose) || (r !== null && r !== undefined && r.emitClose)) { self.emit('close') } } function emitErrorNT(self, err) { const r = self._readableState const w = self._writableState if ((w !== null && w !== undefined && w.errorEmitted) || (r !== null && r !== undefined && r.errorEmitted)) { return } if (w) { w.errorEmitted = true } if (r) { r.errorEmitted = true } self.emit('error', err) } function undestroy() { const r = this._readableState const w = this._writableState if (r) { r.constructed = true r.closed = false r.closeEmitted = false r.destroyed = false r.errored = null r.errorEmitted = false r.reading = false r.ended = r.readable === false r.endEmitted = r.readable === false } if (w) { w.constructed = true w.destroyed = false w.closed = false w.closeEmitted = false w.errored = null w.errorEmitted = false w.finalCalled = false w.prefinished = false w.ended = w.writable === false w.ending = w.writable === false w.finished = w.writable === false } } function errorOrDestroy(stream, err, sync) { // We have tests that rely on errors being emitted // in the same tick, so changing this is semver major. // For now when you opt-in to autoDestroy we allow // the error to be emitted nextTick. In a future // semver major update we should change the default to this. const r = stream._readableState const w = stream._writableState if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { return this } if ((r !== null && r !== undefined && r.autoDestroy) || (w !== null && w !== undefined && w.autoDestroy)) stream.destroy(err) else if (err) { // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 err.stack // eslint-disable-line no-unused-expressions if (w && !w.errored) { w.errored = err } if (r && !r.errored) { r.errored = err } if (sync) { process.nextTick(emitErrorNT, stream, err) } else { emitErrorNT(stream, err) } } } function construct(stream, cb) { if (typeof stream._construct !== 'function') { return } const r = stream._readableState const w = stream._writableState if (r) { r.constructed = false } if (w) { w.constructed = false } stream.once(kConstruct, cb) if (stream.listenerCount(kConstruct) > 1) { // Duplex return } process.nextTick(constructNT, stream) } function constructNT(stream) { let called = false function onConstruct(err) { if (called) { errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK()) return } called = true const r = stream._readableState const w = stream._writableState const s = w || r if (r) { r.constructed = true } if (w) { w.constructed = true } if (s.destroyed) { stream.emit(kDestroy, err) } else if (err) { errorOrDestroy(stream, err, true) } else { process.nextTick(emitConstructNT, stream) } } try { stream._construct((err) => { process.nextTick(onConstruct, err) }) } catch (err) { process.nextTick(onConstruct, err) } } function emitConstructNT(stream) { stream.emit(kConstruct) } function isRequest(stream) { return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === 'function' } function emitCloseLegacy(stream) { stream.emit('close') } function emitErrorCloseLegacy(stream, err) { stream.emit('error', err) process.nextTick(emitCloseLegacy, stream) } // Normalize destroy for legacy. function destroyer(stream, err) { if (!stream || isDestroyed(stream)) { return } if (!err && !isFinished(stream)) { err = new AbortError() } // TODO: Remove isRequest branches. if (isServerRequest(stream)) { stream.socket = null stream.destroy(err) } else if (isRequest(stream)) { stream.abort() } else if (isRequest(stream.req)) { stream.req.abort() } else if (typeof stream.destroy === 'function') { stream.destroy(err) } else if (typeof stream.close === 'function') { // TODO: Don't lose err? stream.close() } else if (err) { process.nextTick(emitErrorCloseLegacy, stream, err) } else { process.nextTick(emitCloseLegacy, stream) } if (!stream.destroyed) { stream[kIsDestroyed] = true } } module.exports = { construct, destroyer, destroy, undestroy, errorOrDestroy } /***/ }), /***/ 2327: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototype inheritance, this class // prototypically inherits from Readable, and then parasitically from // Writable. const { ObjectDefineProperties, ObjectGetOwnPropertyDescriptor, ObjectKeys, ObjectSetPrototypeOf } = __nccwpck_require__(2177) module.exports = Duplex const Readable = __nccwpck_require__(933) const Writable = __nccwpck_require__(9557) ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype) ObjectSetPrototypeOf(Duplex, Readable) { const keys = ObjectKeys(Writable.prototype) // Allow the keys array to be GC'ed. for (let i = 0; i < keys.length; i++) { const method = keys[i] if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method] } } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options) Readable.call(this, options) Writable.call(this, options) if (options) { this.allowHalfOpen = options.allowHalfOpen !== false if (options.readable === false) { this._readableState.readable = false this._readableState.ended = true this._readableState.endEmitted = true } if (options.writable === false) { this._writableState.writable = false this._writableState.ending = true this._writableState.ended = true this._writableState.finished = true } } else { this.allowHalfOpen = true } } ObjectDefineProperties(Duplex.prototype, { writable: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable') }, writableHighWaterMark: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark') }, writableObjectMode: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode') }, writableBuffer: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer') }, writableLength: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength') }, writableFinished: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished') }, writableCorked: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked') }, writableEnded: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded') }, writableNeedDrain: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain') }, destroyed: { __proto__: null, get() { if (this._readableState === undefined || this._writableState === undefined) { return false } return this._readableState.destroyed && this._writableState.destroyed }, set(value) { // Backward compatibility, the user is explicitly // managing destroyed. if (this._readableState && this._writableState) { this._readableState.destroyed = value this._writableState.destroyed = value } } } }) let webStreamsAdapters // Lazy to avoid circular references function lazyWebStreams() { if (webStreamsAdapters === undefined) webStreamsAdapters = {} return webStreamsAdapters } Duplex.fromWeb = function (pair, options) { return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options) } Duplex.toWeb = function (duplex) { return lazyWebStreams().newReadableWritablePairFromDuplex(duplex) } let duplexify Duplex.from = function (body) { if (!duplexify) { duplexify = __nccwpck_require__(725) } return duplexify(body, 'body') } /***/ }), /***/ 725: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ ;('use strict') const bufferModule = __nccwpck_require__(181) const { isReadable, isWritable, isIterable, isNodeStream, isReadableNodeStream, isWritableNodeStream, isDuplexNodeStream, isReadableStream, isWritableStream } = __nccwpck_require__(5848) const eos = __nccwpck_require__(741) const { AbortError, codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE } } = __nccwpck_require__(5358) const { destroyer } = __nccwpck_require__(6127) const Duplex = __nccwpck_require__(2327) const Readable = __nccwpck_require__(933) const Writable = __nccwpck_require__(9557) const { createDeferredPromise } = __nccwpck_require__(1953) const from = __nccwpck_require__(9069) const Blob = globalThis.Blob || bufferModule.Blob const isBlob = typeof Blob !== 'undefined' ? function isBlob(b) { return b instanceof Blob } : function isBlob(b) { return false } const AbortController = globalThis.AbortController || (__nccwpck_require__(7413).AbortController) const { FunctionPrototypeCall } = __nccwpck_require__(2177) // This is needed for pre node 17. class Duplexify extends Duplex { constructor(options) { super(options) // https://github.com/nodejs/node/pull/34385 if ((options === null || options === undefined ? undefined : options.readable) === false) { this._readableState.readable = false this._readableState.ended = true this._readableState.endEmitted = true } if ((options === null || options === undefined ? undefined : options.writable) === false) { this._writableState.writable = false this._writableState.ending = true this._writableState.ended = true this._writableState.finished = true } } } module.exports = function duplexify(body, name) { if (isDuplexNodeStream(body)) { return body } if (isReadableNodeStream(body)) { return _duplexify({ readable: body }) } if (isWritableNodeStream(body)) { return _duplexify({ writable: body }) } if (isNodeStream(body)) { return _duplexify({ writable: false, readable: false }) } if (isReadableStream(body)) { return _duplexify({ readable: Readable.fromWeb(body) }) } if (isWritableStream(body)) { return _duplexify({ writable: Writable.fromWeb(body) }) } if (typeof body === 'function') { const { value, write, final, destroy } = fromAsyncGen(body) if (isIterable(value)) { return from(Duplexify, value, { // TODO (ronag): highWaterMark? objectMode: true, write, final, destroy }) } const then = value === null || value === undefined ? undefined : value.then if (typeof then === 'function') { let d const promise = FunctionPrototypeCall( then, value, (val) => { if (val != null) { throw new ERR_INVALID_RETURN_VALUE('nully', 'body', val) } }, (err) => { destroyer(d, err) } ) return (d = new Duplexify({ // TODO (ronag): highWaterMark? objectMode: true, readable: false, write, final(cb) { final(async () => { try { await promise process.nextTick(cb, null) } catch (err) { process.nextTick(cb, err) } }) }, destroy })) } throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or AsyncFunction', name, value) } if (isBlob(body)) { return duplexify(body.arrayBuffer()) } if (isIterable(body)) { return from(Duplexify, body, { // TODO (ronag): highWaterMark? objectMode: true, writable: false }) } if ( isReadableStream(body === null || body === undefined ? undefined : body.readable) && isWritableStream(body === null || body === undefined ? undefined : body.writable) ) { return Duplexify.fromWeb(body) } if ( typeof (body === null || body === undefined ? undefined : body.writable) === 'object' || typeof (body === null || body === undefined ? undefined : body.readable) === 'object' ) { const readable = body !== null && body !== undefined && body.readable ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable) ? body === null || body === undefined ? undefined : body.readable : duplexify(body.readable) : undefined const writable = body !== null && body !== undefined && body.writable ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable) ? body === null || body === undefined ? undefined : body.writable : duplexify(body.writable) : undefined return _duplexify({ readable, writable }) } const then = body === null || body === undefined ? undefined : body.then if (typeof then === 'function') { let d FunctionPrototypeCall( then, body, (val) => { if (val != null) { d.push(val) } d.push(null) }, (err) => { destroyer(d, err) } ) return (d = new Duplexify({ objectMode: true, writable: false, read() {} })) } throw new ERR_INVALID_ARG_TYPE( name, [ 'Blob', 'ReadableStream', 'WritableStream', 'Stream', 'Iterable', 'AsyncIterable', 'Function', '{ readable, writable } pair', 'Promise' ], body ) } function fromAsyncGen(fn) { let { promise, resolve } = createDeferredPromise() const ac = new AbortController() const signal = ac.signal const value = fn( (async function* () { while (true) { const _promise = promise promise = null const { chunk, done, cb } = await _promise process.nextTick(cb) if (done) return if (signal.aborted) throw new AbortError(undefined, { cause: signal.reason }) ;({ promise, resolve } = createDeferredPromise()) yield chunk } })(), { signal } ) return { value, write(chunk, encoding, cb) { const _resolve = resolve resolve = null _resolve({ chunk, done: false, cb }) }, final(cb) { const _resolve = resolve resolve = null _resolve({ done: true, cb }) }, destroy(err, cb) { ac.abort() cb(err) } } } function _duplexify(pair) { const r = pair.readable && typeof pair.readable.read !== 'function' ? Readable.wrap(pair.readable) : pair.readable const w = pair.writable let readable = !!isReadable(r) let writable = !!isWritable(w) let ondrain let onfinish let onreadable let onclose let d function onfinished(err) { const cb = onclose onclose = null if (cb) { cb(err) } else if (err) { d.destroy(err) } } // TODO(ronag): Avoid double buffering. // Implement Writable/Readable/Duplex traits. // See, https://github.com/nodejs/node/pull/33515. d = new Duplexify({ // TODO (ronag): highWaterMark? readableObjectMode: !!(r !== null && r !== undefined && r.readableObjectMode), writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode), readable, writable }) if (writable) { eos(w, (err) => { writable = false if (err) { destroyer(r, err) } onfinished(err) }) d._write = function (chunk, encoding, callback) { if (w.write(chunk, encoding)) { callback() } else { ondrain = callback } } d._final = function (callback) { w.end() onfinish = callback } w.on('drain', function () { if (ondrain) { const cb = ondrain ondrain = null cb() } }) w.on('finish', function () { if (onfinish) { const cb = onfinish onfinish = null cb() } }) } if (readable) { eos(r, (err) => { readable = false if (err) { destroyer(r, err) } onfinished(err) }) r.on('readable', function () { if (onreadable) { const cb = onreadable onreadable = null cb() } }) r.on('end', function () { d.push(null) }) d._read = function () { while (true) { const buf = r.read() if (buf === null) { onreadable = d._read return } if (!d.push(buf)) { return } } } } d._destroy = function (err, callback) { if (!err && onclose !== null) { err = new AbortError() } onreadable = null ondrain = null onfinish = null if (onclose === null) { callback(err) } else { onclose = callback destroyer(w, err) destroyer(r, err) } } return d } /***/ }), /***/ 741: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Ported from https://github.com/mafintosh/end-of-stream with // permission from the author, Mathias Buus (@mafintosh). /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ const { AbortError, codes } = __nccwpck_require__(5358) const { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes const { kEmptyObject, once } = __nccwpck_require__(1953) const { validateAbortSignal, validateFunction, validateObject, validateBoolean } = __nccwpck_require__(3328) const { Promise, PromisePrototypeThen, SymbolDispose } = __nccwpck_require__(2177) const { isClosed, isReadable, isReadableNodeStream, isReadableStream, isReadableFinished, isReadableErrored, isWritable, isWritableNodeStream, isWritableStream, isWritableFinished, isWritableErrored, isNodeStream, willEmitClose: _willEmitClose, kIsClosedPromise } = __nccwpck_require__(5848) let addAbortListener function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function' } const nop = () => {} function eos(stream, options, callback) { var _options$readable, _options$writable if (arguments.length === 2) { callback = options options = kEmptyObject } else if (options == null) { options = kEmptyObject } else { validateObject(options, 'options') } validateFunction(callback, 'callback') validateAbortSignal(options.signal, 'options.signal') callback = once(callback) if (isReadableStream(stream) || isWritableStream(stream)) { return eosWeb(stream, options, callback) } if (!isNodeStream(stream)) { throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) } const readable = (_options$readable = options.readable) !== null && _options$readable !== undefined ? _options$readable : isReadableNodeStream(stream) const writable = (_options$writable = options.writable) !== null && _options$writable !== undefined ? _options$writable : isWritableNodeStream(stream) const wState = stream._writableState const rState = stream._readableState const onlegacyfinish = () => { if (!stream.writable) { onfinish() } } // TODO (ronag): Improve soft detection to include core modules and // common ecosystem modules that do properly emit 'close' but fail // this generic check. let willEmitClose = _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable let writableFinished = isWritableFinished(stream, false) const onfinish = () => { writableFinished = true // Stream should not be destroyed here. If it is that // means that user space is doing something differently and // we cannot trust willEmitClose. if (stream.destroyed) { willEmitClose = false } if (willEmitClose && (!stream.readable || readable)) { return } if (!readable || readableFinished) { callback.call(stream) } } let readableFinished = isReadableFinished(stream, false) const onend = () => { readableFinished = true // Stream should not be destroyed here. If it is that // means that user space is doing something differently and // we cannot trust willEmitClose. if (stream.destroyed) { willEmitClose = false } if (willEmitClose && (!stream.writable || writable)) { return } if (!writable || writableFinished) { callback.call(stream) } } const onerror = (err) => { callback.call(stream, err) } let closed = isClosed(stream) const onclose = () => { closed = true const errored = isWritableErrored(stream) || isReadableErrored(stream) if (errored && typeof errored !== 'boolean') { return callback.call(stream, errored) } if (readable && !readableFinished && isReadableNodeStream(stream, true)) { if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) } if (writable && !writableFinished) { if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) } callback.call(stream) } const onclosed = () => { closed = true const errored = isWritableErrored(stream) || isReadableErrored(stream) if (errored && typeof errored !== 'boolean') { return callback.call(stream, errored) } callback.call(stream) } const onrequest = () => { stream.req.on('finish', onfinish) } if (isRequest(stream)) { stream.on('complete', onfinish) if (!willEmitClose) { stream.on('abort', onclose) } if (stream.req) { onrequest() } else { stream.on('request', onrequest) } } else if (writable && !wState) { // legacy streams stream.on('end', onlegacyfinish) stream.on('close', onlegacyfinish) } // Not all streams will emit 'close' after 'aborted'. if (!willEmitClose && typeof stream.aborted === 'boolean') { stream.on('aborted', onclose) } stream.on('end', onend) stream.on('finish', onfinish) if (options.error !== false) { stream.on('error', onerror) } stream.on('close', onclose) if (closed) { process.nextTick(onclose) } else if ( (wState !== null && wState !== undefined && wState.errorEmitted) || (rState !== null && rState !== undefined && rState.errorEmitted) ) { if (!willEmitClose) { process.nextTick(onclosed) } } else if ( !readable && (!willEmitClose || isReadable(stream)) && (writableFinished || isWritable(stream) === false) ) { process.nextTick(onclosed) } else if ( !writable && (!willEmitClose || isWritable(stream)) && (readableFinished || isReadable(stream) === false) ) { process.nextTick(onclosed) } else if (rState && stream.req && stream.aborted) { process.nextTick(onclosed) } const cleanup = () => { callback = nop stream.removeListener('aborted', onclose) stream.removeListener('complete', onfinish) stream.removeListener('abort', onclose) stream.removeListener('request', onrequest) if (stream.req) stream.req.removeListener('finish', onfinish) stream.removeListener('end', onlegacyfinish) stream.removeListener('close', onlegacyfinish) stream.removeListener('finish', onfinish) stream.removeListener('end', onend) stream.removeListener('error', onerror) stream.removeListener('close', onclose) } if (options.signal && !closed) { const abort = () => { // Keep it because cleanup removes it. const endCallback = callback cleanup() endCallback.call( stream, new AbortError(undefined, { cause: options.signal.reason }) ) } if (options.signal.aborted) { process.nextTick(abort) } else { addAbortListener = addAbortListener || (__nccwpck_require__(1953).addAbortListener) const disposable = addAbortListener(options.signal, abort) const originalCallback = callback callback = once((...args) => { disposable[SymbolDispose]() originalCallback.apply(stream, args) }) } } return cleanup } function eosWeb(stream, options, callback) { let isAborted = false let abort = nop if (options.signal) { abort = () => { isAborted = true callback.call( stream, new AbortError(undefined, { cause: options.signal.reason }) ) } if (options.signal.aborted) { process.nextTick(abort) } else { addAbortListener = addAbortListener || (__nccwpck_require__(1953).addAbortListener) const disposable = addAbortListener(options.signal, abort) const originalCallback = callback callback = once((...args) => { disposable[SymbolDispose]() originalCallback.apply(stream, args) }) } } const resolverFn = (...args) => { if (!isAborted) { process.nextTick(() => callback.apply(stream, args)) } } PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn) return nop } function finished(stream, opts) { var _opts let autoCleanup = false if (opts === null) { opts = kEmptyObject } if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup) { validateBoolean(opts.cleanup, 'cleanup') autoCleanup = opts.cleanup } return new Promise((resolve, reject) => { const cleanup = eos(stream, opts, (err) => { if (autoCleanup) { cleanup() } if (err) { reject(err) } else { resolve() } }) }) } module.exports = eos module.exports.finished = finished /***/ }), /***/ 9069: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ const { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = __nccwpck_require__(2177) const { Buffer } = __nccwpck_require__(181) const { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = (__nccwpck_require__(5358).codes) function from(Readable, iterable, opts) { let iterator if (typeof iterable === 'string' || iterable instanceof Buffer) { return new Readable({ objectMode: true, ...opts, read() { this.push(iterable) this.push(null) } }) } let isAsync if (iterable && iterable[SymbolAsyncIterator]) { isAsync = true iterator = iterable[SymbolAsyncIterator]() } else if (iterable && iterable[SymbolIterator]) { isAsync = false iterator = iterable[SymbolIterator]() } else { throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable) } const readable = new Readable({ objectMode: true, highWaterMark: 1, // TODO(ronag): What options should be allowed? ...opts }) // Flag to protect against _read // being called before last iteration completion. let reading = false readable._read = function () { if (!reading) { reading = true next() } } readable._destroy = function (error, cb) { PromisePrototypeThen( close(error), () => process.nextTick(cb, error), // nextTick is here in case cb throws (e) => process.nextTick(cb, e || error) ) } async function close(error) { const hadError = error !== undefined && error !== null const hasThrow = typeof iterator.throw === 'function' if (hadError && hasThrow) { const { value, done } = await iterator.throw(error) await value if (done) { return } } if (typeof iterator.return === 'function') { const { value } = await iterator.return() await value } } async function next() { for (;;) { try { const { value, done } = isAsync ? await iterator.next() : iterator.next() if (done) { readable.push(null) } else { const res = value && typeof value.then === 'function' ? await value : value if (res === null) { reading = false throw new ERR_STREAM_NULL_VALUES() } else if (readable.push(res)) { continue } else { reading = false } } } catch (err) { readable.destroy(err) } break } } return readable } module.exports = from /***/ }), /***/ 5246: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { ArrayIsArray, ObjectSetPrototypeOf } = __nccwpck_require__(2177) const { EventEmitter: EE } = __nccwpck_require__(4434) function Stream(opts) { EE.call(this, opts) } ObjectSetPrototypeOf(Stream.prototype, EE.prototype) ObjectSetPrototypeOf(Stream, EE) Stream.prototype.pipe = function (dest, options) { const source = this function ondata(chunk) { if (dest.writable && dest.write(chunk) === false && source.pause) { source.pause() } } source.on('data', ondata) function ondrain() { if (source.readable && source.resume) { source.resume() } } dest.on('drain', ondrain) // If the 'end' option is not supplied, dest.end() will be called when // source gets the 'end' or 'close' events. Only dest.end() once. if (!dest._isStdio && (!options || options.end !== false)) { source.on('end', onend) source.on('close', onclose) } let didOnEnd = false function onend() { if (didOnEnd) return didOnEnd = true dest.end() } function onclose() { if (didOnEnd) return didOnEnd = true if (typeof dest.destroy === 'function') dest.destroy() } // Don't leave dangling pipes when there are errors. function onerror(er) { cleanup() if (EE.listenerCount(this, 'error') === 0) { this.emit('error', er) } } prependListener(source, 'error', onerror) prependListener(dest, 'error', onerror) // Remove all the event listeners that were added. function cleanup() { source.removeListener('data', ondata) dest.removeListener('drain', ondrain) source.removeListener('end', onend) source.removeListener('close', onclose) source.removeListener('error', onerror) dest.removeListener('error', onerror) source.removeListener('end', cleanup) source.removeListener('close', cleanup) dest.removeListener('close', cleanup) } source.on('end', cleanup) source.on('close', cleanup) dest.on('close', cleanup) dest.emit('pipe', source) // Allow for unix-like usage: A.pipe(B).pipe(C) return dest } function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn) // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn) else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn) else emitter._events[event] = [fn, emitter._events[event]] } module.exports = { Stream, prependListener } /***/ }), /***/ 3972: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const AbortController = globalThis.AbortController || (__nccwpck_require__(7413).AbortController) const { codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE }, AbortError } = __nccwpck_require__(5358) const { validateAbortSignal, validateInteger, validateObject } = __nccwpck_require__(3328) const kWeakHandler = (__nccwpck_require__(2177).Symbol)('kWeak') const kResistStopPropagation = (__nccwpck_require__(2177).Symbol)('kResistStopPropagation') const { finished } = __nccwpck_require__(741) const staticCompose = __nccwpck_require__(3177) const { addAbortSignalNoValidate } = __nccwpck_require__(9018) const { isWritable, isNodeStream } = __nccwpck_require__(5848) const { deprecate } = __nccwpck_require__(1953) const { ArrayPrototypePush, Boolean, MathFloor, Number, NumberIsNaN, Promise, PromiseReject, PromiseResolve, PromisePrototypeThen, Symbol } = __nccwpck_require__(2177) const kEmpty = Symbol('kEmpty') const kEof = Symbol('kEof') function compose(stream, options) { if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } if (isNodeStream(stream) && !isWritable(stream)) { throw new ERR_INVALID_ARG_VALUE('stream', stream, 'must be writable') } const composedStream = staticCompose(this, stream) if (options !== null && options !== undefined && options.signal) { // Not validating as we already validated before addAbortSignalNoValidate(options.signal, composedStream) } return composedStream } function map(fn, options) { if (typeof fn !== 'function') { throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) } if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } let concurrency = 1 if ((options === null || options === undefined ? undefined : options.concurrency) != null) { concurrency = MathFloor(options.concurrency) } let highWaterMark = concurrency - 1 if ((options === null || options === undefined ? undefined : options.highWaterMark) != null) { highWaterMark = MathFloor(options.highWaterMark) } validateInteger(concurrency, 'options.concurrency', 1) validateInteger(highWaterMark, 'options.highWaterMark', 0) highWaterMark += concurrency return async function* map() { const signal = (__nccwpck_require__(1953).AbortSignalAny)( [options === null || options === undefined ? undefined : options.signal].filter(Boolean) ) const stream = this const queue = [] const signalOpt = { signal } let next let resume let done = false let cnt = 0 function onCatch() { done = true afterItemProcessed() } function afterItemProcessed() { cnt -= 1 maybeResume() } function maybeResume() { if (resume && !done && cnt < concurrency && queue.length < highWaterMark) { resume() resume = null } } async function pump() { try { for await (let val of stream) { if (done) { return } if (signal.aborted) { throw new AbortError() } try { val = fn(val, signalOpt) if (val === kEmpty) { continue } val = PromiseResolve(val) } catch (err) { val = PromiseReject(err) } cnt += 1 PromisePrototypeThen(val, afterItemProcessed, onCatch) queue.push(val) if (next) { next() next = null } if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) { await new Promise((resolve) => { resume = resolve }) } } queue.push(kEof) } catch (err) { const val = PromiseReject(err) PromisePrototypeThen(val, afterItemProcessed, onCatch) queue.push(val) } finally { done = true if (next) { next() next = null } } } pump() try { while (true) { while (queue.length > 0) { const val = await queue[0] if (val === kEof) { return } if (signal.aborted) { throw new AbortError() } if (val !== kEmpty) { yield val } queue.shift() maybeResume() } await new Promise((resolve) => { next = resolve }) } } finally { done = true if (resume) { resume() resume = null } } }.call(this) } function asIndexedPairs(options = undefined) { if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } return async function* asIndexedPairs() { let index = 0 for await (const val of this) { var _options$signal if ( options !== null && options !== undefined && (_options$signal = options.signal) !== null && _options$signal !== undefined && _options$signal.aborted ) { throw new AbortError({ cause: options.signal.reason }) } yield [index++, val] } }.call(this) } async function some(fn, options = undefined) { for await (const unused of filter.call(this, fn, options)) { return true } return false } async function every(fn, options = undefined) { if (typeof fn !== 'function') { throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) } // https://en.wikipedia.org/wiki/De_Morgan%27s_laws return !(await some.call( this, async (...args) => { return !(await fn(...args)) }, options )) } async function find(fn, options) { for await (const result of filter.call(this, fn, options)) { return result } return undefined } async function forEach(fn, options) { if (typeof fn !== 'function') { throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) } async function forEachFn(value, options) { await fn(value, options) return kEmpty } // eslint-disable-next-line no-unused-vars for await (const unused of map.call(this, forEachFn, options)); } function filter(fn, options) { if (typeof fn !== 'function') { throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) } async function filterFn(value, options) { if (await fn(value, options)) { return value } return kEmpty } return map.call(this, filterFn, options) } // Specific to provide better error to reduce since the argument is only // missing if the stream has no items in it - but the code is still appropriate class ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS { constructor() { super('reduce') this.message = 'Reduce of an empty stream requires an initial value' } } async function reduce(reducer, initialValue, options) { var _options$signal2 if (typeof reducer !== 'function') { throw new ERR_INVALID_ARG_TYPE('reducer', ['Function', 'AsyncFunction'], reducer) } if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } let hasInitialValue = arguments.length > 1 if ( options !== null && options !== undefined && (_options$signal2 = options.signal) !== null && _options$signal2 !== undefined && _options$signal2.aborted ) { const err = new AbortError(undefined, { cause: options.signal.reason }) this.once('error', () => {}) // The error is already propagated await finished(this.destroy(err)) throw err } const ac = new AbortController() const signal = ac.signal if (options !== null && options !== undefined && options.signal) { const opts = { once: true, [kWeakHandler]: this, [kResistStopPropagation]: true } options.signal.addEventListener('abort', () => ac.abort(), opts) } let gotAnyItemFromStream = false try { for await (const value of this) { var _options$signal3 gotAnyItemFromStream = true if ( options !== null && options !== undefined && (_options$signal3 = options.signal) !== null && _options$signal3 !== undefined && _options$signal3.aborted ) { throw new AbortError() } if (!hasInitialValue) { initialValue = value hasInitialValue = true } else { initialValue = await reducer(initialValue, value, { signal }) } } if (!gotAnyItemFromStream && !hasInitialValue) { throw new ReduceAwareErrMissingArgs() } } finally { ac.abort() } return initialValue } async function toArray(options) { if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } const result = [] for await (const val of this) { var _options$signal4 if ( options !== null && options !== undefined && (_options$signal4 = options.signal) !== null && _options$signal4 !== undefined && _options$signal4.aborted ) { throw new AbortError(undefined, { cause: options.signal.reason }) } ArrayPrototypePush(result, val) } return result } function flatMap(fn, options) { const values = map.call(this, fn, options) return async function* flatMap() { for await (const val of values) { yield* val } }.call(this) } function toIntegerOrInfinity(number) { // We coerce here to align with the spec // https://github.com/tc39/proposal-iterator-helpers/issues/169 number = Number(number) if (NumberIsNaN(number)) { return 0 } if (number < 0) { throw new ERR_OUT_OF_RANGE('number', '>= 0', number) } return number } function drop(number, options = undefined) { if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } number = toIntegerOrInfinity(number) return async function* drop() { var _options$signal5 if ( options !== null && options !== undefined && (_options$signal5 = options.signal) !== null && _options$signal5 !== undefined && _options$signal5.aborted ) { throw new AbortError() } for await (const val of this) { var _options$signal6 if ( options !== null && options !== undefined && (_options$signal6 = options.signal) !== null && _options$signal6 !== undefined && _options$signal6.aborted ) { throw new AbortError() } if (number-- <= 0) { yield val } } }.call(this) } function take(number, options = undefined) { if (options != null) { validateObject(options, 'options') } if ((options === null || options === undefined ? undefined : options.signal) != null) { validateAbortSignal(options.signal, 'options.signal') } number = toIntegerOrInfinity(number) return async function* take() { var _options$signal7 if ( options !== null && options !== undefined && (_options$signal7 = options.signal) !== null && _options$signal7 !== undefined && _options$signal7.aborted ) { throw new AbortError() } for await (const val of this) { var _options$signal8 if ( options !== null && options !== undefined && (_options$signal8 = options.signal) !== null && _options$signal8 !== undefined && _options$signal8.aborted ) { throw new AbortError() } if (number-- > 0) { yield val } // Don't get another item from iterator in case we reached the end if (number <= 0) { return } } }.call(this) } module.exports.streamReturningOperators = { asIndexedPairs: deprecate(asIndexedPairs, 'readable.asIndexedPairs will be removed in a future version.'), drop, filter, flatMap, map, take, compose } module.exports.promiseReturningOperators = { every, forEach, reduce, toArray, some, find } /***/ }), /***/ 7179: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. const { ObjectSetPrototypeOf } = __nccwpck_require__(2177) module.exports = PassThrough const Transform = __nccwpck_require__(7689) ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype) ObjectSetPrototypeOf(PassThrough, Transform) function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options) Transform.call(this, options) } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk) } /***/ }), /***/ 4687: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ // Ported from https://github.com/mafintosh/pump with // permission from the author, Mathias Buus (@mafintosh). ;('use strict') const { ArrayIsArray, Promise, SymbolAsyncIterator, SymbolDispose } = __nccwpck_require__(2177) const eos = __nccwpck_require__(741) const { once } = __nccwpck_require__(1953) const destroyImpl = __nccwpck_require__(6127) const Duplex = __nccwpck_require__(2327) const { aggregateTwoErrors, codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE, ERR_MISSING_ARGS, ERR_STREAM_DESTROYED, ERR_STREAM_PREMATURE_CLOSE }, AbortError } = __nccwpck_require__(5358) const { validateFunction, validateAbortSignal } = __nccwpck_require__(3328) const { isIterable, isReadable, isReadableNodeStream, isNodeStream, isTransformStream, isWebStream, isReadableStream, isReadableFinished } = __nccwpck_require__(5848) const AbortController = globalThis.AbortController || (__nccwpck_require__(7413).AbortController) let PassThrough let Readable let addAbortListener function destroyer(stream, reading, writing) { let finished = false stream.on('close', () => { finished = true }) const cleanup = eos( stream, { readable: reading, writable: writing }, (err) => { finished = !err } ) return { destroy: (err) => { if (finished) return finished = true destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED('pipe')) }, cleanup } } function popCallback(streams) { // Streams should never be an empty array. It should always contain at least // a single stream. Therefore optimize for the average case instead of // checking for length === 0 as well. validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]') return streams.pop() } function makeAsyncIterable(val) { if (isIterable(val)) { return val } else if (isReadableNodeStream(val)) { // Legacy streams are not Iterable. return fromReadable(val) } throw new ERR_INVALID_ARG_TYPE('val', ['Readable', 'Iterable', 'AsyncIterable'], val) } async function* fromReadable(val) { if (!Readable) { Readable = __nccwpck_require__(933) } yield* Readable.prototype[SymbolAsyncIterator].call(val) } async function pumpToNode(iterable, writable, finish, { end }) { let error let onresolve = null const resume = (err) => { if (err) { error = err } if (onresolve) { const callback = onresolve onresolve = null callback() } } const wait = () => new Promise((resolve, reject) => { if (error) { reject(error) } else { onresolve = () => { if (error) { reject(error) } else { resolve() } } } }) writable.on('drain', resume) const cleanup = eos( writable, { readable: false }, resume ) try { if (writable.writableNeedDrain) { await wait() } for await (const chunk of iterable) { if (!writable.write(chunk)) { await wait() } } if (end) { writable.end() await wait() } finish() } catch (err) { finish(error !== err ? aggregateTwoErrors(error, err) : err) } finally { cleanup() writable.off('drain', resume) } } async function pumpToWeb(readable, writable, finish, { end }) { if (isTransformStream(writable)) { writable = writable.writable } // https://streams.spec.whatwg.org/#example-manual-write-with-backpressure const writer = writable.getWriter() try { for await (const chunk of readable) { await writer.ready writer.write(chunk).catch(() => {}) } await writer.ready if (end) { await writer.close() } finish() } catch (err) { try { await writer.abort(err) finish(err) } catch (err) { finish(err) } } } function pipeline(...streams) { return pipelineImpl(streams, once(popCallback(streams))) } function pipelineImpl(streams, callback, opts) { if (streams.length === 1 && ArrayIsArray(streams[0])) { streams = streams[0] } if (streams.length < 2) { throw new ERR_MISSING_ARGS('streams') } const ac = new AbortController() const signal = ac.signal const outerSignal = opts === null || opts === undefined ? undefined : opts.signal // Need to cleanup event listeners if last stream is readable // https://github.com/nodejs/node/issues/35452 const lastStreamCleanup = [] validateAbortSignal(outerSignal, 'options.signal') function abort() { finishImpl(new AbortError()) } addAbortListener = addAbortListener || (__nccwpck_require__(1953).addAbortListener) let disposable if (outerSignal) { disposable = addAbortListener(outerSignal, abort) } let error let value const destroys = [] let finishCount = 0 function finish(err) { finishImpl(err, --finishCount === 0) } function finishImpl(err, final) { var _disposable if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) { error = err } if (!error && !final) { return } while (destroys.length) { destroys.shift()(error) } ;(_disposable = disposable) === null || _disposable === undefined ? undefined : _disposable[SymbolDispose]() ac.abort() if (final) { if (!error) { lastStreamCleanup.forEach((fn) => fn()) } process.nextTick(callback, error, value) } } let ret for (let i = 0; i < streams.length; i++) { const stream = streams[i] const reading = i < streams.length - 1 const writing = i > 0 const end = reading || (opts === null || opts === undefined ? undefined : opts.end) !== false const isLastStream = i === streams.length - 1 if (isNodeStream(stream)) { if (end) { const { destroy, cleanup } = destroyer(stream, reading, writing) destroys.push(destroy) if (isReadable(stream) && isLastStream) { lastStreamCleanup.push(cleanup) } } // Catch stream errors that occur after pipe/pump has completed. function onError(err) { if (err && err.name !== 'AbortError' && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { finish(err) } } stream.on('error', onError) if (isReadable(stream) && isLastStream) { lastStreamCleanup.push(() => { stream.removeListener('error', onError) }) } } if (i === 0) { if (typeof stream === 'function') { ret = stream({ signal }) if (!isIterable(ret)) { throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or Stream', 'source', ret) } } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) { ret = stream } else { ret = Duplex.from(stream) } } else if (typeof stream === 'function') { if (isTransformStream(ret)) { var _ret ret = makeAsyncIterable((_ret = ret) === null || _ret === undefined ? undefined : _ret.readable) } else { ret = makeAsyncIterable(ret) } ret = stream(ret, { signal }) if (reading) { if (!isIterable(ret, true)) { throw new ERR_INVALID_RETURN_VALUE('AsyncIterable', `transform[${i - 1}]`, ret) } } else { var _ret2 if (!PassThrough) { PassThrough = __nccwpck_require__(7179) } // If the last argument to pipeline is not a stream // we must create a proxy stream so that pipeline(...) // always returns a stream which can be further // composed through `.pipe(stream)`. const pt = new PassThrough({ objectMode: true }) // Handle Promises/A+ spec, `then` could be a getter that throws on // second use. const then = (_ret2 = ret) === null || _ret2 === undefined ? undefined : _ret2.then if (typeof then === 'function') { finishCount++ then.call( ret, (val) => { value = val if (val != null) { pt.write(val) } if (end) { pt.end() } process.nextTick(finish) }, (err) => { pt.destroy(err) process.nextTick(finish, err) } ) } else if (isIterable(ret, true)) { finishCount++ pumpToNode(ret, pt, finish, { end }) } else if (isReadableStream(ret) || isTransformStream(ret)) { const toRead = ret.readable || ret finishCount++ pumpToNode(toRead, pt, finish, { end }) } else { throw new ERR_INVALID_RETURN_VALUE('AsyncIterable or Promise', 'destination', ret) } ret = pt const { destroy, cleanup } = destroyer(ret, false, true) destroys.push(destroy) if (isLastStream) { lastStreamCleanup.push(cleanup) } } } else if (isNodeStream(stream)) { if (isReadableNodeStream(ret)) { finishCount += 2 const cleanup = pipe(ret, stream, finish, { end }) if (isReadable(stream) && isLastStream) { lastStreamCleanup.push(cleanup) } } else if (isTransformStream(ret) || isReadableStream(ret)) { const toRead = ret.readable || ret finishCount++ pumpToNode(toRead, stream, finish, { end }) } else if (isIterable(ret)) { finishCount++ pumpToNode(ret, stream, finish, { end }) } else { throw new ERR_INVALID_ARG_TYPE( 'val', ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'], ret ) } ret = stream } else if (isWebStream(stream)) { if (isReadableNodeStream(ret)) { finishCount++ pumpToWeb(makeAsyncIterable(ret), stream, finish, { end }) } else if (isReadableStream(ret) || isIterable(ret)) { finishCount++ pumpToWeb(ret, stream, finish, { end }) } else if (isTransformStream(ret)) { finishCount++ pumpToWeb(ret.readable, stream, finish, { end }) } else { throw new ERR_INVALID_ARG_TYPE( 'val', ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'], ret ) } ret = stream } else { ret = Duplex.from(stream) } } if ( (signal !== null && signal !== undefined && signal.aborted) || (outerSignal !== null && outerSignal !== undefined && outerSignal.aborted) ) { process.nextTick(abort) } return ret } function pipe(src, dst, finish, { end }) { let ended = false dst.on('close', () => { if (!ended) { // Finish if the destination closes before the source has completed. finish(new ERR_STREAM_PREMATURE_CLOSE()) } }) src.pipe(dst, { end: false }) // If end is true we already will have a listener to end dst. if (end) { // Compat. Before node v10.12.0 stdio used to throw an error so // pipe() did/does not end() stdio destinations. // Now they allow it but "secretly" don't close the underlying fd. function endFn() { ended = true dst.end() } if (isReadableFinished(src)) { // End the destination if the source has already ended. process.nextTick(endFn) } else { src.once('end', endFn) } } else { finish() } eos( src, { readable: true, writable: false }, (err) => { const rState = src._readableState if ( err && err.code === 'ERR_STREAM_PREMATURE_CLOSE' && rState && rState.ended && !rState.errored && !rState.errorEmitted ) { // Some readable streams will emit 'close' before 'end'. However, since // this is on the readable side 'end' should still be emitted if the // stream has been ended and no error emitted. This should be allowed in // favor of backwards compatibility. Since the stream is piped to a // destination this should not result in any observable difference. // We don't need to check if this is a writable premature close since // eos will only fail with premature close on the reading side for // duplex streams. src.once('end', finish).once('error', finish) } else { finish(err) } } ) return eos( dst, { readable: false, writable: true }, finish ) } module.exports = { pipelineImpl, pipeline } /***/ }), /***/ 933: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ const { ArrayPrototypeIndexOf, NumberIsInteger, NumberIsNaN, NumberParseInt, ObjectDefineProperties, ObjectKeys, ObjectSetPrototypeOf, Promise, SafeSet, SymbolAsyncDispose, SymbolAsyncIterator, Symbol } = __nccwpck_require__(2177) module.exports = Readable Readable.ReadableState = ReadableState const { EventEmitter: EE } = __nccwpck_require__(4434) const { Stream, prependListener } = __nccwpck_require__(5246) const { Buffer } = __nccwpck_require__(181) const { addAbortSignal } = __nccwpck_require__(9018) const eos = __nccwpck_require__(741) let debug = (__nccwpck_require__(1953).debuglog)('stream', (fn) => { debug = fn }) const BufferList = __nccwpck_require__(9794) const destroyImpl = __nccwpck_require__(6127) const { getHighWaterMark, getDefaultHighWaterMark } = __nccwpck_require__(9648) const { aggregateTwoErrors, codes: { ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED, ERR_OUT_OF_RANGE, ERR_STREAM_PUSH_AFTER_EOF, ERR_STREAM_UNSHIFT_AFTER_END_EVENT }, AbortError } = __nccwpck_require__(5358) const { validateObject } = __nccwpck_require__(3328) const kPaused = Symbol('kPaused') const { StringDecoder } = __nccwpck_require__(1064) const from = __nccwpck_require__(9069) ObjectSetPrototypeOf(Readable.prototype, Stream.prototype) ObjectSetPrototypeOf(Readable, Stream) const nop = () => {} const { errorOrDestroy } = destroyImpl const kObjectMode = 1 << 0 const kEnded = 1 << 1 const kEndEmitted = 1 << 2 const kReading = 1 << 3 const kConstructed = 1 << 4 const kSync = 1 << 5 const kNeedReadable = 1 << 6 const kEmittedReadable = 1 << 7 const kReadableListening = 1 << 8 const kResumeScheduled = 1 << 9 const kErrorEmitted = 1 << 10 const kEmitClose = 1 << 11 const kAutoDestroy = 1 << 12 const kDestroyed = 1 << 13 const kClosed = 1 << 14 const kCloseEmitted = 1 << 15 const kMultiAwaitDrain = 1 << 16 const kReadingMore = 1 << 17 const kDataEmitted = 1 << 18 // TODO(benjamingr) it is likely slower to do it this way than with free functions function makeBitMapDescriptor(bit) { return { enumerable: false, get() { return (this.state & bit) !== 0 }, set(value) { if (value) this.state |= bit else this.state &= ~bit } } } ObjectDefineProperties(ReadableState.prototype, { objectMode: makeBitMapDescriptor(kObjectMode), ended: makeBitMapDescriptor(kEnded), endEmitted: makeBitMapDescriptor(kEndEmitted), reading: makeBitMapDescriptor(kReading), // Stream is still being constructed and cannot be // destroyed until construction finished or failed. // Async construction is opt in, therefore we start as // constructed. constructed: makeBitMapDescriptor(kConstructed), // A flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. sync: makeBitMapDescriptor(kSync), // Whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. needReadable: makeBitMapDescriptor(kNeedReadable), emittedReadable: makeBitMapDescriptor(kEmittedReadable), readableListening: makeBitMapDescriptor(kReadableListening), resumeScheduled: makeBitMapDescriptor(kResumeScheduled), // True if the error was already emitted and should not be thrown again. errorEmitted: makeBitMapDescriptor(kErrorEmitted), emitClose: makeBitMapDescriptor(kEmitClose), autoDestroy: makeBitMapDescriptor(kAutoDestroy), // Has it been destroyed. destroyed: makeBitMapDescriptor(kDestroyed), // Indicates whether the stream has finished destroying. closed: makeBitMapDescriptor(kClosed), // True if close has been emitted or would have been emitted // depending on emitClose. closeEmitted: makeBitMapDescriptor(kCloseEmitted), multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain), // If true, a maybeReadMore has been scheduled. readingMore: makeBitMapDescriptor(kReadingMore), dataEmitted: makeBitMapDescriptor(kDataEmitted) }) function ReadableState(options, stream, isDuplex) { // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof __nccwpck_require__(2327) // Bit map field to store ReadableState more effciently with 1 bit per field // instead of a V8 slot per field. this.state = kEmitClose | kAutoDestroy | kConstructed | kSync // Object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away. if (options && options.objectMode) this.state |= kObjectMode if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode // The point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" this.highWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex) : getDefaultHighWaterMark(false) // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift(). this.buffer = new BufferList() this.length = 0 this.pipes = [] this.flowing = null this[kPaused] = null // Should close be emitted on destroy. Defaults to true. if (options && options.emitClose === false) this.state &= ~kEmitClose // Should .destroy() be called after 'end' (and potentially 'finish'). if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy // Indicates whether the stream has errored. When true no further // _read calls, 'data' or 'readable' events should occur. This is needed // since when autoDestroy is disabled we need a way to tell whether the // stream has failed. this.errored = null // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = (options && options.defaultEncoding) || 'utf8' // Ref the piped dest which we need a drain event on it // type: null | Writable | Set. this.awaitDrainWriters = null this.decoder = null this.encoding = null if (options && options.encoding) { this.decoder = new StringDecoder(options.encoding) this.encoding = options.encoding } } function Readable(options) { if (!(this instanceof Readable)) return new Readable(options) // Checking for a Stream.Duplex instance is faster here instead of inside // the ReadableState constructor, at least with V8 6.5. const isDuplex = this instanceof __nccwpck_require__(2327) this._readableState = new ReadableState(options, this, isDuplex) if (options) { if (typeof options.read === 'function') this._read = options.read if (typeof options.destroy === 'function') this._destroy = options.destroy if (typeof options.construct === 'function') this._construct = options.construct if (options.signal && !isDuplex) addAbortSignal(options.signal, this) } Stream.call(this, options) destroyImpl.construct(this, () => { if (this._readableState.needReadable) { maybeReadMore(this, this._readableState) } }) } Readable.prototype.destroy = destroyImpl.destroy Readable.prototype._undestroy = destroyImpl.undestroy Readable.prototype._destroy = function (err, cb) { cb(err) } Readable.prototype[EE.captureRejectionSymbol] = function (err) { this.destroy(err) } Readable.prototype[SymbolAsyncDispose] = function () { let error if (!this.destroyed) { error = this.readableEnded ? null : new AbortError() this.destroy(error) } return new Promise((resolve, reject) => eos(this, (err) => (err && err !== error ? reject(err) : resolve(null)))) } // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { return readableAddChunk(this, chunk, encoding, false) } // Unshift should *always* be something directly out of read(). Readable.prototype.unshift = function (chunk, encoding) { return readableAddChunk(this, chunk, encoding, true) } function readableAddChunk(stream, chunk, encoding, addToFront) { debug('readableAddChunk', chunk) const state = stream._readableState let err if ((state.state & kObjectMode) === 0) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding if (state.encoding !== encoding) { if (addToFront && state.encoding) { // When unshifting, if state.encoding is set, we have to save // the string in the BufferList with the state encoding. chunk = Buffer.from(chunk, encoding).toString(state.encoding) } else { chunk = Buffer.from(chunk, encoding) encoding = '' } } } else if (chunk instanceof Buffer) { encoding = '' } else if (Stream._isUint8Array(chunk)) { chunk = Stream._uint8ArrayToBuffer(chunk) encoding = '' } else if (chunk != null) { err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk) } } if (err) { errorOrDestroy(stream, err) } else if (chunk === null) { state.state &= ~kReading onEofChunk(stream, state) } else if ((state.state & kObjectMode) !== 0 || (chunk && chunk.length > 0)) { if (addToFront) { if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()) else if (state.destroyed || state.errored) return false else addChunk(stream, state, chunk, true) } else if (state.ended) { errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()) } else if (state.destroyed || state.errored) { return false } else { state.state &= ~kReading if (state.decoder && !encoding) { chunk = state.decoder.write(chunk) if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false) else maybeReadMore(stream, state) } else { addChunk(stream, state, chunk, false) } } } else if (!addToFront) { state.state &= ~kReading maybeReadMore(stream, state) } // We can push more data if we are below the highWaterMark. // Also, if we have no data yet, we can stand some more bytes. // This is to work around cases where hwm=0, such as the repl. return !state.ended && (state.length < state.highWaterMark || state.length === 0) } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount('data') > 0) { // Use the guard to avoid creating `Set()` repeatedly // when we have multiple pipes. if ((state.state & kMultiAwaitDrain) !== 0) { state.awaitDrainWriters.clear() } else { state.awaitDrainWriters = null } state.dataEmitted = true stream.emit('data', chunk) } else { // Update the buffer info. state.length += state.objectMode ? 1 : chunk.length if (addToFront) state.buffer.unshift(chunk) else state.buffer.push(chunk) if ((state.state & kNeedReadable) !== 0) emitReadable(stream) } maybeReadMore(stream, state) } Readable.prototype.isPaused = function () { const state = this._readableState return state[kPaused] === true || state.flowing === false } // Backwards compatibility. Readable.prototype.setEncoding = function (enc) { const decoder = new StringDecoder(enc) this._readableState.decoder = decoder // If setEncoding(null), decoder.encoding equals utf8. this._readableState.encoding = this._readableState.decoder.encoding const buffer = this._readableState.buffer // Iterate over current buffer to convert already stored Buffers: let content = '' for (const data of buffer) { content += decoder.write(data) } buffer.clear() if (content !== '') buffer.push(content) this._readableState.length = content.length return this } // Don't raise the hwm > 1GB. const MAX_HWM = 0x40000000 function computeNewHighWaterMark(n) { if (n > MAX_HWM) { throw new ERR_OUT_OF_RANGE('size', '<= 1GiB', n) } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts. n-- n |= n >>> 1 n |= n >>> 2 n |= n >>> 4 n |= n >>> 8 n |= n >>> 16 n++ } return n } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || (state.length === 0 && state.ended)) return 0 if ((state.state & kObjectMode) !== 0) return 1 if (NumberIsNaN(n)) { // Only flow one buffer at a time. if (state.flowing && state.length) return state.buffer.first().length return state.length } if (n <= state.length) return n return state.ended ? state.length : 0 } // You can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n) // Same as parseInt(undefined, 10), however V8 7.3 performance regressed // in this scenario, so we are doing it manually. if (n === undefined) { n = NaN } else if (!NumberIsInteger(n)) { n = NumberParseInt(n, 10) } const state = this._readableState const nOrig = n // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n) if (n !== 0) state.state &= ~kEmittedReadable // If we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if ( n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended) ) { debug('read: emitReadable', state.length, state.ended) if (state.length === 0 && state.ended) endReadable(this) else emitReadable(this) return null } n = howMuchToRead(n, state) // If we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this) return null } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. let doRead = (state.state & kNeedReadable) !== 0 debug('need readable', doRead) // If we currently have less than the highWaterMark, then also read some. if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true debug('length less than watermark', doRead) } // However, if we've ended, then there's no point, if we're already // reading, then it's unnecessary, if we're constructing we have to wait, // and if we're destroyed or errored, then it's not allowed, if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) { doRead = false debug('reading, ended or constructing', doRead) } else if (doRead) { debug('do read') state.state |= kReading | kSync // If the length is currently zero, then we *need* a readable event. if (state.length === 0) state.state |= kNeedReadable // Call internal read method try { this._read(state.highWaterMark) } catch (err) { errorOrDestroy(this, err) } state.state &= ~kSync // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state) } let ret if (n > 0) ret = fromList(n, state) else ret = null if (ret === null) { state.needReadable = state.length <= state.highWaterMark n = 0 } else { state.length -= n if (state.multiAwaitDrain) { state.awaitDrainWriters.clear() } else { state.awaitDrainWriters = null } } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this) } if (ret !== null && !state.errorEmitted && !state.closeEmitted) { state.dataEmitted = true this.emit('data', ret) } return ret } function onEofChunk(stream, state) { debug('onEofChunk') if (state.ended) return if (state.decoder) { const chunk = state.decoder.end() if (chunk && chunk.length) { state.buffer.push(chunk) state.length += state.objectMode ? 1 : chunk.length } } state.ended = true if (state.sync) { // If we are sync, wait until next tick to emit the data. // Otherwise we risk emitting data in the flow() // the readable code triggers during a read() call. emitReadable(stream) } else { // Emit 'readable' now to make sure it gets picked up. state.needReadable = false state.emittedReadable = true // We have to emit readable now that we are EOF. Modules // in the ecosystem (e.g. dicer) rely on this event being sync. emitReadable_(stream) } } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { const state = stream._readableState debug('emitReadable', state.needReadable, state.emittedReadable) state.needReadable = false if (!state.emittedReadable) { debug('emitReadable', state.flowing) state.emittedReadable = true process.nextTick(emitReadable_, stream) } } function emitReadable_(stream) { const state = stream._readableState debug('emitReadable_', state.destroyed, state.length, state.ended) if (!state.destroyed && !state.errored && (state.length || state.ended)) { stream.emit('readable') state.emittedReadable = false } // The stream needs another readable event if: // 1. It is not flowing, as the flow mechanism will take // care of it. // 2. It is not ended. // 3. It is below the highWaterMark, so we can schedule // another readable later. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark flow(stream) } // At this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore && state.constructed) { state.readingMore = true process.nextTick(maybeReadMore_, stream, state) } } function maybeReadMore_(stream, state) { // Attempt to read more data if we should. // // The conditions for reading more data are (one of): // - Not enough data buffered (state.length < state.highWaterMark). The loop // is responsible for filling the buffer with enough data if such data // is available. If highWaterMark is 0 and we are not in the flowing mode // we should _not_ attempt to buffer any extra data. We'll get more data // when the stream consumer calls read() instead. // - No data in the buffer, and the stream is in flowing mode. In this mode // the loop below is responsible for ensuring read() is called. Failing to // call read here would abort the flow and there's no other mechanism for // continuing the flow if the stream consumer has just subscribed to the // 'data' event. // // In addition to the above conditions to keep reading data, the following // conditions prevent the data from being read: // - The stream has ended (state.ended). // - There is already a pending 'read' operation (state.reading). This is a // case where the stream has called the implementation defined _read() // method, but they are processing the call asynchronously and have _not_ // called push() with new data. In this case we skip performing more // read()s. The execution ends in this method again after the _read() ends // up calling push() with more data. while ( !state.reading && !state.ended && (state.length < state.highWaterMark || (state.flowing && state.length === 0)) ) { const len = state.length debug('maybeReadMore read 0') stream.read(0) if (len === state.length) // Didn't get any data, stop spinning. break } state.readingMore = false } // Abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { throw new ERR_METHOD_NOT_IMPLEMENTED('_read()') } Readable.prototype.pipe = function (dest, pipeOpts) { const src = this const state = this._readableState if (state.pipes.length === 1) { if (!state.multiAwaitDrain) { state.multiAwaitDrain = true state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : []) } } state.pipes.push(dest) debug('pipe count=%d opts=%j', state.pipes.length, pipeOpts) const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr const endFn = doEnd ? onend : unpipe if (state.endEmitted) process.nextTick(endFn) else src.once('end', endFn) dest.on('unpipe', onunpipe) function onunpipe(readable, unpipeInfo) { debug('onunpipe') if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true cleanup() } } } function onend() { debug('onend') dest.end() } let ondrain let cleanedUp = false function cleanup() { debug('cleanup') // Cleanup event handlers once the pipe is broken. dest.removeListener('close', onclose) dest.removeListener('finish', onfinish) if (ondrain) { dest.removeListener('drain', ondrain) } dest.removeListener('error', onerror) dest.removeListener('unpipe', onunpipe) src.removeListener('end', onend) src.removeListener('end', unpipe) src.removeListener('data', ondata) cleanedUp = true // If the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain() } function pause() { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if (!cleanedUp) { if (state.pipes.length === 1 && state.pipes[0] === dest) { debug('false write response, pause', 0) state.awaitDrainWriters = dest state.multiAwaitDrain = false } else if (state.pipes.length > 1 && state.pipes.includes(dest)) { debug('false write response, pause', state.awaitDrainWriters.size) state.awaitDrainWriters.add(dest) } src.pause() } if (!ondrain) { // When the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. ondrain = pipeOnDrain(src, dest) dest.on('drain', ondrain) } } src.on('data', ondata) function ondata(chunk) { debug('ondata') const ret = dest.write(chunk) debug('dest.write', ret) if (ret === false) { pause() } } // If the dest has an error, then stop piping into it. // However, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er) unpipe() dest.removeListener('error', onerror) if (dest.listenerCount('error') === 0) { const s = dest._writableState || dest._readableState if (s && !s.errorEmitted) { // User incorrectly emitted 'error' directly on the stream. errorOrDestroy(dest, er) } else { dest.emit('error', er) } } } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror) // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish) unpipe() } dest.once('close', onclose) function onfinish() { debug('onfinish') dest.removeListener('close', onclose) unpipe() } dest.once('finish', onfinish) function unpipe() { debug('unpipe') src.unpipe(dest) } // Tell the dest that it's being piped to. dest.emit('pipe', src) // Start the flow if it hasn't been started already. if (dest.writableNeedDrain === true) { pause() } else if (!state.flowing) { debug('pipe resume') src.resume() } return dest } function pipeOnDrain(src, dest) { return function pipeOnDrainFunctionResult() { const state = src._readableState // `ondrain` will call directly, // `this` maybe not a reference to dest, // so we use the real dest here. if (state.awaitDrainWriters === dest) { debug('pipeOnDrain', 1) state.awaitDrainWriters = null } else if (state.multiAwaitDrain) { debug('pipeOnDrain', state.awaitDrainWriters.size) state.awaitDrainWriters.delete(dest) } if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount('data')) { src.resume() } } } Readable.prototype.unpipe = function (dest) { const state = this._readableState const unpipeInfo = { hasUnpiped: false } // If we're not piping anywhere, then do nothing. if (state.pipes.length === 0) return this if (!dest) { // remove all. const dests = state.pipes state.pipes = [] this.pause() for (let i = 0; i < dests.length; i++) dests[i].emit('unpipe', this, { hasUnpiped: false }) return this } // Try to find the right one. const index = ArrayPrototypeIndexOf(state.pipes, dest) if (index === -1) return this state.pipes.splice(index, 1) if (state.pipes.length === 0) this.pause() dest.emit('unpipe', this, unpipeInfo) return this } // Set up data events if they are asked for // Ensure readable listeners eventually get something. Readable.prototype.on = function (ev, fn) { const res = Stream.prototype.on.call(this, ev, fn) const state = this._readableState if (ev === 'data') { // Update readableListening so that resume() may be a no-op // a few lines down. This is needed to support once('readable'). state.readableListening = this.listenerCount('readable') > 0 // Try start flowing on next tick if stream isn't explicitly paused. if (state.flowing !== false) this.resume() } else if (ev === 'readable') { if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true state.flowing = false state.emittedReadable = false debug('on readable', state.length, state.reading) if (state.length) { emitReadable(this) } else if (!state.reading) { process.nextTick(nReadingNextTick, this) } } } return res } Readable.prototype.addListener = Readable.prototype.on Readable.prototype.removeListener = function (ev, fn) { const res = Stream.prototype.removeListener.call(this, ev, fn) if (ev === 'readable') { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen // after readable has been emitted but before I/O (nextTick) to // support once('readable', fn) cycles. This means that calling // resume within the same tick will have no // effect. process.nextTick(updateReadableListening, this) } return res } Readable.prototype.off = Readable.prototype.removeListener Readable.prototype.removeAllListeners = function (ev) { const res = Stream.prototype.removeAllListeners.apply(this, arguments) if (ev === 'readable' || ev === undefined) { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen // after readable has been emitted but before I/O (nextTick) to // support once('readable', fn) cycles. This means that calling // resume within the same tick will have no // effect. process.nextTick(updateReadableListening, this) } return res } function updateReadableListening(self) { const state = self._readableState state.readableListening = self.listenerCount('readable') > 0 if (state.resumeScheduled && state[kPaused] === false) { // Flowing needs to be set to true now, otherwise // the upcoming resume will not flow. state.flowing = true // Crude way to check if we should resume. } else if (self.listenerCount('data') > 0) { self.resume() } else if (!state.readableListening) { state.flowing = null } } function nReadingNextTick(self) { debug('readable nexttick read 0') self.read(0) } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { const state = this._readableState if (!state.flowing) { debug('resume') // We flow only if there is no one listening // for readable, but we still have to call // resume(). state.flowing = !state.readableListening resume(this, state) } state[kPaused] = false return this } function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true process.nextTick(resume_, stream, state) } } function resume_(stream, state) { debug('resume', state.reading) if (!state.reading) { stream.read(0) } state.resumeScheduled = false stream.emit('resume') flow(stream) if (state.flowing && !state.reading) stream.read(0) } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing) if (this._readableState.flowing !== false) { debug('pause') this._readableState.flowing = false this.emit('pause') } this._readableState[kPaused] = true return this } function flow(stream) { const state = stream._readableState debug('flow', state.flowing) while (state.flowing && stream.read() !== null); } // Wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { let paused = false // TODO (ronag): Should this.destroy(err) emit // 'error' on the wrapped stream? Would require // a static factory method, e.g. Readable.wrap(stream). stream.on('data', (chunk) => { if (!this.push(chunk) && stream.pause) { paused = true stream.pause() } }) stream.on('end', () => { this.push(null) }) stream.on('error', (err) => { errorOrDestroy(this, err) }) stream.on('close', () => { this.destroy() }) stream.on('destroy', () => { this.destroy() }) this._read = () => { if (paused && stream.resume) { paused = false stream.resume() } } // Proxy all the other methods. Important when wrapping filters and duplexes. const streamKeys = ObjectKeys(stream) for (let j = 1; j < streamKeys.length; j++) { const i = streamKeys[j] if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = stream[i].bind(stream) } } return this } Readable.prototype[SymbolAsyncIterator] = function () { return streamToAsyncIterator(this) } Readable.prototype.iterator = function (options) { if (options !== undefined) { validateObject(options, 'options') } return streamToAsyncIterator(this, options) } function streamToAsyncIterator(stream, options) { if (typeof stream.read !== 'function') { stream = Readable.wrap(stream, { objectMode: true }) } const iter = createAsyncIterator(stream, options) iter.stream = stream return iter } async function* createAsyncIterator(stream, options) { let callback = nop function next(resolve) { if (this === stream) { callback() callback = nop } else { callback = resolve } } stream.on('readable', next) let error const cleanup = eos( stream, { writable: false }, (err) => { error = err ? aggregateTwoErrors(error, err) : null callback() callback = nop } ) try { while (true) { const chunk = stream.destroyed ? null : stream.read() if (chunk !== null) { yield chunk } else if (error) { throw error } else if (error === null) { return } else { await new Promise(next) } } } catch (err) { error = aggregateTwoErrors(error, err) throw error } finally { if ( (error || (options === null || options === undefined ? undefined : options.destroyOnReturn) !== false) && (error === undefined || stream._readableState.autoDestroy) ) { destroyImpl.destroyer(stream, null) } else { stream.off('readable', next) cleanup() } } } // Making it explicit these properties are not enumerable // because otherwise some prototype manipulation in // userland will fail. ObjectDefineProperties(Readable.prototype, { readable: { __proto__: null, get() { const r = this._readableState // r.readable === false means that this is part of a Duplex stream // where the readable side was disabled upon construction. // Compat. The user might manually disable readable side through // deprecated setter. return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted }, set(val) { // Backwards compat. if (this._readableState) { this._readableState.readable = !!val } } }, readableDidRead: { __proto__: null, enumerable: false, get: function () { return this._readableState.dataEmitted } }, readableAborted: { __proto__: null, enumerable: false, get: function () { return !!( this._readableState.readable !== false && (this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted ) } }, readableHighWaterMark: { __proto__: null, enumerable: false, get: function () { return this._readableState.highWaterMark } }, readableBuffer: { __proto__: null, enumerable: false, get: function () { return this._readableState && this._readableState.buffer } }, readableFlowing: { __proto__: null, enumerable: false, get: function () { return this._readableState.flowing }, set: function (state) { if (this._readableState) { this._readableState.flowing = state } } }, readableLength: { __proto__: null, enumerable: false, get() { return this._readableState.length } }, readableObjectMode: { __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.objectMode : false } }, readableEncoding: { __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.encoding : null } }, errored: { __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.errored : null } }, closed: { __proto__: null, get() { return this._readableState ? this._readableState.closed : false } }, destroyed: { __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.destroyed : false }, set(value) { // We ignore the value if the stream // has not been initialized yet. if (!this._readableState) { return } // Backward compatibility, the user is explicitly // managing destroyed. this._readableState.destroyed = value } }, readableEnded: { __proto__: null, enumerable: false, get() { return this._readableState ? this._readableState.endEmitted : false } } }) ObjectDefineProperties(ReadableState.prototype, { // Legacy getter for `pipesCount`. pipesCount: { __proto__: null, get() { return this.pipes.length } }, // Legacy property for `paused`. paused: { __proto__: null, get() { return this[kPaused] !== false }, set(value) { this[kPaused] = !!value } } }) // Exposed for testing purposes only. Readable._fromList = fromList // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered. if (state.length === 0) return null let ret if (state.objectMode) ret = state.buffer.shift() else if (!n || n >= state.length) { // Read it all, truncate the list. if (state.decoder) ret = state.buffer.join('') else if (state.buffer.length === 1) ret = state.buffer.first() else ret = state.buffer.concat(state.length) state.buffer.clear() } else { // read part of list. ret = state.buffer.consume(n, state.decoder) } return ret } function endReadable(stream) { const state = stream._readableState debug('endReadable', state.endEmitted) if (!state.endEmitted) { state.ended = true process.nextTick(endReadableNT, state, stream) } } function endReadableNT(state, stream) { debug('endReadableNT', state.endEmitted, state.length) // Check that we didn't get one last unshift. if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) { state.endEmitted = true stream.emit('end') if (stream.writable && stream.allowHalfOpen === false) { process.nextTick(endWritableNT, stream) } else if (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the writable side is ready for autoDestroy as well. const wState = stream._writableState const autoDestroy = !wState || (wState.autoDestroy && // We don't expect the writable to ever 'finish' // if writable is explicitly set to false. (wState.finished || wState.writable === false)) if (autoDestroy) { stream.destroy() } } } } function endWritableNT(stream) { const writable = stream.writable && !stream.writableEnded && !stream.destroyed if (writable) { stream.end() } } Readable.from = function (iterable, opts) { return from(Readable, iterable, opts) } let webStreamsAdapters // Lazy to avoid circular references function lazyWebStreams() { if (webStreamsAdapters === undefined) webStreamsAdapters = {} return webStreamsAdapters } Readable.fromWeb = function (readableStream, options) { return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options) } Readable.toWeb = function (streamReadable, options) { return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options) } Readable.wrap = function (src, options) { var _ref, _src$readableObjectMo return new Readable({ objectMode: (_ref = (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== undefined ? _src$readableObjectMo : src.objectMode) !== null && _ref !== undefined ? _ref : true, ...options, destroy(err, callback) { destroyImpl.destroyer(src, err) callback(err) } }).wrap(src) } /***/ }), /***/ 9648: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { MathFloor, NumberIsInteger } = __nccwpck_require__(2177) const { validateInteger } = __nccwpck_require__(3328) const { ERR_INVALID_ARG_VALUE } = (__nccwpck_require__(5358).codes) let defaultHighWaterMarkBytes = 16 * 1024 let defaultHighWaterMarkObjectMode = 16 function highWaterMarkFrom(options, isDuplex, duplexKey) { return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null } function getDefaultHighWaterMark(objectMode) { return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes } function setDefaultHighWaterMark(objectMode, value) { validateInteger(value, 'value', 0) if (objectMode) { defaultHighWaterMarkObjectMode = value } else { defaultHighWaterMarkBytes = value } } function getHighWaterMark(state, options, duplexKey, isDuplex) { const hwm = highWaterMarkFrom(options, isDuplex, duplexKey) if (hwm != null) { if (!NumberIsInteger(hwm) || hwm < 0) { const name = isDuplex ? `options.${duplexKey}` : 'options.highWaterMark' throw new ERR_INVALID_ARG_VALUE(name, hwm) } return MathFloor(hwm) } // Default value return getDefaultHighWaterMark(state.objectMode) } module.exports = { getHighWaterMark, getDefaultHighWaterMark, setDefaultHighWaterMark } /***/ }), /***/ 7689: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. const { ObjectSetPrototypeOf, Symbol } = __nccwpck_require__(2177) module.exports = Transform const { ERR_METHOD_NOT_IMPLEMENTED } = (__nccwpck_require__(5358).codes) const Duplex = __nccwpck_require__(2327) const { getHighWaterMark } = __nccwpck_require__(9648) ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype) ObjectSetPrototypeOf(Transform, Duplex) const kCallback = Symbol('kCallback') function Transform(options) { if (!(this instanceof Transform)) return new Transform(options) // TODO (ronag): This should preferably always be // applied but would be semver-major. Or even better; // make Transform a Readable with the Writable interface. const readableHighWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', true) : null if (readableHighWaterMark === 0) { // A Duplex will buffer both on the writable and readable side while // a Transform just wants to buffer hwm number of elements. To avoid // buffering twice we disable buffering on the writable side. options = { ...options, highWaterMark: null, readableHighWaterMark, // TODO (ronag): 0 is not optimal since we have // a "bug" where we check needDrain before calling _write and not after. // Refs: https://github.com/nodejs/node/pull/32887 // Refs: https://github.com/nodejs/node/pull/35941 writableHighWaterMark: options.writableHighWaterMark || 0 } } Duplex.call(this, options) // We have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false this[kCallback] = null if (options) { if (typeof options.transform === 'function') this._transform = options.transform if (typeof options.flush === 'function') this._flush = options.flush } // When the writable side finishes, then flush out anything remaining. // Backwards compat. Some Transform streams incorrectly implement _final // instead of or in addition to _flush. By using 'prefinish' instead of // implementing _final we continue supporting this unfortunate use case. this.on('prefinish', prefinish) } function final(cb) { if (typeof this._flush === 'function' && !this.destroyed) { this._flush((er, data) => { if (er) { if (cb) { cb(er) } else { this.destroy(er) } return } if (data != null) { this.push(data) } this.push(null) if (cb) { cb() } }) } else { this.push(null) if (cb) { cb() } } } function prefinish() { if (this._final !== final) { final.call(this) } } Transform.prototype._final = final Transform.prototype._transform = function (chunk, encoding, callback) { throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()') } Transform.prototype._write = function (chunk, encoding, callback) { const rState = this._readableState const wState = this._writableState const length = rState.length this._transform(chunk, encoding, (err, val) => { if (err) { callback(err) return } if (val != null) { this.push(val) } if ( wState.ended || // Backwards compat. length === rState.length || // Backwards compat. rState.length < rState.highWaterMark ) { callback() } else { this[kCallback] = callback } }) } Transform.prototype._read = function () { if (this[kCallback]) { const callback = this[kCallback] this[kCallback] = null callback() } } /***/ }), /***/ 5848: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { SymbolAsyncIterator, SymbolIterator, SymbolFor } = __nccwpck_require__(2177) // We need to use SymbolFor to make these globally available // for interopt with readable-stream, i.e. readable-stream // and node core needs to be able to read/write private state // from each other for proper interoperability. const kIsDestroyed = SymbolFor('nodejs.stream.destroyed') const kIsErrored = SymbolFor('nodejs.stream.errored') const kIsReadable = SymbolFor('nodejs.stream.readable') const kIsWritable = SymbolFor('nodejs.stream.writable') const kIsDisturbed = SymbolFor('nodejs.stream.disturbed') const kIsClosedPromise = SymbolFor('nodejs.webstream.isClosedPromise') const kControllerErrorFunction = SymbolFor('nodejs.webstream.controllerErrorFunction') function isReadableNodeStream(obj, strict = false) { var _obj$_readableState return !!( ( obj && typeof obj.pipe === 'function' && typeof obj.on === 'function' && (!strict || (typeof obj.pause === 'function' && typeof obj.resume === 'function')) && (!obj._writableState || ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === undefined ? undefined : _obj$_readableState.readable) !== false) && // Duplex (!obj._writableState || obj._readableState) ) // Writable has .pipe. ) } function isWritableNodeStream(obj) { var _obj$_writableState return !!( ( obj && typeof obj.write === 'function' && typeof obj.on === 'function' && (!obj._readableState || ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === undefined ? undefined : _obj$_writableState.writable) !== false) ) // Duplex ) } function isDuplexNodeStream(obj) { return !!( obj && typeof obj.pipe === 'function' && obj._readableState && typeof obj.on === 'function' && typeof obj.write === 'function' ) } function isNodeStream(obj) { return ( obj && (obj._readableState || obj._writableState || (typeof obj.write === 'function' && typeof obj.on === 'function') || (typeof obj.pipe === 'function' && typeof obj.on === 'function')) ) } function isReadableStream(obj) { return !!( obj && !isNodeStream(obj) && typeof obj.pipeThrough === 'function' && typeof obj.getReader === 'function' && typeof obj.cancel === 'function' ) } function isWritableStream(obj) { return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === 'function' && typeof obj.abort === 'function') } function isTransformStream(obj) { return !!(obj && !isNodeStream(obj) && typeof obj.readable === 'object' && typeof obj.writable === 'object') } function isWebStream(obj) { return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj) } function isIterable(obj, isAsync) { if (obj == null) return false if (isAsync === true) return typeof obj[SymbolAsyncIterator] === 'function' if (isAsync === false) return typeof obj[SymbolIterator] === 'function' return typeof obj[SymbolAsyncIterator] === 'function' || typeof obj[SymbolIterator] === 'function' } function isDestroyed(stream) { if (!isNodeStream(stream)) return null const wState = stream._writableState const rState = stream._readableState const state = wState || rState return !!(stream.destroyed || stream[kIsDestroyed] || (state !== null && state !== undefined && state.destroyed)) } // Have been end():d. function isWritableEnded(stream) { if (!isWritableNodeStream(stream)) return null if (stream.writableEnded === true) return true const wState = stream._writableState if (wState !== null && wState !== undefined && wState.errored) return false if (typeof (wState === null || wState === undefined ? undefined : wState.ended) !== 'boolean') return null return wState.ended } // Have emitted 'finish'. function isWritableFinished(stream, strict) { if (!isWritableNodeStream(stream)) return null if (stream.writableFinished === true) return true const wState = stream._writableState if (wState !== null && wState !== undefined && wState.errored) return false if (typeof (wState === null || wState === undefined ? undefined : wState.finished) !== 'boolean') return null return !!(wState.finished || (strict === false && wState.ended === true && wState.length === 0)) } // Have been push(null):d. function isReadableEnded(stream) { if (!isReadableNodeStream(stream)) return null if (stream.readableEnded === true) return true const rState = stream._readableState if (!rState || rState.errored) return false if (typeof (rState === null || rState === undefined ? undefined : rState.ended) !== 'boolean') return null return rState.ended } // Have emitted 'end'. function isReadableFinished(stream, strict) { if (!isReadableNodeStream(stream)) return null const rState = stream._readableState if (rState !== null && rState !== undefined && rState.errored) return false if (typeof (rState === null || rState === undefined ? undefined : rState.endEmitted) !== 'boolean') return null return !!(rState.endEmitted || (strict === false && rState.ended === true && rState.length === 0)) } function isReadable(stream) { if (stream && stream[kIsReadable] != null) return stream[kIsReadable] if (typeof (stream === null || stream === undefined ? undefined : stream.readable) !== 'boolean') return null if (isDestroyed(stream)) return false return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream) } function isWritable(stream) { if (stream && stream[kIsWritable] != null) return stream[kIsWritable] if (typeof (stream === null || stream === undefined ? undefined : stream.writable) !== 'boolean') return null if (isDestroyed(stream)) return false return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream) } function isFinished(stream, opts) { if (!isNodeStream(stream)) { return null } if (isDestroyed(stream)) { return true } if ((opts === null || opts === undefined ? undefined : opts.readable) !== false && isReadable(stream)) { return false } if ((opts === null || opts === undefined ? undefined : opts.writable) !== false && isWritable(stream)) { return false } return true } function isWritableErrored(stream) { var _stream$_writableStat, _stream$_writableStat2 if (!isNodeStream(stream)) { return null } if (stream.writableErrored) { return stream.writableErrored } return (_stream$_writableStat = (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === undefined ? undefined : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== undefined ? _stream$_writableStat : null } function isReadableErrored(stream) { var _stream$_readableStat, _stream$_readableStat2 if (!isNodeStream(stream)) { return null } if (stream.readableErrored) { return stream.readableErrored } return (_stream$_readableStat = (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === undefined ? undefined : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== undefined ? _stream$_readableStat : null } function isClosed(stream) { if (!isNodeStream(stream)) { return null } if (typeof stream.closed === 'boolean') { return stream.closed } const wState = stream._writableState const rState = stream._readableState if ( typeof (wState === null || wState === undefined ? undefined : wState.closed) === 'boolean' || typeof (rState === null || rState === undefined ? undefined : rState.closed) === 'boolean' ) { return ( (wState === null || wState === undefined ? undefined : wState.closed) || (rState === null || rState === undefined ? undefined : rState.closed) ) } if (typeof stream._closed === 'boolean' && isOutgoingMessage(stream)) { return stream._closed } return null } function isOutgoingMessage(stream) { return ( typeof stream._closed === 'boolean' && typeof stream._defaultKeepAlive === 'boolean' && typeof stream._removedConnection === 'boolean' && typeof stream._removedContLen === 'boolean' ) } function isServerResponse(stream) { return typeof stream._sent100 === 'boolean' && isOutgoingMessage(stream) } function isServerRequest(stream) { var _stream$req return ( typeof stream._consuming === 'boolean' && typeof stream._dumped === 'boolean' && ((_stream$req = stream.req) === null || _stream$req === undefined ? undefined : _stream$req.upgradeOrConnect) === undefined ) } function willEmitClose(stream) { if (!isNodeStream(stream)) return null const wState = stream._writableState const rState = stream._readableState const state = wState || rState return ( (!state && isServerResponse(stream)) || !!(state && state.autoDestroy && state.emitClose && state.closed === false) ) } function isDisturbed(stream) { var _stream$kIsDisturbed return !!( stream && ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== undefined ? _stream$kIsDisturbed : stream.readableDidRead || stream.readableAborted) ) } function isErrored(stream) { var _ref, _ref2, _ref3, _ref4, _ref5, _stream$kIsErrored, _stream$_readableStat3, _stream$_writableStat3, _stream$_readableStat4, _stream$_writableStat4 return !!( stream && ((_ref = (_ref2 = (_ref3 = (_ref4 = (_ref5 = (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== undefined ? _stream$kIsErrored : stream.readableErrored) !== null && _ref5 !== undefined ? _ref5 : stream.writableErrored) !== null && _ref4 !== undefined ? _ref4 : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === undefined ? undefined : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== undefined ? _ref3 : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === undefined ? undefined : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== undefined ? _ref2 : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === undefined ? undefined : _stream$_readableStat4.errored) !== null && _ref !== undefined ? _ref : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === undefined ? undefined : _stream$_writableStat4.errored) ) } module.exports = { isDestroyed, kIsDestroyed, isDisturbed, kIsDisturbed, isErrored, kIsErrored, isReadable, kIsReadable, kIsClosedPromise, kControllerErrorFunction, kIsWritable, isClosed, isDuplexNodeStream, isFinished, isIterable, isReadableNodeStream, isReadableStream, isReadableEnded, isReadableFinished, isReadableErrored, isNodeStream, isWebStream, isWritable, isWritableNodeStream, isWritableStream, isWritableEnded, isWritableFinished, isWritableErrored, isServerRequest, isServerResponse, willEmitClose, isTransformStream } /***/ }), /***/ 9557: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. /* replacement start */ const process = __nccwpck_require__(7945) /* replacement end */ const { ArrayPrototypeSlice, Error, FunctionPrototypeSymbolHasInstance, ObjectDefineProperty, ObjectDefineProperties, ObjectSetPrototypeOf, StringPrototypeToLowerCase, Symbol, SymbolHasInstance } = __nccwpck_require__(2177) module.exports = Writable Writable.WritableState = WritableState const { EventEmitter: EE } = __nccwpck_require__(4434) const Stream = (__nccwpck_require__(5246).Stream) const { Buffer } = __nccwpck_require__(181) const destroyImpl = __nccwpck_require__(6127) const { addAbortSignal } = __nccwpck_require__(9018) const { getHighWaterMark, getDefaultHighWaterMark } = __nccwpck_require__(9648) const { ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED, ERR_STREAM_ALREADY_FINISHED, ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING } = (__nccwpck_require__(5358).codes) const { errorOrDestroy } = destroyImpl ObjectSetPrototypeOf(Writable.prototype, Stream.prototype) ObjectSetPrototypeOf(Writable, Stream) function nop() {} const kOnFinished = Symbol('kOnFinished') function WritableState(options, stream, isDuplex) { // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream, // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof __nccwpck_require__(2327) // Object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!(options && options.objectMode) if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode) // The point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write(). this.highWaterMark = options ? getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex) : getDefaultHighWaterMark(false) // if _final has been called. this.finalCalled = false // drain event flag. this.needDrain = false // At the start of calling end() this.ending = false // When end() has been called, and returned. this.ended = false // When 'finish' is emitted. this.finished = false // Has it been destroyed this.destroyed = false // Should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. const noDecode = !!(options && options.decodeStrings === false) this.decodeStrings = !noDecode // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = (options && options.defaultEncoding) || 'utf8' // Not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0 // A flag to see when we're in the middle of a write. this.writing = false // When true all writes will be buffered until .uncork() call. this.corked = 0 // A flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true // A flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false // The callback that's passed to _write(chunk, cb). this.onwrite = onwrite.bind(undefined, stream) // The callback that the user supplies to write(chunk, encoding, cb). this.writecb = null // The amount that is being written when _write is called. this.writelen = 0 // Storage for data passed to the afterWrite() callback in case of // synchronous _write() completion. this.afterWriteTickInfo = null resetBuffer(this) // Number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted. this.pendingcb = 0 // Stream is still being constructed and cannot be // destroyed until construction finished or failed. // Async construction is opt in, therefore we start as // constructed. this.constructed = true // Emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams. this.prefinished = false // True if the error was already emitted and should not be thrown again. this.errorEmitted = false // Should close be emitted on destroy. Defaults to true. this.emitClose = !options || options.emitClose !== false // Should .destroy() be called after 'finish' (and potentially 'end'). this.autoDestroy = !options || options.autoDestroy !== false // Indicates whether the stream has errored. When true all write() calls // should return false. This is needed since when autoDestroy // is disabled we need a way to tell whether the stream has failed. this.errored = null // Indicates whether the stream has finished destroying. this.closed = false // True if close has been emitted or would have been emitted // depending on emitClose. this.closeEmitted = false this[kOnFinished] = [] } function resetBuffer(state) { state.buffered = [] state.bufferedIndex = 0 state.allBuffers = true state.allNoop = true } WritableState.prototype.getBuffer = function getBuffer() { return ArrayPrototypeSlice(this.buffered, this.bufferedIndex) } ObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', { __proto__: null, get() { return this.buffered.length - this.bufferedIndex } }) function Writable(options) { // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. // Checking for a Stream.Duplex instance is faster here instead of inside // the WritableState constructor, at least with V8 6.5. const isDuplex = this instanceof __nccwpck_require__(2327) if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options) this._writableState = new WritableState(options, this, isDuplex) if (options) { if (typeof options.write === 'function') this._write = options.write if (typeof options.writev === 'function') this._writev = options.writev if (typeof options.destroy === 'function') this._destroy = options.destroy if (typeof options.final === 'function') this._final = options.final if (typeof options.construct === 'function') this._construct = options.construct if (options.signal) addAbortSignal(options.signal, this) } Stream.call(this, options) destroyImpl.construct(this, () => { const state = this._writableState if (!state.writing) { clearBuffer(this, state) } finishMaybe(this, state) }) } ObjectDefineProperty(Writable, SymbolHasInstance, { __proto__: null, value: function (object) { if (FunctionPrototypeSymbolHasInstance(this, object)) return true if (this !== Writable) return false return object && object._writableState instanceof WritableState } }) // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()) } function _write(stream, chunk, encoding, cb) { const state = stream._writableState if (typeof encoding === 'function') { cb = encoding encoding = state.defaultEncoding } else { if (!encoding) encoding = state.defaultEncoding else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding) if (typeof cb !== 'function') cb = nop } if (chunk === null) { throw new ERR_STREAM_NULL_VALUES() } else if (!state.objectMode) { if (typeof chunk === 'string') { if (state.decodeStrings !== false) { chunk = Buffer.from(chunk, encoding) encoding = 'buffer' } } else if (chunk instanceof Buffer) { encoding = 'buffer' } else if (Stream._isUint8Array(chunk)) { chunk = Stream._uint8ArrayToBuffer(chunk) encoding = 'buffer' } else { throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk) } } let err if (state.ending) { err = new ERR_STREAM_WRITE_AFTER_END() } else if (state.destroyed) { err = new ERR_STREAM_DESTROYED('write') } if (err) { process.nextTick(cb, err) errorOrDestroy(stream, err, true) return err } state.pendingcb++ return writeOrBuffer(stream, state, chunk, encoding, cb) } Writable.prototype.write = function (chunk, encoding, cb) { return _write(this, chunk, encoding, cb) === true } Writable.prototype.cork = function () { this._writableState.corked++ } Writable.prototype.uncork = function () { const state = this._writableState if (state.corked) { state.corked-- if (!state.writing) clearBuffer(this, state) } } Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = StringPrototypeToLowerCase(encoding) if (!Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding) this._writableState.defaultEncoding = encoding return this } // If we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, chunk, encoding, callback) { const len = state.objectMode ? 1 : chunk.length state.length += len // stream._write resets state.length const ret = state.length < state.highWaterMark // We must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true if (state.writing || state.corked || state.errored || !state.constructed) { state.buffered.push({ chunk, encoding, callback }) if (state.allBuffers && encoding !== 'buffer') { state.allBuffers = false } if (state.allNoop && callback !== nop) { state.allNoop = false } } else { state.writelen = len state.writecb = callback state.writing = true state.sync = true stream._write(chunk, encoding, state.onwrite) state.sync = false } // Return false if errored or destroyed in order to break // any synchronous while(stream.write(data)) loops. return ret && !state.errored && !state.destroyed } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len state.writecb = cb state.writing = true state.sync = true if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write')) else if (writev) stream._writev(chunk, state.onwrite) else stream._write(chunk, encoding, state.onwrite) state.sync = false } function onwriteError(stream, state, er, cb) { --state.pendingcb cb(er) // Ensure callbacks are invoked even when autoDestroy is // not enabled. Passing `er` here doesn't make sense since // it's related to one specific write, not to the buffered // writes. errorBuffer(state) // This can emit error, but error must always follow cb. errorOrDestroy(stream, er) } function onwrite(stream, er) { const state = stream._writableState const sync = state.sync const cb = state.writecb if (typeof cb !== 'function') { errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK()) return } state.writing = false state.writecb = null state.length -= state.writelen state.writelen = 0 if (er) { // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 er.stack // eslint-disable-line no-unused-expressions if (!state.errored) { state.errored = er } // In case of duplex streams we need to notify the readable side of the // error. if (stream._readableState && !stream._readableState.errored) { stream._readableState.errored = er } if (sync) { process.nextTick(onwriteError, stream, state, er, cb) } else { onwriteError(stream, state, er, cb) } } else { if (state.buffered.length > state.bufferedIndex) { clearBuffer(stream, state) } if (sync) { // It is a common case that the callback passed to .write() is always // the same. In that case, we do not schedule a new nextTick(), but // rather just increase a counter, to improve performance and avoid // memory allocations. if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) { state.afterWriteTickInfo.count++ } else { state.afterWriteTickInfo = { count: 1, cb, stream, state } process.nextTick(afterWriteTick, state.afterWriteTickInfo) } } else { afterWrite(stream, state, 1, cb) } } } function afterWriteTick({ stream, state, count, cb }) { state.afterWriteTickInfo = null return afterWrite(stream, state, count, cb) } function afterWrite(stream, state, count, cb) { const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain if (needDrain) { state.needDrain = false stream.emit('drain') } while (count-- > 0) { state.pendingcb-- cb() } if (state.destroyed) { errorBuffer(state) } finishMaybe(stream, state) } // If there's something in the buffer waiting, then invoke callbacks. function errorBuffer(state) { if (state.writing) { return } for (let n = state.bufferedIndex; n < state.buffered.length; ++n) { var _state$errored const { chunk, callback } = state.buffered[n] const len = state.objectMode ? 1 : chunk.length state.length -= len callback( (_state$errored = state.errored) !== null && _state$errored !== undefined ? _state$errored : new ERR_STREAM_DESTROYED('write') ) } const onfinishCallbacks = state[kOnFinished].splice(0) for (let i = 0; i < onfinishCallbacks.length; i++) { var _state$errored2 onfinishCallbacks[i]( (_state$errored2 = state.errored) !== null && _state$errored2 !== undefined ? _state$errored2 : new ERR_STREAM_DESTROYED('end') ) } resetBuffer(state) } // If there's something in the buffer waiting, then process it. function clearBuffer(stream, state) { if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) { return } const { buffered, bufferedIndex, objectMode } = state const bufferedLength = buffered.length - bufferedIndex if (!bufferedLength) { return } let i = bufferedIndex state.bufferProcessing = true if (bufferedLength > 1 && stream._writev) { state.pendingcb -= bufferedLength - 1 const callback = state.allNoop ? nop : (err) => { for (let n = i; n < buffered.length; ++n) { buffered[n].callback(err) } } // Make a copy of `buffered` if it's going to be used by `callback` above, // since `doWrite` will mutate the array. const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i) chunks.allBuffers = state.allBuffers doWrite(stream, state, true, state.length, chunks, '', callback) resetBuffer(state) } else { do { const { chunk, encoding, callback } = buffered[i] buffered[i++] = null const len = objectMode ? 1 : chunk.length doWrite(stream, state, false, len, chunk, encoding, callback) } while (i < buffered.length && !state.writing) if (i === buffered.length) { resetBuffer(state) } else if (i > 256) { buffered.splice(0, i) state.bufferedIndex = 0 } else { state.bufferedIndex = i } } state.bufferProcessing = false } Writable.prototype._write = function (chunk, encoding, cb) { if (this._writev) { this._writev( [ { chunk, encoding } ], cb ) } else { throw new ERR_METHOD_NOT_IMPLEMENTED('_write()') } } Writable.prototype._writev = null Writable.prototype.end = function (chunk, encoding, cb) { const state = this._writableState if (typeof chunk === 'function') { cb = chunk chunk = null encoding = null } else if (typeof encoding === 'function') { cb = encoding encoding = null } let err if (chunk !== null && chunk !== undefined) { const ret = _write(this, chunk, encoding) if (ret instanceof Error) { err = ret } } // .end() fully uncorks. if (state.corked) { state.corked = 1 this.uncork() } if (err) { // Do nothing... } else if (!state.errored && !state.ending) { // This is forgiving in terms of unnecessary calls to end() and can hide // logic errors. However, usually such errors are harmless and causing a // hard error can be disproportionately destructive. It is not always // trivial for the user to determine whether end() needs to be called // or not. state.ending = true finishMaybe(this, state, true) state.ended = true } else if (state.finished) { err = new ERR_STREAM_ALREADY_FINISHED('end') } else if (state.destroyed) { err = new ERR_STREAM_DESTROYED('end') } if (typeof cb === 'function') { if (err || state.finished) { process.nextTick(cb, err) } else { state[kOnFinished].push(cb) } } return this } function needFinish(state) { return ( state.ending && !state.destroyed && state.constructed && state.length === 0 && !state.errored && state.buffered.length === 0 && !state.finished && !state.writing && !state.errorEmitted && !state.closeEmitted ) } function callFinal(stream, state) { let called = false function onFinish(err) { if (called) { errorOrDestroy(stream, err !== null && err !== undefined ? err : ERR_MULTIPLE_CALLBACK()) return } called = true state.pendingcb-- if (err) { const onfinishCallbacks = state[kOnFinished].splice(0) for (let i = 0; i < onfinishCallbacks.length; i++) { onfinishCallbacks[i](err) } errorOrDestroy(stream, err, state.sync) } else if (needFinish(state)) { state.prefinished = true stream.emit('prefinish') // Backwards compat. Don't check state.sync here. // Some streams assume 'finish' will be emitted // asynchronously relative to _final callback. state.pendingcb++ process.nextTick(finish, stream, state) } } state.sync = true state.pendingcb++ try { stream._final(onFinish) } catch (err) { onFinish(err) } state.sync = false } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function' && !state.destroyed) { state.finalCalled = true callFinal(stream, state) } else { state.prefinished = true stream.emit('prefinish') } } } function finishMaybe(stream, state, sync) { if (needFinish(state)) { prefinish(stream, state) if (state.pendingcb === 0) { if (sync) { state.pendingcb++ process.nextTick( (stream, state) => { if (needFinish(state)) { finish(stream, state) } else { state.pendingcb-- } }, stream, state ) } else if (needFinish(state)) { state.pendingcb++ finish(stream, state) } } } } function finish(stream, state) { state.pendingcb-- state.finished = true const onfinishCallbacks = state[kOnFinished].splice(0) for (let i = 0; i < onfinishCallbacks.length; i++) { onfinishCallbacks[i]() } stream.emit('finish') if (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the readable side is ready for autoDestroy as well. const rState = stream._readableState const autoDestroy = !rState || (rState.autoDestroy && // We don't expect the readable to ever 'end' // if readable is explicitly set to false. (rState.endEmitted || rState.readable === false)) if (autoDestroy) { stream.destroy() } } } ObjectDefineProperties(Writable.prototype, { closed: { __proto__: null, get() { return this._writableState ? this._writableState.closed : false } }, destroyed: { __proto__: null, get() { return this._writableState ? this._writableState.destroyed : false }, set(value) { // Backward compatibility, the user is explicitly managing destroyed. if (this._writableState) { this._writableState.destroyed = value } } }, writable: { __proto__: null, get() { const w = this._writableState // w.writable === false means that this is part of a Duplex stream // where the writable side was disabled upon construction. // Compat. The user might manually disable writable side through // deprecated setter. return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended }, set(val) { // Backwards compatible. if (this._writableState) { this._writableState.writable = !!val } } }, writableFinished: { __proto__: null, get() { return this._writableState ? this._writableState.finished : false } }, writableObjectMode: { __proto__: null, get() { return this._writableState ? this._writableState.objectMode : false } }, writableBuffer: { __proto__: null, get() { return this._writableState && this._writableState.getBuffer() } }, writableEnded: { __proto__: null, get() { return this._writableState ? this._writableState.ending : false } }, writableNeedDrain: { __proto__: null, get() { const wState = this._writableState if (!wState) return false return !wState.destroyed && !wState.ending && wState.needDrain } }, writableHighWaterMark: { __proto__: null, get() { return this._writableState && this._writableState.highWaterMark } }, writableCorked: { __proto__: null, get() { return this._writableState ? this._writableState.corked : 0 } }, writableLength: { __proto__: null, get() { return this._writableState && this._writableState.length } }, errored: { __proto__: null, enumerable: false, get() { return this._writableState ? this._writableState.errored : null } }, writableAborted: { __proto__: null, enumerable: false, get: function () { return !!( this._writableState.writable !== false && (this._writableState.destroyed || this._writableState.errored) && !this._writableState.finished ) } } }) const destroy = destroyImpl.destroy Writable.prototype.destroy = function (err, cb) { const state = this._writableState // Invoke pending callbacks. if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) { process.nextTick(errorBuffer, state) } destroy.call(this, err, cb) return this } Writable.prototype._undestroy = destroyImpl.undestroy Writable.prototype._destroy = function (err, cb) { cb(err) } Writable.prototype[EE.captureRejectionSymbol] = function (err) { this.destroy(err) } let webStreamsAdapters // Lazy to avoid circular references function lazyWebStreams() { if (webStreamsAdapters === undefined) webStreamsAdapters = {} return webStreamsAdapters } Writable.fromWeb = function (writableStream, options) { return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options) } Writable.toWeb = function (streamWritable) { return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable) } /***/ }), /***/ 3328: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint jsdoc/require-jsdoc: "error" */ const { ArrayIsArray, ArrayPrototypeIncludes, ArrayPrototypeJoin, ArrayPrototypeMap, NumberIsInteger, NumberIsNaN, NumberMAX_SAFE_INTEGER, NumberMIN_SAFE_INTEGER, NumberParseInt, ObjectPrototypeHasOwnProperty, RegExpPrototypeExec, String, StringPrototypeToUpperCase, StringPrototypeTrim } = __nccwpck_require__(2177) const { hideStackFrames, codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL } } = __nccwpck_require__(5358) const { normalizeEncoding } = __nccwpck_require__(1953) const { isAsyncFunction, isArrayBufferView } = (__nccwpck_require__(1953).types) const signals = {} /** * @param {*} value * @returns {boolean} */ function isInt32(value) { return value === (value | 0) } /** * @param {*} value * @returns {boolean} */ function isUint32(value) { return value === value >>> 0 } const octalReg = /^[0-7]+$/ const modeDesc = 'must be a 32-bit unsigned integer or an octal string' /** * Parse and validate values that will be converted into mode_t (the S_* * constants). Only valid numbers and octal strings are allowed. They could be * converted to 32-bit unsigned integers or non-negative signed integers in the * C++ land, but any value higher than 0o777 will result in platform-specific * behaviors. * @param {*} value Values to be validated * @param {string} name Name of the argument * @param {number} [def] If specified, will be returned for invalid values * @returns {number} */ function parseFileMode(value, name, def) { if (typeof value === 'undefined') { value = def } if (typeof value === 'string') { if (RegExpPrototypeExec(octalReg, value) === null) { throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc) } value = NumberParseInt(value, 8) } validateUint32(value, name) return value } /** * @callback validateInteger * @param {*} value * @param {string} name * @param {number} [min] * @param {number} [max] * @returns {asserts value is number} */ /** @type {validateInteger} */ const validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => { if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value) if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, 'an integer', value) if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) }) /** * @callback validateInt32 * @param {*} value * @param {string} name * @param {number} [min] * @param {number} [max] * @returns {asserts value is number} */ /** @type {validateInt32} */ const validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => { // The defaults for min and max correspond to the limits of 32-bit integers. if (typeof value !== 'number') { throw new ERR_INVALID_ARG_TYPE(name, 'number', value) } if (!NumberIsInteger(value)) { throw new ERR_OUT_OF_RANGE(name, 'an integer', value) } if (value < min || value > max) { throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) } }) /** * @callback validateUint32 * @param {*} value * @param {string} name * @param {number|boolean} [positive=false] * @returns {asserts value is number} */ /** @type {validateUint32} */ const validateUint32 = hideStackFrames((value, name, positive = false) => { if (typeof value !== 'number') { throw new ERR_INVALID_ARG_TYPE(name, 'number', value) } if (!NumberIsInteger(value)) { throw new ERR_OUT_OF_RANGE(name, 'an integer', value) } const min = positive ? 1 : 0 // 2 ** 32 === 4294967296 const max = 4294967295 if (value < min || value > max) { throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) } }) /** * @callback validateString * @param {*} value * @param {string} name * @returns {asserts value is string} */ /** @type {validateString} */ function validateString(value, name) { if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value) } /** * @callback validateNumber * @param {*} value * @param {string} name * @param {number} [min] * @param {number} [max] * @returns {asserts value is number} */ /** @type {validateNumber} */ function validateNumber(value, name, min = undefined, max) { if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value) if ( (min != null && value < min) || (max != null && value > max) || ((min != null || max != null) && NumberIsNaN(value)) ) { throw new ERR_OUT_OF_RANGE( name, `${min != null ? `>= ${min}` : ''}${min != null && max != null ? ' && ' : ''}${max != null ? `<= ${max}` : ''}`, value ) } } /** * @callback validateOneOf * @template T * @param {T} value * @param {string} name * @param {T[]} oneOf */ /** @type {validateOneOf} */ const validateOneOf = hideStackFrames((value, name, oneOf) => { if (!ArrayPrototypeIncludes(oneOf, value)) { const allowed = ArrayPrototypeJoin( ArrayPrototypeMap(oneOf, (v) => (typeof v === 'string' ? `'${v}'` : String(v))), ', ' ) const reason = 'must be one of: ' + allowed throw new ERR_INVALID_ARG_VALUE(name, value, reason) } }) /** * @callback validateBoolean * @param {*} value * @param {string} name * @returns {asserts value is boolean} */ /** @type {validateBoolean} */ function validateBoolean(value, name) { if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value) } /** * @param {any} options * @param {string} key * @param {boolean} defaultValue * @returns {boolean} */ function getOwnPropertyValueOrDefault(options, key, defaultValue) { return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key] } /** * @callback validateObject * @param {*} value * @param {string} name * @param {{ * allowArray?: boolean, * allowFunction?: boolean, * nullable?: boolean * }} [options] */ /** @type {validateObject} */ const validateObject = hideStackFrames((value, name, options = null) => { const allowArray = getOwnPropertyValueOrDefault(options, 'allowArray', false) const allowFunction = getOwnPropertyValueOrDefault(options, 'allowFunction', false) const nullable = getOwnPropertyValueOrDefault(options, 'nullable', false) if ( (!nullable && value === null) || (!allowArray && ArrayIsArray(value)) || (typeof value !== 'object' && (!allowFunction || typeof value !== 'function')) ) { throw new ERR_INVALID_ARG_TYPE(name, 'Object', value) } }) /** * @callback validateDictionary - We are using the Web IDL Standard definition * of "dictionary" here, which means any value * whose Type is either Undefined, Null, or * Object (which includes functions). * @param {*} value * @param {string} name * @see https://webidl.spec.whatwg.org/#es-dictionary * @see https://tc39.es/ecma262/#table-typeof-operator-results */ /** @type {validateDictionary} */ const validateDictionary = hideStackFrames((value, name) => { if (value != null && typeof value !== 'object' && typeof value !== 'function') { throw new ERR_INVALID_ARG_TYPE(name, 'a dictionary', value) } }) /** * @callback validateArray * @param {*} value * @param {string} name * @param {number} [minLength] * @returns {asserts value is any[]} */ /** @type {validateArray} */ const validateArray = hideStackFrames((value, name, minLength = 0) => { if (!ArrayIsArray(value)) { throw new ERR_INVALID_ARG_TYPE(name, 'Array', value) } if (value.length < minLength) { const reason = `must be longer than ${minLength}` throw new ERR_INVALID_ARG_VALUE(name, value, reason) } }) /** * @callback validateStringArray * @param {*} value * @param {string} name * @returns {asserts value is string[]} */ /** @type {validateStringArray} */ function validateStringArray(value, name) { validateArray(value, name) for (let i = 0; i < value.length; i++) { validateString(value[i], `${name}[${i}]`) } } /** * @callback validateBooleanArray * @param {*} value * @param {string} name * @returns {asserts value is boolean[]} */ /** @type {validateBooleanArray} */ function validateBooleanArray(value, name) { validateArray(value, name) for (let i = 0; i < value.length; i++) { validateBoolean(value[i], `${name}[${i}]`) } } /** * @callback validateAbortSignalArray * @param {*} value * @param {string} name * @returns {asserts value is AbortSignal[]} */ /** @type {validateAbortSignalArray} */ function validateAbortSignalArray(value, name) { validateArray(value, name) for (let i = 0; i < value.length; i++) { const signal = value[i] const indexedName = `${name}[${i}]` if (signal == null) { throw new ERR_INVALID_ARG_TYPE(indexedName, 'AbortSignal', signal) } validateAbortSignal(signal, indexedName) } } /** * @param {*} signal * @param {string} [name='signal'] * @returns {asserts signal is keyof signals} */ function validateSignalName(signal, name = 'signal') { validateString(signal, name) if (signals[signal] === undefined) { if (signals[StringPrototypeToUpperCase(signal)] !== undefined) { throw new ERR_UNKNOWN_SIGNAL(signal + ' (signals must use all capital letters)') } throw new ERR_UNKNOWN_SIGNAL(signal) } } /** * @callback validateBuffer * @param {*} buffer * @param {string} [name='buffer'] * @returns {asserts buffer is ArrayBufferView} */ /** @type {validateBuffer} */ const validateBuffer = hideStackFrames((buffer, name = 'buffer') => { if (!isArrayBufferView(buffer)) { throw new ERR_INVALID_ARG_TYPE(name, ['Buffer', 'TypedArray', 'DataView'], buffer) } }) /** * @param {string} data * @param {string} encoding */ function validateEncoding(data, encoding) { const normalizedEncoding = normalizeEncoding(encoding) const length = data.length if (normalizedEncoding === 'hex' && length % 2 !== 0) { throw new ERR_INVALID_ARG_VALUE('encoding', encoding, `is invalid for data of length ${length}`) } } /** * Check that the port number is not NaN when coerced to a number, * is an integer and that it falls within the legal range of port numbers. * @param {*} port * @param {string} [name='Port'] * @param {boolean} [allowZero=true] * @returns {number} */ function validatePort(port, name = 'Port', allowZero = true) { if ( (typeof port !== 'number' && typeof port !== 'string') || (typeof port === 'string' && StringPrototypeTrim(port).length === 0) || +port !== +port >>> 0 || port > 0xffff || (port === 0 && !allowZero) ) { throw new ERR_SOCKET_BAD_PORT(name, port, allowZero) } return port | 0 } /** * @callback validateAbortSignal * @param {*} signal * @param {string} name */ /** @type {validateAbortSignal} */ const validateAbortSignal = hideStackFrames((signal, name) => { if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) { throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) } }) /** * @callback validateFunction * @param {*} value * @param {string} name * @returns {asserts value is Function} */ /** @type {validateFunction} */ const validateFunction = hideStackFrames((value, name) => { if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) }) /** * @callback validatePlainFunction * @param {*} value * @param {string} name * @returns {asserts value is Function} */ /** @type {validatePlainFunction} */ const validatePlainFunction = hideStackFrames((value, name) => { if (typeof value !== 'function' || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) }) /** * @callback validateUndefined * @param {*} value * @param {string} name * @returns {asserts value is undefined} */ /** @type {validateUndefined} */ const validateUndefined = hideStackFrames((value, name) => { if (value !== undefined) throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value) }) /** * @template T * @param {T} value * @param {string} name * @param {T[]} union */ function validateUnion(value, name, union) { if (!ArrayPrototypeIncludes(union, value)) { throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value) } } /* The rules for the Link header field are described here: https://www.rfc-editor.org/rfc/rfc8288.html#section-3 This regex validates any string surrounded by angle brackets (not necessarily a valid URI reference) followed by zero or more link-params separated by semicolons. */ const linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/ /** * @param {any} value * @param {string} name */ function validateLinkHeaderFormat(value, name) { if (typeof value === 'undefined' || !RegExpPrototypeExec(linkValueRegExp, value)) { throw new ERR_INVALID_ARG_VALUE( name, value, 'must be an array or string of format "; rel=preload; as=style"' ) } } /** * @param {any} hints * @return {string} */ function validateLinkHeaderValue(hints) { if (typeof hints === 'string') { validateLinkHeaderFormat(hints, 'hints') return hints } else if (ArrayIsArray(hints)) { const hintsLength = hints.length let result = '' if (hintsLength === 0) { return result } for (let i = 0; i < hintsLength; i++) { const link = hints[i] validateLinkHeaderFormat(link, 'hints') result += link if (i !== hintsLength - 1) { result += ', ' } } return result } throw new ERR_INVALID_ARG_VALUE( 'hints', hints, 'must be an array or string of format "; rel=preload; as=style"' ) } module.exports = { isInt32, isUint32, parseFileMode, validateArray, validateStringArray, validateBooleanArray, validateAbortSignalArray, validateBoolean, validateBuffer, validateDictionary, validateEncoding, validateFunction, validateInt32, validateInteger, validateNumber, validateObject, validateOneOf, validatePlainFunction, validatePort, validateSignalName, validateString, validateUint32, validateUndefined, validateUnion, validateAbortSignal, validateLinkHeaderValue } /***/ }), /***/ 5358: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { format, inspect } = __nccwpck_require__(2774) const { AggregateError: CustomAggregateError } = __nccwpck_require__(2177) /* This file is a reduced and adapted version of the main lib/internal/errors.js file defined at https://github.com/nodejs/node/blob/main/lib/internal/errors.js Don't try to replace with the original file and keep it up to date (starting from E(...) definitions) with the upstream file. */ const AggregateError = globalThis.AggregateError || CustomAggregateError const kIsNodeError = Symbol('kIsNodeError') const kTypes = [ 'string', 'function', 'number', 'object', // Accept 'Function' and 'Object' as alternative to the lower cased version. 'Function', 'Object', 'boolean', 'bigint', 'symbol' ] const classRegExp = /^([A-Z][a-z0-9]*)+$/ const nodeInternalPrefix = '__node_internal_' const codes = {} function assert(value, message) { if (!value) { throw new codes.ERR_INTERNAL_ASSERTION(message) } } // Only use this for integers! Decimal numbers do not work with this function. function addNumericalSeparator(val) { let res = '' let i = val.length const start = val[0] === '-' ? 1 : 0 for (; i >= start + 4; i -= 3) { res = `_${val.slice(i - 3, i)}${res}` } return `${val.slice(0, i)}${res}` } function getMessage(key, msg, args) { if (typeof msg === 'function') { assert( msg.length <= args.length, // Default options do not count. `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).` ) return msg(...args) } const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length assert( expectedLength === args.length, `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).` ) if (args.length === 0) { return msg } return format(msg, ...args) } function E(code, message, Base) { if (!Base) { Base = Error } class NodeError extends Base { constructor(...args) { super(getMessage(code, message, args)) } toString() { return `${this.name} [${code}]: ${this.message}` } } Object.defineProperties(NodeError.prototype, { name: { value: Base.name, writable: true, enumerable: false, configurable: true }, toString: { value() { return `${this.name} [${code}]: ${this.message}` }, writable: true, enumerable: false, configurable: true } }) NodeError.prototype.code = code NodeError.prototype[kIsNodeError] = true codes[code] = NodeError } function hideStackFrames(fn) { // We rename the functions that will be hidden to cut off the stacktrace // at the outermost one const hidden = nodeInternalPrefix + fn.name Object.defineProperty(fn, 'name', { value: hidden }) return fn } function aggregateTwoErrors(innerError, outerError) { if (innerError && outerError && innerError !== outerError) { if (Array.isArray(outerError.errors)) { // If `outerError` is already an `AggregateError`. outerError.errors.push(innerError) return outerError } const err = new AggregateError([outerError, innerError], outerError.message) err.code = outerError.code return err } return innerError || outerError } class AbortError extends Error { constructor(message = 'The operation was aborted', options = undefined) { if (options !== undefined && typeof options !== 'object') { throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options) } super(message, options) this.code = 'ABORT_ERR' this.name = 'AbortError' } } E('ERR_ASSERTION', '%s', Error) E( 'ERR_INVALID_ARG_TYPE', (name, expected, actual) => { assert(typeof name === 'string', "'name' must be a string") if (!Array.isArray(expected)) { expected = [expected] } let msg = 'The ' if (name.endsWith(' argument')) { // For cases like 'first argument' msg += `${name} ` } else { msg += `"${name}" ${name.includes('.') ? 'property' : 'argument'} ` } msg += 'must be ' const types = [] const instances = [] const other = [] for (const value of expected) { assert(typeof value === 'string', 'All expected entries have to be of type string') if (kTypes.includes(value)) { types.push(value.toLowerCase()) } else if (classRegExp.test(value)) { instances.push(value) } else { assert(value !== 'object', 'The value "object" should be written as "Object"') other.push(value) } } // Special handle `object` in case other instances are allowed to outline // the differences between each other. if (instances.length > 0) { const pos = types.indexOf('object') if (pos !== -1) { types.splice(types, pos, 1) instances.push('Object') } } if (types.length > 0) { switch (types.length) { case 1: msg += `of type ${types[0]}` break case 2: msg += `one of type ${types[0]} or ${types[1]}` break default: { const last = types.pop() msg += `one of type ${types.join(', ')}, or ${last}` } } if (instances.length > 0 || other.length > 0) { msg += ' or ' } } if (instances.length > 0) { switch (instances.length) { case 1: msg += `an instance of ${instances[0]}` break case 2: msg += `an instance of ${instances[0]} or ${instances[1]}` break default: { const last = instances.pop() msg += `an instance of ${instances.join(', ')}, or ${last}` } } if (other.length > 0) { msg += ' or ' } } switch (other.length) { case 0: break case 1: if (other[0].toLowerCase() !== other[0]) { msg += 'an ' } msg += `${other[0]}` break case 2: msg += `one of ${other[0]} or ${other[1]}` break default: { const last = other.pop() msg += `one of ${other.join(', ')}, or ${last}` } } if (actual == null) { msg += `. Received ${actual}` } else if (typeof actual === 'function' && actual.name) { msg += `. Received function ${actual.name}` } else if (typeof actual === 'object') { var _actual$constructor if ( (_actual$constructor = actual.constructor) !== null && _actual$constructor !== undefined && _actual$constructor.name ) { msg += `. Received an instance of ${actual.constructor.name}` } else { const inspected = inspect(actual, { depth: -1 }) msg += `. Received ${inspected}` } } else { let inspected = inspect(actual, { colors: false }) if (inspected.length > 25) { inspected = `${inspected.slice(0, 25)}...` } msg += `. Received type ${typeof actual} (${inspected})` } return msg }, TypeError ) E( 'ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => { let inspected = inspect(value) if (inspected.length > 128) { inspected = inspected.slice(0, 128) + '...' } const type = name.includes('.') ? 'property' : 'argument' return `The ${type} '${name}' ${reason}. Received ${inspected}` }, TypeError ) E( 'ERR_INVALID_RETURN_VALUE', (input, name, value) => { var _value$constructor const type = value !== null && value !== undefined && (_value$constructor = value.constructor) !== null && _value$constructor !== undefined && _value$constructor.name ? `instance of ${value.constructor.name}` : `type ${typeof value}` return `Expected ${input} to be returned from the "${name}"` + ` function but got ${type}.` }, TypeError ) E( 'ERR_MISSING_ARGS', (...args) => { assert(args.length > 0, 'At least one arg needs to be specified') let msg const len = args.length args = (Array.isArray(args) ? args : [args]).map((a) => `"${a}"`).join(' or ') switch (len) { case 1: msg += `The ${args[0]} argument` break case 2: msg += `The ${args[0]} and ${args[1]} arguments` break default: { const last = args.pop() msg += `The ${args.join(', ')}, and ${last} arguments` } break } return `${msg} must be specified` }, TypeError ) E( 'ERR_OUT_OF_RANGE', (str, range, input) => { assert(range, 'Missing "range" argument') let received if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { received = addNumericalSeparator(String(input)) } else if (typeof input === 'bigint') { received = String(input) const limit = BigInt(2) ** BigInt(32) if (input > limit || input < -limit) { received = addNumericalSeparator(received) } received += 'n' } else { received = inspect(input) } return `The value of "${str}" is out of range. It must be ${range}. Received ${received}` }, RangeError ) E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error) E('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error) E('ERR_STREAM_ALREADY_FINISHED', 'Cannot call %s after a stream was finished', Error) E('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error) E('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error) E('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError) E('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error) E('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error) E('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event', Error) E('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error) E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError) module.exports = { AbortError, aggregateTwoErrors: hideStackFrames(aggregateTwoErrors), hideStackFrames, codes } /***/ }), /***/ 1657: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Stream = __nccwpck_require__(2203) if (Stream && process.env.READABLE_STREAM === 'disable') { const promises = Stream.promises // Explicit export naming is needed for ESM module.exports._uint8ArrayToBuffer = Stream._uint8ArrayToBuffer module.exports._isUint8Array = Stream._isUint8Array module.exports.isDisturbed = Stream.isDisturbed module.exports.isErrored = Stream.isErrored module.exports.isReadable = Stream.isReadable module.exports.Readable = Stream.Readable module.exports.Writable = Stream.Writable module.exports.Duplex = Stream.Duplex module.exports.Transform = Stream.Transform module.exports.PassThrough = Stream.PassThrough module.exports.addAbortSignal = Stream.addAbortSignal module.exports.finished = Stream.finished module.exports.destroy = Stream.destroy module.exports.pipeline = Stream.pipeline module.exports.compose = Stream.compose Object.defineProperty(Stream, 'promises', { configurable: true, enumerable: true, get() { return promises } }) module.exports.Stream = Stream.Stream } else { const CustomStream = __nccwpck_require__(4985) const promises = __nccwpck_require__(1898) const originalDestroy = CustomStream.Readable.destroy module.exports = CustomStream.Readable // Explicit export naming is needed for ESM module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer module.exports._isUint8Array = CustomStream._isUint8Array module.exports.isDisturbed = CustomStream.isDisturbed module.exports.isErrored = CustomStream.isErrored module.exports.isReadable = CustomStream.isReadable module.exports.Readable = CustomStream.Readable module.exports.Writable = CustomStream.Writable module.exports.Duplex = CustomStream.Duplex module.exports.Transform = CustomStream.Transform module.exports.PassThrough = CustomStream.PassThrough module.exports.addAbortSignal = CustomStream.addAbortSignal module.exports.finished = CustomStream.finished module.exports.destroy = CustomStream.destroy module.exports.destroy = originalDestroy module.exports.pipeline = CustomStream.pipeline module.exports.compose = CustomStream.compose Object.defineProperty(CustomStream, 'promises', { configurable: true, enumerable: true, get() { return promises } }) module.exports.Stream = CustomStream.Stream } // Allow default importing module.exports["default"] = module.exports /***/ }), /***/ 2177: /***/ ((module) => { "use strict"; /* This file is a reduced and adapted version of the main lib/internal/per_context/primordials.js file defined at https://github.com/nodejs/node/blob/main/lib/internal/per_context/primordials.js Don't try to replace with the original file and keep it up to date with the upstream file. */ // This is a simplified version of AggregateError class AggregateError extends Error { constructor(errors) { if (!Array.isArray(errors)) { throw new TypeError(`Expected input to be an Array, got ${typeof errors}`) } let message = '' for (let i = 0; i < errors.length; i++) { message += ` ${errors[i].stack}\n` } super(message) this.name = 'AggregateError' this.errors = errors } } module.exports = { AggregateError, ArrayIsArray(self) { return Array.isArray(self) }, ArrayPrototypeIncludes(self, el) { return self.includes(el) }, ArrayPrototypeIndexOf(self, el) { return self.indexOf(el) }, ArrayPrototypeJoin(self, sep) { return self.join(sep) }, ArrayPrototypeMap(self, fn) { return self.map(fn) }, ArrayPrototypePop(self, el) { return self.pop(el) }, ArrayPrototypePush(self, el) { return self.push(el) }, ArrayPrototypeSlice(self, start, end) { return self.slice(start, end) }, Error, FunctionPrototypeCall(fn, thisArgs, ...args) { return fn.call(thisArgs, ...args) }, FunctionPrototypeSymbolHasInstance(self, instance) { return Function.prototype[Symbol.hasInstance].call(self, instance) }, MathFloor: Math.floor, Number, NumberIsInteger: Number.isInteger, NumberIsNaN: Number.isNaN, NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, NumberParseInt: Number.parseInt, ObjectDefineProperties(self, props) { return Object.defineProperties(self, props) }, ObjectDefineProperty(self, name, prop) { return Object.defineProperty(self, name, prop) }, ObjectGetOwnPropertyDescriptor(self, name) { return Object.getOwnPropertyDescriptor(self, name) }, ObjectKeys(obj) { return Object.keys(obj) }, ObjectSetPrototypeOf(target, proto) { return Object.setPrototypeOf(target, proto) }, Promise, PromisePrototypeCatch(self, fn) { return self.catch(fn) }, PromisePrototypeThen(self, thenFn, catchFn) { return self.then(thenFn, catchFn) }, PromiseReject(err) { return Promise.reject(err) }, PromiseResolve(val) { return Promise.resolve(val) }, ReflectApply: Reflect.apply, RegExpPrototypeTest(self, value) { return self.test(value) }, SafeSet: Set, String, StringPrototypeSlice(self, start, end) { return self.slice(start, end) }, StringPrototypeToLowerCase(self) { return self.toLowerCase() }, StringPrototypeToUpperCase(self) { return self.toUpperCase() }, StringPrototypeTrim(self) { return self.trim() }, Symbol, SymbolFor: Symbol.for, SymbolAsyncIterator: Symbol.asyncIterator, SymbolHasInstance: Symbol.hasInstance, SymbolIterator: Symbol.iterator, SymbolDispose: Symbol.dispose || Symbol('Symbol.dispose'), SymbolAsyncDispose: Symbol.asyncDispose || Symbol('Symbol.asyncDispose'), TypedArrayPrototypeSet(self, buf, len) { return self.set(buf, len) }, Boolean, Uint8Array } /***/ }), /***/ 1953: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const bufferModule = __nccwpck_require__(181) const { format, inspect } = __nccwpck_require__(2774) const { codes: { ERR_INVALID_ARG_TYPE } } = __nccwpck_require__(5358) const { kResistStopPropagation, AggregateError, SymbolDispose } = __nccwpck_require__(2177) const AbortSignal = globalThis.AbortSignal || (__nccwpck_require__(7413).AbortSignal) const AbortController = globalThis.AbortController || (__nccwpck_require__(7413).AbortController) const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor const Blob = globalThis.Blob || bufferModule.Blob /* eslint-disable indent */ const isBlob = typeof Blob !== 'undefined' ? function isBlob(b) { // eslint-disable-next-line indent return b instanceof Blob } : function isBlob(b) { return false } /* eslint-enable indent */ const validateAbortSignal = (signal, name) => { if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) { throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) } } const validateFunction = (value, name) => { if (typeof value !== 'function') { throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) } } module.exports = { AggregateError, kEmptyObject: Object.freeze({}), once(callback) { let called = false return function (...args) { if (called) { return } called = true callback.apply(this, args) } }, createDeferredPromise: function () { let resolve let reject // eslint-disable-next-line promise/param-names const promise = new Promise((res, rej) => { resolve = res reject = rej }) return { promise, resolve, reject } }, promisify(fn) { return new Promise((resolve, reject) => { fn((err, ...args) => { if (err) { return reject(err) } return resolve(...args) }) }) }, debuglog() { return function () {} }, format, inspect, types: { isAsyncFunction(fn) { return fn instanceof AsyncFunction }, isArrayBufferView(arr) { return ArrayBuffer.isView(arr) } }, isBlob, deprecate(fn, message) { return fn }, addAbortListener: (__nccwpck_require__(4434).addAbortListener) || function addAbortListener(signal, listener) { if (signal === undefined) { throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal) } validateAbortSignal(signal, 'signal') validateFunction(listener, 'listener') let removeEventListener if (signal.aborted) { queueMicrotask(() => listener()) } else { signal.addEventListener('abort', listener, { __proto__: null, once: true, [kResistStopPropagation]: true }) removeEventListener = () => { signal.removeEventListener('abort', listener) } } return { __proto__: null, [SymbolDispose]() { var _removeEventListener ;(_removeEventListener = removeEventListener) === null || _removeEventListener === undefined ? undefined : _removeEventListener() } } }, AbortSignalAny: AbortSignal.any || function AbortSignalAny(signals) { // Fast path if there is only one signal. if (signals.length === 1) { return signals[0] } const ac = new AbortController() const abort = () => ac.abort() signals.forEach((signal) => { validateAbortSignal(signal, 'signals') signal.addEventListener('abort', abort, { once: true }) }) ac.signal.addEventListener( 'abort', () => { signals.forEach((signal) => signal.removeEventListener('abort', abort)) }, { once: true } ) return ac.signal } } module.exports.promisify.custom = Symbol.for('nodejs.util.promisify.custom') /***/ }), /***/ 2774: /***/ ((module) => { "use strict"; /* This file is a reduced and adapted version of the main lib/internal/util/inspect.js file defined at https://github.com/nodejs/node/blob/main/lib/internal/util/inspect.js Don't try to replace with the original file and keep it up to date with the upstream file. */ module.exports = { format(format, ...args) { // Simplified version of https://nodejs.org/api/util.html#utilformatformat-args return format.replace(/%([sdifj])/g, function (...[_unused, type]) { const replacement = args.shift() if (type === 'f') { return replacement.toFixed(6) } else if (type === 'j') { return JSON.stringify(replacement) } else if (type === 's' && typeof replacement === 'object') { const ctor = replacement.constructor !== Object ? replacement.constructor.name : '' return `${ctor} {}`.trim() } else { return replacement.toString() } }) }, inspect(value) { // Vastly simplified version of https://nodejs.org/api/util.html#utilinspectobject-options switch (typeof value) { case 'string': if (value.includes("'")) { if (!value.includes('"')) { return `"${value}"` } else if (!value.includes('`') && !value.includes('${')) { return `\`${value}\`` } } return `'${value}'` case 'number': if (isNaN(value)) { return 'NaN' } else if (Object.is(value, -0)) { return String(value) } return value case 'bigint': return `${String(value)}n` case 'boolean': case 'undefined': return String(value) case 'object': return '{}' } } } /***/ }), /***/ 4985: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /* replacement start */ const { Buffer } = __nccwpck_require__(181) /* replacement end */ const { ObjectDefineProperty, ObjectKeys, ReflectApply } = __nccwpck_require__(2177) const { promisify: { custom: customPromisify } } = __nccwpck_require__(1953) const { streamReturningOperators, promiseReturningOperators } = __nccwpck_require__(3972) const { codes: { ERR_ILLEGAL_CONSTRUCTOR } } = __nccwpck_require__(5358) const compose = __nccwpck_require__(3177) const { setDefaultHighWaterMark, getDefaultHighWaterMark } = __nccwpck_require__(9648) const { pipeline } = __nccwpck_require__(4687) const { destroyer } = __nccwpck_require__(6127) const eos = __nccwpck_require__(741) const internalBuffer = {} const promises = __nccwpck_require__(1898) const utils = __nccwpck_require__(5848) const Stream = (module.exports = __nccwpck_require__(5246).Stream) Stream.isDestroyed = utils.isDestroyed Stream.isDisturbed = utils.isDisturbed Stream.isErrored = utils.isErrored Stream.isReadable = utils.isReadable Stream.isWritable = utils.isWritable Stream.Readable = __nccwpck_require__(933) for (const key of ObjectKeys(streamReturningOperators)) { const op = streamReturningOperators[key] function fn(...args) { if (new.target) { throw ERR_ILLEGAL_CONSTRUCTOR() } return Stream.Readable.from(ReflectApply(op, this, args)) } ObjectDefineProperty(fn, 'name', { __proto__: null, value: op.name }) ObjectDefineProperty(fn, 'length', { __proto__: null, value: op.length }) ObjectDefineProperty(Stream.Readable.prototype, key, { __proto__: null, value: fn, enumerable: false, configurable: true, writable: true }) } for (const key of ObjectKeys(promiseReturningOperators)) { const op = promiseReturningOperators[key] function fn(...args) { if (new.target) { throw ERR_ILLEGAL_CONSTRUCTOR() } return ReflectApply(op, this, args) } ObjectDefineProperty(fn, 'name', { __proto__: null, value: op.name }) ObjectDefineProperty(fn, 'length', { __proto__: null, value: op.length }) ObjectDefineProperty(Stream.Readable.prototype, key, { __proto__: null, value: fn, enumerable: false, configurable: true, writable: true }) } Stream.Writable = __nccwpck_require__(9557) Stream.Duplex = __nccwpck_require__(2327) Stream.Transform = __nccwpck_require__(7689) Stream.PassThrough = __nccwpck_require__(7179) Stream.pipeline = pipeline const { addAbortSignal } = __nccwpck_require__(9018) Stream.addAbortSignal = addAbortSignal Stream.finished = eos Stream.destroy = destroyer Stream.compose = compose Stream.setDefaultHighWaterMark = setDefaultHighWaterMark Stream.getDefaultHighWaterMark = getDefaultHighWaterMark ObjectDefineProperty(Stream, 'promises', { __proto__: null, configurable: true, enumerable: true, get() { return promises } }) ObjectDefineProperty(pipeline, customPromisify, { __proto__: null, enumerable: true, get() { return promises.pipeline } }) ObjectDefineProperty(eos, customPromisify, { __proto__: null, enumerable: true, get() { return promises.finished } }) // Backwards-compat with node 0.4.x Stream.Stream = Stream Stream._isUint8Array = function isUint8Array(value) { return value instanceof Uint8Array } Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) } /***/ }), /***/ 1898: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { ArrayPrototypePop, Promise } = __nccwpck_require__(2177) const { isIterable, isNodeStream, isWebStream } = __nccwpck_require__(5848) const { pipelineImpl: pl } = __nccwpck_require__(4687) const { finished } = __nccwpck_require__(741) __nccwpck_require__(4985) function pipeline(...streams) { return new Promise((resolve, reject) => { let signal let end const lastArg = streams[streams.length - 1] if ( lastArg && typeof lastArg === 'object' && !isNodeStream(lastArg) && !isIterable(lastArg) && !isWebStream(lastArg) ) { const options = ArrayPrototypePop(streams) signal = options.signal end = options.end } pl( streams, (err, value) => { if (err) { reject(err) } else { resolve(value) } }, { signal, end } ) }) } module.exports = { finished, pipeline } /***/ }), /***/ 2532: /***/ ((module, exports, __nccwpck_require__) => { /*! safe-buffer. MIT License. Feross Aboukhadijeh */ /* eslint-disable node/no-deprecated-api */ var buffer = __nccwpck_require__(181) var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } SafeBuffer.prototype = Object.create(Buffer.prototype) // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } /***/ }), /***/ 1064: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /**/ var Buffer = (__nccwpck_require__(2532).Buffer); /**/ var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.StringDecoder = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. If an invalid byte is detected, -2 is returned. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return byte >> 6 === 0x02 ? -1 : -2; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'; } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'; } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'; } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character is added when ending on a partial // character. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'; return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } /***/ }), /***/ 744: /***/ ((module) => { /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } /***/ }), /***/ 6733: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Copyright Takatoshi Kondo 2021 // // Distributed under the MIT License const NumberAllocator = __nccwpck_require__(4448) module.exports.NumberAllocator = NumberAllocator /***/ }), /***/ 4448: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Takatoshi Kondo 2021 // // Distributed under the MIT License const SortedSet = (__nccwpck_require__(1098)/* .OrderedSet */ .CD) const debugTrace = __nccwpck_require__(2830)('number-allocator:trace') const debugError = __nccwpck_require__(2830)('number-allocator:error') /** * Interval constructor * @constructor * @param {Number} low - The lowest value of the interval * @param {Number} high - The highest value of the interval */ function Interval (low, high) { this.low = low this.high = high } Interval.prototype.equals = function (other) { return this.low === other.low && this.high === other.high } Interval.prototype.compare = function (other) { if (this.low < other.low && this.high < other.low) return -1 if (other.low < this.low && other.high < this.low) return 1 return 0 } /** * NumberAllocator constructor. * The all numbers are set to vacant status. * Time Complexity O(1) * @constructor * @param {Number} min - The maximum number of allocatable. The number must be integer. * @param {Number} maxh - The minimum number of allocatable. The number must be integer. */ function NumberAllocator (min, max) { if (!(this instanceof NumberAllocator)) { return new NumberAllocator(min, max) } this.min = min this.max = max this.ss = new SortedSet( [], (lhs, rhs) => { return lhs.compare(rhs) } ) debugTrace('Create') this.clear() } /** * Get the first vacant number. The status of the number is not updated. * Time Complexity O(1) * @return {Number} - The first vacant number. If all numbers are occupied, return null. * When alloc() is called then the same value will be allocated. */ NumberAllocator.prototype.firstVacant = function () { if (this.ss.size() === 0) return null return this.ss.front().low } /** * Allocate the first vacant number. The number become occupied status. * Time Complexity O(1) * @return {Number} - The first vacant number. If all numbers are occupied, return null. */ NumberAllocator.prototype.alloc = function () { if (this.ss.size() === 0) { debugTrace('alloc():empty') return null } const it = this.ss.begin() const low = it.pointer.low const high = it.pointer.high const num = low if (num + 1 <= high) { // x|----| this.ss.updateKeyByIterator(it, new Interval(low + 1, high)) } else { this.ss.eraseElementByPos(0) } debugTrace('alloc():' + num) return num } /** * Use the number. The number become occupied status. * If the number has already been occupied, then return false. * Time Complexity O(logN) : N is the number of intervals (not numbers) * @param {Number} num - The number to request use. * @return {Boolean} - If `num` was not occupied, then return true, otherwise return false. */ NumberAllocator.prototype.use = function (num) { const key = new Interval(num, num) const it = this.ss.lowerBound(key) if (!it.equals(this.ss.end())) { const low = it.pointer.low const high = it.pointer.high if (it.pointer.equals(key)) { // |x| this.ss.eraseElementByIterator(it) debugTrace('use():' + num) return true } // x |-----| if (low > num) return false // |x----| if (low === num) { // x|----| this.ss.updateKeyByIterator(it, new Interval(low + 1, high)) debugTrace('use():' + num) return true } // |----x| if (high === num) { // |----|x this.ss.updateKeyByIterator(it, new Interval(low, high - 1)) debugTrace('use():' + num) return true } // |--x--| // x|--| this.ss.updateKeyByIterator(it, new Interval(num + 1, high)) // |--|x|--| this.ss.insert(new Interval(low, num - 1)) debugTrace('use():' + num) return true } debugTrace('use():failed') return false } /** * Deallocate the number. The number become vacant status. * Time Complexity O(logN) : N is the number of intervals (not numbers) * @param {Number} num - The number to deallocate. The number must be occupied status. * In other words, the number must be allocated by alloc() or occupied be use(). */ NumberAllocator.prototype.free = function (num) { if (num < this.min || num > this.max) { debugError('free():' + num + ' is out of range') return } const key = new Interval(num, num) const it = this.ss.upperBound(key) if (it.equals(this.ss.end())) { // ....v if (it.equals(this.ss.begin())) { // Insert new interval this.ss.insert(key) return } it.pre() const low = it.pointer.high const high = it.pointer.high if (high + 1 === num) { // Concat to left this.ss.updateKeyByIterator(it, new Interval(low, num)) } else { // Insert new interval this.ss.insert(key) } } else { if (it.equals(this.ss.begin())) { // v.... if (num + 1 === it.pointer.low) { // Concat to right const high = it.pointer.high this.ss.updateKeyByIterator(it, new Interval(num, high)) } else { // Insert new interval this.ss.insert(key) } } else { // ..v.. const rLow = it.pointer.low const rHigh = it.pointer.high it.pre() const lLow = it.pointer.low const lHigh = it.pointer.high if (lHigh + 1 === num) { if (num + 1 === rLow) { // Concat to left and right this.ss.eraseElementByIterator(it) this.ss.updateKeyByIterator(it, new Interval(lLow, rHigh)) } else { // Concat to left this.ss.updateKeyByIterator(it, new Interval(lLow, num)) } } else { if (num + 1 === rLow) { // Concat to right this.ss.eraseElementByIterator(it.next()) this.ss.insert(new Interval(num, rHigh)) } else { // Insert new interval this.ss.insert(key) } } } } debugTrace('free():' + num) } /** * Clear all occupied numbers. * The all numbers are set to vacant status. * Time Complexity O(1) */ NumberAllocator.prototype.clear = function () { debugTrace('clear()') this.ss.clear() this.ss.insert(new Interval(this.min, this.max)) } /** * Get the number of intervals. Interval is internal structure of this library. * This function is for debugging. * Time Complexity O(1) * @return {Number} - The number of intervals. */ NumberAllocator.prototype.intervalCount = function () { return this.ss.size() } /** * Dump the internal structor of the library. * This function is for debugging. * Time Complexity O(N) : N is the number of intervals (not numbers) */ NumberAllocator.prototype.dump = function () { console.log('length:' + this.ss.size()) for (const element of this.ss) { console.log(element) } } module.exports = NumberAllocator /***/ }), /***/ 506: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var hasMap = typeof Map === 'function' && Map.prototype; var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; var mapForEach = hasMap && Map.prototype.forEach; var hasSet = typeof Set === 'function' && Set.prototype; var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; var setForEach = hasSet && Set.prototype.forEach; var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; var booleanValueOf = Boolean.prototype.valueOf; var objectToString = Object.prototype.toString; var functionToString = Function.prototype.toString; var $match = String.prototype.match; var $slice = String.prototype.slice; var $replace = String.prototype.replace; var $toUpperCase = String.prototype.toUpperCase; var $toLowerCase = String.prototype.toLowerCase; var $test = RegExp.prototype.test; var $concat = Array.prototype.concat; var $join = Array.prototype.join; var $arrSlice = Array.prototype.slice; var $floor = Math.floor; var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; var gOPS = Object.getOwnPropertySymbols; var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; // ie, `has-tostringtag/shams var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') ? Symbol.toStringTag : null; var isEnumerable = Object.prototype.propertyIsEnumerable; var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( [].__proto__ === Array.prototype // eslint-disable-line no-proto ? function (O) { return O.__proto__; // eslint-disable-line no-proto } : null ); function addNumericSeparator(num, str) { if ( num === Infinity || num === -Infinity || num !== num || (num && num > -1000 && num < 1000) || $test.call(/e/, str) ) { return str; } var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; if (typeof num === 'number') { var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) if (int !== num) { var intStr = String(int); var dec = $slice.call(str, intStr.length + 1); return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); } } return $replace.call(str, sepRegex, '$&_'); } var utilInspect = __nccwpck_require__(8502); var inspectCustom = utilInspect.custom; var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; var quotes = { __proto__: null, 'double': '"', single: "'" }; var quoteREs = { __proto__: null, 'double': /(["\\])/g, single: /(['\\])/g }; module.exports = function inspect_(obj, options, depth, seen) { var opts = options || {}; if (has(opts, 'quoteStyle') && !has(quotes, opts.quoteStyle)) { throw new TypeError('option "quoteStyle" must be "single" or "double"'); } if ( has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null ) ) { throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); } var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); } if ( has(opts, 'indent') && opts.indent !== null && opts.indent !== '\t' && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) ) { throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); } if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); } var numericSeparator = opts.numericSeparator; if (typeof obj === 'undefined') { return 'undefined'; } if (obj === null) { return 'null'; } if (typeof obj === 'boolean') { return obj ? 'true' : 'false'; } if (typeof obj === 'string') { return inspectString(obj, opts); } if (typeof obj === 'number') { if (obj === 0) { return Infinity / obj > 0 ? '0' : '-0'; } var str = String(obj); return numericSeparator ? addNumericSeparator(obj, str) : str; } if (typeof obj === 'bigint') { var bigIntStr = String(obj) + 'n'; return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; } var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; if (typeof depth === 'undefined') { depth = 0; } if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { return isArray(obj) ? '[Array]' : '[Object]'; } var indent = getIndent(opts, depth); if (typeof seen === 'undefined') { seen = []; } else if (indexOf(seen, obj) >= 0) { return '[Circular]'; } function inspect(value, from, noIndent) { if (from) { seen = $arrSlice.call(seen); seen.push(from); } if (noIndent) { var newOpts = { depth: opts.depth }; if (has(opts, 'quoteStyle')) { newOpts.quoteStyle = opts.quoteStyle; } return inspect_(value, newOpts, depth + 1, seen); } return inspect_(value, opts, depth + 1, seen); } if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable var name = nameOf(obj); var keys = arrObjKeys(obj, inspect); return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); } if (isSymbol(obj)) { var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; } if (isElement(obj)) { var s = '<' + $toLowerCase.call(String(obj.nodeName)); var attrs = obj.attributes || []; for (var i = 0; i < attrs.length; i++) { s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); } s += '>'; if (obj.childNodes && obj.childNodes.length) { s += '...'; } s += ''; return s; } if (isArray(obj)) { if (obj.length === 0) { return '[]'; } var xs = arrObjKeys(obj, inspect); if (indent && !singleLineValues(xs)) { return '[' + indentedJoin(xs, indent) + ']'; } return '[ ' + $join.call(xs, ', ') + ' ]'; } if (isError(obj)) { var parts = arrObjKeys(obj, inspect); if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; } if (parts.length === 0) { return '[' + String(obj) + ']'; } return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; } if (typeof obj === 'object' && customInspect) { if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { return utilInspect(obj, { depth: maxDepth - depth }); } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { return obj.inspect(); } } if (isMap(obj)) { var mapParts = []; if (mapForEach) { mapForEach.call(obj, function (value, key) { mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); }); } return collectionOf('Map', mapSize.call(obj), mapParts, indent); } if (isSet(obj)) { var setParts = []; if (setForEach) { setForEach.call(obj, function (value) { setParts.push(inspect(value, obj)); }); } return collectionOf('Set', setSize.call(obj), setParts, indent); } if (isWeakMap(obj)) { return weakCollectionOf('WeakMap'); } if (isWeakSet(obj)) { return weakCollectionOf('WeakSet'); } if (isWeakRef(obj)) { return weakCollectionOf('WeakRef'); } if (isNumber(obj)) { return markBoxed(inspect(Number(obj))); } if (isBigInt(obj)) { return markBoxed(inspect(bigIntValueOf.call(obj))); } if (isBoolean(obj)) { return markBoxed(booleanValueOf.call(obj)); } if (isString(obj)) { return markBoxed(inspect(String(obj))); } // note: in IE 8, sometimes `global !== window` but both are the prototypes of each other /* eslint-env browser */ if (typeof window !== 'undefined' && obj === window) { return '{ [object Window] }'; } if ( (typeof globalThis !== 'undefined' && obj === globalThis) || (typeof global !== 'undefined' && obj === global) ) { return '{ [object globalThis] }'; } if (!isDate(obj) && !isRegExp(obj)) { var ys = arrObjKeys(obj, inspect); var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; var protoTag = obj instanceof Object ? '' : 'null prototype'; var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); if (ys.length === 0) { return tag + '{}'; } if (indent) { return tag + '{' + indentedJoin(ys, indent) + '}'; } return tag + '{ ' + $join.call(ys, ', ') + ' }'; } return String(obj); }; function wrapQuotes(s, defaultStyle, opts) { var style = opts.quoteStyle || defaultStyle; var quoteChar = quotes[style]; return quoteChar + s + quoteChar; } function quote(s) { return $replace.call(String(s), /"/g, '"'); } function canTrustToString(obj) { return !toStringTag || !(typeof obj === 'object' && (toStringTag in obj || typeof obj[toStringTag] !== 'undefined')); } function isArray(obj) { return toStr(obj) === '[object Array]' && canTrustToString(obj); } function isDate(obj) { return toStr(obj) === '[object Date]' && canTrustToString(obj); } function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && canTrustToString(obj); } function isError(obj) { return toStr(obj) === '[object Error]' && canTrustToString(obj); } function isString(obj) { return toStr(obj) === '[object String]' && canTrustToString(obj); } function isNumber(obj) { return toStr(obj) === '[object Number]' && canTrustToString(obj); } function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && canTrustToString(obj); } // Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives function isSymbol(obj) { if (hasShammedSymbols) { return obj && typeof obj === 'object' && obj instanceof Symbol; } if (typeof obj === 'symbol') { return true; } if (!obj || typeof obj !== 'object' || !symToString) { return false; } try { symToString.call(obj); return true; } catch (e) {} return false; } function isBigInt(obj) { if (!obj || typeof obj !== 'object' || !bigIntValueOf) { return false; } try { bigIntValueOf.call(obj); return true; } catch (e) {} return false; } var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; function has(obj, key) { return hasOwn.call(obj, key); } function toStr(obj) { return objectToString.call(obj); } function nameOf(f) { if (f.name) { return f.name; } var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); if (m) { return m[1]; } return null; } function indexOf(xs, x) { if (xs.indexOf) { return xs.indexOf(x); } for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) { return i; } } return -1; } function isMap(x) { if (!mapSize || !x || typeof x !== 'object') { return false; } try { mapSize.call(x); try { setSize.call(x); } catch (s) { return true; } return x instanceof Map; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isWeakMap(x) { if (!weakMapHas || !x || typeof x !== 'object') { return false; } try { weakMapHas.call(x, weakMapHas); try { weakSetHas.call(x, weakSetHas); } catch (s) { return true; } return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isWeakRef(x) { if (!weakRefDeref || !x || typeof x !== 'object') { return false; } try { weakRefDeref.call(x); return true; } catch (e) {} return false; } function isSet(x) { if (!setSize || !x || typeof x !== 'object') { return false; } try { setSize.call(x); try { mapSize.call(x); } catch (m) { return true; } return x instanceof Set; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isWeakSet(x) { if (!weakSetHas || !x || typeof x !== 'object') { return false; } try { weakSetHas.call(x, weakSetHas); try { weakMapHas.call(x, weakMapHas); } catch (s) { return true; } return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isElement(x) { if (!x || typeof x !== 'object') { return false; } if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { return true; } return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; } function inspectString(str, opts) { if (str.length > opts.maxStringLength) { var remaining = str.length - opts.maxStringLength; var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; } var quoteRE = quoteREs[opts.quoteStyle || 'single']; quoteRE.lastIndex = 0; // eslint-disable-next-line no-control-regex var s = $replace.call($replace.call(str, quoteRE, '\\$1'), /[\x00-\x1f]/g, lowbyte); return wrapQuotes(s, 'single', opts); } function lowbyte(c) { var n = c.charCodeAt(0); var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n]; if (x) { return '\\' + x; } return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); } function markBoxed(str) { return 'Object(' + str + ')'; } function weakCollectionOf(type) { return type + ' { ? }'; } function collectionOf(type, size, entries, indent) { var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); return type + ' (' + size + ') {' + joinedEntries + '}'; } function singleLineValues(xs) { for (var i = 0; i < xs.length; i++) { if (indexOf(xs[i], '\n') >= 0) { return false; } } return true; } function getIndent(opts, depth) { var baseIndent; if (opts.indent === '\t') { baseIndent = '\t'; } else if (typeof opts.indent === 'number' && opts.indent > 0) { baseIndent = $join.call(Array(opts.indent + 1), ' '); } else { return null; } return { base: baseIndent, prev: $join.call(Array(depth + 1), baseIndent) }; } function indentedJoin(xs, indent) { if (xs.length === 0) { return ''; } var lineJoiner = '\n' + indent.prev + indent.base; return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; } function arrObjKeys(obj, inspect) { var isArr = isArray(obj); var xs = []; if (isArr) { xs.length = obj.length; for (var i = 0; i < obj.length; i++) { xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; } } var syms = typeof gOPS === 'function' ? gOPS(obj) : []; var symMap; if (hasShammedSymbols) { symMap = {}; for (var k = 0; k < syms.length; k++) { symMap['$' + syms[k]] = syms[k]; } } for (var key in obj) { // eslint-disable-line no-restricted-syntax if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section continue; // eslint-disable-line no-restricted-syntax, no-continue } else if ($test.call(/[^\w$]/, key)) { xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); } else { xs.push(key + ': ' + inspect(obj[key], obj)); } } if (typeof gOPS === 'function') { for (var j = 0; j < syms.length; j++) { if (isEnumerable.call(obj, syms[j])) { xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); } } } return xs; } /***/ }), /***/ 8502: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(9023).inspect; /***/ }), /***/ 5560: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var wrappy = __nccwpck_require__(5883) module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }) Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict(this) }, configurable: true }) }) function once (fn) { var f = function () { if (f.called) return f.value f.called = true return f.value = fn.apply(this, arguments) } f.called = false return f } function onceStrict (fn) { var f = function () { if (f.called) throw new Error(f.onceError) f.called = true return f.value = fn.apply(this, arguments) } var name = fn.name || 'Function wrapped with `once`' f.onceError = name + " shouldn't be called more than once" f.called = false return f } /***/ }), /***/ 5992: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var Readable = __nccwpck_require__(6131); var util = __nccwpck_require__(9023); function isReadable(stream) { if (typeof stream.pipe !== 'function') { return false; } if (!stream.readable) { return false; } if (typeof stream._read !== 'function') { return false; } if (!stream._readableState) { return false; } return true; } function addStream (streams, stream) { if (!isReadable(stream)) { throw new Error('All input streams must be readable'); } var self = this; stream._buffer = []; stream.on('readable', function () { var chunk = stream.read(); while (chunk) { if (this === streams[0]) { self.push(chunk); } else { this._buffer.push(chunk); } chunk = stream.read(); } }); stream.on('end', function () { for (var stream = streams[0]; stream && stream._readableState.ended; stream = streams[0]) { while (stream._buffer.length) { self.push(stream._buffer.shift()); } streams.shift(); } if (!streams.length) { self.push(null); } }); stream.on('error', this.emit.bind(this, 'error')); streams.push(stream); } function OrderedStreams (streams, options) { if (!(this instanceof(OrderedStreams))) { return new OrderedStreams(streams, options); } streams = streams || []; options = options || {}; options.objectMode = true; Readable.call(this, options); if (!Array.isArray(streams)) { streams = [streams]; } if (!streams.length) { return this.push(null); // no streams, close } var addStreamBinded = addStream.bind(this, []); streams.forEach(function (item) { if (Array.isArray(item)) { item.forEach(addStreamBinded); } else { addStreamBinded(item); } }); } util.inherits(OrderedStreams, Readable); OrderedStreams.prototype._read = function () {}; module.exports = OrderedStreams; /***/ }), /***/ 9782: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var path = __nccwpck_require__(6928); var inspect = (__nccwpck_require__(9023).inspect); function assertPath(path) { if (typeof path !== 'string') { throw new TypeError('Path must be a string. Received ' + inspect(path)); } } function posix(path) { assertPath(path); if (path.length === 0) return '.'; var code = path.charCodeAt(0); var hasRoot = (code === 47/*/*/); var end = -1; var matchedSlash = true; for (var i = path.length - 1; i >= 1; --i) { code = path.charCodeAt(i); if (code === 47/*/*/) { if (!matchedSlash) { end = i; break; } } else { // We saw the first non-path separator matchedSlash = false; } } if (end === -1) return hasRoot ? '/' : '.'; if (hasRoot && end === 1) return '//'; return path.slice(0, end); } function win32(path) { assertPath(path); var len = path.length; if (len === 0) return '.'; var rootEnd = -1; var end = -1; var matchedSlash = true; var offset = 0; var code = path.charCodeAt(0); // Try to match a root if (len > 1) { if (code === 47/*/*/ || code === 92/*\*/) { // Possible UNC root rootEnd = offset = 1; code = path.charCodeAt(1); if (code === 47/*/*/ || code === 92/*\*/) { // Matched double path separator at beginning var j = 2; var last = j; // Match 1 or more non-path separators for (; j < len; ++j) { code = path.charCodeAt(j); if (code === 47/*/*/ || code === 92/*\*/) break; } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more path separators for (; j < len; ++j) { code = path.charCodeAt(j); if (code !== 47/*/*/ && code !== 92/*\*/) break; } if (j < len && j !== last) { // Matched! last = j; // Match 1 or more non-path separators for (; j < len; ++j) { code = path.charCodeAt(j); if (code === 47/*/*/ || code === 92/*\*/) break; } if (j === len) { // We matched a UNC root only return path; } if (j !== last) { // We matched a UNC root with leftovers // Offset by 1 to include the separator after the UNC root to // treat it as a "normal root" on top of a (UNC) root rootEnd = offset = j + 1; } } } } } else if ((code >= 65/*A*/ && code <= 90/*Z*/) || (code >= 97/*a*/ && code <= 122/*z*/)) { // Possible device root code = path.charCodeAt(1); if (path.charCodeAt(1) === 58/*:*/) { rootEnd = offset = 2; if (len > 2) { code = path.charCodeAt(2); if (code === 47/*/*/ || code === 92/*\*/) rootEnd = offset = 3; } } } } else if (code === 47/*/*/ || code === 92/*\*/) { return path[0]; } for (var i = len - 1; i >= offset; --i) { code = path.charCodeAt(i); if (code === 47/*/*/ || code === 92/*\*/) { if (!matchedSlash) { end = i; break; } } else { // We saw the first non-path separator matchedSlash = false; } } if (end === -1) { if (rootEnd === -1) return '.'; else end = rootEnd; } return path.slice(0, end); } module.exports = process.platform === 'win32' ? win32 : posix; module.exports.posix = posix; module.exports.win32 = win32; /***/ }), /***/ 9024: /***/ ((module) => { "use strict"; function posix(path) { return path.charAt(0) === '/'; } function win32(path) { // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; var result = splitDeviceRe.exec(path); var device = result[1] || ''; var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute return Boolean(result[2] || isUnc); } module.exports = process.platform === 'win32' ? win32 : posix; module.exports.posix = posix; module.exports.win32 = win32; /***/ }), /***/ 1564: /***/ ((module) => { "use strict"; if (typeof process === 'undefined' || !process.version || process.version.indexOf('v0.') === 0 || process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { module.exports = { nextTick: nextTick }; } else { module.exports = process } function nextTick(fn, arg1, arg2, arg3) { if (typeof fn !== 'function') { throw new TypeError('"callback" argument must be a function'); } var len = arguments.length; var args, i; switch (len) { case 0: case 1: return process.nextTick(fn); case 2: return process.nextTick(function afterTickOne() { fn.call(null, arg1); }); case 3: return process.nextTick(function afterTickTwo() { fn.call(null, arg1, arg2); }); case 4: return process.nextTick(function afterTickThree() { fn.call(null, arg1, arg2, arg3); }); default: args = new Array(len - 1); i = 0; while (i < args.length) { args[i++] = arguments[i]; } return process.nextTick(function afterTick() { fn.apply(null, args); }); } } /***/ }), /***/ 7945: /***/ ((module) => { // for now just expose the builtin process global from node.js module.exports = global.process; /***/ }), /***/ 7898: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var once = __nccwpck_require__(5560) var eos = __nccwpck_require__(1424) var fs try { fs = __nccwpck_require__(9896) // we only need fs to get the ReadStream and WriteStream prototypes } catch (e) {} var noop = function () {} var ancient = typeof process === 'undefined' ? false : /^v?\.0/.test(process.version) var isFn = function (fn) { return typeof fn === 'function' } var isFS = function (stream) { if (!ancient) return false // newer node version do not need to care about fs is a special way if (!fs) return false // browser return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) } var isRequest = function (stream) { return stream.setHeader && isFn(stream.abort) } var destroyer = function (stream, reading, writing, callback) { callback = once(callback) var closed = false stream.on('close', function () { closed = true }) eos(stream, {readable: reading, writable: writing}, function (err) { if (err) return callback(err) closed = true callback() }) var destroyed = false return function (err) { if (closed) return if (destroyed) return destroyed = true if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want if (isFn(stream.destroy)) return stream.destroy() callback(err || new Error('stream was destroyed')) } } var call = function (fn) { fn() } var pipe = function (from, to) { return from.pipe(to) } var pump = function () { var streams = Array.prototype.slice.call(arguments) var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop if (Array.isArray(streams[0])) streams = streams[0] if (streams.length < 2) throw new Error('pump requires two streams per minimum') var error var destroys = streams.map(function (stream, i) { var reading = i < streams.length - 1 var writing = i > 0 return destroyer(stream, reading, writing, function (err) { if (!error) error = err if (err) destroys.forEach(call) if (reading) return destroys.forEach(call) callback(error) }) }) return streams.reduce(pipe) } module.exports = pump /***/ }), /***/ 2432: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var pump = __nccwpck_require__(5922) var inherits = __nccwpck_require__(9598) var Duplexify = __nccwpck_require__(9112) var toArray = function(args) { if (!args.length) return [] return Array.isArray(args[0]) ? args[0] : Array.prototype.slice.call(args) } var define = function(opts) { var Pumpify = function() { var streams = toArray(arguments) if (!(this instanceof Pumpify)) return new Pumpify(streams) Duplexify.call(this, null, null, opts) if (streams.length) this.setPipeline(streams) } inherits(Pumpify, Duplexify) Pumpify.prototype.setPipeline = function() { var streams = toArray(arguments) var self = this var ended = false var w = streams[0] var r = streams[streams.length-1] r = r.readable ? r : null w = w.writable ? w : null var onclose = function() { streams[0].emit('error', new Error('stream was destroyed')) } this.on('close', onclose) this.on('prefinish', function() { if (!ended) self.cork() }) pump(streams, function(err) { self.removeListener('close', onclose) if (err) return self.destroy(err.message === 'premature close' ? null : err) ended = true // pump ends after the last stream is not writable *but* // pumpify still forwards the readable part so we need to catch errors // still, so reenable autoDestroy in this case if (self._autoDestroy === false) self._autoDestroy = true self.uncork() }) if (this.destroyed) return onclose() this.setWritable(w) this.setReadable(r) } return Pumpify } module.exports = define({autoDestroy:false, destroy:false}) module.exports.obj = define({autoDestroy: false, destroy:false, objectMode:true, highWaterMark:16}) module.exports.ctor = define /***/ }), /***/ 5922: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var once = __nccwpck_require__(5560) var eos = __nccwpck_require__(1424) var fs = __nccwpck_require__(9896) // we only need fs to get the ReadStream and WriteStream prototypes var noop = function () {} var ancient = /^v?\.0/.test(process.version) var isFn = function (fn) { return typeof fn === 'function' } var isFS = function (stream) { if (!ancient) return false // newer node version do not need to care about fs is a special way if (!fs) return false // browser return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) } var isRequest = function (stream) { return stream.setHeader && isFn(stream.abort) } var destroyer = function (stream, reading, writing, callback) { callback = once(callback) var closed = false stream.on('close', function () { closed = true }) eos(stream, {readable: reading, writable: writing}, function (err) { if (err) return callback(err) closed = true callback() }) var destroyed = false return function (err) { if (closed) return if (destroyed) return destroyed = true if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want if (isFn(stream.destroy)) return stream.destroy() callback(err || new Error('stream was destroyed')) } } var call = function (fn) { fn() } var pipe = function (from, to) { return from.pipe(to) } var pump = function () { var streams = Array.prototype.slice.call(arguments) var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop if (Array.isArray(streams[0])) streams = streams[0] if (streams.length < 2) throw new Error('pump requires two streams per minimum') var error var destroys = streams.map(function (stream, i) { var reading = i < streams.length - 1 var writing = i > 0 return destroyer(stream, reading, writing, function (err) { if (!error) error = err if (err) destroys.forEach(call) if (reading) return destroys.forEach(call) callback(error) }) }) streams.reduce(pipe) } module.exports = pump /***/ }), /***/ 6032: /***/ ((module) => { "use strict"; var replace = String.prototype.replace; var percentTwenties = /%20/g; var Format = { RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; module.exports = { 'default': Format.RFC3986, formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return String(value); } }, RFC1738: Format.RFC1738, RFC3986: Format.RFC3986 }; /***/ }), /***/ 240: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var stringify = __nccwpck_require__(1293); var parse = __nccwpck_require__(9091); var formats = __nccwpck_require__(6032); module.exports = { formats: formats, parse: parse, stringify: stringify }; /***/ }), /***/ 9091: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var utils = __nccwpck_require__(5225); var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var defaults = { allowDots: false, allowEmptyArrays: false, allowPrototypes: false, allowSparse: false, arrayLimit: 20, charset: 'utf-8', charsetSentinel: false, comma: false, decodeDotInKeys: false, decoder: utils.decode, delimiter: '&', depth: 5, duplicates: 'combine', ignoreQueryPrefix: false, interpretNumericEntities: false, parameterLimit: 1000, parseArrays: true, plainObjects: false, strictDepth: false, strictMerge: true, strictNullHandling: false, throwOnLimitExceeded: false }; var interpretNumericEntities = function (str) { return str.replace(/&#(\d+);/g, function ($0, numberStr) { return String.fromCharCode(parseInt(numberStr, 10)); }); }; var parseArrayValue = function (val, options, currentArrayLength) { if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { return val.split(','); } if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) { throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); } return val; }; // This is what browsers will submit when the ✓ character occurs in an // application/x-www-form-urlencoded body and the encoding of the page containing // the form is iso-8859-1, or when the submitted form has an accept-charset // attribute of iso-8859-1. Presumably also with other charsets that do not contain // the ✓ character, such as us-ascii. var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') // These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') var parseValues = function parseQueryStringValues(str, options) { var obj = { __proto__: null }; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; cleanStr = cleanStr.replace(/%5B/gi, '[').replace(/%5D/gi, ']'); var limit = options.parameterLimit === Infinity ? void undefined : options.parameterLimit; var parts = cleanStr.split( options.delimiter, options.throwOnLimitExceeded && typeof limit !== 'undefined' ? limit + 1 : limit ); if (options.throwOnLimitExceeded && typeof limit !== 'undefined' && parts.length > limit) { throw new RangeError('Parameter limit exceeded. Only ' + limit + ' parameter' + (limit === 1 ? '' : 's') + ' allowed.'); } var skipIndex = -1; // Keep track of where the utf8 sentinel was found var i; var charset = options.charset; if (options.charsetSentinel) { for (i = 0; i < parts.length; ++i) { if (parts[i].indexOf('utf8=') === 0) { if (parts[i] === charsetSentinel) { charset = 'utf-8'; } else if (parts[i] === isoSentinel) { charset = 'iso-8859-1'; } skipIndex = i; i = parts.length; // The eslint settings do not allow break; } } } for (i = 0; i < parts.length; ++i) { if (i === skipIndex) { continue; } var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key; var val; if (pos === -1) { key = options.decoder(part, defaults.decoder, charset, 'key'); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); if (key !== null) { val = utils.maybeMap( parseArrayValue( part.slice(pos + 1), options, isArray(obj[key]) ? obj[key].length : 0 ), function (encodedVal) { return options.decoder(encodedVal, defaults.decoder, charset, 'value'); } ); } } if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { val = interpretNumericEntities(String(val)); } if (part.indexOf('[]=') > -1) { val = isArray(val) ? [val] : val; } if (options.comma && isArray(val) && val.length > options.arrayLimit) { if (options.throwOnLimitExceeded) { throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); } val = utils.combine([], val, options.arrayLimit, options.plainObjects); } if (key !== null) { var existing = has.call(obj, key); if (existing && (options.duplicates === 'combine' || part.indexOf('[]=') > -1)) { obj[key] = utils.combine( obj[key], val, options.arrayLimit, options.plainObjects ); } else if (!existing || options.duplicates === 'last') { obj[key] = val; } } } return obj; }; var parseObject = function (chain, val, options, valuesParsed) { var currentArrayLength = 0; if (chain.length > 0 && chain[chain.length - 1] === '[]') { var parentKey = chain.slice(0, -1).join(''); currentArrayLength = Array.isArray(val) && val[parentKey] ? val[parentKey].length : 0; } var leaf = valuesParsed ? val : parseArrayValue(val, options, currentArrayLength); for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]' && options.parseArrays) { if (utils.isOverflow(leaf)) { // leaf is already an overflow object, preserve it obj = leaf; } else { obj = options.allowEmptyArrays && (leaf === '' || (options.strictNullHandling && leaf === null)) ? [] : utils.combine( [], leaf, options.arrayLimit, options.plainObjects ); } } else { obj = options.plainObjects ? { __proto__: null } : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, '.') : cleanRoot; var index = parseInt(decodedRoot, 10); var isValidArrayIndex = !isNaN(index) && root !== decodedRoot && String(index) === decodedRoot && index >= 0 && options.parseArrays; if (!options.parseArrays && decodedRoot === '') { obj = { 0: leaf }; } else if (isValidArrayIndex && index < options.arrayLimit) { obj = []; obj[index] = leaf; } else if (isValidArrayIndex && options.throwOnLimitExceeded) { throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); } else if (isValidArrayIndex) { obj[index] = leaf; utils.markOverflow(obj, index); } else if (decodedRoot !== '__proto__') { obj[decodedRoot] = leaf; } } leaf = obj; } return leaf; }; var splitKeyIntoSegments = function splitKeyIntoSegments(givenKey, options) { var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; if (options.depth <= 0) { if (!options.plainObjects && has.call(Object.prototype, key)) { if (!options.allowPrototypes) { return; } } return [key]; } var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; var segment = brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; var keys = []; if (parent) { if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys[keys.length] = parent; } var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { i += 1; var segmentContent = segment[1].slice(1, -1); if (!options.plainObjects && has.call(Object.prototype, segmentContent)) { if (!options.allowPrototypes) { return; } } keys[keys.length] = segment[1]; } if (segment) { if (options.strictDepth === true) { throw new RangeError('Input depth exceeded depth option of ' + options.depth + ' and strictDepth is true'); } keys[keys.length] = '[' + key.slice(segment.index) + ']'; } return keys; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { if (!givenKey) { return; } var keys = splitKeyIntoSegments(givenKey, options); if (!keys) { return; } return parseObject(keys, val, options, valuesParsed); }; var normalizeParseOptions = function normalizeParseOptions(opts) { if (!opts) { return defaults; } if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); } if (typeof opts.decodeDotInKeys !== 'undefined' && typeof opts.decodeDotInKeys !== 'boolean') { throw new TypeError('`decodeDotInKeys` option can only be `true` or `false`, when provided'); } if (opts.decoder !== null && typeof opts.decoder !== 'undefined' && typeof opts.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } if (typeof opts.throwOnLimitExceeded !== 'undefined' && typeof opts.throwOnLimitExceeded !== 'boolean') { throw new TypeError('`throwOnLimitExceeded` option must be a boolean'); } var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; var duplicates = typeof opts.duplicates === 'undefined' ? defaults.duplicates : opts.duplicates; if (duplicates !== 'combine' && duplicates !== 'first' && duplicates !== 'last') { throw new TypeError('The duplicates option must be either combine, first, or last'); } var allowDots = typeof opts.allowDots === 'undefined' ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; return { allowDots: allowDots, allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, decodeDotInKeys: typeof opts.decodeDotInKeys === 'boolean' ? opts.decodeDotInKeys : defaults.decodeDotInKeys, decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, // eslint-disable-next-line no-implicit-coercion, no-extra-parens depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, duplicates: duplicates, ignoreQueryPrefix: opts.ignoreQueryPrefix === true, interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, parseArrays: opts.parseArrays !== false, plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, strictDepth: typeof opts.strictDepth === 'boolean' ? !!opts.strictDepth : defaults.strictDepth, strictMerge: typeof opts.strictMerge === 'boolean' ? !!opts.strictMerge : defaults.strictMerge, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, throwOnLimitExceeded: typeof opts.throwOnLimitExceeded === 'boolean' ? opts.throwOnLimitExceeded : false }; }; module.exports = function (str, opts) { var options = normalizeParseOptions(opts); if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? { __proto__: null } : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? { __proto__: null } : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); obj = utils.merge(obj, newObj, options); } if (options.allowSparse === true) { return obj; } return utils.compact(obj); }; /***/ }), /***/ 1293: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var getSideChannel = __nccwpck_require__(4753); var utils = __nccwpck_require__(5225); var formats = __nccwpck_require__(6032); var has = Object.prototype.hasOwnProperty; var arrayPrefixGenerators = { brackets: function brackets(prefix) { return prefix + '[]'; }, comma: 'comma', indices: function indices(prefix, key) { return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { return prefix; } }; var isArray = Array.isArray; var push = Array.prototype.push; var pushToArray = function (arr, valueOrArray) { push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); }; var toISO = Date.prototype.toISOString; var defaultFormat = formats['default']; var defaults = { addQueryPrefix: false, allowDots: false, allowEmptyArrays: false, arrayFormat: 'indices', charset: 'utf-8', charsetSentinel: false, commaRoundTrip: false, delimiter: '&', encode: true, encodeDotInKeys: false, encoder: utils.encode, encodeValuesOnly: false, filter: void undefined, format: defaultFormat, formatter: formats.formatters[defaultFormat], // deprecated indices: false, serializeDate: function serializeDate(date) { return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var isNonNullishPrimitive = function isNonNullishPrimitive(v) { return typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || typeof v === 'symbol' || typeof v === 'bigint'; }; var sentinel = {}; var stringify = function stringify( object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel ) { var obj = object; var tmpSc = sideChannel; var step = 0; var findFlag = false; while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { // Where object last appeared in the ref tree var pos = tmpSc.get(object); step += 1; if (typeof pos !== 'undefined') { if (pos === step) { throw new RangeError('Cyclic object value'); } else { findFlag = true; // Break while } } if (typeof tmpSc.get(sentinel) === 'undefined') { step = 0; } } if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (generateArrayPrefix === 'comma' && isArray(obj)) { obj = utils.maybeMap(obj, function (value) { if (value instanceof Date) { return serializeDate(value); } return value; }); } if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; } obj = ''; } if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (generateArrayPrefix === 'comma' && isArray(obj)) { // we need to join elements in if (encodeValuesOnly && encoder) { obj = utils.maybeMap(obj, encoder); } objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; } else if (isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + '[]' : encodedPrefix; if (allowEmptyArrays && isArray(obj) && obj.length === 0) { return adjustedPrefix + '[]'; } for (var j = 0; j < objKeys.length; ++j) { var key = objKeys[j]; var value = typeof key === 'object' && key && typeof key.value !== 'undefined' ? key.value : obj[key]; if (skipNulls && value === null) { continue; } var encodedKey = allowDots && encodeDotInKeys ? String(key).replace(/\./g, '%2E') : String(key); var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix : adjustedPrefix + (allowDots ? '.' + encodedKey : '[' + encodedKey + ']'); sideChannel.set(object, step); var valueSideChannel = getSideChannel(); valueSideChannel.set(sentinel, sideChannel); pushToArray(values, stringify( value, keyPrefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel )); } return values; }; var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { if (!opts) { return defaults; } if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); } if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); } if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var charset = opts.charset || defaults.charset; if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var format = formats['default']; if (typeof opts.format !== 'undefined') { if (!has.call(formats.formatters, opts.format)) { throw new TypeError('Unknown format option provided.'); } format = opts.format; } var formatter = formats.formatters[format]; var filter = defaults.filter; if (typeof opts.filter === 'function' || isArray(opts.filter)) { filter = opts.filter; } var arrayFormat; if (opts.arrayFormat in arrayPrefixGenerators) { arrayFormat = opts.arrayFormat; } else if ('indices' in opts) { arrayFormat = opts.indices ? 'indices' : 'repeat'; } else { arrayFormat = defaults.arrayFormat; } if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); } var allowDots = typeof opts.allowDots === 'undefined' ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; return { addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, allowDots: allowDots, allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, arrayFormat: arrayFormat, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, commaRoundTrip: !!opts.commaRoundTrip, delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, filter: filter, format: format, formatter: formatter, serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, sort: typeof opts.sort === 'function' ? opts.sort : null, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (object, opts) { var obj = object; var options = normalizeStringifyOptions(opts); var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat]; var commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; if (!objKeys) { objKeys = Object.keys(obj); } if (options.sort) { objKeys.sort(options.sort); } var sideChannel = getSideChannel(); for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; var value = obj[key]; if (options.skipNulls && value === null) { continue; } pushToArray(keys, stringify( value, key, generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel )); } var joined = keys.join(options.delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; if (options.charsetSentinel) { if (options.charset === 'iso-8859-1') { // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark prefix += 'utf8=%26%2310003%3B&'; } else { // encodeURIComponent('✓') prefix += 'utf8=%E2%9C%93&'; } } return joined.length > 0 ? prefix + joined : ''; }; /***/ }), /***/ 5225: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var formats = __nccwpck_require__(6032); var getSideChannel = __nccwpck_require__(4753); var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; // Track objects created from arrayLimit overflow using side-channel // Stores the current max numeric index for O(1) lookup var overflowChannel = getSideChannel(); var markOverflow = function markOverflow(obj, maxIndex) { overflowChannel.set(obj, maxIndex); return obj; }; var isOverflow = function isOverflow(obj) { return overflowChannel.has(obj); }; var getMaxIndex = function getMaxIndex(obj) { return overflowChannel.get(obj); }; var setMaxIndex = function setMaxIndex(obj, maxIndex) { overflowChannel.set(obj, maxIndex); }; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array[array.length] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase(); } return array; }()); var compactQueue = function compactQueue(queue) { while (queue.length > 1) { var item = queue.pop(); var obj = item.obj[item.prop]; if (isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted[compacted.length] = obj[j]; } } item.obj[item.prop] = compacted; } } }; var arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? { __proto__: null } : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; var merge = function merge(target, source, options) { /* eslint no-param-reassign: 0 */ if (!source) { return target; } if (typeof source !== 'object' && typeof source !== 'function') { if (isArray(target)) { var nextIndex = target.length; if (options && typeof options.arrayLimit === 'number' && nextIndex > options.arrayLimit) { return markOverflow(arrayToObject(target.concat(source), options), nextIndex); } target[nextIndex] = source; } else if (target && typeof target === 'object') { if (isOverflow(target)) { // Add at next numeric index for overflow objects var newIndex = getMaxIndex(target) + 1; target[newIndex] = source; setMaxIndex(target, newIndex); } else if (options && options.strictMerge) { return [target, source]; } else if ( (options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source) ) { target[source] = true; } } else { return [target, source]; } return target; } if (!target || typeof target !== 'object') { if (isOverflow(source)) { // Create new object with target at 0, source values shifted by 1 var sourceKeys = Object.keys(source); var result = options && options.plainObjects ? { __proto__: null, 0: target } : { 0: target }; for (var m = 0; m < sourceKeys.length; m++) { var oldKey = parseInt(sourceKeys[m], 10); result[oldKey + 1] = source[sourceKeys[m]]; } return markOverflow(result, getMaxIndex(source) + 1); } var combined = [target].concat(source); if (options && typeof options.arrayLimit === 'number' && combined.length > options.arrayLimit) { return markOverflow(arrayToObject(combined, options), combined.length - 1); } return combined; } var mergeTarget = target; if (isArray(target) && !isArray(source)) { mergeTarget = arrayToObject(target, options); } if (isArray(target) && isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { var targetItem = target[i]; if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { target[i] = merge(targetItem, item, options); } else { target[target.length] = item; } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = merge(acc[key], value, options); } else { acc[key] = value; } if (isOverflow(source) && !isOverflow(acc)) { markOverflow(acc, getMaxIndex(source)); } if (isOverflow(acc)) { var keyNum = parseInt(key, 10); if (String(keyNum) === key && keyNum >= 0 && keyNum > getMaxIndex(acc)) { setMaxIndex(acc, keyNum); } } return acc; }, mergeTarget); }; var assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; var decode = function (str, defaultDecoder, charset) { var strWithoutPlus = str.replace(/\+/g, ' '); if (charset === 'iso-8859-1') { // unescape never throws, no try...catch needed: return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); } // utf-8 try { return decodeURIComponent(strWithoutPlus); } catch (e) { return strWithoutPlus; } }; var limit = 1024; /* eslint operator-linebreak: [2, "before"] */ var encode = function encode(str, defaultEncoder, charset, kind, format) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = str; if (typeof str === 'symbol') { string = Symbol.prototype.toString.call(str); } else if (typeof str !== 'string') { string = String(str); } if (charset === 'iso-8859-1') { return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; }); } var out = ''; for (var j = 0; j < string.length; j += limit) { var segment = string.length >= limit ? string.slice(j, j + limit) : string; var arr = []; for (var i = 0; i < segment.length; ++i) { var c = segment.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) ) { arr[arr.length] = segment.charAt(i); continue; } if (c < 0x80) { arr[arr.length] = hexTable[c]; continue; } if (c < 0x800) { arr[arr.length] = hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]; continue; } if (c < 0xD800 || c >= 0xE000) { arr[arr.length] = hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (segment.charCodeAt(i) & 0x3FF)); arr[arr.length] = hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } out += arr.join(''); } return out; }; var compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue[queue.length] = { obj: obj, prop: key }; refs[refs.length] = val; } } } compactQueue(queue); return value; }; var isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; var isBuffer = function isBuffer(obj) { if (!obj || typeof obj !== 'object') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; var combine = function combine(a, b, arrayLimit, plainObjects) { // If 'a' is already an overflow object, add to it if (isOverflow(a)) { var newIndex = getMaxIndex(a) + 1; a[newIndex] = b; setMaxIndex(a, newIndex); return a; } var result = [].concat(a, b); if (result.length > arrayLimit) { return markOverflow(arrayToObject(result, { plainObjects: plainObjects }), result.length - 1); } return result; }; var maybeMap = function maybeMap(val, fn) { if (isArray(val)) { var mapped = []; for (var i = 0; i < val.length; i += 1) { mapped[mapped.length] = fn(val[i]); } return mapped; } return fn(val); }; module.exports = { arrayToObject: arrayToObject, assign: assign, combine: combine, compact: compact, decode: decode, encode: encode, isBuffer: isBuffer, isOverflow: isOverflow, isRegExp: isRegExp, markOverflow: markOverflow, maybeMap: maybeMap, merge: merge }; /***/ }), /***/ 8522: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(6131).Duplex /***/ }), /***/ 2063: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. /**/ var pna = __nccwpck_require__(1564); /**/ /**/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); }return keys; }; /**/ module.exports = Duplex; /**/ var util = Object.create(__nccwpck_require__(5481)); util.inherits = __nccwpck_require__(9598); /**/ var Readable = __nccwpck_require__(6893); var Writable = __nccwpck_require__(8797); util.inherits(Duplex, Readable); { // avoid scope creep, the keys array can then be collected var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._writableState.highWaterMark; } }); // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. pna.nextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { get: function () { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); Duplex.prototype._destroy = function (err, cb) { this.push(null); this.end(); pna.nextTick(cb, err); }; /***/ }), /***/ 5283: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. module.exports = PassThrough; var Transform = __nccwpck_require__(2337); /**/ var util = Object.create(__nccwpck_require__(5481)); util.inherits = __nccwpck_require__(9598); /**/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; /***/ }), /***/ 6893: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /**/ var pna = __nccwpck_require__(1564); /**/ module.exports = Readable; /**/ var isArray = __nccwpck_require__(2513); /**/ /**/ var Duplex; /**/ Readable.ReadableState = ReadableState; /**/ var EE = (__nccwpck_require__(4434).EventEmitter); var EElistenerCount = function (emitter, type) { return emitter.listeners(type).length; }; /**/ /**/ var Stream = __nccwpck_require__(3283); /**/ /**/ var Buffer = (__nccwpck_require__(3058).Buffer); var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ /**/ var util = Object.create(__nccwpck_require__(5481)); util.inherits = __nccwpck_require__(9598); /**/ /**/ var debugUtil = __nccwpck_require__(9023); var debug = void 0; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function () {}; } /**/ var BufferList = __nccwpck_require__(9381); var destroyImpl = __nccwpck_require__(5089); var StringDecoder; util.inherits(Readable, Stream); var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream) { Duplex = Duplex || __nccwpck_require__(2063); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; var readableHwm = options.readableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = (__nccwpck_require__(634)/* .StringDecoder */ .I); this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || __nccwpck_require__(2063); if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { get: function () { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { this.push(null); cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); } else if (state.ended) { stream.emit('error', new Error('stream.push() after EOF')); } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; } } return needMoreData(state); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { stream.emit('data', chunk); stream.read(0); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = (__nccwpck_require__(634)/* .StringDecoder */ .I); this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; }; // Don't raise the hwm > 8MB var MAX_HWM = 0x800000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = true; n = 0; } else { state.length -= n; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // emit 'readable' now to make sure it gets picked up. emitReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { debug('emit readable'); stream.emit('readable'); flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; pna.nextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break;else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { this.emit('error', new Error('_read() is not implemented')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } // If the user pushes more data while we're writing to dest then we'll end up // in ondata again. However, we only want to increase awaitDrain once because // dest will only emit one 'drain' event for the multiple writes. // => Introduce a guard on increasing awaitDrain. var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { debug('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', state.awaitDrain); state.awaitDrain++; increasedAwaitDrain = true; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function () { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) { dests[i].emit('unpipe', this, { hasUnpiped: false }); }return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); if (ev === 'data') { // Start flowing on next tick if stream isn't explicitly paused if (this._readableState.flowing !== false) this.resume(); } else if (ev === 'readable') { var state = this._readableState; if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { pna.nextTick(nReadingNextTick, this); } else if (state.length) { emitReadable(this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); state.flowing = true; resume(this, state); } return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; pna.nextTick(resume_, stream, state); } } function resume_(stream, state) { if (!state.reading) { debug('resume read 0'); stream.read(0); } state.resumeScheduled = false; state.awaitDrain = 0; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function (method) { return function () { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return this; }; Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._readableState.highWaterMark; } }); // exposed for testing purposes only. Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = fromListPartial(n, state.buffer, state.decoder); } return ret; } // Extracts only enough buffered data to satisfy the amount requested. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromListPartial(n, list, hasStrings) { var ret; if (n < list.head.data.length) { // slice is the same for buffers and strings ret = list.head.data.slice(0, n); list.head.data = list.head.data.slice(n); } else if (n === list.head.data.length) { // first chunk is a perfect match ret = list.shift(); } else { // result spans more than one buffer ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } return ret; } // Copies a specified amount of characters from the list of buffered data // chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBufferString(n, list) { var p = list.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = str.slice(nb); } break; } ++c; } list.length -= c; return ret; } // Copies a specified amount of bytes from the list of buffered data chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = buf.slice(nb); } break; } ++c; } list.length -= c; return ret; } function endReadable(stream) { var state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); if (!state.endEmitted) { state.ended = true; pna.nextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); } } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } /***/ }), /***/ 2337: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. module.exports = Transform; var Duplex = __nccwpck_require__(2063); /**/ var util = Object.create(__nccwpck_require__(5481)); util.inherits = __nccwpck_require__(9598); /**/ util.inherits(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) { return this.emit('error', new Error('write callback called multiple times')); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function') { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { throw new Error('_transform() is not implemented'); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { var _this2 = this; Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); _this2.emit('close'); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); return stream.push(null); } /***/ }), /***/ 8797: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. /**/ var pna = __nccwpck_require__(1564); /**/ module.exports = Writable; /* */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* */ /**/ var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; /**/ /**/ var Duplex; /**/ Writable.WritableState = WritableState; /**/ var util = Object.create(__nccwpck_require__(5481)); util.inherits = __nccwpck_require__(9598); /**/ /**/ var internalUtil = { deprecate: __nccwpck_require__(4488) }; /**/ /**/ var Stream = __nccwpck_require__(3283); /**/ /**/ var Buffer = (__nccwpck_require__(3058).Buffer); var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ var destroyImpl = __nccwpck_require__(5089); util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { Duplex = Duplex || __nccwpck_require__(2063); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. var isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; var writableHwm = options.writableHighWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function () { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function (object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function (object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || __nccwpck_require__(2063); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { return new Writable(options); } this._writableState = new WritableState(options, this); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { this.emit('error', new Error('Cannot pipe, not readable')); }; function writeAfterEnd(stream, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); pna.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var valid = true; var er = false; if (chunk === null) { er = new TypeError('May not write null values to stream'); } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { stream.emit('error', er); pna.nextTick(cb, er); valid = false; } return valid; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { var state = this._writableState; state.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); this._writableState.defaultEncoding = encoding; return this; }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function () { return this._writableState.highWaterMark; } }); // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack pna.nextTick(cb, er); // this can emit finish, and it will always happen // after error pna.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; stream.emit('error', er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; stream.emit('error', er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state); if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { /**/ asyncWrite(afterWrite, stream, state, finished, cb); /**/ } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new Error('_write() is not implemented')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending) endWritable(this, state, cb); }; function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { stream.emit('error', err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function') { state.pendingcb++; state.finalCalled = true; pna.nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } // reuse the free corkReq. state.corkedRequestsFree.next = corkReq; } Object.defineProperty(Writable.prototype, 'destroyed', { get: function () { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { this.end(); cb(err); }; /***/ }), /***/ 9381: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Buffer = (__nccwpck_require__(3058).Buffer); var util = __nccwpck_require__(9023); function copyBuffer(src, target, offset) { src.copy(target, offset); } module.exports = function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } BufferList.prototype.push = function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; }; BufferList.prototype.unshift = function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; }; BufferList.prototype.shift = function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; }; BufferList.prototype.clear = function clear() { this.head = this.tail = null; this.length = 0; }; BufferList.prototype.join = function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) { ret += s + p.data; }return ret; }; BufferList.prototype.concat = function concat(n) { if (this.length === 0) return Buffer.alloc(0); var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; }; return BufferList; }(); if (util && util.inspect && util.inspect.custom) { module.exports.prototype[util.inspect.custom] = function () { var obj = util.inspect({ length: this.length }); return this.constructor.name + ' ' + obj; }; } /***/ }), /***/ 5089: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /**/ var pna = __nccwpck_require__(1564); /**/ // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err) { if (!this._writableState) { pna.nextTick(emitErrorNT, this, err); } else if (!this._writableState.errorEmitted) { this._writableState.errorEmitted = true; pna.nextTick(emitErrorNT, this, err); } } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { if (!_this._writableState) { pna.nextTick(emitErrorNT, _this, err); } else if (!_this._writableState.errorEmitted) { _this._writableState.errorEmitted = true; pna.nextTick(emitErrorNT, _this, err); } } else if (cb) { cb(err); } }); return this; } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finalCalled = false; this._writableState.prefinished = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy }; /***/ }), /***/ 3283: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(2203); /***/ }), /***/ 6131: /***/ ((module, exports, __nccwpck_require__) => { var Stream = __nccwpck_require__(2203); if (process.env.READABLE_STREAM === 'disable' && Stream) { module.exports = Stream; exports = module.exports = Stream.Readable; exports.Readable = Stream.Readable; exports.Writable = Stream.Writable; exports.Duplex = Stream.Duplex; exports.Transform = Stream.Transform; exports.PassThrough = Stream.PassThrough; exports.Stream = Stream; } else { exports = module.exports = __nccwpck_require__(6893); exports.Stream = Stream || exports; exports.Readable = exports; exports.Writable = __nccwpck_require__(8797); exports.Duplex = __nccwpck_require__(2063); exports.Transform = __nccwpck_require__(2337); exports.PassThrough = __nccwpck_require__(5283); } /***/ }), /***/ 902: /***/ ((module) => { "use strict"; function ReInterval (callback, interval, args) { var self = this; this._callback = callback; this._args = args; this._interval = setInterval(callback, interval, this._args); this.reschedule = function (interval) { // if no interval entered, use the interval passed in on creation if (!interval) interval = self._interval; if (self._interval) clearInterval(self._interval); self._interval = setInterval(self._callback, interval, self._args); }; this.clear = function () { if (self._interval) { clearInterval(self._interval); self._interval = undefined; } }; this.destroy = function () { if (self._interval) { clearInterval(self._interval); } self._callback = undefined; self._interval = undefined; self._args = undefined; }; } function reInterval () { if (typeof arguments[0] !== 'function') throw new Error('callback needed'); if (typeof arguments[1] !== 'number') throw new Error('interval needed'); var args; if (arguments.length > 0) { args = new Array(arguments.length - 2); for (var i = 0; i < args.length; i++) { args[i] = arguments[i + 2]; } } return new ReInterval(arguments[0], arguments[1], args); } module.exports = reInterval; /***/ }), /***/ 3961: /***/ ((module) => { var isWin = process.platform === 'win32'; module.exports = function (str) { var i = str.length - 1; if (i < 2) { return str; } while (isSeparator(str, i)) { i--; } return str.substr(0, i + 1); }; function isSeparator(str, i) { var char = str[i]; return i > 0 && (char === '/' || (isWin && char === '\\')); } /***/ }), /***/ 6748: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(8825)() /***/ }), /***/ 8825: /***/ ((module) => { "use strict"; module.exports = rfdc function copyBuffer (cur) { if (cur instanceof Buffer) { return Buffer.from(cur) } return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length) } function rfdc (opts) { opts = opts || {} if (opts.circles) return rfdcCircles(opts) const constructorHandlers = new Map() constructorHandlers.set(Date, (o) => new Date(o)) constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn))) constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn))) if (opts.constructorHandlers) { for (const handler of opts.constructorHandlers) { constructorHandlers.set(handler[0], handler[1]) } } let handler = null return opts.proto ? cloneProto : clone function cloneArray (a, fn) { const keys = Object.keys(a) const a2 = new Array(keys.length) for (let i = 0; i < keys.length; i++) { const k = keys[i] const cur = a[k] if (typeof cur !== 'object' || cur === null) { a2[k] = cur } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { a2[k] = handler(cur, fn) } else if (ArrayBuffer.isView(cur)) { a2[k] = copyBuffer(cur) } else { a2[k] = fn(cur) } } return a2 } function clone (o) { if (typeof o !== 'object' || o === null) return o if (Array.isArray(o)) return cloneArray(o, clone) if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { return handler(o, clone) } const o2 = {} for (const k in o) { if (Object.hasOwnProperty.call(o, k) === false) continue const cur = o[k] if (typeof cur !== 'object' || cur === null) { o2[k] = cur } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { o2[k] = handler(cur, clone) } else if (ArrayBuffer.isView(cur)) { o2[k] = copyBuffer(cur) } else { o2[k] = clone(cur) } } return o2 } function cloneProto (o) { if (typeof o !== 'object' || o === null) return o if (Array.isArray(o)) return cloneArray(o, cloneProto) if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { return handler(o, cloneProto) } const o2 = {} for (const k in o) { const cur = o[k] if (typeof cur !== 'object' || cur === null) { o2[k] = cur } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { o2[k] = handler(cur, cloneProto) } else if (ArrayBuffer.isView(cur)) { o2[k] = copyBuffer(cur) } else { o2[k] = cloneProto(cur) } } return o2 } } function rfdcCircles (opts) { const refs = [] const refsNew = [] const constructorHandlers = new Map() constructorHandlers.set(Date, (o) => new Date(o)) constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn))) constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn))) if (opts.constructorHandlers) { for (const handler of opts.constructorHandlers) { constructorHandlers.set(handler[0], handler[1]) } } let handler = null return opts.proto ? cloneProto : clone function cloneArray (a, fn) { const keys = Object.keys(a) const a2 = new Array(keys.length) for (let i = 0; i < keys.length; i++) { const k = keys[i] const cur = a[k] if (typeof cur !== 'object' || cur === null) { a2[k] = cur } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { a2[k] = handler(cur, fn) } else if (ArrayBuffer.isView(cur)) { a2[k] = copyBuffer(cur) } else { const index = refs.indexOf(cur) if (index !== -1) { a2[k] = refsNew[index] } else { a2[k] = fn(cur) } } } return a2 } function clone (o) { if (typeof o !== 'object' || o === null) return o if (Array.isArray(o)) return cloneArray(o, clone) if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { return handler(o, clone) } const o2 = {} refs.push(o) refsNew.push(o2) for (const k in o) { if (Object.hasOwnProperty.call(o, k) === false) continue const cur = o[k] if (typeof cur !== 'object' || cur === null) { o2[k] = cur } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { o2[k] = handler(cur, clone) } else if (ArrayBuffer.isView(cur)) { o2[k] = copyBuffer(cur) } else { const i = refs.indexOf(cur) if (i !== -1) { o2[k] = refsNew[i] } else { o2[k] = clone(cur) } } } refs.pop() refsNew.pop() return o2 } function cloneProto (o) { if (typeof o !== 'object' || o === null) return o if (Array.isArray(o)) return cloneArray(o, cloneProto) if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) { return handler(o, cloneProto) } const o2 = {} refs.push(o) refsNew.push(o2) for (const k in o) { const cur = o[k] if (typeof cur !== 'object' || cur === null) { o2[k] = cur } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) { o2[k] = handler(cur, cloneProto) } else if (ArrayBuffer.isView(cur)) { o2[k] = copyBuffer(cur) } else { const i = refs.indexOf(cur) if (i !== -1) { o2[k] = refsNew[i] } else { o2[k] = cloneProto(cur) } } } refs.pop() refsNew.pop() return o2 } } /***/ }), /***/ 3058: /***/ ((module, exports, __nccwpck_require__) => { /* eslint-disable node/no-deprecated-api */ var buffer = __nccwpck_require__(181) var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } /***/ }), /***/ 6567: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var inspect = __nccwpck_require__(506); var $TypeError = __nccwpck_require__(3314); /* * This function traverses the list returning the node corresponding to the given key. * * That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. * By doing so, all the recently used nodes can be accessed relatively quickly. */ /** @type {import('./list.d.ts').listGetNode} */ // eslint-disable-next-line consistent-return var listGetNode = function (list, key, isDelete) { /** @type {typeof list | NonNullable<(typeof list)['next']>} */ var prev = list; /** @type {(typeof list)['next']} */ var curr; // eslint-disable-next-line eqeqeq for (; (curr = prev.next) != null; prev = curr) { if (curr.key === key) { prev.next = curr.next; if (!isDelete) { // eslint-disable-next-line no-extra-parens curr.next = /** @type {NonNullable} */ (list.next); list.next = curr; // eslint-disable-line no-param-reassign } return curr; } } }; /** @type {import('./list.d.ts').listGet} */ var listGet = function (objects, key) { if (!objects) { return void undefined; } var node = listGetNode(objects, key); return node && node.value; }; /** @type {import('./list.d.ts').listSet} */ var listSet = function (objects, key, value) { var node = listGetNode(objects, key); if (node) { node.value = value; } else { // Prepend the new node to the beginning of the list objects.next = /** @type {import('./list.d.ts').ListNode} */ ({ // eslint-disable-line no-param-reassign, no-extra-parens key: key, next: objects.next, value: value }); } }; /** @type {import('./list.d.ts').listHas} */ var listHas = function (objects, key) { if (!objects) { return false; } return !!listGetNode(objects, key); }; /** @type {import('./list.d.ts').listDelete} */ // eslint-disable-next-line consistent-return var listDelete = function (objects, key) { if (objects) { return listGetNode(objects, key, true); } }; /** @type {import('.')} */ module.exports = function getSideChannelList() { /** @typedef {ReturnType} Channel */ /** @typedef {Parameters[0]} K */ /** @typedef {Parameters[1]} V */ /** @type {import('./list.d.ts').RootNode | undefined} */ var $o; /** @type {Channel} */ var channel = { assert: function (key) { if (!channel.has(key)) { throw new $TypeError('Side channel does not contain ' + inspect(key)); } }, 'delete': function (key) { var deletedNode = listDelete($o, key); if (deletedNode && $o && !$o.next) { $o = void undefined; } return !!deletedNode; }, get: function (key) { return listGet($o, key); }, has: function (key) { return listHas($o, key); }, set: function (key, value) { if (!$o) { // Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head $o = { next: void undefined }; } // eslint-disable-next-line no-extra-parens listSet(/** @type {NonNullable} */ ($o), key, value); } }; return channel; }; /***/ }), /***/ 2622: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var GetIntrinsic = __nccwpck_require__(470); var callBound = __nccwpck_require__(3105); var inspect = __nccwpck_require__(506); var $TypeError = __nccwpck_require__(3314); var $Map = GetIntrinsic('%Map%', true); /** @type {(thisArg: Map, key: K) => V} */ var $mapGet = callBound('Map.prototype.get', true); /** @type {(thisArg: Map, key: K, value: V) => void} */ var $mapSet = callBound('Map.prototype.set', true); /** @type {(thisArg: Map, key: K) => boolean} */ var $mapHas = callBound('Map.prototype.has', true); /** @type {(thisArg: Map, key: K) => boolean} */ var $mapDelete = callBound('Map.prototype.delete', true); /** @type {(thisArg: Map) => number} */ var $mapSize = callBound('Map.prototype.size', true); /** @type {import('.')} */ module.exports = !!$Map && /** @type {Exclude} */ function getSideChannelMap() { /** @typedef {ReturnType} Channel */ /** @typedef {Parameters[0]} K */ /** @typedef {Parameters[1]} V */ /** @type {Map | undefined} */ var $m; /** @type {Channel} */ var channel = { assert: function (key) { if (!channel.has(key)) { throw new $TypeError('Side channel does not contain ' + inspect(key)); } }, 'delete': function (key) { if ($m) { var result = $mapDelete($m, key); if ($mapSize($m) === 0) { $m = void undefined; } return result; } return false; }, get: function (key) { // eslint-disable-line consistent-return if ($m) { return $mapGet($m, key); } }, has: function (key) { if ($m) { return $mapHas($m, key); } return false; }, set: function (key, value) { if (!$m) { // @ts-expect-error TS can't handle narrowing a variable inside a closure $m = new $Map(); } $mapSet($m, key, value); } }; // @ts-expect-error TODO: figure out why TS is erroring here return channel; }; /***/ }), /***/ 2870: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var GetIntrinsic = __nccwpck_require__(470); var callBound = __nccwpck_require__(3105); var inspect = __nccwpck_require__(506); var getSideChannelMap = __nccwpck_require__(2622); var $TypeError = __nccwpck_require__(3314); var $WeakMap = GetIntrinsic('%WeakMap%', true); /** @type {(thisArg: WeakMap, key: K) => V} */ var $weakMapGet = callBound('WeakMap.prototype.get', true); /** @type {(thisArg: WeakMap, key: K, value: V) => void} */ var $weakMapSet = callBound('WeakMap.prototype.set', true); /** @type {(thisArg: WeakMap, key: K) => boolean} */ var $weakMapHas = callBound('WeakMap.prototype.has', true); /** @type {(thisArg: WeakMap, key: K) => boolean} */ var $weakMapDelete = callBound('WeakMap.prototype.delete', true); /** @type {import('.')} */ module.exports = $WeakMap ? /** @type {Exclude} */ function getSideChannelWeakMap() { /** @typedef {ReturnType} Channel */ /** @typedef {Parameters[0]} K */ /** @typedef {Parameters[1]} V */ /** @type {WeakMap | undefined} */ var $wm; /** @type {Channel | undefined} */ var $m; /** @type {Channel} */ var channel = { assert: function (key) { if (!channel.has(key)) { throw new $TypeError('Side channel does not contain ' + inspect(key)); } }, 'delete': function (key) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapDelete($wm, key); } } else if (getSideChannelMap) { if ($m) { return $m['delete'](key); } } return false; }, get: function (key) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapGet($wm, key); } } return $m && $m.get(key); }, has: function (key) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapHas($wm, key); } } return !!$m && $m.has(key); }, set: function (key, value) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if (!$wm) { $wm = new $WeakMap(); } $weakMapSet($wm, key, value); } else if (getSideChannelMap) { if (!$m) { $m = getSideChannelMap(); } // eslint-disable-next-line no-extra-parens /** @type {NonNullable} */ ($m).set(key, value); } } }; // @ts-expect-error TODO: figure out why this is erroring return channel; } : getSideChannelMap; /***/ }), /***/ 4753: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var $TypeError = __nccwpck_require__(3314); var inspect = __nccwpck_require__(506); var getSideChannelList = __nccwpck_require__(6567); var getSideChannelMap = __nccwpck_require__(2622); var getSideChannelWeakMap = __nccwpck_require__(2870); var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList; /** @type {import('.')} */ module.exports = function getSideChannel() { /** @typedef {ReturnType} Channel */ /** @type {Channel | undefined} */ var $channelData; /** @type {Channel} */ var channel = { assert: function (key) { if (!channel.has(key)) { throw new $TypeError('Side channel does not contain ' + inspect(key)); } }, 'delete': function (key) { return !!$channelData && $channelData['delete'](key); }, get: function (key) { return $channelData && $channelData.get(key); }, has: function (key) { return !!$channelData && $channelData.has(key); }, set: function (key, value) { if (!$channelData) { $channelData = makeChannel(); } $channelData.set(key, value); } }; // @ts-expect-error TODO: figure out why this is erroring return channel; }; /***/ }), /***/ 7290: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const utils_1 = __nccwpck_require__(8632); // The default Buffer size if one is not provided. const DEFAULT_SMARTBUFFER_SIZE = 4096; // The default string encoding to use for reading/writing strings. const DEFAULT_SMARTBUFFER_ENCODING = 'utf8'; class SmartBuffer { /** * Creates a new SmartBuffer instance. * * @param options { SmartBufferOptions } The SmartBufferOptions to apply to this instance. */ constructor(options) { this.length = 0; this._encoding = DEFAULT_SMARTBUFFER_ENCODING; this._writeOffset = 0; this._readOffset = 0; if (SmartBuffer.isSmartBufferOptions(options)) { // Checks for encoding if (options.encoding) { utils_1.checkEncoding(options.encoding); this._encoding = options.encoding; } // Checks for initial size length if (options.size) { if (utils_1.isFiniteInteger(options.size) && options.size > 0) { this._buff = Buffer.allocUnsafe(options.size); } else { throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE); } // Check for initial Buffer } else if (options.buff) { if (Buffer.isBuffer(options.buff)) { this._buff = options.buff; this.length = options.buff.length; } else { throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER); } } else { this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); } } else { // If something was passed but it's not a SmartBufferOptions object if (typeof options !== 'undefined') { throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT); } // Otherwise default to sane options this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); } } /** * Creates a new SmartBuffer instance with the provided internal Buffer size and optional encoding. * * @param size { Number } The size of the internal Buffer. * @param encoding { String } The BufferEncoding to use for strings. * * @return { SmartBuffer } */ static fromSize(size, encoding) { return new this({ size: size, encoding: encoding }); } /** * Creates a new SmartBuffer instance with the provided Buffer and optional encoding. * * @param buffer { Buffer } The Buffer to use as the internal Buffer value. * @param encoding { String } The BufferEncoding to use for strings. * * @return { SmartBuffer } */ static fromBuffer(buff, encoding) { return new this({ buff: buff, encoding: encoding }); } /** * Creates a new SmartBuffer instance with the provided SmartBufferOptions options. * * @param options { SmartBufferOptions } The options to use when creating the SmartBuffer instance. */ static fromOptions(options) { return new this(options); } /** * Type checking function that determines if an object is a SmartBufferOptions object. */ static isSmartBufferOptions(options) { const castOptions = options; return (castOptions && (castOptions.encoding !== undefined || castOptions.size !== undefined || castOptions.buff !== undefined)); } // Signed integers /** * Reads an Int8 value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt8(offset) { return this._readNumberValue(Buffer.prototype.readInt8, 1, offset); } /** * Reads an Int16BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt16BE(offset) { return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset); } /** * Reads an Int16LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt16LE(offset) { return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset); } /** * Reads an Int32BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt32BE(offset) { return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset); } /** * Reads an Int32LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt32LE(offset) { return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset); } /** * Reads a BigInt64BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigInt64BE(offset) { utils_1.bigIntAndBufferInt64Check('readBigInt64BE'); return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset); } /** * Reads a BigInt64LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigInt64LE(offset) { utils_1.bigIntAndBufferInt64Check('readBigInt64LE'); return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset); } /** * Writes an Int8 value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt8(value, offset) { this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset); return this; } /** * Inserts an Int8 value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt8(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset); } /** * Writes an Int16BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt16BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); } /** * Inserts an Int16BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt16BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); } /** * Writes an Int16LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt16LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); } /** * Inserts an Int16LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt16LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); } /** * Writes an Int32BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt32BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); } /** * Inserts an Int32BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt32BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); } /** * Writes an Int32LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt32LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); } /** * Inserts an Int32LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt32LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); } /** * Writes a BigInt64BE value to the current write position (or at optional offset). * * @param value { BigInt } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); } /** * Inserts a BigInt64BE value at the given offset value. * * @param value { BigInt } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); } /** * Writes a BigInt64LE value to the current write position (or at optional offset). * * @param value { BigInt } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); } /** * Inserts a Int64LE value at the given offset value. * * @param value { BigInt } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); } // Unsigned Integers /** * Reads an UInt8 value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt8(offset) { return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset); } /** * Reads an UInt16BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt16BE(offset) { return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset); } /** * Reads an UInt16LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt16LE(offset) { return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset); } /** * Reads an UInt32BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt32BE(offset) { return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset); } /** * Reads an UInt32LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt32LE(offset) { return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset); } /** * Reads a BigUInt64BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigUInt64BE(offset) { utils_1.bigIntAndBufferInt64Check('readBigUInt64BE'); return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset); } /** * Reads a BigUInt64LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigUInt64LE(offset) { utils_1.bigIntAndBufferInt64Check('readBigUInt64LE'); return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset); } /** * Writes an UInt8 value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt8(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); } /** * Inserts an UInt8 value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt8(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); } /** * Writes an UInt16BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt16BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); } /** * Inserts an UInt16BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt16BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); } /** * Writes an UInt16LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt16LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); } /** * Inserts an UInt16LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt16LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); } /** * Writes an UInt32BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt32BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); } /** * Inserts an UInt32BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt32BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); } /** * Writes an UInt32LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt32LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); } /** * Inserts an UInt32LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt32LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); } /** * Writes a BigUInt64BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigUInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); } /** * Inserts a BigUInt64BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigUInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); } /** * Writes a BigUInt64LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigUInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); } /** * Inserts a BigUInt64LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigUInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); } // Floating Point /** * Reads an FloatBE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readFloatBE(offset) { return this._readNumberValue(Buffer.prototype.readFloatBE, 4, offset); } /** * Reads an FloatLE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readFloatLE(offset) { return this._readNumberValue(Buffer.prototype.readFloatLE, 4, offset); } /** * Writes a FloatBE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeFloatBE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset); } /** * Inserts a FloatBE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertFloatBE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset); } /** * Writes a FloatLE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeFloatLE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset); } /** * Inserts a FloatLE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertFloatLE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset); } // Double Floating Point /** * Reads an DoublEBE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readDoubleBE(offset) { return this._readNumberValue(Buffer.prototype.readDoubleBE, 8, offset); } /** * Reads an DoubleLE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readDoubleLE(offset) { return this._readNumberValue(Buffer.prototype.readDoubleLE, 8, offset); } /** * Writes a DoubleBE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeDoubleBE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset); } /** * Inserts a DoubleBE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertDoubleBE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset); } /** * Writes a DoubleLE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeDoubleLE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset); } /** * Inserts a DoubleLE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertDoubleLE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset); } // Strings /** * Reads a String from the current read position. * * @param arg1 { Number | String } The number of bytes to read as a String, or the BufferEncoding to use for * the string (Defaults to instance level encoding). * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). * * @return { String } */ readString(arg1, encoding) { let lengthVal; // Length provided if (typeof arg1 === 'number') { utils_1.checkLengthValue(arg1); lengthVal = Math.min(arg1, this.length - this._readOffset); } else { encoding = arg1; lengthVal = this.length - this._readOffset; } // Check encoding if (typeof encoding !== 'undefined') { utils_1.checkEncoding(encoding); } const value = this._buff.slice(this._readOffset, this._readOffset + lengthVal).toString(encoding || this._encoding); this._readOffset += lengthVal; return value; } /** * Inserts a String * * @param value { String } The String value to insert. * @param offset { Number } The offset to insert the string at. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ insertString(value, offset, encoding) { utils_1.checkOffsetValue(offset); return this._handleString(value, true, offset, encoding); } /** * Writes a String * * @param value { String } The String value to write. * @param arg2 { Number | String } The offset to write the string at, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ writeString(value, arg2, encoding) { return this._handleString(value, false, arg2, encoding); } /** * Reads a null-terminated String from the current read position. * * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). * * @return { String } */ readStringNT(encoding) { if (typeof encoding !== 'undefined') { utils_1.checkEncoding(encoding); } // Set null character position to the end SmartBuffer instance. let nullPos = this.length; // Find next null character (if one is not found, default from above is used) for (let i = this._readOffset; i < this.length; i++) { if (this._buff[i] === 0x00) { nullPos = i; break; } } // Read string value const value = this._buff.slice(this._readOffset, nullPos); // Increment internal Buffer read offset this._readOffset = nullPos + 1; return value.toString(encoding || this._encoding); } /** * Inserts a null-terminated String. * * @param value { String } The String value to write. * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ insertStringNT(value, offset, encoding) { utils_1.checkOffsetValue(offset); // Write Values this.insertString(value, offset, encoding); this.insertUInt8(0x00, offset + value.length); return this; } /** * Writes a null-terminated String. * * @param value { String } The String value to write. * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ writeStringNT(value, arg2, encoding) { // Write Values this.writeString(value, arg2, encoding); this.writeUInt8(0x00, typeof arg2 === 'number' ? arg2 + value.length : this.writeOffset); return this; } // Buffers /** * Reads a Buffer from the internal read position. * * @param length { Number } The length of data to read as a Buffer. * * @return { Buffer } */ readBuffer(length) { if (typeof length !== 'undefined') { utils_1.checkLengthValue(length); } const lengthVal = typeof length === 'number' ? length : this.length; const endPoint = Math.min(this.length, this._readOffset + lengthVal); // Read buffer value const value = this._buff.slice(this._readOffset, endPoint); // Increment internal Buffer read offset this._readOffset = endPoint; return value; } /** * Writes a Buffer to the current write position. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ insertBuffer(value, offset) { utils_1.checkOffsetValue(offset); return this._handleBuffer(value, true, offset); } /** * Writes a Buffer to the current write position. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ writeBuffer(value, offset) { return this._handleBuffer(value, false, offset); } /** * Reads a null-terminated Buffer from the current read poisiton. * * @return { Buffer } */ readBufferNT() { // Set null character position to the end SmartBuffer instance. let nullPos = this.length; // Find next null character (if one is not found, default from above is used) for (let i = this._readOffset; i < this.length; i++) { if (this._buff[i] === 0x00) { nullPos = i; break; } } // Read value const value = this._buff.slice(this._readOffset, nullPos); // Increment internal Buffer read offset this._readOffset = nullPos + 1; return value; } /** * Inserts a null-terminated Buffer. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ insertBufferNT(value, offset) { utils_1.checkOffsetValue(offset); // Write Values this.insertBuffer(value, offset); this.insertUInt8(0x00, offset + value.length); return this; } /** * Writes a null-terminated Buffer. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ writeBufferNT(value, offset) { // Checks for valid numberic value; if (typeof offset !== 'undefined') { utils_1.checkOffsetValue(offset); } // Write Values this.writeBuffer(value, offset); this.writeUInt8(0x00, typeof offset === 'number' ? offset + value.length : this._writeOffset); return this; } /** * Clears the SmartBuffer instance to its original empty state. */ clear() { this._writeOffset = 0; this._readOffset = 0; this.length = 0; return this; } /** * Gets the remaining data left to be read from the SmartBuffer instance. * * @return { Number } */ remaining() { return this.length - this._readOffset; } /** * Gets the current read offset value of the SmartBuffer instance. * * @return { Number } */ get readOffset() { return this._readOffset; } /** * Sets the read offset value of the SmartBuffer instance. * * @param offset { Number } - The offset value to set. */ set readOffset(offset) { utils_1.checkOffsetValue(offset); // Check for bounds. utils_1.checkTargetOffset(offset, this); this._readOffset = offset; } /** * Gets the current write offset value of the SmartBuffer instance. * * @return { Number } */ get writeOffset() { return this._writeOffset; } /** * Sets the write offset value of the SmartBuffer instance. * * @param offset { Number } - The offset value to set. */ set writeOffset(offset) { utils_1.checkOffsetValue(offset); // Check for bounds. utils_1.checkTargetOffset(offset, this); this._writeOffset = offset; } /** * Gets the currently set string encoding of the SmartBuffer instance. * * @return { BufferEncoding } The string Buffer encoding currently set. */ get encoding() { return this._encoding; } /** * Sets the string encoding of the SmartBuffer instance. * * @param encoding { BufferEncoding } The string Buffer encoding to set. */ set encoding(encoding) { utils_1.checkEncoding(encoding); this._encoding = encoding; } /** * Gets the underlying internal Buffer. (This includes unmanaged data in the Buffer) * * @return { Buffer } The Buffer value. */ get internalBuffer() { return this._buff; } /** * Gets the value of the internal managed Buffer (Includes managed data only) * * @param { Buffer } */ toBuffer() { return this._buff.slice(0, this.length); } /** * Gets the String value of the internal managed Buffer * * @param encoding { String } The BufferEncoding to display the Buffer as (defaults to instance level encoding). */ toString(encoding) { const encodingVal = typeof encoding === 'string' ? encoding : this._encoding; // Check for invalid encoding. utils_1.checkEncoding(encodingVal); return this._buff.toString(encodingVal, 0, this.length); } /** * Destroys the SmartBuffer instance. */ destroy() { this.clear(); return this; } /** * Handles inserting and writing strings. * * @param value { String } The String value to insert. * @param isInsert { Boolean } True if inserting a string, false if writing. * @param arg2 { Number | String } The offset to insert the string at, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). */ _handleString(value, isInsert, arg3, encoding) { let offsetVal = this._writeOffset; let encodingVal = this._encoding; // Check for offset if (typeof arg3 === 'number') { offsetVal = arg3; // Check for encoding } else if (typeof arg3 === 'string') { utils_1.checkEncoding(arg3); encodingVal = arg3; } // Check for encoding (third param) if (typeof encoding === 'string') { utils_1.checkEncoding(encoding); encodingVal = encoding; } // Calculate bytelength of string. const byteLength = Buffer.byteLength(value, encodingVal); // Ensure there is enough internal Buffer capacity. if (isInsert) { this.ensureInsertable(byteLength, offsetVal); } else { this._ensureWriteable(byteLength, offsetVal); } // Write value this._buff.write(value, offsetVal, byteLength, encodingVal); // Increment internal Buffer write offset; if (isInsert) { this._writeOffset += byteLength; } else { // If an offset was given, check to see if we wrote beyond the current writeOffset. if (typeof arg3 === 'number') { this._writeOffset = Math.max(this._writeOffset, offsetVal + byteLength); } else { // If no offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. this._writeOffset += byteLength; } } return this; } /** * Handles writing or insert of a Buffer. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. */ _handleBuffer(value, isInsert, offset) { const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; // Ensure there is enough internal Buffer capacity. if (isInsert) { this.ensureInsertable(value.length, offsetVal); } else { this._ensureWriteable(value.length, offsetVal); } // Write buffer value value.copy(this._buff, offsetVal); // Increment internal Buffer write offset; if (isInsert) { this._writeOffset += value.length; } else { // If an offset was given, check to see if we wrote beyond the current writeOffset. if (typeof offset === 'number') { this._writeOffset = Math.max(this._writeOffset, offsetVal + value.length); } else { // If no offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. this._writeOffset += value.length; } } return this; } /** * Ensures that the internal Buffer is large enough to read data. * * @param length { Number } The length of the data that needs to be read. * @param offset { Number } The offset of the data that needs to be read. */ ensureReadable(length, offset) { // Offset value defaults to managed read offset. let offsetVal = this._readOffset; // If an offset was provided, use it. if (typeof offset !== 'undefined') { // Checks for valid numberic value; utils_1.checkOffsetValue(offset); // Overide with custom offset. offsetVal = offset; } // Checks if offset is below zero, or the offset+length offset is beyond the total length of the managed data. if (offsetVal < 0 || offsetVal + length > this.length) { throw new Error(utils_1.ERRORS.INVALID_READ_BEYOND_BOUNDS); } } /** * Ensures that the internal Buffer is large enough to insert data. * * @param dataLength { Number } The length of the data that needs to be written. * @param offset { Number } The offset of the data to be written. */ ensureInsertable(dataLength, offset) { // Checks for valid numberic value; utils_1.checkOffsetValue(offset); // Ensure there is enough internal Buffer capacity. this._ensureCapacity(this.length + dataLength); // If an offset was provided and its not the very end of the buffer, copy data into appropriate location in regards to the offset. if (offset < this.length) { this._buff.copy(this._buff, offset + dataLength, offset, this._buff.length); } // Adjust tracked smart buffer length if (offset + dataLength > this.length) { this.length = offset + dataLength; } else { this.length += dataLength; } } /** * Ensures that the internal Buffer is large enough to write data. * * @param dataLength { Number } The length of the data that needs to be written. * @param offset { Number } The offset of the data to be written (defaults to writeOffset). */ _ensureWriteable(dataLength, offset) { const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; // Ensure enough capacity to write data. this._ensureCapacity(offsetVal + dataLength); // Adjust SmartBuffer length (if offset + length is larger than managed length, adjust length) if (offsetVal + dataLength > this.length) { this.length = offsetVal + dataLength; } } /** * Ensures that the internal Buffer is large enough to write at least the given amount of data. * * @param minLength { Number } The minimum length of the data needs to be written. */ _ensureCapacity(minLength) { const oldLength = this._buff.length; if (minLength > oldLength) { let data = this._buff; let newLength = (oldLength * 3) / 2 + 1; if (newLength < minLength) { newLength = minLength; } this._buff = Buffer.allocUnsafe(newLength); data.copy(this._buff, 0, 0, oldLength); } } /** * Reads a numeric number value using the provided function. * * @typeparam T { number | bigint } The type of the value to be read * * @param func { Function(offset: number) => number } The function to read data on the internal Buffer with. * @param byteSize { Number } The number of bytes read. * @param offset { Number } The offset to read from (optional). When this is not provided, the managed readOffset is used instead. * * @returns { T } the number value */ _readNumberValue(func, byteSize, offset) { this.ensureReadable(byteSize, offset); // Call Buffer.readXXXX(); const value = func.call(this._buff, typeof offset === 'number' ? offset : this._readOffset); // Adjust internal read offset if an optional read offset was not provided. if (typeof offset === 'undefined') { this._readOffset += byteSize; } return value; } /** * Inserts a numeric number value based on the given offset and value. * * @typeparam T { number | bigint } The type of the value to be written * * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. * @param byteSize { Number } The number of bytes written. * @param value { T } The number value to write. * @param offset { Number } the offset to write the number at (REQUIRED). * * @returns SmartBuffer this buffer */ _insertNumberValue(func, byteSize, value, offset) { // Check for invalid offset values. utils_1.checkOffsetValue(offset); // Ensure there is enough internal Buffer capacity. (raw offset is passed) this.ensureInsertable(byteSize, offset); // Call buffer.writeXXXX(); func.call(this._buff, value, offset); // Adjusts internally managed write offset. this._writeOffset += byteSize; return this; } /** * Writes a numeric number value based on the given offset and value. * * @typeparam T { number | bigint } The type of the value to be written * * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. * @param byteSize { Number } The number of bytes written. * @param value { T } The number value to write. * @param offset { Number } the offset to write the number at (REQUIRED). * * @returns SmartBuffer this buffer */ _writeNumberValue(func, byteSize, value, offset) { // If an offset was provided, validate it. if (typeof offset === 'number') { // Check if we're writing beyond the bounds of the managed data. if (offset < 0) { throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS); } utils_1.checkOffsetValue(offset); } // Default to writeOffset if no offset value was given. const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; // Ensure there is enough internal Buffer capacity. (raw offset is passed) this._ensureWriteable(byteSize, offsetVal); func.call(this._buff, value, offsetVal); // If an offset was given, check to see if we wrote beyond the current writeOffset. if (typeof offset === 'number') { this._writeOffset = Math.max(this._writeOffset, offsetVal + byteSize); } else { // If no numeric offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. this._writeOffset += byteSize; } return this; } } exports.SmartBuffer = SmartBuffer; //# sourceMappingURL=smartbuffer.js.map /***/ }), /***/ 8632: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const buffer_1 = __nccwpck_require__(181); /** * Error strings */ const ERRORS = { INVALID_ENCODING: 'Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.', INVALID_SMARTBUFFER_SIZE: 'Invalid size provided. Size must be a valid integer greater than zero.', INVALID_SMARTBUFFER_BUFFER: 'Invalid Buffer provided in SmartBufferOptions.', INVALID_SMARTBUFFER_OBJECT: 'Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.', INVALID_OFFSET: 'An invalid offset value was provided.', INVALID_OFFSET_NON_NUMBER: 'An invalid offset value was provided. A numeric value is required.', INVALID_LENGTH: 'An invalid length value was provided.', INVALID_LENGTH_NON_NUMBER: 'An invalid length value was provived. A numeric value is required.', INVALID_TARGET_OFFSET: 'Target offset is beyond the bounds of the internal SmartBuffer data.', INVALID_TARGET_LENGTH: 'Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.', INVALID_READ_BEYOND_BOUNDS: 'Attempted to read beyond the bounds of the managed data.', INVALID_WRITE_BEYOND_BOUNDS: 'Attempted to write beyond the bounds of the managed data.' }; exports.ERRORS = ERRORS; /** * Checks if a given encoding is a valid Buffer encoding. (Throws an exception if check fails) * * @param { String } encoding The encoding string to check. */ function checkEncoding(encoding) { if (!buffer_1.Buffer.isEncoding(encoding)) { throw new Error(ERRORS.INVALID_ENCODING); } } exports.checkEncoding = checkEncoding; /** * Checks if a given number is a finite integer. (Throws an exception if check fails) * * @param { Number } value The number value to check. */ function isFiniteInteger(value) { return typeof value === 'number' && isFinite(value) && isInteger(value); } exports.isFiniteInteger = isFiniteInteger; /** * Checks if an offset/length value is valid. (Throws an exception if check fails) * * @param value The value to check. * @param offset True if checking an offset, false if checking a length. */ function checkOffsetOrLengthValue(value, offset) { if (typeof value === 'number') { // Check for non finite/non integers if (!isFiniteInteger(value) || value < 0) { throw new Error(offset ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH); } } else { throw new Error(offset ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER); } } /** * Checks if a length value is valid. (Throws an exception if check fails) * * @param { Number } length The value to check. */ function checkLengthValue(length) { checkOffsetOrLengthValue(length, false); } exports.checkLengthValue = checkLengthValue; /** * Checks if a offset value is valid. (Throws an exception if check fails) * * @param { Number } offset The value to check. */ function checkOffsetValue(offset) { checkOffsetOrLengthValue(offset, true); } exports.checkOffsetValue = checkOffsetValue; /** * Checks if a target offset value is out of bounds. (Throws an exception if check fails) * * @param { Number } offset The offset value to check. * @param { SmartBuffer } buff The SmartBuffer instance to check against. */ function checkTargetOffset(offset, buff) { if (offset < 0 || offset > buff.length) { throw new Error(ERRORS.INVALID_TARGET_OFFSET); } } exports.checkTargetOffset = checkTargetOffset; /** * Determines whether a given number is a integer. * @param value The number to check. */ function isInteger(value) { return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; } /** * Throws if Node.js version is too low to support bigint */ function bigIntAndBufferInt64Check(bufferMethod) { if (typeof BigInt === 'undefined') { throw new Error('Platform does not support JS BigInt type.'); } if (typeof buffer_1.Buffer.prototype[bufferMethod] === 'undefined') { throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`); } } exports.bigIntAndBufferInt64Check = bigIntAndBufferInt64Check; //# sourceMappingURL=utils.js.map /***/ }), /***/ 7142: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __awaiter = (this && this.__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()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SocksClientError = exports.SocksClient = void 0; const events_1 = __nccwpck_require__(4434); const net = __nccwpck_require__(9278); const smart_buffer_1 = __nccwpck_require__(7290); const constants_1 = __nccwpck_require__(4223); const helpers_1 = __nccwpck_require__(639); const receivebuffer_1 = __nccwpck_require__(1129); const util_1 = __nccwpck_require__(9712); Object.defineProperty(exports, "SocksClientError", ({ enumerable: true, get: function () { return util_1.SocksClientError; } })); const ip_address_1 = __nccwpck_require__(1634); class SocksClient extends events_1.EventEmitter { constructor(options) { super(); this.options = Object.assign({}, options); // Validate SocksClientOptions (0, helpers_1.validateSocksClientOptions)(options); // Default state this.setState(constants_1.SocksClientState.Created); } /** * Creates a new SOCKS connection. * * Note: Supports callbacks and promises. Only supports the connect command. * @param options { SocksClientOptions } Options. * @param callback { Function } An optional callback function. * @returns { Promise } */ static createConnection(options, callback) { return new Promise((resolve, reject) => { // Validate SocksClientOptions try { (0, helpers_1.validateSocksClientOptions)(options, ['connect']); } catch (err) { if (typeof callback === 'function') { callback(err); // eslint-disable-next-line @typescript-eslint/no-explicit-any return resolve(err); // Resolves pending promise (prevents memory leaks). } else { return reject(err); } } const client = new SocksClient(options); client.connect(options.existing_socket); client.once('established', (info) => { client.removeAllListeners(); if (typeof callback === 'function') { callback(null, info); resolve(info); // Resolves pending promise (prevents memory leaks). } else { resolve(info); } }); // Error occurred, failed to establish connection. client.once('error', (err) => { client.removeAllListeners(); if (typeof callback === 'function') { callback(err); // eslint-disable-next-line @typescript-eslint/no-explicit-any resolve(err); // Resolves pending promise (prevents memory leaks). } else { reject(err); } }); }); } /** * Creates a new SOCKS connection chain to a destination host through 2 or more SOCKS proxies. * * Note: Supports callbacks and promises. Only supports the connect method. * Note: Implemented via createConnection() factory function. * @param options { SocksClientChainOptions } Options * @param callback { Function } An optional callback function. * @returns { Promise } */ static createConnectionChain(options, callback) { // eslint-disable-next-line no-async-promise-executor return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { // Validate SocksClientChainOptions try { (0, helpers_1.validateSocksClientChainOptions)(options); } catch (err) { if (typeof callback === 'function') { callback(err); // eslint-disable-next-line @typescript-eslint/no-explicit-any return resolve(err); // Resolves pending promise (prevents memory leaks). } else { return reject(err); } } // Shuffle proxies if (options.randomizeChain) { (0, util_1.shuffleArray)(options.proxies); } try { let sock; for (let i = 0; i < options.proxies.length; i++) { const nextProxy = options.proxies[i]; // If we've reached the last proxy in the chain, the destination is the actual destination, otherwise it's the next proxy. const nextDestination = i === options.proxies.length - 1 ? options.destination : { host: options.proxies[i + 1].host || options.proxies[i + 1].ipaddress, port: options.proxies[i + 1].port, }; // Creates the next connection in the chain. const result = yield SocksClient.createConnection({ command: 'connect', proxy: nextProxy, destination: nextDestination, existing_socket: sock, }); // If sock is undefined, assign it here. sock = sock || result.socket; } if (typeof callback === 'function') { callback(null, { socket: sock }); resolve({ socket: sock }); // Resolves pending promise (prevents memory leaks). } else { resolve({ socket: sock }); } } catch (err) { if (typeof callback === 'function') { callback(err); // eslint-disable-next-line @typescript-eslint/no-explicit-any resolve(err); // Resolves pending promise (prevents memory leaks). } else { reject(err); } } })); } /** * Creates a SOCKS UDP Frame. * @param options */ static createUDPFrame(options) { const buff = new smart_buffer_1.SmartBuffer(); buff.writeUInt16BE(0); buff.writeUInt8(options.frameNumber || 0); // IPv4/IPv6/Hostname if (net.isIPv4(options.remoteHost.host)) { buff.writeUInt8(constants_1.Socks5HostType.IPv4); buff.writeUInt32BE((0, helpers_1.ipv4ToInt32)(options.remoteHost.host)); } else if (net.isIPv6(options.remoteHost.host)) { buff.writeUInt8(constants_1.Socks5HostType.IPv6); buff.writeBuffer((0, helpers_1.ipToBuffer)(options.remoteHost.host)); } else { buff.writeUInt8(constants_1.Socks5HostType.Hostname); buff.writeUInt8(Buffer.byteLength(options.remoteHost.host)); buff.writeString(options.remoteHost.host); } // Port buff.writeUInt16BE(options.remoteHost.port); // Data buff.writeBuffer(options.data); return buff.toBuffer(); } /** * Parses a SOCKS UDP frame. * @param data */ static parseUDPFrame(data) { const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); buff.readOffset = 2; const frameNumber = buff.readUInt8(); const hostType = buff.readUInt8(); let remoteHost; if (hostType === constants_1.Socks5HostType.IPv4) { remoteHost = (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()); } else if (hostType === constants_1.Socks5HostType.IPv6) { remoteHost = ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(); } else { remoteHost = buff.readString(buff.readUInt8()); } const remotePort = buff.readUInt16BE(); return { frameNumber, remoteHost: { host: remoteHost, port: remotePort, }, data: buff.readBuffer(), }; } /** * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state. */ setState(newState) { if (this.state !== constants_1.SocksClientState.Error) { this.state = newState; } } /** * Starts the connection establishment to the proxy and destination. * @param existingSocket Connected socket to use instead of creating a new one (internal use). */ connect(existingSocket) { this.onDataReceived = (data) => this.onDataReceivedHandler(data); this.onClose = () => this.onCloseHandler(); this.onError = (err) => this.onErrorHandler(err); this.onConnect = () => this.onConnectHandler(); // Start timeout timer (defaults to 30 seconds) const timer = setTimeout(() => this.onEstablishedTimeout(), this.options.timeout || constants_1.DEFAULT_TIMEOUT); // check whether unref is available as it differs from browser to NodeJS (#33) if (timer.unref && typeof timer.unref === 'function') { timer.unref(); } // If an existing socket is provided, use it to negotiate SOCKS handshake. Otherwise create a new Socket. if (existingSocket) { this.socket = existingSocket; } else { this.socket = new net.Socket(); } // Attach Socket error handlers. this.socket.once('close', this.onClose); this.socket.once('error', this.onError); this.socket.once('connect', this.onConnect); this.socket.on('data', this.onDataReceived); this.setState(constants_1.SocksClientState.Connecting); this.receiveBuffer = new receivebuffer_1.ReceiveBuffer(); if (existingSocket) { this.socket.emit('connect'); } else { this.socket.connect(this.getSocketOptions()); if (this.options.set_tcp_nodelay !== undefined && this.options.set_tcp_nodelay !== null) { this.socket.setNoDelay(!!this.options.set_tcp_nodelay); } } // Listen for established event so we can re-emit any excess data received during handshakes. this.prependOnceListener('established', (info) => { setImmediate(() => { if (this.receiveBuffer.length > 0) { const excessData = this.receiveBuffer.get(this.receiveBuffer.length); info.socket.emit('data', excessData); } info.socket.resume(); }); }); } // Socket options (defaults host/port to options.proxy.host/options.proxy.port) getSocketOptions() { return Object.assign(Object.assign({}, this.options.socket_options), { host: this.options.proxy.host || this.options.proxy.ipaddress, port: this.options.proxy.port }); } /** * Handles internal Socks timeout callback. * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed. */ onEstablishedTimeout() { if (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.BoundWaitingForConnection) { this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut); } } /** * Handles Socket connect event. */ onConnectHandler() { this.setState(constants_1.SocksClientState.Connected); // Send initial handshake. if (this.options.proxy.type === 4) { this.sendSocks4InitialHandshake(); } else { this.sendSocks5InitialHandshake(); } this.setState(constants_1.SocksClientState.SentInitialHandshake); } /** * Handles Socket data event. * @param data */ onDataReceivedHandler(data) { /* All received data is appended to a ReceiveBuffer. This makes sure that all the data we need is received before we attempt to process it. */ this.receiveBuffer.append(data); // Process data that we have. this.processData(); } /** * Handles processing of the data we have received. */ processData() { // If we have enough data to process the next step in the SOCKS handshake, proceed. while (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.Error && this.receiveBuffer.length >= this.nextRequiredPacketBufferSize) { // Sent initial handshake, waiting for response. if (this.state === constants_1.SocksClientState.SentInitialHandshake) { if (this.options.proxy.type === 4) { // Socks v4 only has one handshake response. this.handleSocks4FinalHandshakeResponse(); } else { // Socks v5 has two handshakes, handle initial one here. this.handleInitialSocks5HandshakeResponse(); } // Sent auth request for Socks v5, waiting for response. } else if (this.state === constants_1.SocksClientState.SentAuthentication) { this.handleInitialSocks5AuthenticationHandshakeResponse(); // Sent final Socks v5 handshake, waiting for final response. } else if (this.state === constants_1.SocksClientState.SentFinalHandshake) { this.handleSocks5FinalHandshakeResponse(); // Socks BIND established. Waiting for remote connection via proxy. } else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) { if (this.options.proxy.type === 4) { this.handleSocks4IncomingConnectionResponse(); } else { this.handleSocks5IncomingConnectionResponse(); } } else { this.closeSocket(constants_1.ERRORS.InternalError); break; } } } /** * Handles Socket close event. * @param had_error */ onCloseHandler() { this.closeSocket(constants_1.ERRORS.SocketClosed); } /** * Handles Socket error event. * @param err */ onErrorHandler(err) { this.closeSocket(err.message); } /** * Removes internal event listeners on the underlying Socket. */ removeInternalSocketHandlers() { // Pauses data flow of the socket (this is internally resumed after 'established' is emitted) this.socket.pause(); this.socket.removeListener('data', this.onDataReceived); this.socket.removeListener('close', this.onClose); this.socket.removeListener('error', this.onError); this.socket.removeListener('connect', this.onConnect); } /** * Closes and destroys the underlying Socket. Emits an error event. * @param err { String } An error string to include in error event. */ closeSocket(err) { // Make sure only one 'error' event is fired for the lifetime of this SocksClient instance. if (this.state !== constants_1.SocksClientState.Error) { // Set internal state to Error. this.setState(constants_1.SocksClientState.Error); // Destroy Socket this.socket.destroy(); // Remove internal listeners this.removeInternalSocketHandlers(); // Fire 'error' event. this.emit('error', new util_1.SocksClientError(err, this.options)); } } /** * Sends initial Socks v4 handshake request. */ sendSocks4InitialHandshake() { const userId = this.options.proxy.userId || ''; const buff = new smart_buffer_1.SmartBuffer(); buff.writeUInt8(0x04); buff.writeUInt8(constants_1.SocksCommand[this.options.command]); buff.writeUInt16BE(this.options.destination.port); // Socks 4 (IPv4) if (net.isIPv4(this.options.destination.host)) { buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host)); buff.writeStringNT(userId); // Socks 4a (hostname) } else { buff.writeUInt8(0x00); buff.writeUInt8(0x00); buff.writeUInt8(0x00); buff.writeUInt8(0x01); buff.writeStringNT(userId); buff.writeStringNT(this.options.destination.host); } this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response; this.socket.write(buff.toBuffer()); } /** * Handles Socks v4 handshake response. * @param data */ handleSocks4FinalHandshakeResponse() { const data = this.receiveBuffer.get(8); if (data[1] !== constants_1.Socks4Response.Granted) { this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`); } else { // Bind response if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) { const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); buff.readOffset = 2; const remoteHost = { port: buff.readUInt16BE(), host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()), }; // If host is 0.0.0.0, set to proxy host. if (remoteHost.host === '0.0.0.0') { remoteHost.host = this.options.proxy.ipaddress; } this.setState(constants_1.SocksClientState.BoundWaitingForConnection); this.emit('bound', { remoteHost, socket: this.socket }); // Connect response } else { this.setState(constants_1.SocksClientState.Established); this.removeInternalSocketHandlers(); this.emit('established', { socket: this.socket }); } } } /** * Handles Socks v4 incoming connection request (BIND) * @param data */ handleSocks4IncomingConnectionResponse() { const data = this.receiveBuffer.get(8); if (data[1] !== constants_1.Socks4Response.Granted) { this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`); } else { const buff = smart_buffer_1.SmartBuffer.fromBuffer(data); buff.readOffset = 2; const remoteHost = { port: buff.readUInt16BE(), host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()), }; this.setState(constants_1.SocksClientState.Established); this.removeInternalSocketHandlers(); this.emit('established', { remoteHost, socket: this.socket }); } } /** * Sends initial Socks v5 handshake request. */ sendSocks5InitialHandshake() { const buff = new smart_buffer_1.SmartBuffer(); // By default we always support no auth. const supportedAuthMethods = [constants_1.Socks5Auth.NoAuth]; // We should only tell the proxy we support user/pass auth if auth info is actually provided. // Note: As of Tor v0.3.5.7+, if user/pass auth is an option from the client, by default it will always take priority. if (this.options.proxy.userId || this.options.proxy.password) { supportedAuthMethods.push(constants_1.Socks5Auth.UserPass); } // Custom auth method? if (this.options.proxy.custom_auth_method !== undefined) { supportedAuthMethods.push(this.options.proxy.custom_auth_method); } // Build handshake packet buff.writeUInt8(0x05); buff.writeUInt8(supportedAuthMethods.length); for (const authMethod of supportedAuthMethods) { buff.writeUInt8(authMethod); } this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse; this.socket.write(buff.toBuffer()); this.setState(constants_1.SocksClientState.SentInitialHandshake); } /** * Handles initial Socks v5 handshake response. * @param data */ handleInitialSocks5HandshakeResponse() { const data = this.receiveBuffer.get(2); if (data[0] !== 0x05) { this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion); } else if (data[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) { this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType); } else { // If selected Socks v5 auth method is no auth, send final handshake request. if (data[1] === constants_1.Socks5Auth.NoAuth) { this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth; this.sendSocks5CommandRequest(); // If selected Socks v5 auth method is user/password, send auth handshake. } else if (data[1] === constants_1.Socks5Auth.UserPass) { this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass; this.sendSocks5UserPassAuthentication(); // If selected Socks v5 auth method is the custom_auth_method, send custom handshake. } else if (data[1] === this.options.proxy.custom_auth_method) { this.socks5ChosenAuthType = this.options.proxy.custom_auth_method; this.sendSocks5CustomAuthentication(); } else { this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType); } } } /** * Sends Socks v5 user & password auth handshake. * * Note: No auth and user/pass are currently supported. */ sendSocks5UserPassAuthentication() { const userId = this.options.proxy.userId || ''; const password = this.options.proxy.password || ''; const buff = new smart_buffer_1.SmartBuffer(); buff.writeUInt8(0x01); buff.writeUInt8(Buffer.byteLength(userId)); buff.writeString(userId); buff.writeUInt8(Buffer.byteLength(password)); buff.writeString(password); this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse; this.socket.write(buff.toBuffer()); this.setState(constants_1.SocksClientState.SentAuthentication); } sendSocks5CustomAuthentication() { return __awaiter(this, void 0, void 0, function* () { this.nextRequiredPacketBufferSize = this.options.proxy.custom_auth_response_size; this.socket.write(yield this.options.proxy.custom_auth_request_handler()); this.setState(constants_1.SocksClientState.SentAuthentication); }); } handleSocks5CustomAuthHandshakeResponse(data) { return __awaiter(this, void 0, void 0, function* () { return yield this.options.proxy.custom_auth_response_handler(data); }); } handleSocks5AuthenticationNoAuthHandshakeResponse(data) { return __awaiter(this, void 0, void 0, function* () { return data[1] === 0x00; }); } handleSocks5AuthenticationUserPassHandshakeResponse(data) { return __awaiter(this, void 0, void 0, function* () { return data[1] === 0x00; }); } /** * Handles Socks v5 auth handshake response. * @param data */ handleInitialSocks5AuthenticationHandshakeResponse() { return __awaiter(this, void 0, void 0, function* () { this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse); let authResult = false; if (this.socks5ChosenAuthType === constants_1.Socks5Auth.NoAuth) { authResult = yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2)); } else if (this.socks5ChosenAuthType === constants_1.Socks5Auth.UserPass) { authResult = yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2)); } else if (this.socks5ChosenAuthType === this.options.proxy.custom_auth_method) { authResult = yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size)); } if (!authResult) { this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed); } else { this.sendSocks5CommandRequest(); } }); } /** * Sends Socks v5 final handshake request. */ sendSocks5CommandRequest() { const buff = new smart_buffer_1.SmartBuffer(); buff.writeUInt8(0x05); buff.writeUInt8(constants_1.SocksCommand[this.options.command]); buff.writeUInt8(0x00); // ipv4, ipv6, domain? if (net.isIPv4(this.options.destination.host)) { buff.writeUInt8(constants_1.Socks5HostType.IPv4); buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host)); } else if (net.isIPv6(this.options.destination.host)) { buff.writeUInt8(constants_1.Socks5HostType.IPv6); buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host)); } else { buff.writeUInt8(constants_1.Socks5HostType.Hostname); buff.writeUInt8(this.options.destination.host.length); buff.writeString(this.options.destination.host); } buff.writeUInt16BE(this.options.destination.port); this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; this.socket.write(buff.toBuffer()); this.setState(constants_1.SocksClientState.SentFinalHandshake); } /** * Handles Socks v5 final handshake response. * @param data */ handleSocks5FinalHandshakeResponse() { // Peek at available data (we need at least 5 bytes to get the hostname length) const header = this.receiveBuffer.peek(5); if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) { this.closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`); } else { // Read address type const addressType = header[3]; let remoteHost; let buff; // IPv4 if (addressType === constants_1.Socks5HostType.IPv4) { // Check if data is available. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; if (this.receiveBuffer.length < dataNeeded) { this.nextRequiredPacketBufferSize = dataNeeded; return; } buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); remoteHost = { host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()), port: buff.readUInt16BE(), }; // If given host is 0.0.0.0, assume remote proxy ip instead. if (remoteHost.host === '0.0.0.0') { remoteHost.host = this.options.proxy.ipaddress; } // Hostname } else if (addressType === constants_1.Socks5HostType.Hostname) { const hostLength = header[4]; const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + host + port // Check if data is available. if (this.receiveBuffer.length < dataNeeded) { this.nextRequiredPacketBufferSize = dataNeeded; return; } buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)); remoteHost = { host: buff.readString(hostLength), port: buff.readUInt16BE(), }; // IPv6 } else if (addressType === constants_1.Socks5HostType.IPv6) { // Check if data is available. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; if (this.receiveBuffer.length < dataNeeded) { this.nextRequiredPacketBufferSize = dataNeeded; return; } buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); remoteHost = { host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(), port: buff.readUInt16BE(), }; } // We have everything we need this.setState(constants_1.SocksClientState.ReceivedFinalResponse); // If using CONNECT, the client is now in the established state. if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.connect) { this.setState(constants_1.SocksClientState.Established); this.removeInternalSocketHandlers(); this.emit('established', { remoteHost, socket: this.socket }); } else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) { /* If using BIND, the Socks client is now in BoundWaitingForConnection state. This means that the remote proxy server is waiting for a remote connection to the bound port. */ this.setState(constants_1.SocksClientState.BoundWaitingForConnection); this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader; this.emit('bound', { remoteHost, socket: this.socket }); /* If using Associate, the Socks client is now Established. And the proxy server is now accepting UDP packets at the given bound port. This initial Socks TCP connection must remain open for the UDP relay to continue to work. */ } else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.associate) { this.setState(constants_1.SocksClientState.Established); this.removeInternalSocketHandlers(); this.emit('established', { remoteHost, socket: this.socket, }); } } } /** * Handles Socks v5 incoming connection request (BIND). */ handleSocks5IncomingConnectionResponse() { // Peek at available data (we need at least 5 bytes to get the hostname length) const header = this.receiveBuffer.peek(5); if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) { this.closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`); } else { // Read address type const addressType = header[3]; let remoteHost; let buff; // IPv4 if (addressType === constants_1.Socks5HostType.IPv4) { // Check if data is available. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4; if (this.receiveBuffer.length < dataNeeded) { this.nextRequiredPacketBufferSize = dataNeeded; return; } buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); remoteHost = { host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()), port: buff.readUInt16BE(), }; // If given host is 0.0.0.0, assume remote proxy ip instead. if (remoteHost.host === '0.0.0.0') { remoteHost.host = this.options.proxy.ipaddress; } // Hostname } else if (addressType === constants_1.Socks5HostType.Hostname) { const hostLength = header[4]; const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + port // Check if data is available. if (this.receiveBuffer.length < dataNeeded) { this.nextRequiredPacketBufferSize = dataNeeded; return; } buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)); remoteHost = { host: buff.readString(hostLength), port: buff.readUInt16BE(), }; // IPv6 } else if (addressType === constants_1.Socks5HostType.IPv6) { // Check if data is available. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6; if (this.receiveBuffer.length < dataNeeded) { this.nextRequiredPacketBufferSize = dataNeeded; return; } buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)); remoteHost = { host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(), port: buff.readUInt16BE(), }; } this.setState(constants_1.SocksClientState.Established); this.removeInternalSocketHandlers(); this.emit('established', { remoteHost, socket: this.socket }); } } get socksClientOptions() { return Object.assign({}, this.options); } } exports.SocksClient = SocksClient; //# sourceMappingURL=socksclient.js.map /***/ }), /***/ 4223: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SOCKS5_NO_ACCEPTABLE_AUTH = exports.SOCKS5_CUSTOM_AUTH_END = exports.SOCKS5_CUSTOM_AUTH_START = exports.SOCKS_INCOMING_PACKET_SIZES = exports.SocksClientState = exports.Socks5Response = exports.Socks5HostType = exports.Socks5Auth = exports.Socks4Response = exports.SocksCommand = exports.ERRORS = exports.DEFAULT_TIMEOUT = void 0; const DEFAULT_TIMEOUT = 30000; exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; // prettier-ignore const ERRORS = { InvalidSocksCommand: 'An invalid SOCKS command was provided. Valid options are connect, bind, and associate.', InvalidSocksCommandForOperation: 'An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.', InvalidSocksCommandChain: 'An invalid SOCKS command was provided. Chaining currently only supports the connect command.', InvalidSocksClientOptionsDestination: 'An invalid destination host was provided.', InvalidSocksClientOptionsExistingSocket: 'An invalid existing socket was provided. This should be an instance of stream.Duplex.', InvalidSocksClientOptionsProxy: 'Invalid SOCKS proxy details were provided.', InvalidSocksClientOptionsTimeout: 'An invalid timeout value was provided. Please enter a value above 0 (in ms).', InvalidSocksClientOptionsProxiesLength: 'At least two socks proxies must be provided for chaining.', InvalidSocksClientOptionsCustomAuthRange: 'Custom auth must be a value between 0x80 and 0xFE.', InvalidSocksClientOptionsCustomAuthOptions: 'When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.', NegotiationError: 'Negotiation error', SocketClosed: 'Socket closed', ProxyConnectionTimedOut: 'Proxy connection timed out', InternalError: 'SocksClient internal error (this should not happen)', InvalidSocks4HandshakeResponse: 'Received invalid Socks4 handshake response', Socks4ProxyRejectedConnection: 'Socks4 Proxy rejected connection', InvalidSocks4IncomingConnectionResponse: 'Socks4 invalid incoming connection response', Socks4ProxyRejectedIncomingBoundConnection: 'Socks4 Proxy rejected incoming bound connection', InvalidSocks5InitialHandshakeResponse: 'Received invalid Socks5 initial handshake response', InvalidSocks5IntiailHandshakeSocksVersion: 'Received invalid Socks5 initial handshake (invalid socks version)', InvalidSocks5InitialHandshakeNoAcceptedAuthType: 'Received invalid Socks5 initial handshake (no accepted authentication type)', InvalidSocks5InitialHandshakeUnknownAuthType: 'Received invalid Socks5 initial handshake (unknown authentication type)', Socks5AuthenticationFailed: 'Socks5 Authentication failed', InvalidSocks5FinalHandshake: 'Received invalid Socks5 final handshake response', InvalidSocks5FinalHandshakeRejected: 'Socks5 proxy rejected connection', InvalidSocks5IncomingConnectionResponse: 'Received invalid Socks5 incoming connection response', Socks5ProxyRejectedIncomingBoundConnection: 'Socks5 Proxy rejected incoming bound connection', }; exports.ERRORS = ERRORS; const SOCKS_INCOMING_PACKET_SIZES = { Socks5InitialHandshakeResponse: 2, Socks5UserPassAuthenticationResponse: 2, // Command response + incoming connection (bind) Socks5ResponseHeader: 5, // We need at least 5 to read the hostname length, then we wait for the address+port information. Socks5ResponseIPv4: 10, // 4 header + 4 ip + 2 port Socks5ResponseIPv6: 22, // 4 header + 16 ip + 2 port Socks5ResponseHostname: (hostNameLength) => hostNameLength + 7, // 4 header + 1 host length + host + 2 port // Command response + incoming connection (bind) Socks4Response: 8, // 2 header + 2 port + 4 ip }; exports.SOCKS_INCOMING_PACKET_SIZES = SOCKS_INCOMING_PACKET_SIZES; var SocksCommand; (function (SocksCommand) { SocksCommand[SocksCommand["connect"] = 1] = "connect"; SocksCommand[SocksCommand["bind"] = 2] = "bind"; SocksCommand[SocksCommand["associate"] = 3] = "associate"; })(SocksCommand || (exports.SocksCommand = SocksCommand = {})); var Socks4Response; (function (Socks4Response) { Socks4Response[Socks4Response["Granted"] = 90] = "Granted"; Socks4Response[Socks4Response["Failed"] = 91] = "Failed"; Socks4Response[Socks4Response["Rejected"] = 92] = "Rejected"; Socks4Response[Socks4Response["RejectedIdent"] = 93] = "RejectedIdent"; })(Socks4Response || (exports.Socks4Response = Socks4Response = {})); var Socks5Auth; (function (Socks5Auth) { Socks5Auth[Socks5Auth["NoAuth"] = 0] = "NoAuth"; Socks5Auth[Socks5Auth["GSSApi"] = 1] = "GSSApi"; Socks5Auth[Socks5Auth["UserPass"] = 2] = "UserPass"; })(Socks5Auth || (exports.Socks5Auth = Socks5Auth = {})); const SOCKS5_CUSTOM_AUTH_START = 0x80; exports.SOCKS5_CUSTOM_AUTH_START = SOCKS5_CUSTOM_AUTH_START; const SOCKS5_CUSTOM_AUTH_END = 0xfe; exports.SOCKS5_CUSTOM_AUTH_END = SOCKS5_CUSTOM_AUTH_END; const SOCKS5_NO_ACCEPTABLE_AUTH = 0xff; exports.SOCKS5_NO_ACCEPTABLE_AUTH = SOCKS5_NO_ACCEPTABLE_AUTH; var Socks5Response; (function (Socks5Response) { Socks5Response[Socks5Response["Granted"] = 0] = "Granted"; Socks5Response[Socks5Response["Failure"] = 1] = "Failure"; Socks5Response[Socks5Response["NotAllowed"] = 2] = "NotAllowed"; Socks5Response[Socks5Response["NetworkUnreachable"] = 3] = "NetworkUnreachable"; Socks5Response[Socks5Response["HostUnreachable"] = 4] = "HostUnreachable"; Socks5Response[Socks5Response["ConnectionRefused"] = 5] = "ConnectionRefused"; Socks5Response[Socks5Response["TTLExpired"] = 6] = "TTLExpired"; Socks5Response[Socks5Response["CommandNotSupported"] = 7] = "CommandNotSupported"; Socks5Response[Socks5Response["AddressNotSupported"] = 8] = "AddressNotSupported"; })(Socks5Response || (exports.Socks5Response = Socks5Response = {})); var Socks5HostType; (function (Socks5HostType) { Socks5HostType[Socks5HostType["IPv4"] = 1] = "IPv4"; Socks5HostType[Socks5HostType["Hostname"] = 3] = "Hostname"; Socks5HostType[Socks5HostType["IPv6"] = 4] = "IPv6"; })(Socks5HostType || (exports.Socks5HostType = Socks5HostType = {})); var SocksClientState; (function (SocksClientState) { SocksClientState[SocksClientState["Created"] = 0] = "Created"; SocksClientState[SocksClientState["Connecting"] = 1] = "Connecting"; SocksClientState[SocksClientState["Connected"] = 2] = "Connected"; SocksClientState[SocksClientState["SentInitialHandshake"] = 3] = "SentInitialHandshake"; SocksClientState[SocksClientState["ReceivedInitialHandshakeResponse"] = 4] = "ReceivedInitialHandshakeResponse"; SocksClientState[SocksClientState["SentAuthentication"] = 5] = "SentAuthentication"; SocksClientState[SocksClientState["ReceivedAuthenticationResponse"] = 6] = "ReceivedAuthenticationResponse"; SocksClientState[SocksClientState["SentFinalHandshake"] = 7] = "SentFinalHandshake"; SocksClientState[SocksClientState["ReceivedFinalResponse"] = 8] = "ReceivedFinalResponse"; SocksClientState[SocksClientState["BoundWaitingForConnection"] = 9] = "BoundWaitingForConnection"; SocksClientState[SocksClientState["Established"] = 10] = "Established"; SocksClientState[SocksClientState["Disconnected"] = 11] = "Disconnected"; SocksClientState[SocksClientState["Error"] = 99] = "Error"; })(SocksClientState || (exports.SocksClientState = SocksClientState = {})); //# sourceMappingURL=constants.js.map /***/ }), /***/ 639: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ipToBuffer = exports.int32ToIpv4 = exports.ipv4ToInt32 = exports.validateSocksClientChainOptions = exports.validateSocksClientOptions = void 0; const util_1 = __nccwpck_require__(9712); const constants_1 = __nccwpck_require__(4223); const stream = __nccwpck_require__(2203); const ip_address_1 = __nccwpck_require__(1634); const net = __nccwpck_require__(9278); /** * Validates the provided SocksClientOptions * @param options { SocksClientOptions } * @param acceptedCommands { string[] } A list of accepted SocksProxy commands. */ function validateSocksClientOptions(options, acceptedCommands = ['connect', 'bind', 'associate']) { // Check SOCKs command option. if (!constants_1.SocksCommand[options.command]) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommand, options); } // Check SocksCommand for acceptable command. if (acceptedCommands.indexOf(options.command) === -1) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandForOperation, options); } // Check destination if (!isValidSocksRemoteHost(options.destination)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options); } // Check SOCKS proxy to use if (!isValidSocksProxy(options.proxy)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options); } // Validate custom auth (if set) validateCustomProxyAuth(options.proxy, options); // Check timeout if (options.timeout && !isValidTimeoutValue(options.timeout)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options); } // Check existing_socket (if provided) if (options.existing_socket && !(options.existing_socket instanceof stream.Duplex)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsExistingSocket, options); } } exports.validateSocksClientOptions = validateSocksClientOptions; /** * Validates the SocksClientChainOptions * @param options { SocksClientChainOptions } */ function validateSocksClientChainOptions(options) { // Only connect is supported when chaining. if (options.command !== 'connect') { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandChain, options); } // Check destination if (!isValidSocksRemoteHost(options.destination)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options); } // Validate proxies (length) if (!(options.proxies && Array.isArray(options.proxies) && options.proxies.length >= 2)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength, options); } // Validate proxies options.proxies.forEach((proxy) => { if (!isValidSocksProxy(proxy)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options); } // Validate custom auth (if set) validateCustomProxyAuth(proxy, options); }); // Check timeout if (options.timeout && !isValidTimeoutValue(options.timeout)) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options); } } exports.validateSocksClientChainOptions = validateSocksClientChainOptions; function validateCustomProxyAuth(proxy, options) { if (proxy.custom_auth_method !== undefined) { // Invalid auth method range if (proxy.custom_auth_method < constants_1.SOCKS5_CUSTOM_AUTH_START || proxy.custom_auth_method > constants_1.SOCKS5_CUSTOM_AUTH_END) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthRange, options); } // Missing custom_auth_request_handler if (proxy.custom_auth_request_handler === undefined || typeof proxy.custom_auth_request_handler !== 'function') { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options); } // Missing custom_auth_response_size if (proxy.custom_auth_response_size === undefined) { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options); } // Missing/invalid custom_auth_response_handler if (proxy.custom_auth_response_handler === undefined || typeof proxy.custom_auth_response_handler !== 'function') { throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options); } } } /** * Validates a SocksRemoteHost * @param remoteHost { SocksRemoteHost } */ function isValidSocksRemoteHost(remoteHost) { return (remoteHost && typeof remoteHost.host === 'string' && Buffer.byteLength(remoteHost.host) < 256 && typeof remoteHost.port === 'number' && remoteHost.port >= 0 && remoteHost.port <= 65535); } /** * Validates a SocksProxy * @param proxy { SocksProxy } */ function isValidSocksProxy(proxy) { return (proxy && (typeof proxy.host === 'string' || typeof proxy.ipaddress === 'string') && typeof proxy.port === 'number' && proxy.port >= 0 && proxy.port <= 65535 && (proxy.type === 4 || proxy.type === 5)); } /** * Validates a timeout value. * @param value { Number } */ function isValidTimeoutValue(value) { return typeof value === 'number' && value > 0; } function ipv4ToInt32(ip) { const address = new ip_address_1.Address4(ip); // Convert the IPv4 address parts to an integer return address.toArray().reduce((acc, part) => (acc << 8) + part, 0) >>> 0; } exports.ipv4ToInt32 = ipv4ToInt32; function int32ToIpv4(int32) { // Extract each byte (octet) from the 32-bit integer const octet1 = (int32 >>> 24) & 0xff; const octet2 = (int32 >>> 16) & 0xff; const octet3 = (int32 >>> 8) & 0xff; const octet4 = int32 & 0xff; // Combine the octets into a string in IPv4 format return [octet1, octet2, octet3, octet4].join('.'); } exports.int32ToIpv4 = int32ToIpv4; function ipToBuffer(ip) { if (net.isIPv4(ip)) { // Handle IPv4 addresses const address = new ip_address_1.Address4(ip); return Buffer.from(address.toArray()); } else if (net.isIPv6(ip)) { // Handle IPv6 addresses const address = new ip_address_1.Address6(ip); return Buffer.from(address .canonicalForm() .split(':') .map((segment) => segment.padStart(4, '0')) .join(''), 'hex'); } else { throw new Error('Invalid IP address format'); } } exports.ipToBuffer = ipToBuffer; //# sourceMappingURL=helpers.js.map /***/ }), /***/ 1129: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReceiveBuffer = void 0; class ReceiveBuffer { constructor(size = 4096) { this.buffer = Buffer.allocUnsafe(size); this.offset = 0; this.originalSize = size; } get length() { return this.offset; } append(data) { if (!Buffer.isBuffer(data)) { throw new Error('Attempted to append a non-buffer instance to ReceiveBuffer.'); } if (this.offset + data.length >= this.buffer.length) { const tmp = this.buffer; this.buffer = Buffer.allocUnsafe(Math.max(this.buffer.length + this.originalSize, this.buffer.length + data.length)); tmp.copy(this.buffer); } data.copy(this.buffer, this.offset); return (this.offset += data.length); } peek(length) { if (length > this.offset) { throw new Error('Attempted to read beyond the bounds of the managed internal data.'); } return this.buffer.slice(0, length); } get(length) { if (length > this.offset) { throw new Error('Attempted to read beyond the bounds of the managed internal data.'); } const value = Buffer.allocUnsafe(length); this.buffer.slice(0, length).copy(value); this.buffer.copyWithin(0, length, length + this.offset - length); this.offset -= length; return value; } } exports.ReceiveBuffer = ReceiveBuffer; //# sourceMappingURL=receivebuffer.js.map /***/ }), /***/ 9712: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.shuffleArray = exports.SocksClientError = void 0; /** * Error wrapper for SocksClient */ class SocksClientError extends Error { constructor(message, options) { super(message); this.options = options; } } exports.SocksClientError = SocksClientError; /** * Shuffles a given array. * @param array The array to shuffle. */ function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } } exports.shuffleArray = shuffleArray; //# sourceMappingURL=util.js.map /***/ }), /***/ 2474: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); __exportStar(__nccwpck_require__(7142), exports); //# sourceMappingURL=index.js.map /***/ }), /***/ 4633: /***/ ((module) => { module.exports = shift function shift (stream) { var rs = stream._readableState if (!rs) return null return (rs.objectMode || typeof stream._duplexState === 'number') ? stream.read() : stream.read(getStateLength(rs)) } function getStateLength (state) { if (state.buffer.length) { var idx = state.bufferIndex || 0 // Since node 6.3.0 state.buffer is a BufferList not an array if (state.buffer.head) { return state.buffer.head.data.length } else if (state.buffer.length - idx > 0 && state.buffer[idx]) { return state.buffer[idx].length } } return state.length } /***/ }), /***/ 634: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. /**/ var Buffer = (__nccwpck_require__(3058).Buffer); /**/ var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.I = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. If an invalid byte is detected, -2 is returned. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return byte >> 6 === 0x02 ? -1 : -2; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i || nb === -2) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'; } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'; } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'; } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character is added when ending on a partial // character. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'; return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } /***/ }), /***/ 1450: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const os = __nccwpck_require__(857); const tty = __nccwpck_require__(2018); const hasFlag = __nccwpck_require__(3813); const {env} = process; let flagForceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) { flagForceColor = 0; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { flagForceColor = 1; } function envForceColor() { if ('FORCE_COLOR' in env) { if (env.FORCE_COLOR === 'true') { return 1; } if (env.FORCE_COLOR === 'false') { return 0; } return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { const noFlagForceColor = envForceColor(); if (noFlagForceColor !== undefined) { flagForceColor = noFlagForceColor; } const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; if (forceColor === 0) { return 0; } if (sniffFlags) { if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } } if (haveStream && !streamIsTTY && forceColor === undefined) { return 0; } const min = forceColor || 0; if (env.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = os.release().split('.'); if ( Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env) { const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } return min; } function getSupportLevel(stream, options = {}) { const level = supportsColor(stream, { streamIsTTY: stream && stream.isTTY, ...options }); return translateLevel(level); } module.exports = { supportsColor: getSupportLevel, stdout: getSupportLevel({isTTY: tty.isatty(1)}), stderr: getSupportLevel({isTTY: tty.isatty(2)}) }; /***/ }), /***/ 8694: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = make module.exports.ctor = ctor module.exports.objCtor = objCtor module.exports.obj = obj var through2 = __nccwpck_require__(4612) var xtend = __nccwpck_require__(869) function ctor(options, fn) { if (typeof options == "function") { fn = options options = {} } var Filter = through2.ctor(options, function (chunk, encoding, callback) { if (this.options.wantStrings) chunk = chunk.toString() try { if (fn.call(this, chunk, this._index++)) this.push(chunk) return callback() } catch (e) { return callback(e) } }) Filter.prototype._index = 0 return Filter } function objCtor(options, fn) { if (typeof options === "function") { fn = options options = {} } options = xtend({objectMode: true, highWaterMark: 16}, options) return ctor(options, fn) } function make(options, fn) { return ctor(options, fn)() } function obj(options, fn) { if (typeof options === "function") { fn = options options = {} } options = xtend({objectMode: true, highWaterMark: 16}, options) return make(options, fn) } /***/ }), /***/ 4612: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var Transform = (__nccwpck_require__(6131).Transform) , inherits = (__nccwpck_require__(9023).inherits) , xtend = __nccwpck_require__(869) function DestroyableTransform(opts) { Transform.call(this, opts) this._destroyed = false } inherits(DestroyableTransform, Transform) DestroyableTransform.prototype.destroy = function(err) { if (this._destroyed) return this._destroyed = true var self = this process.nextTick(function() { if (err) self.emit('error', err) self.emit('close') }) } // a noop _transform function function noop (chunk, enc, callback) { callback(null, chunk) } // create a new export function, used by both the main export and // the .ctor export, contains common logic for dealing with arguments function through2 (construct) { return function (options, transform, flush) { if (typeof options == 'function') { flush = transform transform = options options = {} } if (typeof transform != 'function') transform = noop if (typeof flush != 'function') flush = null return construct(options, transform, flush) } } // main export, just make me a transform stream! module.exports = through2(function (options, transform, flush) { var t2 = new DestroyableTransform(options) t2._transform = transform if (flush) t2._flush = flush return t2 }) // make me a reusable prototype that I can `new`, or implicitly `new` // with a constructor call module.exports.ctor = through2(function (options, transform, flush) { function Through2 (override) { if (!(this instanceof Through2)) return new Through2(override) this.options = xtend(options, override) DestroyableTransform.call(this, this.options) } inherits(Through2, DestroyableTransform) Through2.prototype._transform = transform if (flush) Through2.prototype._flush = flush return Through2 }) module.exports.obj = through2(function (options, transform, flush) { var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options)) t2._transform = transform if (flush) t2._flush = flush return t2 }) /***/ }), /***/ 5025: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var path = __nccwpck_require__(6928); var isNegated = __nccwpck_require__(228); var isAbsolute = __nccwpck_require__(9194); module.exports = function(glob, options) { // default options var opts = options || {}; // ensure cwd is absolute var cwd = path.resolve(opts.cwd ? opts.cwd : process.cwd()); cwd = unixify(cwd); var rootDir = opts.root; // if `options.root` is defined, ensure it's absolute if (rootDir) { rootDir = unixify(rootDir); if (process.platform === 'win32' || !isAbsolute(rootDir)) { rootDir = unixify(path.resolve(rootDir)); } } // trim starting ./ from glob patterns if (glob.slice(0, 2) === './') { glob = glob.slice(2); } // when the glob pattern is only a . use an empty string if (glob.length === 1 && glob === '.') { glob = ''; } // store last character before glob is modified var suffix = glob.slice(-1); // check to see if glob is negated (and not a leading negated-extglob) var ing = isNegated(glob); glob = ing.pattern; // make glob absolute if (rootDir && glob.charAt(0) === '/') { glob = join(rootDir, glob); } else if (!isAbsolute(glob) || glob.slice(0, 1) === '\\') { glob = join(cwd, glob); } // if glob had a trailing `/`, re-add it now in case it was removed if (suffix === '/' && glob.slice(-1) !== '/') { glob += '/'; } // re-add leading `!` if it was removed return ing.negated ? '!' + glob : glob; }; function unixify(filepath) { return filepath.replace(/\\/g, '/'); } function join(dir, glob) { if (dir.charAt(dir.length - 1) === '/') { dir = dir.slice(0, -1); } if (glob.charAt(0) === '/') { glob = glob.slice(1); } if (!glob) return dir; return dir + '/' + glob; } /***/ }), /***/ 2589: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isPrototype = __nccwpck_require__(6349); module.exports = function (value) { if (typeof value !== "function") return false; if (!hasOwnProperty.call(value, "length")) return false; try { if (typeof value.length !== "number") return false; if (typeof value.call !== "function") return false; if (typeof value.apply !== "function") return false; } catch (error) { return false; } return !isPrototype(value); }; /***/ }), /***/ 1413: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var stringCoerce = __nccwpck_require__(5427) , toShortString = __nccwpck_require__(1512); module.exports = function (errorMessage, value, inputOptions) { if (inputOptions && inputOptions.errorMessage) { errorMessage = stringCoerce(inputOptions.errorMessage); } var valueInsertIndex = errorMessage.indexOf("%v"); var valueToken = valueInsertIndex > -1 ? toShortString(value) : null; if (inputOptions && inputOptions.name) { var nameInsertIndex = errorMessage.indexOf("%n"); if (nameInsertIndex > -1) { if (valueInsertIndex > -1) { var firstToken, secondToken, firstInsertIndex, secondInsertIndex; if (nameInsertIndex > valueInsertIndex) { firstToken = valueToken; firstInsertIndex = valueInsertIndex; secondToken = inputOptions.name; secondInsertIndex = nameInsertIndex; } else { firstToken = inputOptions.name; firstInsertIndex = nameInsertIndex; secondToken = valueToken; secondInsertIndex = valueInsertIndex; } return ( errorMessage.slice(0, firstInsertIndex) + firstToken + errorMessage.slice(firstInsertIndex + 2, secondInsertIndex) + secondToken + errorMessage.slice(secondInsertIndex + 2) ); } return ( errorMessage.slice(0, nameInsertIndex) + inputOptions.name + errorMessage.slice(nameInsertIndex + 2) ); } } if (valueInsertIndex > -1) { return ( errorMessage.slice(0, valueInsertIndex) + valueToken + errorMessage.slice(valueInsertIndex + 2) ); } return errorMessage; }; /***/ }), /***/ 6704: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isValue = __nccwpck_require__(3796) , resolveErrorMessage = __nccwpck_require__(1413); module.exports = function (value, defaultMessage, inputOptions) { if (inputOptions && !isValue(value)) { if ("default" in inputOptions) return inputOptions["default"]; if (inputOptions.isOptional) return null; } var ErrorConstructor = (inputOptions && inputOptions.Error) || TypeError; var error = new ErrorConstructor(resolveErrorMessage(defaultMessage, value, inputOptions)); if (inputOptions && inputOptions.errorCode) error.code = inputOptions.errorCode; throw error; }; /***/ }), /***/ 6263: /***/ ((module) => { "use strict"; module.exports = function (value) { try { return value.toString(); } catch (error) { try { return String(value); } catch (error2) { return null; } } }; /***/ }), /***/ 1512: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var safeToString = __nccwpck_require__(6263); var reNewLine = /[\n\r\u2028\u2029]/g; module.exports = function (value) { var string = safeToString(value); if (string === null) return ""; // Trim if too long if (string.length > 100) string = string.slice(0, 99) + "…"; // Replace eventual new lines string = string.replace(reNewLine, function (char) { switch (char) { case "\n": return "\\n"; case "\r": return "\\r"; case "\u2028": return "\\u2028"; case "\u2029": return "\\u2029"; /* istanbul ignore next */ default: throw new Error("Unexpected character"); } }); return string; }; /***/ }), /***/ 5220: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isValue = __nccwpck_require__(3796); // prettier-ignore var possibleTypes = { "object": true, "function": true, "undefined": true /* document.all */ }; module.exports = function (value) { if (!isValue(value)) return false; return hasOwnProperty.call(possibleTypes, typeof value); }; /***/ }), /***/ 8650: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var resolveException = __nccwpck_require__(6704) , is = __nccwpck_require__(4031); module.exports = function (value/*, options*/) { if (is(value)) return value; var options = arguments[1]; var errorMessage = options && options.name ? "Expected a plain function for %n, received %v" : "%v is not a plain function"; return resolveException(value, errorMessage, options); }; /***/ }), /***/ 4031: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isFunction = __nccwpck_require__(2589); var classRe = /^\s*class[\s{/}]/, functionToString = Function.prototype.toString; module.exports = function (value) { if (!isFunction(value)) return false; if (classRe.test(functionToString.call(value))) return false; return true; }; /***/ }), /***/ 6349: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isObject = __nccwpck_require__(5220); module.exports = function (value) { if (!isObject(value)) return false; try { if (!value.constructor) return false; return value.constructor.prototype === value; } catch (error) { return false; } }; /***/ }), /***/ 5427: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isValue = __nccwpck_require__(3796) , isObject = __nccwpck_require__(5220); var objectToString = Object.prototype.toString; module.exports = function (value) { if (!isValue(value)) return null; if (isObject(value)) { // Reject Object.prototype.toString coercion var valueToString = value.toString; if (typeof valueToString !== "function") return null; if (valueToString === objectToString) return null; // Note: It can be object coming from other realm, still as there's no ES3 and CSP compliant // way to resolve its realm's Object.prototype.toString it's left as not addressed edge case } try { return "" + value; // Ensure implicit coercion } catch (error) { return null; } }; /***/ }), /***/ 7362: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var resolveException = __nccwpck_require__(6704) , is = __nccwpck_require__(3796); module.exports = function (value/*, options*/) { if (is(value)) return value; var options = arguments[1]; var errorMessage = options && options.name ? "Expected a value for %n, received %v" : "Cannot use %v"; return resolveException(value, errorMessage, options); }; /***/ }), /***/ 3796: /***/ ((module) => { "use strict"; // ES3 safe var _undefined = void 0; module.exports = function (value) { return value !== _undefined && value !== null; }; /***/ }), /***/ 2317: /***/ ((__unused_webpack_module, exports) => { var undefined = (void 0); // Paranoia // Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to // create, and consume so much memory, that the browser appears frozen. var MAX_ARRAY_LENGTH = 1e5; // Approximations of internal ECMAScript conversion functions var ECMAScript = (function() { // Stash a copy in case other scripts modify these var opts = Object.prototype.toString, ophop = Object.prototype.hasOwnProperty; return { // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues: Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); }, HasProperty: function(o, p) { return p in o; }, HasOwnProperty: function(o, p) { return ophop.call(o, p); }, IsCallable: function(o) { return typeof o === 'function'; }, ToInt32: function(v) { return v >> 0; }, ToUint32: function(v) { return v >>> 0; } }; }()); // Snapshot intrinsics var LN2 = Math.LN2, abs = Math.abs, floor = Math.floor, log = Math.log, min = Math.min, pow = Math.pow, round = Math.round; // ES5: lock down object properties function configureProperties(obj) { if (getOwnPropNames && defineProp) { var props = getOwnPropNames(obj), i; for (i = 0; i < props.length; i += 1) { defineProp(obj, props[i], { value: obj[props[i]], writable: false, enumerable: false, configurable: false }); } } } // emulate ES5 getter/setter API using legacy APIs // http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx // (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but // note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless) var defineProp if (Object.defineProperty && (function() { try { Object.defineProperty({}, 'x', {}); return true; } catch (e) { return false; } })()) { defineProp = Object.defineProperty; } else { defineProp = function(o, p, desc) { if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object"); if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); } if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); } if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; } return o; }; } var getOwnPropNames = Object.getOwnPropertyNames || function (o) { if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object"); var props = [], p; for (p in o) { if (ECMAScript.HasOwnProperty(o, p)) { props.push(p); } } return props; }; // ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value) // for index in 0 ... obj.length function makeArrayAccessors(obj) { if (!defineProp) { return; } if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill"); function makeArrayAccessor(index) { defineProp(obj, index, { 'get': function() { return obj._getter(index); }, 'set': function(v) { obj._setter(index, v); }, enumerable: true, configurable: false }); } var i; for (i = 0; i < obj.length; i += 1) { makeArrayAccessor(i); } } // Internal conversion functions: // pack() - take a number (interpreted as Type), output a byte array // unpack() - take a byte array, output a Type-like number function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; } function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; } function packI8(n) { return [n & 0xff]; } function unpackI8(bytes) { return as_signed(bytes[0], 8); } function packU8(n) { return [n & 0xff]; } function unpackU8(bytes) { return as_unsigned(bytes[0], 8); } function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; } function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; } function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); } function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; } function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); } function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; } function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); } function packIEEE754(v, ebits, fbits) { var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str, bytes; function roundToEven(n) { var w = floor(n), f = n - w; if (f < 0.5) return w; if (f > 0.5) return w + 1; return w % 2 ? w + 1 : w; } // Compute sign, exponent, fraction if (v !== v) { // NaN // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0; } else if (v === Infinity || v === -Infinity) { e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; } else if (v === 0) { e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; } else { s = v < 0; v = abs(v); if (v >= pow(2, 1 - bias)) { e = min(floor(log(v) / LN2), 1023); f = roundToEven(v / pow(2, e) * pow(2, fbits)); if (f / pow(2, fbits) >= 2) { e = e + 1; f = 1; } if (e > bias) { // Overflow e = (1 << ebits) - 1; f = 0; } else { // Normalized e = e + bias; f = f - pow(2, fbits); } } else { // Denormalized e = 0; f = roundToEven(v / pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); str = bits.join(''); // Bits to bytes bytes = []; while (str.length) { bytes.push(parseInt(str.substring(0, 8), 2)); str = str.substring(8); } return bytes; } function unpackIEEE754(bytes, ebits, fbits) { // Bytes to bits var bits = [], i, j, b, str, bias, s, e, f; for (i = bytes.length; i; i -= 1) { b = bytes[i - 1]; for (j = 8; j; j -= 1) { bits.push(b % 2 ? 1 : 0); b = b >> 1; } } bits.reverse(); str = bits.join(''); // Unpack sign, exponent, fraction bias = (1 << (ebits - 1)) - 1; s = parseInt(str.substring(0, 1), 2) ? -1 : 1; e = parseInt(str.substring(1, 1 + ebits), 2); f = parseInt(str.substring(1 + ebits), 2); // Produce number if (e === (1 << ebits) - 1) { return f !== 0 ? NaN : s * Infinity; } else if (e > 0) { // Normalized return s * pow(2, e - bias) * (1 + f / pow(2, fbits)); } else if (f !== 0) { // Denormalized return s * pow(2, -(bias - 1)) * (f / pow(2, fbits)); } else { return s < 0 ? -0 : 0; } } function unpackF64(b) { return unpackIEEE754(b, 11, 52); } function packF64(v) { return packIEEE754(v, 11, 52); } function unpackF32(b) { return unpackIEEE754(b, 8, 23); } function packF32(v) { return packIEEE754(v, 8, 23); } // // 3 The ArrayBuffer Type // (function() { /** @constructor */ var ArrayBuffer = function ArrayBuffer(length) { length = ECMAScript.ToInt32(length); if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer'); this.byteLength = length; this._bytes = []; this._bytes.length = length; var i; for (i = 0; i < this.byteLength; i += 1) { this._bytes[i] = 0; } configureProperties(this); }; exports.Az = exports.Az || ArrayBuffer; // // 4 The ArrayBufferView Type // // NOTE: this constructor is not exported /** @constructor */ var ArrayBufferView = function ArrayBufferView() { //this.buffer = null; //this.byteOffset = 0; //this.byteLength = 0; }; // // 5 The Typed Array View Types // function makeConstructor(bytesPerElement, pack, unpack) { // Each TypedArray type requires a distinct constructor instance with // identical logic, which this produces. var ctor; ctor = function(buffer, byteOffset, length) { var array, sequence, i, s; if (!arguments.length || typeof arguments[0] === 'number') { // Constructor(unsigned long length) this.length = ECMAScript.ToInt32(arguments[0]); if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer'); this.byteLength = this.length * this.BYTES_PER_ELEMENT; this.buffer = new ArrayBuffer(this.byteLength); this.byteOffset = 0; } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) { // Constructor(TypedArray array) array = arguments[0]; this.length = array.length; this.byteLength = this.length * this.BYTES_PER_ELEMENT; this.buffer = new ArrayBuffer(this.byteLength); this.byteOffset = 0; for (i = 0; i < this.length; i += 1) { this._setter(i, array._getter(i)); } } else if (typeof arguments[0] === 'object' && !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { // Constructor(sequence array) sequence = arguments[0]; this.length = ECMAScript.ToUint32(sequence.length); this.byteLength = this.length * this.BYTES_PER_ELEMENT; this.buffer = new ArrayBuffer(this.byteLength); this.byteOffset = 0; for (i = 0; i < this.length; i += 1) { s = sequence[i]; this._setter(i, Number(s)); } } else if (typeof arguments[0] === 'object' && (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) { // Constructor(ArrayBuffer buffer, // optional unsigned long byteOffset, optional unsigned long length) this.buffer = buffer; this.byteOffset = ECMAScript.ToUint32(byteOffset); if (this.byteOffset > this.buffer.byteLength) { throw new RangeError("byteOffset out of range"); } if (this.byteOffset % this.BYTES_PER_ELEMENT) { // The given byteOffset must be a multiple of the element // size of the specific type, otherwise an exception is raised. throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size."); } if (arguments.length < 3) { this.byteLength = this.buffer.byteLength - this.byteOffset; if (this.byteLength % this.BYTES_PER_ELEMENT) { throw new RangeError("length of buffer minus byteOffset not a multiple of the element size"); } this.length = this.byteLength / this.BYTES_PER_ELEMENT; } else { this.length = ECMAScript.ToUint32(length); this.byteLength = this.length * this.BYTES_PER_ELEMENT; } if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); } } else { throw new TypeError("Unexpected argument type(s)"); } this.constructor = ctor; configureProperties(this); makeArrayAccessors(this); }; ctor.prototype = new ArrayBufferView(); ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement; ctor.prototype._pack = pack; ctor.prototype._unpack = unpack; ctor.BYTES_PER_ELEMENT = bytesPerElement; // getter type (unsigned long index); ctor.prototype._getter = function(index) { if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); index = ECMAScript.ToUint32(index); if (index >= this.length) { return undefined; } var bytes = [], i, o; for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; i < this.BYTES_PER_ELEMENT; i += 1, o += 1) { bytes.push(this.buffer._bytes[o]); } return this._unpack(bytes); }; // NONSTANDARD: convenience alias for getter: type get(unsigned long index); ctor.prototype.get = ctor.prototype._getter; // setter void (unsigned long index, type value); ctor.prototype._setter = function(index, value) { if (arguments.length < 2) throw new SyntaxError("Not enough arguments"); index = ECMAScript.ToUint32(index); if (index >= this.length) { return undefined; } var bytes = this._pack(value), i, o; for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT; i < this.BYTES_PER_ELEMENT; i += 1, o += 1) { this.buffer._bytes[o] = bytes[i]; } }; // void set(TypedArray array, optional unsigned long offset); // void set(sequence array, optional unsigned long offset); ctor.prototype.set = function(index, value) { if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); var array, sequence, offset, len, i, s, d, byteOffset, byteLength, tmp; if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) { // void set(TypedArray array, optional unsigned long offset); array = arguments[0]; offset = ECMAScript.ToUint32(arguments[1]); if (offset + array.length > this.length) { throw new RangeError("Offset plus length of array is out of range"); } byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT; byteLength = array.length * this.BYTES_PER_ELEMENT; if (array.buffer === this.buffer) { tmp = []; for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) { tmp[i] = array.buffer._bytes[s]; } for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) { this.buffer._bytes[d] = tmp[i]; } } else { for (i = 0, s = array.byteOffset, d = byteOffset; i < byteLength; i += 1, s += 1, d += 1) { this.buffer._bytes[d] = array.buffer._bytes[s]; } } } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') { // void set(sequence array, optional unsigned long offset); sequence = arguments[0]; len = ECMAScript.ToUint32(sequence.length); offset = ECMAScript.ToUint32(arguments[1]); if (offset + len > this.length) { throw new RangeError("Offset plus length of array is out of range"); } for (i = 0; i < len; i += 1) { s = sequence[i]; this._setter(offset + i, Number(s)); } } else { throw new TypeError("Unexpected argument type(s)"); } }; // TypedArray subarray(long begin, optional long end); ctor.prototype.subarray = function(start, end) { function clamp(v, min, max) { return v < min ? min : v > max ? max : v; } start = ECMAScript.ToInt32(start); end = ECMAScript.ToInt32(end); if (arguments.length < 1) { start = 0; } if (arguments.length < 2) { end = this.length; } if (start < 0) { start = this.length + start; } if (end < 0) { end = this.length + end; } start = clamp(start, 0, this.length); end = clamp(end, 0, this.length); var len = end - start; if (len < 0) { len = 0; } return new this.constructor( this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len); }; return ctor; } var Int8Array = makeConstructor(1, packI8, unpackI8); var Uint8Array = makeConstructor(1, packU8, unpackU8); var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8); var Int16Array = makeConstructor(2, packI16, unpackI16); var Uint16Array = makeConstructor(2, packU16, unpackU16); var Int32Array = makeConstructor(4, packI32, unpackI32); var Uint32Array = makeConstructor(4, packU32, unpackU32); var Float32Array = makeConstructor(4, packF32, unpackF32); var Float64Array = makeConstructor(8, packF64, unpackF64); exports.fo = exports.fo || Int8Array; exports.SE = exports.SE || Uint8Array; exports.ER = exports.ER || Uint8ClampedArray; exports.ss = exports.ss || Int16Array; exports.hR = exports.hR || Uint16Array; exports.GM = exports.GM || Int32Array; exports.bt = exports.bt || Uint32Array; exports.l6 = exports.l6 || Float32Array; exports.aQ = exports.aQ || Float64Array; }()); // // 6 The DataView View Type // (function() { function r(array, index) { return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index]; } var IS_BIG_ENDIAN = (function() { var u16array = new(exports.hR)([0x1234]), u8array = new(exports.SE)(u16array.buffer); return r(u8array, 0) === 0x12; }()); // Constructor(ArrayBuffer buffer, // optional unsigned long byteOffset, // optional unsigned long byteLength) /** @constructor */ var DataView = function DataView(buffer, byteOffset, byteLength) { if (arguments.length === 0) { buffer = new exports.Az(0); } else if (!(buffer instanceof exports.Az || ECMAScript.Class(buffer) === 'ArrayBuffer')) { throw new TypeError("TypeError"); } this.buffer = buffer || new exports.Az(0); this.byteOffset = ECMAScript.ToUint32(byteOffset); if (this.byteOffset > this.buffer.byteLength) { throw new RangeError("byteOffset out of range"); } if (arguments.length < 3) { this.byteLength = this.buffer.byteLength - this.byteOffset; } else { this.byteLength = ECMAScript.ToUint32(byteLength); } if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) { throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); } configureProperties(this); }; function makeGetter(arrayType) { return function(byteOffset, littleEndian) { byteOffset = ECMAScript.ToUint32(byteOffset); if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { throw new RangeError("Array index out of range"); } byteOffset += this.byteOffset; var uint8Array = new exports.SE(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT), bytes = [], i; for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { bytes.push(r(uint8Array, i)); } if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { bytes.reverse(); } return r(new arrayType(new exports.SE(bytes).buffer), 0); }; } DataView.prototype.getUint8 = makeGetter(exports.SE); DataView.prototype.getInt8 = makeGetter(exports.fo); DataView.prototype.getUint16 = makeGetter(exports.hR); DataView.prototype.getInt16 = makeGetter(exports.ss); DataView.prototype.getUint32 = makeGetter(exports.bt); DataView.prototype.getInt32 = makeGetter(exports.GM); DataView.prototype.getFloat32 = makeGetter(exports.l6); DataView.prototype.getFloat64 = makeGetter(exports.aQ); function makeSetter(arrayType) { return function(byteOffset, value, littleEndian) { byteOffset = ECMAScript.ToUint32(byteOffset); if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) { throw new RangeError("Array index out of range"); } // Get bytes var typeArray = new arrayType([value]), byteArray = new exports.SE(typeArray.buffer), bytes = [], i, byteView; for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) { bytes.push(r(byteArray, i)); } // Flip if necessary if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { bytes.reverse(); } // Write them byteView = new exports.SE(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT); byteView.set(bytes); }; } DataView.prototype.setUint8 = makeSetter(exports.SE); DataView.prototype.setInt8 = makeSetter(exports.fo); DataView.prototype.setUint16 = makeSetter(exports.hR); DataView.prototype.setInt16 = makeSetter(exports.ss); DataView.prototype.setUint32 = makeSetter(exports.bt); DataView.prototype.setInt32 = makeSetter(exports.GM); DataView.prototype.setFloat32 = makeSetter(exports.l6); DataView.prototype.setFloat64 = makeSetter(exports.aQ); exports.U$ = exports.U$ || DataView; }()); /***/ }), /***/ 1958: /***/ ((module) => { "use strict"; module.exports = function uncPathRegex() { return /^[\\\/]{2,}[^\\\/]+[\\\/]+[^\\\/]+/; }; /***/ }), /***/ 3966: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var filter = (__nccwpck_require__(8694).obj); var stringify = __nccwpck_require__(4202); var ES6Set; if (typeof global.Set === 'function') { ES6Set = global.Set; } else { ES6Set = function() { this.keys = []; this.has = function(val) { return this.keys.indexOf(val) !== -1; }, this.add = function(val) { this.keys.push(val); } } } function prop(propName) { return function (data) { return data[propName]; }; } module.exports = unique; function unique(propName, keyStore) { keyStore = keyStore || new ES6Set(); var keyfn = stringify; if (typeof propName === 'string') { keyfn = prop(propName); } else if (typeof propName === 'function') { keyfn = propName; } return filter(function (data) { var key = keyfn(data); if (keyStore.has(key)) { return false; } keyStore.add(key); return true; }); } /***/ }), /***/ 4488: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** * For Node.js, simply re-export the core `util.deprecate` function. */ module.exports = __nccwpck_require__(9023).deprecate; /***/ }), /***/ 6302: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var server = __nccwpck_require__(6875) module.exports = __nccwpck_require__(6444) module.exports.Server = server.Server module.exports.createServer = server.createServer /***/ }), /***/ 5534: /***/ ((module) => { "use strict"; const codes = {}; function createErrorType(code, message, Base) { if (!Base) { Base = Error } function getMessage (arg1, arg2, arg3) { if (typeof message === 'string') { return message } else { return message(arg1, arg2, arg3) } } class NodeError extends Base { constructor (arg1, arg2, arg3) { super(getMessage(arg1, arg2, arg3)); } } NodeError.prototype.name = Base.name; NodeError.prototype.code = code; codes[code] = NodeError; } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js function oneOf(expected, thing) { if (Array.isArray(expected)) { const len = expected.length; expected = expected.map((i) => String(i)); if (len > 2) { return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + expected[len - 1]; } else if (len === 2) { return `one of ${thing} ${expected[0]} or ${expected[1]}`; } else { return `of ${thing} ${expected[0]}`; } } else { return `of ${thing} ${String(expected)}`; } } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith function startsWith(str, search, pos) { return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith function endsWith(str, search, this_len) { if (this_len === undefined || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes function includes(str, search, start) { if (typeof start !== 'number') { start = 0; } if (start + search.length > str.length) { return false; } else { return str.indexOf(search, start) !== -1; } } createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { return 'The value "' + value + '" is invalid for option "' + name + '"' }, TypeError); createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { // determiner: 'must be' or 'must not be' let determiner; if (typeof expected === 'string' && startsWith(expected, 'not ')) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } let msg; if (endsWith(name, ' argument')) { // For cases like 'first argument' msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; } else { const type = includes(name, '.') ? 'property' : 'argument'; msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; } msg += `. Received type ${typeof actual}`; return msg; }, TypeError); createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { return 'The ' + name + ' method is not implemented' }); createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); createErrorType('ERR_STREAM_DESTROYED', function (name) { return 'Cannot call ' + name + ' after a stream was destroyed'; }); createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { return 'Unknown encoding: ' + arg }, TypeError); createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); module.exports.F = codes; /***/ }), /***/ 9373: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. /**/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) keys.push(key); return keys; }; /**/ module.exports = Duplex; var Readable = __nccwpck_require__(211); var Writable = __nccwpck_require__(8487); __nccwpck_require__(9598)(Duplex, Readable); { // Allow the keys array to be GC'ed. var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); this.allowHalfOpen = true; if (options) { if (options.readable === false) this.readable = false; if (options.writable === false) this.writable = false; if (options.allowHalfOpen === false) { this.allowHalfOpen = false; this.once('end', onend); } } } Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.highWaterMark; } }); Object.defineProperty(Duplex.prototype, 'writableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState && this._writableState.getBuffer(); } }); Object.defineProperty(Duplex.prototype, 'writableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.length; } }); // the no-half-open enforcer function onend() { // If the writable side ended, then we're ok. if (this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. process.nextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); /***/ }), /***/ 5849: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. module.exports = PassThrough; var Transform = __nccwpck_require__(3747); __nccwpck_require__(9598)(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; /***/ }), /***/ 211: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. module.exports = Readable; /**/ var Duplex; /**/ Readable.ReadableState = ReadableState; /**/ var EE = (__nccwpck_require__(4434).EventEmitter); var EElistenerCount = function EElistenerCount(emitter, type) { return emitter.listeners(type).length; }; /**/ /**/ var Stream = __nccwpck_require__(2669); /**/ var Buffer = (__nccwpck_require__(181).Buffer); var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ var debugUtil = __nccwpck_require__(9023); var debug; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function debug() {}; } /**/ var BufferList = __nccwpck_require__(1534); var destroyImpl = __nccwpck_require__(8419); var _require = __nccwpck_require__(204), getHighWaterMark = _require.getHighWaterMark; var _require$codes = (__nccwpck_require__(5534)/* .codes */ .F), ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. var StringDecoder; var createReadableStreamAsyncIterator; var from; __nccwpck_require__(9598)(Readable, Stream); var errorOrDestroy = destroyImpl.errorOrDestroy; var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } function ReadableState(options, stream, isDuplex) { Duplex = Duplex || __nccwpck_require__(9373); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream. // These options can be provided separately as readableXXX and writableXXX. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; this.paused = true; // Should close be emitted on destroy. Defaults to true. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') this.autoDestroy = !!options.autoDestroy; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = (__nccwpck_require__(634)/* .StringDecoder */ .I); this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || __nccwpck_require__(9373); if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside // the ReadableState constructor, at least with V8 6.5 var isDuplex = this instanceof Duplex; this._readableState = new ReadableState(options, this, isDuplex); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { debug('readableAddChunk', chunk); var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { errorOrDestroy(stream, er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); } else if (state.ended) { errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); } else if (state.destroyed) { return false; } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; maybeReadMore(stream, state); } } // We can push more data if we are below the highWaterMark. // Also, if we have no data yet, we can stand some more bytes. // This is to work around cases where hwm=0, such as the repl. return !state.ended && (state.length < state.highWaterMark || state.length === 0); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { state.awaitDrain = 0; stream.emit('data', chunk); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); } return er; } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = (__nccwpck_require__(634)/* .StringDecoder */ .I); var decoder = new StringDecoder(enc); this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: var p = this._readableState.buffer.head; var content = ''; while (p !== null) { content += decoder.write(p.data); p = p.next; } this._readableState.buffer.clear(); if (content !== '') this._readableState.buffer.push(content); this._readableState.length = content.length; return this; }; // Don't raise the hwm > 1GB var MAX_HWM = 0x40000000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = state.length <= state.highWaterMark; n = 0; } else { state.length -= n; state.awaitDrain = 0; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { debug('onEofChunk'); if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; if (state.sync) { // if we are sync, wait until next tick to emit the data. // Otherwise we risk emitting data in the flow() // the readable code triggers during a read() call emitReadable(stream); } else { // emit 'readable' now to make sure it gets picked up. state.needReadable = false; if (!state.emittedReadable) { state.emittedReadable = true; emitReadable_(stream); } } } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; debug('emitReadable', state.needReadable, state.emittedReadable); state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; process.nextTick(emitReadable_, stream); } } function emitReadable_(stream) { var state = stream._readableState; debug('emitReadable_', state.destroyed, state.length, state.ended); if (!state.destroyed && (state.length || state.ended)) { stream.emit('readable'); state.emittedReadable = false; } // The stream needs another readable event if // 1. It is not flowing, as the flow mechanism will take // care of it. // 2. It is not ended. // 3. It is below the highWaterMark, so we can schedule // another readable later. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; process.nextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { // Attempt to read more data if we should. // // The conditions for reading more data are (one of): // - Not enough data buffered (state.length < state.highWaterMark). The loop // is responsible for filling the buffer with enough data if such data // is available. If highWaterMark is 0 and we are not in the flowing mode // we should _not_ attempt to buffer any extra data. We'll get more data // when the stream consumer calls read() instead. // - No data in the buffer, and the stream is in flowing mode. In this mode // the loop below is responsible for ensuring read() is called. Failing to // call read here would abort the flow and there's no other mechanism for // continuing the flow if the stream consumer has just subscribed to the // 'data' event. // // In addition to the above conditions to keep reading data, the following // conditions prevent the data from being read: // - The stream has ended (state.ended). // - There is already a pending 'read' operation (state.reading). This is a // case where the the stream has called the implementation defined _read() // method, but they are processing the call asynchronously and have _not_ // called push() with new data. In this case we skip performing more // read()s. The execution ends in this method again after the _read() ends // up calling push() with more data. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { var len = state.length; debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } src.on('data', ondata); function ondata(chunk) { debug('ondata'); var ret = dest.write(chunk); debug('dest.write', ret); if (ret === false) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', state.awaitDrain); state.awaitDrain++; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function pipeOnDrainFunctionResult() { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { hasUnpiped: false }); return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); var state = this._readableState; if (ev === 'data') { // update readableListening so that resume() may be a no-op // a few lines down. This is needed to support once('readable'). state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused if (state.flowing !== false) this.resume(); } else if (ev === 'readable') { if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.flowing = false; state.emittedReadable = false; debug('on readable', state.length, state.reading); if (state.length) { emitReadable(this); } else if (!state.reading) { process.nextTick(nReadingNextTick, this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; Readable.prototype.removeListener = function (ev, fn) { var res = Stream.prototype.removeListener.call(this, ev, fn); if (ev === 'readable') { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen // after readable has been emitted but before I/O (nextTick) to // support once('readable', fn) cycles. This means that calling // resume within the same tick will have no // effect. process.nextTick(updateReadableListening, this); } return res; }; Readable.prototype.removeAllListeners = function (ev) { var res = Stream.prototype.removeAllListeners.apply(this, arguments); if (ev === 'readable' || ev === undefined) { // We need to check if there is someone still listening to // readable and reset the state. However this needs to happen // after readable has been emitted but before I/O (nextTick) to // support once('readable', fn) cycles. This means that calling // resume within the same tick will have no // effect. process.nextTick(updateReadableListening, this); } return res; }; function updateReadableListening(self) { var state = self._readableState; state.readableListening = self.listenerCount('readable') > 0; if (state.resumeScheduled && !state.paused) { // flowing needs to be set to true now, otherwise // the upcoming resume will not flow. state.flowing = true; // crude way to check if we should resume } else if (self.listenerCount('data') > 0) { self.resume(); } } function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); // we flow only if there is no one listening // for readable, but we still have to call // resume() state.flowing = !state.readableListening; resume(this, state); } state.paused = false; return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; process.nextTick(resume_, stream, state); } } function resume_(stream, state) { debug('resume', state.reading); if (!state.reading) { stream.read(0); } state.resumeScheduled = false; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (this._readableState.flowing !== false) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } this._readableState.paused = true; return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null); } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var _this = this; var state = this._readableState; var paused = false; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) _this.push(chunk); } _this.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = _this.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function methodWrap(method) { return function methodWrapReturnFunction() { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. this._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return this; }; if (typeof Symbol === 'function') { Readable.prototype[Symbol.asyncIterator] = function () { if (createReadableStreamAsyncIterator === undefined) { createReadableStreamAsyncIterator = __nccwpck_require__(3826); } return createReadableStreamAsyncIterator(this); }; } Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._readableState.highWaterMark; } }); Object.defineProperty(Readable.prototype, 'readableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._readableState && this._readableState.buffer; } }); Object.defineProperty(Readable.prototype, 'readableFlowing', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._readableState.flowing; }, set: function set(state) { if (this._readableState) { this._readableState.flowing = state; } } }); // exposed for testing purposes only. Readable._fromList = fromList; Object.defineProperty(Readable.prototype, 'readableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._readableState.length; } }); // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = state.buffer.consume(n, state.decoder); } return ret; } function endReadable(stream) { var state = stream._readableState; debug('endReadable', state.endEmitted); if (!state.endEmitted) { state.ended = true; process.nextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); if (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the writable side is ready for autoDestroy as well var wState = stream._writableState; if (!wState || wState.autoDestroy && wState.finished) { stream.destroy(); } } } } if (typeof Symbol === 'function') { Readable.from = function (iterable, opts) { if (from === undefined) { from = __nccwpck_require__(9889); } return from(Readable, iterable, opts); }; } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } /***/ }), /***/ 3747: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. module.exports = Transform; var _require$codes = (__nccwpck_require__(5534)/* .codes */ .F), ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; var Duplex = __nccwpck_require__(9373); __nccwpck_require__(9598)(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (cb === null) { return this.emit('error', new ERR_MULTIPLE_CALLBACK()); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function' && !this._readableState.destroyed) { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // TODO(BridgeAR): Write a test for these two error cases // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); return stream.push(null); } /***/ }), /***/ 8487: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. module.exports = Writable; /* */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* */ /**/ var Duplex; /**/ Writable.WritableState = WritableState; /**/ var internalUtil = { deprecate: __nccwpck_require__(4488) }; /**/ /**/ var Stream = __nccwpck_require__(2669); /**/ var Buffer = (__nccwpck_require__(181).Buffer); var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } var destroyImpl = __nccwpck_require__(8419); var _require = __nccwpck_require__(204), getHighWaterMark = _require.getHighWaterMark; var _require$codes = (__nccwpck_require__(5534)/* .codes */ .F), ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; var errorOrDestroy = destroyImpl.errorOrDestroy; __nccwpck_require__(9598)(Writable, Stream); function nop() {} function WritableState(options, stream, isDuplex) { Duplex = Duplex || __nccwpck_require__(9373); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream, // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') this.autoDestroy = !!options.autoDestroy; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function writableStateBufferGetter() { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function value(object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function realHasInstance(object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || __nccwpck_require__(9373); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. // Checking for a Stream.Duplex instance is faster here instead of inside // the WritableState constructor, at least with V8 6.5 var isDuplex = this instanceof Duplex; if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); this._writableState = new WritableState(options, this, isDuplex); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); }; function writeAfterEnd(stream, cb) { var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb errorOrDestroy(stream, er); process.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var er; if (chunk === null) { er = new ERR_STREAM_NULL_VALUES(); } else if (typeof chunk !== 'string' && !state.objectMode) { er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); } if (er) { errorOrDestroy(stream, er); process.nextTick(cb, er); return false; } return true; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { this._writableState.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); this._writableState.defaultEncoding = encoding; return this; }; Object.defineProperty(Writable.prototype, 'writableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState && this._writableState.getBuffer(); } }); function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.highWaterMark; } }); // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack process.nextTick(cb, er); // this can emit finish, and it will always happen // after error process.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; errorOrDestroy(stream, er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; errorOrDestroy(stream, er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state) || stream.destroyed; if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { process.nextTick(afterWrite, stream, state, finished, cb); } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending) endWritable(this, state, cb); return this; }; Object.defineProperty(Writable.prototype, 'writableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.length; } }); function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { errorOrDestroy(stream, err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function' && !state.destroyed) { state.pendingcb++; state.finalCalled = true; process.nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); if (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the readable side is ready for autoDestroy as well var rState = stream._readableState; if (!rState || rState.autoDestroy && rState.endEmitted) { stream.destroy(); } } } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) process.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } // reuse the free corkReq. state.corkedRequestsFree.next = corkReq; } Object.defineProperty(Writable.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { cb(err); }; /***/ }), /***/ 3826: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var _Object$setPrototypeO; 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 _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } 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); } var finished = __nccwpck_require__(9737); var kLastResolve = Symbol('lastResolve'); var kLastReject = Symbol('lastReject'); var kError = Symbol('error'); var kEnded = Symbol('ended'); var kLastPromise = Symbol('lastPromise'); var kHandlePromise = Symbol('handlePromise'); var kStream = Symbol('stream'); function createIterResult(value, done) { return { value: value, done: done }; } function readAndResolve(iter) { var resolve = iter[kLastResolve]; if (resolve !== null) { var data = iter[kStream].read(); // we defer if data is null // we can be expecting either 'end' or // 'error' if (data !== null) { iter[kLastPromise] = null; iter[kLastResolve] = null; iter[kLastReject] = null; resolve(createIterResult(data, false)); } } } function onReadable(iter) { // we wait for the next tick, because it might // emit an error with process.nextTick process.nextTick(readAndResolve, iter); } function wrapForNext(lastPromise, iter) { return function (resolve, reject) { lastPromise.then(function () { if (iter[kEnded]) { resolve(createIterResult(undefined, true)); return; } iter[kHandlePromise](resolve, reject); }, reject); }; } var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { get stream() { return this[kStream]; }, next: function next() { var _this = this; // if we have detected an error in the meanwhile // reject straight away var error = this[kError]; if (error !== null) { return Promise.reject(error); } if (this[kEnded]) { return Promise.resolve(createIterResult(undefined, true)); } if (this[kStream].destroyed) { // We need to defer via nextTick because if .destroy(err) is // called, the error will be emitted via nextTick, and // we cannot guarantee that there is no error lingering around // waiting to be emitted. return new Promise(function (resolve, reject) { process.nextTick(function () { if (_this[kError]) { reject(_this[kError]); } else { resolve(createIterResult(undefined, true)); } }); }); } // if we have multiple next() calls // we will wait for the previous Promise to finish // this logic is optimized to support for await loops, // where next() is only called once at a time var lastPromise = this[kLastPromise]; var promise; if (lastPromise) { promise = new Promise(wrapForNext(lastPromise, this)); } else { // fast path needed to support multiple this.push() // without triggering the next() queue var data = this[kStream].read(); if (data !== null) { return Promise.resolve(createIterResult(data, false)); } promise = new Promise(this[kHandlePromise]); } this[kLastPromise] = promise; return promise; } }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { return this; }), _defineProperty(_Object$setPrototypeO, "return", function _return() { var _this2 = this; // destroy(err, cb) is a private API // we can guarantee we have that here, because we control the // Readable class this is attached to return new Promise(function (resolve, reject) { _this2[kStream].destroy(null, function (err) { if (err) { reject(err); return; } resolve(createIterResult(undefined, true)); }); }); }), _Object$setPrototypeO), AsyncIteratorPrototype); var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { var _Object$create; var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { value: stream, writable: true }), _defineProperty(_Object$create, kLastResolve, { value: null, writable: true }), _defineProperty(_Object$create, kLastReject, { value: null, writable: true }), _defineProperty(_Object$create, kError, { value: null, writable: true }), _defineProperty(_Object$create, kEnded, { value: stream._readableState.endEmitted, writable: true }), _defineProperty(_Object$create, kHandlePromise, { value: function value(resolve, reject) { var data = iterator[kStream].read(); if (data) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; resolve(createIterResult(data, false)); } else { iterator[kLastResolve] = resolve; iterator[kLastReject] = reject; } }, writable: true }), _Object$create)); iterator[kLastPromise] = null; finished(stream, function (err) { if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise // returned by next() and store the error if (reject !== null) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; reject(err); } iterator[kError] = err; return; } var resolve = iterator[kLastResolve]; if (resolve !== null) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; resolve(createIterResult(undefined, true)); } iterator[kEnded] = true; }); stream.on('readable', onReadable.bind(null, iterator)); return iterator; }; module.exports = createReadableStreamAsyncIterator; /***/ }), /***/ 1534: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "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 _objectSpread(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 _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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } 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); } var _require = __nccwpck_require__(181), Buffer = _require.Buffer; var _require2 = __nccwpck_require__(9023), inspect = _require2.inspect; var custom = inspect && inspect.custom || 'inspect'; function copyBuffer(src, target, offset) { Buffer.prototype.copy.call(src, target, offset); } module.exports = /*#__PURE__*/function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } _createClass(BufferList, [{ key: "push", value: function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; } }, { key: "unshift", value: function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; } }, { key: "shift", value: function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; } }, { key: "clear", value: function clear() { this.head = this.tail = null; this.length = 0; } }, { key: "join", value: function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) ret += s + p.data; return ret; } }, { key: "concat", value: function concat(n) { if (this.length === 0) return Buffer.alloc(0); var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; } // Consumes a specified amount of bytes or characters from the buffered data. }, { key: "consume", value: function consume(n, hasStrings) { var ret; if (n < this.head.data.length) { // `slice` is the same for buffers and strings. ret = this.head.data.slice(0, n); this.head.data = this.head.data.slice(n); } else if (n === this.head.data.length) { // First chunk is a perfect match. ret = this.shift(); } else { // Result spans more than one buffer. ret = hasStrings ? this._getString(n) : this._getBuffer(n); } return ret; } }, { key: "first", value: function first() { return this.head.data; } // Consumes a specified amount of characters from the buffered data. }, { key: "_getString", value: function _getString(n) { var p = this.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) this.head = p.next;else this.head = this.tail = null; } else { this.head = p; p.data = str.slice(nb); } break; } ++c; } this.length -= c; return ret; } // Consumes a specified amount of bytes from the buffered data. }, { key: "_getBuffer", value: function _getBuffer(n) { var ret = Buffer.allocUnsafe(n); var p = this.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) this.head = p.next;else this.head = this.tail = null; } else { this.head = p; p.data = buf.slice(nb); } break; } ++c; } this.length -= c; return ret; } // Make sure the linked list only shows the minimal necessary information. }, { key: custom, value: function value(_, options) { return inspect(this, _objectSpread(_objectSpread({}, options), {}, { // Only inspect one level. depth: 0, // It should not recurse. customInspect: false })); } }]); return BufferList; }(); /***/ }), /***/ 8419: /***/ ((module) => { "use strict"; // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err) { if (!this._writableState) { process.nextTick(emitErrorNT, this, err); } else if (!this._writableState.errorEmitted) { this._writableState.errorEmitted = true; process.nextTick(emitErrorNT, this, err); } } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { if (!_this._writableState) { process.nextTick(emitErrorAndCloseNT, _this, err); } else if (!_this._writableState.errorEmitted) { _this._writableState.errorEmitted = true; process.nextTick(emitErrorAndCloseNT, _this, err); } else { process.nextTick(emitCloseNT, _this); } } else if (cb) { process.nextTick(emitCloseNT, _this); cb(err); } else { process.nextTick(emitCloseNT, _this); } }); return this; } function emitErrorAndCloseNT(self, err) { emitErrorNT(self, err); emitCloseNT(self); } function emitCloseNT(self) { if (self._writableState && !self._writableState.emitClose) return; if (self._readableState && !self._readableState.emitClose) return; self.emit('close'); } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finalCalled = false; this._writableState.prefinished = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } function errorOrDestroy(stream, err) { // We have tests that rely on errors being emitted // in the same tick, so changing this is semver major. // For now when you opt-in to autoDestroy we allow // the error to be emitted nextTick. In a future // semver major update we should change the default to this. var rState = stream._readableState; var wState = stream._writableState; if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy, errorOrDestroy: errorOrDestroy }; /***/ }), /***/ 9737: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Ported from https://github.com/mafintosh/end-of-stream with // permission from the author, Mathias Buus (@mafintosh). var ERR_STREAM_PREMATURE_CLOSE = (__nccwpck_require__(5534)/* .codes */ .F).ERR_STREAM_PREMATURE_CLOSE; function once(callback) { var called = false; return function () { if (called) return; called = true; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } callback.apply(this, args); }; } function noop() {} function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; } function eos(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var readable = opts.readable || opts.readable !== false && stream.readable; var writable = opts.writable || opts.writable !== false && stream.writable; var onlegacyfinish = function onlegacyfinish() { if (!stream.writable) onfinish(); }; var writableEnded = stream._writableState && stream._writableState.finished; var onfinish = function onfinish() { writable = false; writableEnded = true; if (!readable) callback.call(stream); }; var readableEnded = stream._readableState && stream._readableState.endEmitted; var onend = function onend() { readable = false; readableEnded = true; if (!writable) callback.call(stream); }; var onerror = function onerror(err) { callback.call(stream, err); }; var onclose = function onclose() { var err; if (readable && !readableEnded) { if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); return callback.call(stream, err); } if (writable && !writableEnded) { if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); return callback.call(stream, err); } }; var onrequest = function onrequest() { stream.req.on('finish', onfinish); }; if (isRequest(stream)) { stream.on('complete', onfinish); stream.on('abort', onclose); if (stream.req) onrequest();else stream.on('request', onrequest); } else if (writable && !stream._writableState) { // legacy streams stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', onerror); stream.on('close', onclose); return function () { stream.removeListener('complete', onfinish); stream.removeListener('abort', onclose); stream.removeListener('request', onrequest); if (stream.req) stream.req.removeListener('finish', onfinish); stream.removeListener('end', onlegacyfinish); stream.removeListener('close', onlegacyfinish); stream.removeListener('finish', onfinish); stream.removeListener('end', onend); stream.removeListener('error', onerror); stream.removeListener('close', onclose); }; } module.exports = eos; /***/ }), /***/ 9889: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; 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 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 _objectSpread(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 _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 _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } 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); } var ERR_INVALID_ARG_TYPE = (__nccwpck_require__(5534)/* .codes */ .F).ERR_INVALID_ARG_TYPE; function from(Readable, iterable, opts) { var iterator; if (iterable && typeof iterable.next === 'function') { iterator = iterable; } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); var readable = new Readable(_objectSpread({ objectMode: true }, opts)); // Reading boolean to protect against _read // being called before last iteration completion. var reading = false; readable._read = function () { if (!reading) { reading = true; next(); } }; function next() { return _next2.apply(this, arguments); } function _next2() { _next2 = _asyncToGenerator(function* () { try { var _yield$iterator$next = yield iterator.next(), value = _yield$iterator$next.value, done = _yield$iterator$next.done; if (done) { readable.push(null); } else if (readable.push(yield value)) { next(); } else { reading = false; } } catch (err) { readable.destroy(err); } }); return _next2.apply(this, arguments); } return readable; } module.exports = from; /***/ }), /***/ 4651: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Ported from https://github.com/mafintosh/pump with // permission from the author, Mathias Buus (@mafintosh). var eos; function once(callback) { var called = false; return function () { if (called) return; called = true; callback.apply(void 0, arguments); }; } var _require$codes = (__nccwpck_require__(5534)/* .codes */ .F), ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; function noop(err) { // Rethrow the error if it exists to avoid swallowing it if (err) throw err; } function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; } function destroyer(stream, reading, writing, callback) { callback = once(callback); var closed = false; stream.on('close', function () { closed = true; }); if (eos === undefined) eos = __nccwpck_require__(9737); eos(stream, { readable: reading, writable: writing }, function (err) { if (err) return callback(err); closed = true; callback(); }); var destroyed = false; return function (err) { if (closed) return; if (destroyed) return; destroyed = true; // request.destroy just do .end - .abort is what we want if (isRequest(stream)) return stream.abort(); if (typeof stream.destroy === 'function') return stream.destroy(); callback(err || new ERR_STREAM_DESTROYED('pipe')); }; } function call(fn) { fn(); } function pipe(from, to) { return from.pipe(to); } function popCallback(streams) { if (!streams.length) return noop; if (typeof streams[streams.length - 1] !== 'function') return noop; return streams.pop(); } function pipeline() { for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { streams[_key] = arguments[_key]; } var callback = popCallback(streams); if (Array.isArray(streams[0])) streams = streams[0]; if (streams.length < 2) { throw new ERR_MISSING_ARGS('streams'); } var error; var destroys = streams.map(function (stream, i) { var reading = i < streams.length - 1; var writing = i > 0; return destroyer(stream, reading, writing, function (err) { if (!error) error = err; if (err) destroys.forEach(call); if (reading) return; destroys.forEach(call); callback(error); }); }); return streams.reduce(pipe); } module.exports = pipeline; /***/ }), /***/ 204: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var ERR_INVALID_OPT_VALUE = (__nccwpck_require__(5534)/* .codes */ .F).ERR_INVALID_OPT_VALUE; function highWaterMarkFrom(options, isDuplex, duplexKey) { return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } function getHighWaterMark(state, options, duplexKey, isDuplex) { var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); if (hwm != null) { if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { var name = isDuplex ? duplexKey : 'highWaterMark'; throw new ERR_INVALID_OPT_VALUE(name, hwm); } return Math.floor(hwm); } // Default value return state.objectMode ? 16 : 16 * 1024; } module.exports = { getHighWaterMark: getHighWaterMark }; /***/ }), /***/ 2669: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(2203); /***/ }), /***/ 5713: /***/ ((module, exports, __nccwpck_require__) => { var Stream = __nccwpck_require__(2203); if (process.env.READABLE_STREAM === 'disable' && Stream) { module.exports = Stream.Readable; Object.assign(module.exports, Stream); module.exports.Stream = Stream; } else { exports = module.exports = __nccwpck_require__(211); exports.Stream = Stream || exports; exports.Readable = exports; exports.Writable = __nccwpck_require__(8487); exports.Duplex = __nccwpck_require__(9373); exports.Transform = __nccwpck_require__(3747); exports.PassThrough = __nccwpck_require__(5849); exports.finished = __nccwpck_require__(9737); exports.pipeline = __nccwpck_require__(4651); } /***/ }), /***/ 5476: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const WebSocket = __nccwpck_require__(1855); WebSocket.Server = __nccwpck_require__(9419); WebSocket.Receiver = __nccwpck_require__(9692); WebSocket.Sender = __nccwpck_require__(4779); module.exports = WebSocket; /***/ }), /***/ 9161: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { EMPTY_BUFFER } = __nccwpck_require__(101); /** * Merges an array of buffers into a new buffer. * * @param {Buffer[]} list The array of buffers to concat * @param {Number} totalLength The total length of buffers in the list * @return {Buffer} The resulting buffer * @public */ function concat(list, totalLength) { if (list.length === 0) return EMPTY_BUFFER; if (list.length === 1) return list[0]; const target = Buffer.allocUnsafe(totalLength); var offset = 0; for (var i = 0; i < list.length; i++) { const buf = list[i]; buf.copy(target, offset); offset += buf.length; } return target; } /** * Masks a buffer using the given mask. * * @param {Buffer} source The buffer to mask * @param {Buffer} mask The mask to use * @param {Buffer} output The buffer where to store the result * @param {Number} offset The offset at which to start writing * @param {Number} length The number of bytes to mask. * @public */ function _mask(source, mask, output, offset, length) { for (var i = 0; i < length; i++) { output[offset + i] = source[i] ^ mask[i & 3]; } } /** * Unmasks a buffer using the given mask. * * @param {Buffer} buffer The buffer to unmask * @param {Buffer} mask The mask to use * @public */ function _unmask(buffer, mask) { // Required until https://github.com/nodejs/node/issues/9006 is resolved. const length = buffer.length; for (var i = 0; i < length; i++) { buffer[i] ^= mask[i & 3]; } } /** * Converts a buffer to an `ArrayBuffer`. * * @param {Buffer} buf The buffer to convert * @return {ArrayBuffer} Converted buffer * @public */ function toArrayBuffer(buf) { if (buf.byteLength === buf.buffer.byteLength) { return buf.buffer; } return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); } /** * Converts `data` to a `Buffer`. * * @param {*} data The data to convert * @return {Buffer} The buffer * @throws {TypeError} * @public */ function toBuffer(data) { toBuffer.readOnly = true; if (Buffer.isBuffer(data)) return data; var buf; if (data instanceof ArrayBuffer) { buf = Buffer.from(data); } else if (ArrayBuffer.isView(data)) { buf = viewToBuffer(data); } else { buf = Buffer.from(data); toBuffer.readOnly = false; } return buf; } /** * Converts an `ArrayBuffer` view into a buffer. * * @param {(DataView|TypedArray)} view The view to convert * @return {Buffer} Converted view * @private */ function viewToBuffer(view) { const buf = Buffer.from(view.buffer); if (view.byteLength !== view.buffer.byteLength) { return buf.slice(view.byteOffset, view.byteOffset + view.byteLength); } return buf; } try { const bufferUtil = __nccwpck_require__(8327); const bu = bufferUtil.BufferUtil || bufferUtil; module.exports = { concat, mask(source, mask, output, offset, length) { if (length < 48) _mask(source, mask, output, offset, length); else bu.mask(source, mask, output, offset, length); }, toArrayBuffer, toBuffer, unmask(buffer, mask) { if (buffer.length < 32) _unmask(buffer, mask); else bu.unmask(buffer, mask); } }; } catch (e) /* istanbul ignore next */ { module.exports = { concat, mask: _mask, toArrayBuffer, toBuffer, unmask: _unmask }; } /***/ }), /***/ 101: /***/ ((module) => { "use strict"; module.exports = { BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', kStatusCode: Symbol('status-code'), kWebSocket: Symbol('websocket'), EMPTY_BUFFER: Buffer.alloc(0), NOOP: () => {} }; /***/ }), /***/ 8948: /***/ ((module) => { "use strict"; /** * Class representing an event. * * @private */ class Event { /** * Create a new `Event`. * * @param {String} type The name of the event * @param {Object} target A reference to the target to which the event was dispatched */ constructor(type, target) { this.target = target; this.type = type; } } /** * Class representing a message event. * * @extends Event * @private */ class MessageEvent extends Event { /** * Create a new `MessageEvent`. * * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data * @param {WebSocket} target A reference to the target to which the event was dispatched */ constructor(data, target) { super('message', target); this.data = data; } } /** * Class representing a close event. * * @extends Event * @private */ class CloseEvent extends Event { /** * Create a new `CloseEvent`. * * @param {Number} code The status code explaining why the connection is being closed * @param {String} reason A human-readable string explaining why the connection is closing * @param {WebSocket} target A reference to the target to which the event was dispatched */ constructor(code, reason, target) { super('close', target); this.wasClean = target._closeFrameReceived && target._closeFrameSent; this.reason = reason; this.code = code; } } /** * Class representing an open event. * * @extends Event * @private */ class OpenEvent extends Event { /** * Create a new `OpenEvent`. * * @param {WebSocket} target A reference to the target to which the event was dispatched */ constructor(target) { super('open', target); } } /** * Class representing an error event. * * @extends Event * @private */ class ErrorEvent extends Event { /** * Create a new `ErrorEvent`. * * @param {Object} error The error that generated this event * @param {WebSocket} target A reference to the target to which the event was dispatched */ constructor(error, target) { super('error', target); this.message = error.message; this.error = error; } } /** * This provides methods for emulating the `EventTarget` interface. It's not * meant to be used directly. * * @mixin */ const EventTarget = { /** * Register an event listener. * * @param {String} method A string representing the event type to listen for * @param {Function} listener The listener to add * @public */ addEventListener(method, listener) { if (typeof listener !== 'function') return; function onMessage(data) { listener.call(this, new MessageEvent(data, this)); } function onClose(code, message) { listener.call(this, new CloseEvent(code, message, this)); } function onError(error) { listener.call(this, new ErrorEvent(error, this)); } function onOpen() { listener.call(this, new OpenEvent(this)); } if (method === 'message') { onMessage._listener = listener; this.on(method, onMessage); } else if (method === 'close') { onClose._listener = listener; this.on(method, onClose); } else if (method === 'error') { onError._listener = listener; this.on(method, onError); } else if (method === 'open') { onOpen._listener = listener; this.on(method, onOpen); } else { this.on(method, listener); } }, /** * Remove an event listener. * * @param {String} method A string representing the event type to remove * @param {Function} listener The listener to remove * @public */ removeEventListener(method, listener) { const listeners = this.listeners(method); for (var i = 0; i < listeners.length; i++) { if (listeners[i] === listener || listeners[i]._listener === listener) { this.removeListener(method, listeners[i]); } } } }; module.exports = EventTarget; /***/ }), /***/ 1621: /***/ ((module) => { "use strict"; // // Allowed token characters: // // '!', '#', '$', '%', '&', ''', '*', '+', '-', // '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' // // tokenChars[32] === 0 // ' ' // tokenChars[33] === 1 // '!' // tokenChars[34] === 0 // '"' // ... // // prettier-ignore const tokenChars = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 ]; /** * Adds an offer to the map of extension offers or a parameter to the map of * parameters. * * @param {Object} dest The map of extension offers or parameters * @param {String} name The extension or parameter name * @param {(Object|Boolean|String)} elem The extension parameters or the * parameter value * @private */ function push(dest, name, elem) { if (Object.prototype.hasOwnProperty.call(dest, name)) dest[name].push(elem); else dest[name] = [elem]; } /** * Parses the `Sec-WebSocket-Extensions` header into an object. * * @param {String} header The field value of the header * @return {Object} The parsed object * @public */ function parse(header) { const offers = {}; if (header === undefined || header === '') return offers; var params = {}; var mustUnescape = false; var isEscaping = false; var inQuotes = false; var extensionName; var paramName; var start = -1; var end = -1; for (var i = 0; i < header.length; i++) { const code = header.charCodeAt(i); if (extensionName === undefined) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 0x20 /* ' ' */ || code === 0x09 /* '\t' */) { if (end === -1 && start !== -1) end = i; } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; const name = header.slice(start, end); if (code === 0x2c) { push(offers, name, params); params = {}; } else { extensionName = name; } start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else if (paramName === undefined) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 0x20 || code === 0x09) { if (end === -1 && start !== -1) end = i; } else if (code === 0x3b || code === 0x2c) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; push(params, header.slice(start, end), true); if (code === 0x2c) { push(offers, extensionName, params); params = {}; extensionName = undefined; } start = end = -1; } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { paramName = header.slice(start, i); start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else { // // The value of a quoted-string after unescaping must conform to the // token ABNF, so only token characters are valid. // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 // if (isEscaping) { if (tokenChars[code] !== 1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (start === -1) start = i; else if (!mustUnescape) mustUnescape = true; isEscaping = false; } else if (inQuotes) { if (tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 0x22 /* '"' */ && start !== -1) { inQuotes = false; end = i; } else if (code === 0x5c /* '\' */) { isEscaping = true; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { inQuotes = true; } else if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (start !== -1 && (code === 0x20 || code === 0x09)) { if (end === -1) end = i; } else if (code === 0x3b || code === 0x2c) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; var value = header.slice(start, end); if (mustUnescape) { value = value.replace(/\\/g, ''); mustUnescape = false; } push(params, paramName, value); if (code === 0x2c) { push(offers, extensionName, params); params = {}; extensionName = undefined; } paramName = undefined; start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } } if (start === -1 || inQuotes) { throw new SyntaxError('Unexpected end of input'); } if (end === -1) end = i; const token = header.slice(start, end); if (extensionName === undefined) { push(offers, token, {}); } else { if (paramName === undefined) { push(params, token, true); } else if (mustUnescape) { push(params, paramName, token.replace(/\\/g, '')); } else { push(params, paramName, token); } push(offers, extensionName, params); } return offers; } /** * Builds the `Sec-WebSocket-Extensions` header field value. * * @param {Object} extensions The map of extensions and parameters to format * @return {String} A string representing the given object * @public */ function format(extensions) { return Object.keys(extensions) .map((extension) => { var configurations = extensions[extension]; if (!Array.isArray(configurations)) configurations = [configurations]; return configurations .map((params) => { return [extension] .concat( Object.keys(params).map((k) => { var values = params[k]; if (!Array.isArray(values)) values = [values]; return values .map((v) => (v === true ? k : `${k}=${v}`)) .join('; '); }) ) .join('; '); }) .join(', '); }) .join(', '); } module.exports = { format, parse }; /***/ }), /***/ 1974: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Limiter = __nccwpck_require__(2693); const zlib = __nccwpck_require__(3106); const bufferUtil = __nccwpck_require__(9161); const { kStatusCode, NOOP } = __nccwpck_require__(101); const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); const EMPTY_BLOCK = Buffer.from([0x00]); const kPerMessageDeflate = Symbol('permessage-deflate'); const kTotalLength = Symbol('total-length'); const kCallback = Symbol('callback'); const kBuffers = Symbol('buffers'); const kError = Symbol('error'); // // We limit zlib concurrency, which prevents severe memory fragmentation // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 // and https://github.com/websockets/ws/issues/1202 // // Intentionally global; it's the global thread pool that's an issue. // let zlibLimiter; /** * permessage-deflate implementation. */ class PerMessageDeflate { /** * Creates a PerMessageDeflate instance. * * @param {Object} options Configuration options * @param {Boolean} options.serverNoContextTakeover Request/accept disabling * of server context takeover * @param {Boolean} options.clientNoContextTakeover Advertise/acknowledge * disabling of client context takeover * @param {(Boolean|Number)} options.serverMaxWindowBits Request/confirm the * use of a custom server window size * @param {(Boolean|Number)} options.clientMaxWindowBits Advertise support * for, or request, a custom client window size * @param {Object} options.zlibDeflateOptions Options to pass to zlib on deflate * @param {Object} options.zlibInflateOptions Options to pass to zlib on inflate * @param {Number} options.threshold Size (in bytes) below which messages * should not be compressed * @param {Number} options.concurrencyLimit The number of concurrent calls to * zlib * @param {Boolean} isServer Create the instance in either server or client * mode * @param {Number} maxPayload The maximum allowed message length */ constructor(options, isServer, maxPayload) { this._maxPayload = maxPayload | 0; this._options = options || {}; this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024; this._isServer = !!isServer; this._deflate = null; this._inflate = null; this.params = null; if (!zlibLimiter) { const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10; zlibLimiter = new Limiter({ concurrency }); } } /** * @type {String} */ static get extensionName() { return 'permessage-deflate'; } /** * Create an extension negotiation offer. * * @return {Object} Extension parameters * @public */ offer() { const params = {}; if (this._options.serverNoContextTakeover) { params.server_no_context_takeover = true; } if (this._options.clientNoContextTakeover) { params.client_no_context_takeover = true; } if (this._options.serverMaxWindowBits) { params.server_max_window_bits = this._options.serverMaxWindowBits; } if (this._options.clientMaxWindowBits) { params.client_max_window_bits = this._options.clientMaxWindowBits; } else if (this._options.clientMaxWindowBits == null) { params.client_max_window_bits = true; } return params; } /** * Accept an extension negotiation offer/response. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Object} Accepted configuration * @public */ accept(configurations) { configurations = this.normalizeParams(configurations); this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); return this.params; } /** * Releases all resources used by the extension. * * @public */ cleanup() { if (this._inflate) { this._inflate.close(); this._inflate = null; } if (this._deflate) { this._deflate.close(); this._deflate = null; } } /** * Accept an extension negotiation offer. * * @param {Array} offers The extension negotiation offers * @return {Object} Accepted configuration * @private */ acceptAsServer(offers) { const opts = this._options; const accepted = offers.find((params) => { if ( (opts.serverNoContextTakeover === false && params.server_no_context_takeover) || (params.server_max_window_bits && (opts.serverMaxWindowBits === false || (typeof opts.serverMaxWindowBits === 'number' && opts.serverMaxWindowBits > params.server_max_window_bits))) || (typeof opts.clientMaxWindowBits === 'number' && !params.client_max_window_bits) ) { return false; } return true; }); if (!accepted) { throw new Error('None of the extension offers can be accepted'); } if (opts.serverNoContextTakeover) { accepted.server_no_context_takeover = true; } if (opts.clientNoContextTakeover) { accepted.client_no_context_takeover = true; } if (typeof opts.serverMaxWindowBits === 'number') { accepted.server_max_window_bits = opts.serverMaxWindowBits; } if (typeof opts.clientMaxWindowBits === 'number') { accepted.client_max_window_bits = opts.clientMaxWindowBits; } else if ( accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false ) { delete accepted.client_max_window_bits; } return accepted; } /** * Accept the extension negotiation response. * * @param {Array} response The extension negotiation response * @return {Object} Accepted configuration * @private */ acceptAsClient(response) { const params = response[0]; if ( this._options.clientNoContextTakeover === false && params.client_no_context_takeover ) { throw new Error('Unexpected parameter "client_no_context_takeover"'); } if (!params.client_max_window_bits) { if (typeof this._options.clientMaxWindowBits === 'number') { params.client_max_window_bits = this._options.clientMaxWindowBits; } } else if ( this._options.clientMaxWindowBits === false || (typeof this._options.clientMaxWindowBits === 'number' && params.client_max_window_bits > this._options.clientMaxWindowBits) ) { throw new Error( 'Unexpected or invalid parameter "client_max_window_bits"' ); } return params; } /** * Normalize parameters. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Array} The offers/response with normalized parameters * @private */ normalizeParams(configurations) { configurations.forEach((params) => { Object.keys(params).forEach((key) => { var value = params[key]; if (value.length > 1) { throw new Error(`Parameter "${key}" must have only a single value`); } value = value[0]; if (key === 'client_max_window_bits') { if (value !== true) { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if (!this._isServer) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else if (key === 'server_max_window_bits') { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if ( key === 'client_no_context_takeover' || key === 'server_no_context_takeover' ) { if (value !== true) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else { throw new Error(`Unknown parameter "${key}"`); } params[key] = value; }); }); return configurations; } /** * Decompress data. Concurrency limited by async-limiter. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ decompress(data, fin, callback) { zlibLimiter.push((done) => { this._decompress(data, fin, (err, result) => { done(); callback(err, result); }); }); } /** * Compress data. Concurrency limited by async-limiter. * * @param {Buffer} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ compress(data, fin, callback) { zlibLimiter.push((done) => { this._compress(data, fin, (err, result) => { done(); callback(err, result); }); }); } /** * Decompress data. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _decompress(data, fin, callback) { const endpoint = this._isServer ? 'client' : 'server'; if (!this._inflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== 'number' ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; this._inflate = zlib.createInflateRaw( Object.assign({}, this._options.zlibInflateOptions, { windowBits }) ); this._inflate[kPerMessageDeflate] = this; this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; this._inflate.on('error', inflateOnError); this._inflate.on('data', inflateOnData); } this._inflate[kCallback] = callback; this._inflate.write(data); if (fin) this._inflate.write(TRAILER); this._inflate.flush(() => { const err = this._inflate[kError]; if (err) { this._inflate.close(); this._inflate = null; callback(err); return; } const data = bufferUtil.concat( this._inflate[kBuffers], this._inflate[kTotalLength] ); if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._inflate.close(); this._inflate = null; } else { this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; } callback(null, data); }); } /** * Compress data. * * @param {Buffer} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _compress(data, fin, callback) { if (!data || data.length === 0) { process.nextTick(callback, null, EMPTY_BLOCK); return; } const endpoint = this._isServer ? 'server' : 'client'; if (!this._deflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== 'number' ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; this._deflate = zlib.createDeflateRaw( Object.assign({}, this._options.zlibDeflateOptions, { windowBits }) ); this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; // // An `'error'` event is emitted, only on Node.js < 10.0.0, if the // `zlib.DeflateRaw` instance is closed while data is being processed. // This can happen if `PerMessageDeflate#cleanup()` is called at the wrong // time due to an abnormal WebSocket closure. // this._deflate.on('error', NOOP); this._deflate.on('data', deflateOnData); } this._deflate.write(data); this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { if (!this._deflate) { // // This `if` statement is only needed for Node.js < 10.0.0 because as of // commit https://github.com/nodejs/node/commit/5e3f5164, the flush // callback is no longer called if the deflate stream is closed while // data is being processed. // return; } var data = bufferUtil.concat( this._deflate[kBuffers], this._deflate[kTotalLength] ); if (fin) data = data.slice(0, data.length - 4); if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._deflate.close(); this._deflate = null; } else { this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; } callback(null, data); }); } } module.exports = PerMessageDeflate; /** * The listener of the `zlib.DeflateRaw` stream `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function deflateOnData(chunk) { this[kBuffers].push(chunk); this[kTotalLength] += chunk.length; } /** * The listener of the `zlib.InflateRaw` stream `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function inflateOnData(chunk) { this[kTotalLength] += chunk.length; if ( this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload ) { this[kBuffers].push(chunk); return; } this[kError] = new RangeError('Max payload size exceeded'); this[kError][kStatusCode] = 1009; this.removeListener('data', inflateOnData); this.reset(); } /** * The listener of the `zlib.InflateRaw` stream `'error'` event. * * @param {Error} err The emitted error * @private */ function inflateOnError(err) { // // There is no need to call `Zlib#close()` as the handle is automatically // closed when an error is emitted. // this[kPerMessageDeflate]._inflate = null; err[kStatusCode] = 1007; this[kCallback](err); } /***/ }), /***/ 9692: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Writable } = __nccwpck_require__(2203); const PerMessageDeflate = __nccwpck_require__(1974); const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = __nccwpck_require__(101); const { concat, toArrayBuffer, unmask } = __nccwpck_require__(9161); const { isValidStatusCode, isValidUTF8 } = __nccwpck_require__(9485); const GET_INFO = 0; const GET_PAYLOAD_LENGTH_16 = 1; const GET_PAYLOAD_LENGTH_64 = 2; const GET_MASK = 3; const GET_DATA = 4; const INFLATING = 5; /** * HyBi Receiver implementation. * * @extends stream.Writable */ class Receiver extends Writable { /** * Creates a Receiver instance. * * @param {String} binaryType The type for binary data * @param {Object} extensions An object containing the negotiated extensions * @param {Number} maxPayload The maximum allowed message length */ constructor(binaryType, extensions, maxPayload) { super(); this._binaryType = binaryType || BINARY_TYPES[0]; this[kWebSocket] = undefined; this._extensions = extensions || {}; this._maxPayload = maxPayload | 0; this._bufferedBytes = 0; this._buffers = []; this._compressed = false; this._payloadLength = 0; this._mask = undefined; this._fragmented = 0; this._masked = false; this._fin = false; this._opcode = 0; this._totalPayloadLength = 0; this._messageLength = 0; this._fragments = []; this._state = GET_INFO; this._loop = false; } /** * Implements `Writable.prototype._write()`. * * @param {Buffer} chunk The chunk of data to write * @param {String} encoding The character encoding of `chunk` * @param {Function} cb Callback */ _write(chunk, encoding, cb) { if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); this._bufferedBytes += chunk.length; this._buffers.push(chunk); this.startLoop(cb); } /** * Consumes `n` bytes from the buffered data. * * @param {Number} n The number of bytes to consume * @return {Buffer} The consumed bytes * @private */ consume(n) { this._bufferedBytes -= n; if (n === this._buffers[0].length) return this._buffers.shift(); if (n < this._buffers[0].length) { const buf = this._buffers[0]; this._buffers[0] = buf.slice(n); return buf.slice(0, n); } const dst = Buffer.allocUnsafe(n); do { const buf = this._buffers[0]; if (n >= buf.length) { this._buffers.shift().copy(dst, dst.length - n); } else { buf.copy(dst, dst.length - n, 0, n); this._buffers[0] = buf.slice(n); } n -= buf.length; } while (n > 0); return dst; } /** * Starts the parsing loop. * * @param {Function} cb Callback * @private */ startLoop(cb) { var err; this._loop = true; do { switch (this._state) { case GET_INFO: err = this.getInfo(); break; case GET_PAYLOAD_LENGTH_16: err = this.getPayloadLength16(); break; case GET_PAYLOAD_LENGTH_64: err = this.getPayloadLength64(); break; case GET_MASK: this.getMask(); break; case GET_DATA: err = this.getData(cb); break; default: // `INFLATING` this._loop = false; return; } } while (this._loop); cb(err); } /** * Reads the first two bytes of a frame. * * @return {(RangeError|undefined)} A possible error * @private */ getInfo() { if (this._bufferedBytes < 2) { this._loop = false; return; } const buf = this.consume(2); if ((buf[0] & 0x30) !== 0x00) { this._loop = false; return error(RangeError, 'RSV2 and RSV3 must be clear', true, 1002); } const compressed = (buf[0] & 0x40) === 0x40; if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { this._loop = false; return error(RangeError, 'RSV1 must be clear', true, 1002); } this._fin = (buf[0] & 0x80) === 0x80; this._opcode = buf[0] & 0x0f; this._payloadLength = buf[1] & 0x7f; if (this._opcode === 0x00) { if (compressed) { this._loop = false; return error(RangeError, 'RSV1 must be clear', true, 1002); } if (!this._fragmented) { this._loop = false; return error(RangeError, 'invalid opcode 0', true, 1002); } this._opcode = this._fragmented; } else if (this._opcode === 0x01 || this._opcode === 0x02) { if (this._fragmented) { this._loop = false; return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002); } this._compressed = compressed; } else if (this._opcode > 0x07 && this._opcode < 0x0b) { if (!this._fin) { this._loop = false; return error(RangeError, 'FIN must be set', true, 1002); } if (compressed) { this._loop = false; return error(RangeError, 'RSV1 must be clear', true, 1002); } if (this._payloadLength > 0x7d) { this._loop = false; return error( RangeError, `invalid payload length ${this._payloadLength}`, true, 1002 ); } } else { this._loop = false; return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002); } if (!this._fin && !this._fragmented) this._fragmented = this._opcode; this._masked = (buf[1] & 0x80) === 0x80; if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; else return this.haveLength(); } /** * Gets extended payload length (7+16). * * @return {(RangeError|undefined)} A possible error * @private */ getPayloadLength16() { if (this._bufferedBytes < 2) { this._loop = false; return; } this._payloadLength = this.consume(2).readUInt16BE(0); return this.haveLength(); } /** * Gets extended payload length (7+64). * * @return {(RangeError|undefined)} A possible error * @private */ getPayloadLength64() { if (this._bufferedBytes < 8) { this._loop = false; return; } const buf = this.consume(8); const num = buf.readUInt32BE(0); // // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned // if payload length is greater than this number. // if (num > Math.pow(2, 53 - 32) - 1) { this._loop = false; return error( RangeError, 'Unsupported WebSocket frame: payload length > 2^53 - 1', false, 1009 ); } this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); return this.haveLength(); } /** * Payload length has been read. * * @return {(RangeError|undefined)} A possible error * @private */ haveLength() { if (this._payloadLength && this._opcode < 0x08) { this._totalPayloadLength += this._payloadLength; if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { this._loop = false; return error(RangeError, 'Max payload size exceeded', false, 1009); } } if (this._masked) this._state = GET_MASK; else this._state = GET_DATA; } /** * Reads mask bytes. * * @private */ getMask() { if (this._bufferedBytes < 4) { this._loop = false; return; } this._mask = this.consume(4); this._state = GET_DATA; } /** * Reads data bytes. * * @param {Function} cb Callback * @return {(Error|RangeError|undefined)} A possible error * @private */ getData(cb) { var data = EMPTY_BUFFER; if (this._payloadLength) { if (this._bufferedBytes < this._payloadLength) { this._loop = false; return; } data = this.consume(this._payloadLength); if (this._masked) unmask(data, this._mask); } if (this._opcode > 0x07) return this.controlMessage(data); if (this._compressed) { this._state = INFLATING; this.decompress(data, cb); return; } if (data.length) { // // This message is not compressed so its lenght is the sum of the payload // length of all fragments. // this._messageLength = this._totalPayloadLength; this._fragments.push(data); } return this.dataMessage(); } /** * Decompresses data. * * @param {Buffer} data Compressed data * @param {Function} cb Callback * @private */ decompress(data, cb) { const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; perMessageDeflate.decompress(data, this._fin, (err, buf) => { if (err) return cb(err); if (buf.length) { this._messageLength += buf.length; if (this._messageLength > this._maxPayload && this._maxPayload > 0) { return cb( error(RangeError, 'Max payload size exceeded', false, 1009) ); } this._fragments.push(buf); } const er = this.dataMessage(); if (er) return cb(er); this.startLoop(cb); }); } /** * Handles a data message. * * @return {(Error|undefined)} A possible error * @private */ dataMessage() { if (this._fin) { const messageLength = this._messageLength; const fragments = this._fragments; this._totalPayloadLength = 0; this._messageLength = 0; this._fragmented = 0; this._fragments = []; if (this._opcode === 2) { var data; if (this._binaryType === 'nodebuffer') { data = concat(fragments, messageLength); } else if (this._binaryType === 'arraybuffer') { data = toArrayBuffer(concat(fragments, messageLength)); } else { data = fragments; } this.emit('message', data); } else { const buf = concat(fragments, messageLength); if (!isValidUTF8(buf)) { this._loop = false; return error(Error, 'invalid UTF-8 sequence', true, 1007); } this.emit('message', buf.toString()); } } this._state = GET_INFO; } /** * Handles a control message. * * @param {Buffer} data Data to handle * @return {(Error|RangeError|undefined)} A possible error * @private */ controlMessage(data) { if (this._opcode === 0x08) { this._loop = false; if (data.length === 0) { this.emit('conclude', 1005, ''); this.end(); } else if (data.length === 1) { return error(RangeError, 'invalid payload length 1', true, 1002); } else { const code = data.readUInt16BE(0); if (!isValidStatusCode(code)) { return error(RangeError, `invalid status code ${code}`, true, 1002); } const buf = data.slice(2); if (!isValidUTF8(buf)) { return error(Error, 'invalid UTF-8 sequence', true, 1007); } this.emit('conclude', code, buf.toString()); this.end(); } } else if (this._opcode === 0x09) { this.emit('ping', data); } else { this.emit('pong', data); } this._state = GET_INFO; } } module.exports = Receiver; /** * Builds an error object. * * @param {(Error|RangeError)} ErrorCtor The error constructor * @param {String} message The error message * @param {Boolean} prefix Specifies whether or not to add a default prefix to * `message` * @param {Number} statusCode The status code * @return {(Error|RangeError)} The error * @private */ function error(ErrorCtor, message, prefix, statusCode) { const err = new ErrorCtor( prefix ? `Invalid WebSocket frame: ${message}` : message ); Error.captureStackTrace(err, error); err[kStatusCode] = statusCode; return err; } /***/ }), /***/ 4779: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { randomBytes } = __nccwpck_require__(6982); const PerMessageDeflate = __nccwpck_require__(1974); const { EMPTY_BUFFER } = __nccwpck_require__(101); const { isValidStatusCode } = __nccwpck_require__(9485); const { mask: applyMask, toBuffer } = __nccwpck_require__(9161); /** * HyBi Sender implementation. */ class Sender { /** * Creates a Sender instance. * * @param {net.Socket} socket The connection socket * @param {Object} extensions An object containing the negotiated extensions */ constructor(socket, extensions) { this._extensions = extensions || {}; this._socket = socket; this._firstFragment = true; this._compress = false; this._bufferedBytes = 0; this._deflating = false; this._queue = []; } /** * Frames a piece of data according to the HyBi WebSocket protocol. * * @param {Buffer} data The data to frame * @param {Object} options Options object * @param {Number} options.opcode The opcode * @param {Boolean} options.readOnly Specifies whether `data` can be modified * @param {Boolean} options.fin Specifies whether or not to set the FIN bit * @param {Boolean} options.mask Specifies whether or not to mask `data` * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit * @return {Buffer[]} The framed data as a list of `Buffer` instances * @public */ static frame(data, options) { const merge = options.mask && options.readOnly; var offset = options.mask ? 6 : 2; var payloadLength = data.length; if (data.length >= 65536) { offset += 8; payloadLength = 127; } else if (data.length > 125) { offset += 2; payloadLength = 126; } const target = Buffer.allocUnsafe(merge ? data.length + offset : offset); target[0] = options.fin ? options.opcode | 0x80 : options.opcode; if (options.rsv1) target[0] |= 0x40; target[1] = payloadLength; if (payloadLength === 126) { target.writeUInt16BE(data.length, 2); } else if (payloadLength === 127) { target.writeUInt32BE(0, 2); target.writeUInt32BE(data.length, 6); } if (!options.mask) return [target, data]; const mask = randomBytes(4); target[1] |= 0x80; target[offset - 4] = mask[0]; target[offset - 3] = mask[1]; target[offset - 2] = mask[2]; target[offset - 1] = mask[3]; if (merge) { applyMask(data, mask, target, offset, data.length); return [target]; } applyMask(data, mask, data, 0, data.length); return [target, data]; } /** * Sends a close message to the other peer. * * @param {(Number|undefined)} code The status code component of the body * @param {String} data The message component of the body * @param {Boolean} mask Specifies whether or not to mask the message * @param {Function} cb Callback * @public */ close(code, data, mask, cb) { var buf; if (code === undefined) { buf = EMPTY_BUFFER; } else if (typeof code !== 'number' || !isValidStatusCode(code)) { throw new TypeError('First argument must be a valid error code number'); } else if (data === undefined || data === '') { buf = Buffer.allocUnsafe(2); buf.writeUInt16BE(code, 0); } else { buf = Buffer.allocUnsafe(2 + Buffer.byteLength(data)); buf.writeUInt16BE(code, 0); buf.write(data, 2); } if (this._deflating) { this.enqueue([this.doClose, buf, mask, cb]); } else { this.doClose(buf, mask, cb); } } /** * Frames and sends a close message. * * @param {Buffer} data The message to send * @param {Boolean} mask Specifies whether or not to mask `data` * @param {Function} cb Callback * @private */ doClose(data, mask, cb) { this.sendFrame( Sender.frame(data, { fin: true, rsv1: false, opcode: 0x08, mask, readOnly: false }), cb ); } /** * Sends a ping message to the other peer. * * @param {*} data The message to send * @param {Boolean} mask Specifies whether or not to mask `data` * @param {Function} cb Callback * @public */ ping(data, mask, cb) { const buf = toBuffer(data); if (this._deflating) { this.enqueue([this.doPing, buf, mask, toBuffer.readOnly, cb]); } else { this.doPing(buf, mask, toBuffer.readOnly, cb); } } /** * Frames and sends a ping message. * * @param {*} data The message to send * @param {Boolean} mask Specifies whether or not to mask `data` * @param {Boolean} readOnly Specifies whether `data` can be modified * @param {Function} cb Callback * @private */ doPing(data, mask, readOnly, cb) { this.sendFrame( Sender.frame(data, { fin: true, rsv1: false, opcode: 0x09, mask, readOnly }), cb ); } /** * Sends a pong message to the other peer. * * @param {*} data The message to send * @param {Boolean} mask Specifies whether or not to mask `data` * @param {Function} cb Callback * @public */ pong(data, mask, cb) { const buf = toBuffer(data); if (this._deflating) { this.enqueue([this.doPong, buf, mask, toBuffer.readOnly, cb]); } else { this.doPong(buf, mask, toBuffer.readOnly, cb); } } /** * Frames and sends a pong message. * * @param {*} data The message to send * @param {Boolean} mask Specifies whether or not to mask `data` * @param {Boolean} readOnly Specifies whether `data` can be modified * @param {Function} cb Callback * @private */ doPong(data, mask, readOnly, cb) { this.sendFrame( Sender.frame(data, { fin: true, rsv1: false, opcode: 0x0a, mask, readOnly }), cb ); } /** * Sends a data message to the other peer. * * @param {*} data The message to send * @param {Object} options Options object * @param {Boolean} options.compress Specifies whether or not to compress `data` * @param {Boolean} options.binary Specifies whether `data` is binary or text * @param {Boolean} options.fin Specifies whether the fragment is the last one * @param {Boolean} options.mask Specifies whether or not to mask `data` * @param {Function} cb Callback * @public */ send(data, options, cb) { const buf = toBuffer(data); const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; var opcode = options.binary ? 2 : 1; var rsv1 = options.compress; if (this._firstFragment) { this._firstFragment = false; if (rsv1 && perMessageDeflate) { rsv1 = buf.length >= perMessageDeflate._threshold; } this._compress = rsv1; } else { rsv1 = false; opcode = 0; } if (options.fin) this._firstFragment = true; if (perMessageDeflate) { const opts = { fin: options.fin, rsv1, opcode, mask: options.mask, readOnly: toBuffer.readOnly }; if (this._deflating) { this.enqueue([this.dispatch, buf, this._compress, opts, cb]); } else { this.dispatch(buf, this._compress, opts, cb); } } else { this.sendFrame( Sender.frame(buf, { fin: options.fin, rsv1: false, opcode, mask: options.mask, readOnly: toBuffer.readOnly }), cb ); } } /** * Dispatches a data message. * * @param {Buffer} data The message to send * @param {Boolean} compress Specifies whether or not to compress `data` * @param {Object} options Options object * @param {Number} options.opcode The opcode * @param {Boolean} options.readOnly Specifies whether `data` can be modified * @param {Boolean} options.fin Specifies whether or not to set the FIN bit * @param {Boolean} options.mask Specifies whether or not to mask `data` * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit * @param {Function} cb Callback * @private */ dispatch(data, compress, options, cb) { if (!compress) { this.sendFrame(Sender.frame(data, options), cb); return; } const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; this._deflating = true; perMessageDeflate.compress(data, options.fin, (_, buf) => { this._deflating = false; options.readOnly = false; this.sendFrame(Sender.frame(buf, options), cb); this.dequeue(); }); } /** * Executes queued send operations. * * @private */ dequeue() { while (!this._deflating && this._queue.length) { const params = this._queue.shift(); this._bufferedBytes -= params[1].length; params[0].apply(this, params.slice(1)); } } /** * Enqueues a send operation. * * @param {Array} params Send operation parameters. * @private */ enqueue(params) { this._bufferedBytes += params[1].length; this._queue.push(params); } /** * Sends a frame. * * @param {Buffer[]} list The frame to send * @param {Function} cb Callback * @private */ sendFrame(list, cb) { if (list.length === 2) { this._socket.cork(); this._socket.write(list[0]); this._socket.write(list[1], cb); this._socket.uncork(); } else { this._socket.write(list[0], cb); } } } module.exports = Sender; /***/ }), /***/ 9485: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; try { const isValidUTF8 = __nccwpck_require__(2414); exports.isValidUTF8 = typeof isValidUTF8 === 'object' ? isValidUTF8.Validation.isValidUTF8 // utf-8-validate@<3.0.0 : isValidUTF8; } catch (e) /* istanbul ignore next */ { exports.isValidUTF8 = () => true; } /** * Checks if a status code is allowed in a close frame. * * @param {Number} code The status code * @return {Boolean} `true` if the status code is valid, else `false` * @public */ exports.isValidStatusCode = (code) => { return ( (code >= 1000 && code <= 1013 && code !== 1004 && code !== 1005 && code !== 1006) || (code >= 3000 && code <= 4999) ); }; /***/ }), /***/ 9419: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const EventEmitter = __nccwpck_require__(4434); const crypto = __nccwpck_require__(6982); const http = __nccwpck_require__(8611); const PerMessageDeflate = __nccwpck_require__(1974); const extension = __nccwpck_require__(1621); const WebSocket = __nccwpck_require__(1855); const { GUID } = __nccwpck_require__(101); const keyRegex = /^[+/0-9A-Za-z]{22}==$/; /** * Class representing a WebSocket server. * * @extends EventEmitter */ class WebSocketServer extends EventEmitter { /** * Create a `WebSocketServer` instance. * * @param {Object} options Configuration options * @param {Number} options.backlog The maximum length of the queue of pending * connections * @param {Boolean} options.clientTracking Specifies whether or not to track * clients * @param {Function} options.handleProtocols An hook to handle protocols * @param {String} options.host The hostname where to bind the server * @param {Number} options.maxPayload The maximum allowed message size * @param {Boolean} options.noServer Enable no server mode * @param {String} options.path Accept only connections matching this path * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable * permessage-deflate * @param {Number} options.port The port where to bind the server * @param {http.Server} options.server A pre-created HTTP/S server to use * @param {Function} options.verifyClient An hook to reject connections * @param {Function} callback A listener for the `listening` event */ constructor(options, callback) { super(); options = Object.assign( { maxPayload: 100 * 1024 * 1024, perMessageDeflate: false, handleProtocols: null, clientTracking: true, verifyClient: null, noServer: false, backlog: null, // use default (511 as implemented in net.js) server: null, host: null, path: null, port: null }, options ); if (options.port == null && !options.server && !options.noServer) { throw new TypeError( 'One of the "port", "server", or "noServer" options must be specified' ); } if (options.port != null) { this._server = http.createServer((req, res) => { const body = http.STATUS_CODES[426]; res.writeHead(426, { 'Content-Length': body.length, 'Content-Type': 'text/plain' }); res.end(body); }); this._server.listen( options.port, options.host, options.backlog, callback ); } else if (options.server) { this._server = options.server; } if (this._server) { this._removeListeners = addListeners(this._server, { listening: this.emit.bind(this, 'listening'), error: this.emit.bind(this, 'error'), upgrade: (req, socket, head) => { this.handleUpgrade(req, socket, head, (ws) => { this.emit('connection', ws, req); }); } }); } if (options.perMessageDeflate === true) options.perMessageDeflate = {}; if (options.clientTracking) this.clients = new Set(); this.options = options; } /** * Returns the bound address, the address family name, and port of the server * as reported by the operating system if listening on an IP socket. * If the server is listening on a pipe or UNIX domain socket, the name is * returned as a string. * * @return {(Object|String|null)} The address of the server * @public */ address() { if (this.options.noServer) { throw new Error('The server is operating in "noServer" mode'); } if (!this._server) return null; return this._server.address(); } /** * Close the server. * * @param {Function} cb Callback * @public */ close(cb) { if (cb) this.once('close', cb); // // Terminate all associated clients. // if (this.clients) { for (const client of this.clients) client.terminate(); } const server = this._server; if (server) { this._removeListeners(); this._removeListeners = this._server = null; // // Close the http server if it was internally created. // if (this.options.port != null) { server.close(() => this.emit('close')); return; } } process.nextTick(emitClose, this); } /** * See if a given request should be handled by this server instance. * * @param {http.IncomingMessage} req Request object to inspect * @return {Boolean} `true` if the request is valid, else `false` * @public */ shouldHandle(req) { if (this.options.path) { const index = req.url.indexOf('?'); const pathname = index !== -1 ? req.url.slice(0, index) : req.url; if (pathname !== this.options.path) return false; } return true; } /** * Handle a HTTP Upgrade request. * * @param {http.IncomingMessage} req The request object * @param {net.Socket} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @public */ handleUpgrade(req, socket, head, cb) { socket.on('error', socketOnError); const key = req.headers['sec-websocket-key'] !== undefined ? req.headers['sec-websocket-key'].trim() : false; const upgrade = req.headers.upgrade; const version = +req.headers['sec-websocket-version']; const extensions = {}; if ( req.method !== 'GET' || upgrade === undefined || upgrade.toLowerCase() !== 'websocket' || !key || !keyRegex.test(key) || (version !== 8 && version !== 13) || !this.shouldHandle(req) ) { return abortHandshake(socket, 400); } if (this.options.perMessageDeflate) { const perMessageDeflate = new PerMessageDeflate( this.options.perMessageDeflate, true, this.options.maxPayload ); try { const offers = extension.parse(req.headers['sec-websocket-extensions']); if (offers[PerMessageDeflate.extensionName]) { perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } } catch (err) { return abortHandshake(socket, 400); } } // // Optionally call external client verification handler. // if (this.options.verifyClient) { const info = { origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], secure: !!(req.connection.authorized || req.connection.encrypted), req }; if (this.options.verifyClient.length === 2) { this.options.verifyClient(info, (verified, code, message, headers) => { if (!verified) { return abortHandshake(socket, code || 401, message, headers); } this.completeUpgrade(key, extensions, req, socket, head, cb); }); return; } if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); } this.completeUpgrade(key, extensions, req, socket, head, cb); } /** * Upgrade the connection to WebSocket. * * @param {String} key The value of the `Sec-WebSocket-Key` header * @param {Object} extensions The accepted extensions * @param {http.IncomingMessage} req The request object * @param {net.Socket} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @private */ completeUpgrade(key, extensions, req, socket, head, cb) { // // Destroy the socket if the client has already sent a FIN packet. // if (!socket.readable || !socket.writable) return socket.destroy(); const digest = crypto .createHash('sha1') .update(key + GUID) .digest('base64'); const headers = [ 'HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Accept: ${digest}` ]; const ws = new WebSocket(null); var protocol = req.headers['sec-websocket-protocol']; if (protocol) { protocol = protocol.split(',').map(trim); // // Optionally call external protocol selection handler. // if (this.options.handleProtocols) { protocol = this.options.handleProtocols(protocol, req); } else { protocol = protocol[0]; } if (protocol) { headers.push(`Sec-WebSocket-Protocol: ${protocol}`); ws.protocol = protocol; } } if (extensions[PerMessageDeflate.extensionName]) { const params = extensions[PerMessageDeflate.extensionName].params; const value = extension.format({ [PerMessageDeflate.extensionName]: [params] }); headers.push(`Sec-WebSocket-Extensions: ${value}`); ws._extensions = extensions; } // // Allow external modification/inspection of handshake headers. // this.emit('headers', headers, req); socket.write(headers.concat('\r\n').join('\r\n')); socket.removeListener('error', socketOnError); ws.setSocket(socket, head, this.options.maxPayload); if (this.clients) { this.clients.add(ws); ws.on('close', () => this.clients.delete(ws)); } cb(ws); } } module.exports = WebSocketServer; /** * Add event listeners on an `EventEmitter` using a map of * pairs. * * @param {EventEmitter} server The event emitter * @param {Object.} map The listeners to add * @return {Function} A function that will remove the added listeners when called * @private */ function addListeners(server, map) { for (const event of Object.keys(map)) server.on(event, map[event]); return function removeListeners() { for (const event of Object.keys(map)) { server.removeListener(event, map[event]); } }; } /** * Emit a `'close'` event on an `EventEmitter`. * * @param {EventEmitter} server The event emitter * @private */ function emitClose(server) { server.emit('close'); } /** * Handle premature socket errors. * * @private */ function socketOnError() { this.destroy(); } /** * Close the connection when preconditions are not fulfilled. * * @param {net.Socket} socket The socket of the upgrade request * @param {Number} code The HTTP response status code * @param {String} [message] The HTTP response body * @param {Object} [headers] Additional HTTP response headers * @private */ function abortHandshake(socket, code, message, headers) { if (socket.writable) { message = message || http.STATUS_CODES[code]; headers = Object.assign( { Connection: 'close', 'Content-type': 'text/html', 'Content-Length': Buffer.byteLength(message) }, headers ); socket.write( `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + Object.keys(headers) .map((h) => `${h}: ${headers[h]}`) .join('\r\n') + '\r\n\r\n' + message ); } socket.removeListener('error', socketOnError); socket.destroy(); } /** * Remove whitespace characters from both ends of a string. * * @param {String} str The string * @return {String} A new string representing `str` stripped of whitespace * characters from both its beginning and end * @private */ function trim(str) { return str.trim(); } /***/ }), /***/ 1855: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const EventEmitter = __nccwpck_require__(4434); const crypto = __nccwpck_require__(6982); const https = __nccwpck_require__(5692); const http = __nccwpck_require__(8611); const net = __nccwpck_require__(9278); const tls = __nccwpck_require__(4756); const url = __nccwpck_require__(7016); const PerMessageDeflate = __nccwpck_require__(1974); const EventTarget = __nccwpck_require__(8948); const extension = __nccwpck_require__(1621); const Receiver = __nccwpck_require__(9692); const Sender = __nccwpck_require__(4779); const { BINARY_TYPES, EMPTY_BUFFER, GUID, kStatusCode, kWebSocket, NOOP } = __nccwpck_require__(101); const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; const protocolVersions = [8, 13]; const closeTimeout = 30 * 1000; /** * Class representing a WebSocket. * * @extends EventEmitter */ class WebSocket extends EventEmitter { /** * Create a new `WebSocket`. * * @param {(String|url.Url|url.URL)} address The URL to which to connect * @param {(String|String[])} protocols The subprotocols * @param {Object} options Connection options */ constructor(address, protocols, options) { super(); this.readyState = WebSocket.CONNECTING; this.protocol = ''; this._binaryType = BINARY_TYPES[0]; this._closeFrameReceived = false; this._closeFrameSent = false; this._closeMessage = ''; this._closeTimer = null; this._closeCode = 1006; this._extensions = {}; this._receiver = null; this._sender = null; this._socket = null; if (address !== null) { this._isServer = false; this._redirects = 0; if (Array.isArray(protocols)) { protocols = protocols.join(', '); } else if (typeof protocols === 'object' && protocols !== null) { options = protocols; protocols = undefined; } initAsClient(this, address, protocols, options); } else { this._isServer = true; } } get CONNECTING() { return WebSocket.CONNECTING; } get CLOSING() { return WebSocket.CLOSING; } get CLOSED() { return WebSocket.CLOSED; } get OPEN() { return WebSocket.OPEN; } /** * This deviates from the WHATWG interface since ws doesn't support the * required default "blob" type (instead we define a custom "nodebuffer" * type). * * @type {String} */ get binaryType() { return this._binaryType; } set binaryType(type) { if (!BINARY_TYPES.includes(type)) return; this._binaryType = type; // // Allow to change `binaryType` on the fly. // if (this._receiver) this._receiver._binaryType = type; } /** * @type {Number} */ get bufferedAmount() { if (!this._socket) return 0; // // `socket.bufferSize` is `undefined` if the socket is closed. // return (this._socket.bufferSize || 0) + this._sender._bufferedBytes; } /** * @type {String} */ get extensions() { return Object.keys(this._extensions).join(); } /** * Set up the socket and the internal resources. * * @param {net.Socket} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Number} maxPayload The maximum allowed message size * @private */ setSocket(socket, head, maxPayload) { const receiver = new Receiver( this._binaryType, this._extensions, maxPayload ); this._sender = new Sender(socket, this._extensions); this._receiver = receiver; this._socket = socket; receiver[kWebSocket] = this; socket[kWebSocket] = this; receiver.on('conclude', receiverOnConclude); receiver.on('drain', receiverOnDrain); receiver.on('error', receiverOnError); receiver.on('message', receiverOnMessage); receiver.on('ping', receiverOnPing); receiver.on('pong', receiverOnPong); socket.setTimeout(0); socket.setNoDelay(); if (head.length > 0) socket.unshift(head); socket.on('close', socketOnClose); socket.on('data', socketOnData); socket.on('end', socketOnEnd); socket.on('error', socketOnError); this.readyState = WebSocket.OPEN; this.emit('open'); } /** * Emit the `'close'` event. * * @private */ emitClose() { this.readyState = WebSocket.CLOSED; if (!this._socket) { this.emit('close', this._closeCode, this._closeMessage); return; } if (this._extensions[PerMessageDeflate.extensionName]) { this._extensions[PerMessageDeflate.extensionName].cleanup(); } this._receiver.removeAllListeners(); this.emit('close', this._closeCode, this._closeMessage); } /** * Start a closing handshake. * * +----------+ +-----------+ +----------+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - * | +----------+ +-----------+ +----------+ | * +----------+ +-----------+ | * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING * +----------+ +-----------+ | * | | | +---+ | * +------------------------+-->|fin| - - - - * | +---+ | +---+ * - - - - -|fin|<---------------------+ * +---+ * * @param {Number} code Status code explaining why the connection is closing * @param {String} data A string explaining why the connection is closing * @public */ close(code, data) { if (this.readyState === WebSocket.CLOSED) return; if (this.readyState === WebSocket.CONNECTING) { const msg = 'WebSocket was closed before the connection was established'; return abortHandshake(this, this._req, msg); } if (this.readyState === WebSocket.CLOSING) { if (this._closeFrameSent && this._closeFrameReceived) this._socket.end(); return; } this.readyState = WebSocket.CLOSING; this._sender.close(code, data, !this._isServer, (err) => { // // This error is handled by the `'error'` listener on the socket. We only // want to know if the close frame has been sent here. // if (err) return; this._closeFrameSent = true; if (this._closeFrameReceived) this._socket.end(); }); // // Specify a timeout for the closing handshake to complete. // this._closeTimer = setTimeout( this._socket.destroy.bind(this._socket), closeTimeout ); } /** * Send a ping. * * @param {*} data The data to send * @param {Boolean} mask Indicates whether or not to mask `data` * @param {Function} cb Callback which is executed when the ping is sent * @public */ ping(data, mask, cb) { if (typeof data === 'function') { cb = data; data = mask = undefined; } else if (typeof mask === 'function') { cb = mask; mask = undefined; } if (this.readyState !== WebSocket.OPEN) { const err = new Error( `WebSocket is not open: readyState ${this.readyState} ` + `(${readyStates[this.readyState]})` ); if (cb) return cb(err); throw err; } if (typeof data === 'number') data = data.toString(); if (mask === undefined) mask = !this._isServer; this._sender.ping(data || EMPTY_BUFFER, mask, cb); } /** * Send a pong. * * @param {*} data The data to send * @param {Boolean} mask Indicates whether or not to mask `data` * @param {Function} cb Callback which is executed when the pong is sent * @public */ pong(data, mask, cb) { if (typeof data === 'function') { cb = data; data = mask = undefined; } else if (typeof mask === 'function') { cb = mask; mask = undefined; } if (this.readyState !== WebSocket.OPEN) { const err = new Error( `WebSocket is not open: readyState ${this.readyState} ` + `(${readyStates[this.readyState]})` ); if (cb) return cb(err); throw err; } if (typeof data === 'number') data = data.toString(); if (mask === undefined) mask = !this._isServer; this._sender.pong(data || EMPTY_BUFFER, mask, cb); } /** * Send a data message. * * @param {*} data The message to send * @param {Object} options Options object * @param {Boolean} options.compress Specifies whether or not to compress `data` * @param {Boolean} options.binary Specifies whether `data` is binary or text * @param {Boolean} options.fin Specifies whether the fragment is the last one * @param {Boolean} options.mask Specifies whether or not to mask `data` * @param {Function} cb Callback which is executed when data is written out * @public */ send(data, options, cb) { if (typeof options === 'function') { cb = options; options = {}; } if (this.readyState !== WebSocket.OPEN) { const err = new Error( `WebSocket is not open: readyState ${this.readyState} ` + `(${readyStates[this.readyState]})` ); if (cb) return cb(err); throw err; } if (typeof data === 'number') data = data.toString(); const opts = Object.assign( { binary: typeof data !== 'string', mask: !this._isServer, compress: true, fin: true }, options ); if (!this._extensions[PerMessageDeflate.extensionName]) { opts.compress = false; } this._sender.send(data || EMPTY_BUFFER, opts, cb); } /** * Forcibly close the connection. * * @public */ terminate() { if (this.readyState === WebSocket.CLOSED) return; if (this.readyState === WebSocket.CONNECTING) { const msg = 'WebSocket was closed before the connection was established'; return abortHandshake(this, this._req, msg); } if (this._socket) { this.readyState = WebSocket.CLOSING; this._socket.destroy(); } } } readyStates.forEach((readyState, i) => { WebSocket[readyState] = i; }); // // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface // ['open', 'error', 'close', 'message'].forEach((method) => { Object.defineProperty(WebSocket.prototype, `on${method}`, { /** * Return the listener of the event. * * @return {(Function|undefined)} The event listener or `undefined` * @public */ get() { const listeners = this.listeners(method); for (var i = 0; i < listeners.length; i++) { if (listeners[i]._listener) return listeners[i]._listener; } return undefined; }, /** * Add a listener for the event. * * @param {Function} listener The listener to add * @public */ set(listener) { const listeners = this.listeners(method); for (var i = 0; i < listeners.length; i++) { // // Remove only the listeners added via `addEventListener`. // if (listeners[i]._listener) this.removeListener(method, listeners[i]); } this.addEventListener(method, listener); } }); }); WebSocket.prototype.addEventListener = EventTarget.addEventListener; WebSocket.prototype.removeEventListener = EventTarget.removeEventListener; module.exports = WebSocket; /** * Initialize a WebSocket client. * * @param {WebSocket} websocket The client to initialize * @param {(String|url.Url|url.URL)} address The URL to which to connect * @param {String} protocols The subprotocols * @param {Object} options Connection options * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable * permessage-deflate * @param {Number} options.handshakeTimeout Timeout in milliseconds for the * handshake request * @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version` * header * @param {String} options.origin Value of the `Origin` or * `Sec-WebSocket-Origin` header * @param {Number} options.maxPayload The maximum allowed message size * @param {Boolean} options.followRedirects Whether or not to follow redirects * @param {Number} options.maxRedirects The maximum number of redirects allowed * @private */ function initAsClient(websocket, address, protocols, options) { const opts = Object.assign( { protocolVersion: protocolVersions[1], maxPayload: 100 * 1024 * 1024, perMessageDeflate: true, followRedirects: false, maxRedirects: 10 }, options, { createConnection: undefined, socketPath: undefined, hostname: undefined, protocol: undefined, timeout: undefined, method: undefined, auth: undefined, host: undefined, path: undefined, port: undefined } ); if (!protocolVersions.includes(opts.protocolVersion)) { throw new RangeError( `Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(', ')})` ); } var parsedUrl; if (typeof address === 'object' && address.href !== undefined) { parsedUrl = address; websocket.url = address.href; } else { // // The WHATWG URL constructor is not available on Node.js < 6.13.0 // parsedUrl = url.URL ? new url.URL(address) : url.parse(address); websocket.url = address; } const isUnixSocket = parsedUrl.protocol === 'ws+unix:'; if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) { throw new Error(`Invalid URL: ${websocket.url}`); } const isSecure = parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:'; const defaultPort = isSecure ? 443 : 80; const key = crypto.randomBytes(16).toString('base64'); const get = isSecure ? https.get : http.get; const path = parsedUrl.search ? `${parsedUrl.pathname || '/'}${parsedUrl.search}` : parsedUrl.pathname || '/'; var perMessageDeflate; opts.createConnection = isSecure ? tlsConnect : netConnect; opts.defaultPort = opts.defaultPort || defaultPort; opts.port = parsedUrl.port || defaultPort; opts.host = parsedUrl.hostname.startsWith('[') ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; opts.headers = Object.assign( { 'Sec-WebSocket-Version': opts.protocolVersion, 'Sec-WebSocket-Key': key, Connection: 'Upgrade', Upgrade: 'websocket' }, opts.headers ); opts.path = path; opts.timeout = opts.handshakeTimeout; if (opts.perMessageDeflate) { perMessageDeflate = new PerMessageDeflate( opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload ); opts.headers['Sec-WebSocket-Extensions'] = extension.format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() }); } if (protocols) { opts.headers['Sec-WebSocket-Protocol'] = protocols; } if (opts.origin) { if (opts.protocolVersion < 13) { opts.headers['Sec-WebSocket-Origin'] = opts.origin; } else { opts.headers.Origin = opts.origin; } } if (parsedUrl.auth) { opts.auth = parsedUrl.auth; } else if (parsedUrl.username || parsedUrl.password) { opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; } if (isUnixSocket) { const parts = path.split(':'); opts.socketPath = parts[0]; opts.path = parts[1]; } var req = (websocket._req = get(opts)); if (opts.timeout) { req.on('timeout', () => { abortHandshake(websocket, req, 'Opening handshake has timed out'); }); } req.on('error', (err) => { if (websocket._req.aborted) return; req = websocket._req = null; websocket.readyState = WebSocket.CLOSING; websocket.emit('error', err); websocket.emitClose(); }); req.on('response', (res) => { const location = res.headers.location; const statusCode = res.statusCode; if ( location && opts.followRedirects && statusCode >= 300 && statusCode < 400 ) { if (++websocket._redirects > opts.maxRedirects) { abortHandshake(websocket, req, 'Maximum redirects exceeded'); return; } req.abort(); const addr = url.URL ? new url.URL(location, address) : url.resolve(address, location); initAsClient(websocket, addr, protocols, options); } else if (!websocket.emit('unexpected-response', req, res)) { abortHandshake( websocket, req, `Unexpected server response: ${res.statusCode}` ); } }); req.on('upgrade', (res, socket, head) => { websocket.emit('upgrade', res); // // The user may have closed the connection from a listener of the `upgrade` // event. // if (websocket.readyState !== WebSocket.CONNECTING) return; req = websocket._req = null; const digest = crypto .createHash('sha1') .update(key + GUID) .digest('base64'); if (res.headers['sec-websocket-accept'] !== digest) { abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); return; } const serverProt = res.headers['sec-websocket-protocol']; const protList = (protocols || '').split(/, */); var protError; if (!protocols && serverProt) { protError = 'Server sent a subprotocol but none was requested'; } else if (protocols && !serverProt) { protError = 'Server sent no subprotocol'; } else if (serverProt && !protList.includes(serverProt)) { protError = 'Server sent an invalid subprotocol'; } if (protError) { abortHandshake(websocket, socket, protError); return; } if (serverProt) websocket.protocol = serverProt; if (perMessageDeflate) { try { const extensions = extension.parse( res.headers['sec-websocket-extensions'] ); if (extensions[PerMessageDeflate.extensionName]) { perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); websocket._extensions[ PerMessageDeflate.extensionName ] = perMessageDeflate; } } catch (err) { abortHandshake( websocket, socket, 'Invalid Sec-WebSocket-Extensions header' ); return; } } websocket.setSocket(socket, head, opts.maxPayload); }); } /** * Create a `net.Socket` and initiate a connection. * * @param {Object} options Connection options * @return {net.Socket} The newly created socket used to start the connection * @private */ function netConnect(options) { // // Override `options.path` only if `options` is a copy of the original options // object. This is always true on Node.js >= 8 but not on Node.js 6 where // `options.socketPath` might be `undefined` even if the `socketPath` option // was originally set. // if (options.protocolVersion) options.path = options.socketPath; return net.connect(options); } /** * Create a `tls.TLSSocket` and initiate a connection. * * @param {Object} options Connection options * @return {tls.TLSSocket} The newly created socket used to start the connection * @private */ function tlsConnect(options) { options.path = undefined; options.servername = options.servername || options.host; return tls.connect(options); } /** * Abort the handshake and emit an error. * * @param {WebSocket} websocket The WebSocket instance * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the * socket to destroy * @param {String} message The error message * @private */ function abortHandshake(websocket, stream, message) { websocket.readyState = WebSocket.CLOSING; const err = new Error(message); Error.captureStackTrace(err, abortHandshake); if (stream.setHeader) { stream.abort(); stream.once('abort', websocket.emitClose.bind(websocket)); websocket.emit('error', err); } else { stream.destroy(err); stream.once('error', websocket.emit.bind(websocket, 'error')); stream.once('close', websocket.emitClose.bind(websocket)); } } /** * The listener of the `Receiver` `'conclude'` event. * * @param {Number} code The status code * @param {String} reason The reason for closing * @private */ function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket._socket.resume(); websocket._closeFrameReceived = true; websocket._closeMessage = reason; websocket._closeCode = code; if (code === 1005) websocket.close(); else websocket.close(code, reason); } /** * The listener of the `Receiver` `'drain'` event. * * @private */ function receiverOnDrain() { this[kWebSocket]._socket.resume(); } /** * The listener of the `Receiver` `'error'` event. * * @param {(RangeError|Error)} err The emitted error * @private */ function receiverOnError(err) { const websocket = this[kWebSocket]; websocket._socket.removeListener('data', socketOnData); websocket.readyState = WebSocket.CLOSING; websocket._closeCode = err[kStatusCode]; websocket.emit('error', err); websocket._socket.destroy(); } /** * The listener of the `Receiver` `'finish'` event. * * @private */ function receiverOnFinish() { this[kWebSocket].emitClose(); } /** * The listener of the `Receiver` `'message'` event. * * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message * @private */ function receiverOnMessage(data) { this[kWebSocket].emit('message', data); } /** * The listener of the `Receiver` `'ping'` event. * * @param {Buffer} data The data included in the ping frame * @private */ function receiverOnPing(data) { const websocket = this[kWebSocket]; websocket.pong(data, !websocket._isServer, NOOP); websocket.emit('ping', data); } /** * The listener of the `Receiver` `'pong'` event. * * @param {Buffer} data The data included in the pong frame * @private */ function receiverOnPong(data) { this[kWebSocket].emit('pong', data); } /** * The listener of the `net.Socket` `'close'` event. * * @private */ function socketOnClose() { const websocket = this[kWebSocket]; this.removeListener('close', socketOnClose); this.removeListener('end', socketOnEnd); websocket.readyState = WebSocket.CLOSING; // // The close frame might not have been received or the `'end'` event emitted, // for example, if the socket was destroyed due to an error. Ensure that the // `receiver` stream is closed after writing any remaining buffered data to // it. If the readable side of the socket is in flowing mode then there is no // buffered data as everything has been already written and `readable.read()` // will return `null`. If instead, the socket is paused, any possible buffered // data will be read as a single chunk and emitted synchronously in a single // `'data'` event. // websocket._socket.read(); websocket._receiver.end(); this.removeListener('data', socketOnData); this[kWebSocket] = undefined; clearTimeout(websocket._closeTimer); if ( websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted ) { websocket.emitClose(); } else { websocket._receiver.on('error', receiverOnFinish); websocket._receiver.on('finish', receiverOnFinish); } } /** * The listener of the `net.Socket` `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function socketOnData(chunk) { if (!this[kWebSocket]._receiver.write(chunk)) { this.pause(); } } /** * The listener of the `net.Socket` `'end'` event. * * @private */ function socketOnEnd() { const websocket = this[kWebSocket]; websocket.readyState = WebSocket.CLOSING; websocket._receiver.end(); this.end(); } /** * The listener of the `net.Socket` `'error'` event. * * @private */ function socketOnError() { const websocket = this[kWebSocket]; this.removeListener('error', socketOnError); this.on('error', NOOP); websocket.readyState = WebSocket.CLOSING; this.destroy(); } /***/ }), /***/ 6875: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var WebSocketServer = (__nccwpck_require__(5476).Server) var stream = __nccwpck_require__(6444) class Server extends WebSocketServer{ constructor(opts, cb) { super(opts) var proxied = false this.on('newListener', function(event) { if (!proxied && event === 'stream') { proxied = true this.on('connection', function(conn, req) { this.emit('stream', stream(conn, opts), req) }) } }) if (cb) { this.on('stream', cb) } } } module.exports.Server = Server module.exports.createServer = function(opts, cb) { return new Server(opts, cb) } /***/ }), /***/ 6444: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var Transform = (__nccwpck_require__(5713).Transform) var duplexify = __nccwpck_require__(9112) var WS = __nccwpck_require__(5476) var Buffer = (__nccwpck_require__(3058).Buffer) module.exports = WebSocketStream function buildProxy (options, socketWrite, socketEnd) { var proxy = new Transform({ objectMode: options.objectMode }) proxy._write = socketWrite proxy._flush = socketEnd return proxy } function WebSocketStream(target, protocols, options) { var stream, socket var isBrowser = process.title === 'browser' var isNative = !!global.WebSocket var socketWrite = isBrowser ? socketWriteBrowser : socketWriteNode if (protocols && !Array.isArray(protocols) && 'object' === typeof protocols) { // accept the "options" Object as the 2nd argument options = protocols protocols = null if (typeof options.protocol === 'string' || Array.isArray(options.protocol)) { protocols = options.protocol; } } if (!options) options = {} if (options.objectMode === undefined) { options.objectMode = !(options.binary === true || options.binary === undefined) } var proxy = buildProxy(options, socketWrite, socketEnd) if (!options.objectMode) { proxy._writev = writev } // browser only: sets the maximum socket buffer size before throttling var bufferSize = options.browserBufferSize || 1024 * 512 // browser only: how long to wait when throttling var bufferTimeout = options.browserBufferTimeout || 1000 // use existing WebSocket object that was passed in if (typeof target === 'object') { socket = target // otherwise make a new one } else { // special constructor treatment for native websockets in browsers, see // https://github.com/maxogden/websocket-stream/issues/82 if (isNative && isBrowser) { socket = new WS(target, protocols) } else { socket = new WS(target, protocols, options) } socket.binaryType = 'arraybuffer' } // was already open when passed in if (socket.readyState === socket.OPEN) { stream = proxy } else if (isBrowser) { stream = proxy stream.cork() socket.onopen = onopenBrowser } else { stream = duplexify.obj() socket.onopen = onopen } stream.socket = socket socket.onclose = onclose socket.onerror = onerror socket.onmessage = onmessage proxy.on('close', destroy) var coerceToBuffer = !options.objectMode function socketWriteNode(chunk, enc, next) { // avoid errors, this never happens unless // destroy() is called if (socket.readyState !== socket.OPEN) { next() return } if (coerceToBuffer && typeof chunk === 'string') { chunk = Buffer.from(chunk, 'utf8') } socket.send(chunk, next) } function socketWriteBrowser(chunk, enc, next) { if (socket.bufferedAmount > bufferSize) { setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next) return } if (coerceToBuffer && typeof chunk === 'string') { chunk = Buffer.from(chunk, 'utf8') } try { socket.send(chunk) } catch(err) { return next(err) } next() } function socketEnd(done) { socket.close() done() } function onopen() { stream.setReadable(proxy) stream.setWritable(proxy) stream.emit('connect') } function onopenBrowser () { stream.uncork() stream.emit('connect') } function onclose() { stream.end() stream.destroy() } function onerror(err) { stream.destroy(err) } function onmessage(event) { var data = event.data if (data instanceof ArrayBuffer) data = Buffer.from(data) else data = Buffer.from(data, 'utf8') proxy.push(data) } function destroy() { socket.close() } // this is to be enabled only if objectMode is false function writev (chunks, cb) { var buffers = new Array(chunks.length) for (var i = 0; i < chunks.length; i++) { if (typeof chunks[i].chunk === 'string') { buffers[i] = Buffer.from(chunks[i], 'utf8') } else { buffers[i] = chunks[i].chunk } } this._write(Buffer.concat(buffers), 'binary', cb) } return stream } /***/ }), /***/ 7834: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { (function (global, factory) { true ? factory(exports, __nccwpck_require__(8577), __nccwpck_require__(2979), __nccwpck_require__(7087)) : 0; })(this, (function (exports, brokerFactory, fastUniqueNumbers, _typeof) { 'use strict'; var createClearIntervalFactory = function createClearIntervalFactory(scheduledIntervalsState) { return function (clear) { return function (timerId) { if (_typeof(scheduledIntervalsState.get(timerId)) === 'symbol') { scheduledIntervalsState.set(timerId, null); clear(timerId).then(function () { scheduledIntervalsState["delete"](timerId); }); } }; }; }; var createClearTimeoutFactory = function createClearTimeoutFactory(scheduledTimeoutsState) { return function (clear) { return function (timerId) { if (_typeof(scheduledTimeoutsState.get(timerId)) === 'symbol') { scheduledTimeoutsState.set(timerId, null); clear(timerId).then(function () { scheduledTimeoutsState["delete"](timerId); }); } }; }; }; var createSetIntervalFactory = function createSetIntervalFactory(generateUniqueNumber, scheduledIntervalsState) { return function (set) { return function (func) { var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } var symbol = Symbol(); var timerId = generateUniqueNumber(scheduledIntervalsState); scheduledIntervalsState.set(timerId, symbol); var _schedule = function schedule() { return set(delay, timerId).then(function () { var state = scheduledIntervalsState.get(timerId); if (state === undefined) { throw new Error('The timer is in an undefined state.'); } if (state === symbol) { func.apply(void 0, args); // Doublecheck if the interval should still be rescheduled because it could have been cleared inside of func(). if (scheduledIntervalsState.get(timerId) === symbol) { _schedule(); } } }); }; _schedule(); return timerId; }; }; }; var createSetTimeoutFactory = function createSetTimeoutFactory(generateUniqueNumber, scheduledTimeoutsState) { return function (set) { return function (func) { var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } var symbol = Symbol(); var timerId = generateUniqueNumber(scheduledTimeoutsState); scheduledTimeoutsState.set(timerId, symbol); set(delay, timerId).then(function () { var state = scheduledTimeoutsState.get(timerId); if (state === undefined) { throw new Error('The timer is in an undefined state.'); } if (state === symbol) { // A timeout can be savely deleted because it is only called once. scheduledTimeoutsState["delete"](timerId); func.apply(void 0, args); } }); return timerId; }; }; }; // Prefilling the Maps with a function indexed by zero is necessary to be compliant with the specification. var scheduledIntervalsState = new Map([[0, null]]); // tslint:disable-line no-empty var scheduledTimeoutsState = new Map([[0, null]]); // tslint:disable-line no-empty var createClearInterval = createClearIntervalFactory(scheduledIntervalsState); var createClearTimeout = createClearTimeoutFactory(scheduledTimeoutsState); var createSetInterval = createSetIntervalFactory(fastUniqueNumbers.generateUniqueNumber, scheduledIntervalsState); var createSetTimeout = createSetTimeoutFactory(fastUniqueNumbers.generateUniqueNumber, scheduledTimeoutsState); var wrap = brokerFactory.createBroker({ clearInterval: function clearInterval(_ref) { var call = _ref.call; return createClearInterval(function (timerId) { return call('clear', { timerId: timerId, timerType: 'interval' }); }); }, clearTimeout: function clearTimeout(_ref2) { var call = _ref2.call; return createClearTimeout(function (timerId) { return call('clear', { timerId: timerId, timerType: 'timeout' }); }); }, setInterval: function setInterval(_ref3) { var call = _ref3.call; return createSetInterval(function (delay, timerId) { return call('set', { delay: delay, now: performance.timeOrigin + performance.now(), timerId: timerId, timerType: 'interval' }); }); }, setTimeout: function setTimeout(_ref4) { var call = _ref4.call; return createSetTimeout(function (delay, timerId) { return call('set', { delay: delay, now: performance.timeOrigin + performance.now(), timerId: timerId, timerType: 'timeout' }); }); } }); var load = function load(url) { var worker = new Worker(url); return wrap(worker); }; exports.load = load; exports.wrap = wrap; })); /***/ }), /***/ 4886: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { (function (global, factory) { true ? factory(exports, __nccwpck_require__(7834)) : 0; })(this, (function (exports, workerTimersBroker) { 'use strict'; var createLoadOrReturnBroker = function createLoadOrReturnBroker(loadBroker, worker) { var broker = null; return function () { if (broker !== null) { return broker; } var blob = new Blob([worker], { type: 'application/javascript; charset=utf-8' }); var url = URL.createObjectURL(blob); broker = loadBroker(url); // Bug #1: Edge up until v18 didn't like the URL to be revoked directly. setTimeout(function () { return URL.revokeObjectURL(url); }); return broker; }; }; // This is the minified and stringified code of the worker-timers-worker package. var worker = "(()=>{var e={389(e,t){!function(e){\"use strict\";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:an)throw new Error(\"Congratulations, you created a collection of unique numbers which uses all available integers!\");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},623(e,t,r){!function(e,t,r,n,o){\"use strict\";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called \"'.concat(e,'\" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called \"'.concat(e,'\" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called \"'.concat(e,'\" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called \"portId\" with the given value \"'.concat(e,'\" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark(function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case\"end\":return t.stop()}},t,null,[[1,11]])}));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise(function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])})};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function v(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener(\"message\",n),function(){return e.removeEventListener(\"message\",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},472(e,t,r){!function(e,t,r,n){\"use strict\";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise(function(t){e.set(a,[r(n,s,i,e,t,a),t])})}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark(function e(r){var n,o,u;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,\"interval\"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt(\"return\",{result:u});case 2:case\"end\":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark(function e(r){var n,o,u,a,i;return t.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,(\"interval\"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt(\"return\",{result:i});case 2:case\"end\":return e.stop()}},e)}));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},172(e){e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},79(e){e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&dn||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError(\"Generator is already running\");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o=\"next\"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError(\"iterator result is not an object\");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError(\"The iterator does not provide a '\"+o+\"' method\"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,function(){return this}),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,\"GeneratorFunction\")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,\"constructor\",p),n(p,\"constructor\",l),l.displayName=\"GeneratorFunction\",n(p,i,\"GeneratorFunction\"),n(v),n(v,i,\"Generator\"),n(v,a,function(){return this}),n(v,\"toString\",function(){return\"[object Generator]\"}),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports},869(e,t,r){var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then(function(e){return e.done?e.value:a.next()})},e.exports.__esModule=!0,e.exports.default=e.exports},887(e,t,r){var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},791(e,t,r){var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then(function(e){u(\"next\",e,a,i)},function(e){u(\"throw\",e,a,i)}):r.resolve(c).then(function(e){s.value=e,a(s)},function(e){return u(\"throw\",e,a,i)})}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,\"function\"==typeof Symbol&&Symbol.asyncIterator||\"@asyncIterator\",function(){return this})),o(this,\"_invoke\",function(e,t,n){function o(){return new r(function(t,r){u(e,n,t,r)})}return a=a?a.then(o,o):o()},!0)},e.exports.__esModule=!0,e.exports.default=e.exports},546(e){function t(r,n,o,u){var a=Object.defineProperty;try{a({},\"\",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){function u(r,n){t(e,r,function(e){return this._invoke(r,n,e)})}r?a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n:(u(\"next\",0),u(\"throw\",1),u(\"return\",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},373(e){e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},633(e,t,r){var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){\"use strict\";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t=\"function\"==typeof e&&e.constructor;return!!t&&(t===l||\"GeneratorFunction\"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},579(e,t,r){var n=r(738).default;e.exports=function(e){if(null!=e){var t=e[\"function\"==typeof Symbol&&Symbol.iterator||\"@@iterator\"],r=0;if(t)return t.call(e);if(\"function\"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+\" is not iterable\")},e.exports.__esModule=!0,e.exports.default=e.exports},715(e,t,r){var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},45(e,t,r){var n=r(738).default;e.exports=function(e,t){if(\"object\"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||\"default\");if(\"object\"!=n(o))return o;throw new TypeError(\"@@toPrimitive must return a primitive value.\")}return(\"string\"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},736(e,t,r){var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,\"string\");return\"symbol\"==n(t)?t:t+\"\"},e.exports.__esModule=!0,e.exports.default=e.exports},738(e){function t(r){return e.exports=t=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&\"function\"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?\"symbol\":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},122(e,t,r){var n=r(79);e.exports=function(e,t){if(e){if(\"string\"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return\"Object\"===r&&e.constructor&&(r=e.constructor.name),\"Map\"===r||\"Set\"===r?Array.from(e):\"Arguments\"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},756(e,t,r){var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){\"object\"==typeof globalThis?globalThis.regeneratorRuntime=n:Function(\"r\",\"regeneratorRuntime = r\")(n)}}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{\"use strict\";r(472)})()})();"; // tslint:disable-line:max-line-length var loadOrReturnBroker = createLoadOrReturnBroker(workerTimersBroker.load, worker); var clearInterval = function clearInterval(timerId) { return loadOrReturnBroker().clearInterval(timerId); }; var clearTimeout = function clearTimeout(timerId) { return loadOrReturnBroker().clearTimeout(timerId); }; var setInterval = function setInterval() { var _loadOrReturnBroker; return (_loadOrReturnBroker = loadOrReturnBroker()).setInterval.apply(_loadOrReturnBroker, arguments); }; var setTimeout$1 = function setTimeout() { var _loadOrReturnBroker2; return (_loadOrReturnBroker2 = loadOrReturnBroker()).setTimeout.apply(_loadOrReturnBroker2, arguments); }; exports.clearInterval = clearInterval; exports.clearTimeout = clearTimeout; exports.setInterval = setInterval; exports.setTimeout = setTimeout$1; })); /***/ }), /***/ 5883: /***/ ((module) => { // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. module.exports = wrappy function wrappy (fn, cb) { if (fn && cb) return wrappy(fn)(cb) if (typeof fn !== 'function') throw new TypeError('need wrapper function') Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k] }) return wrapper function wrapper() { var args = new Array(arguments.length) for (var i = 0; i < args.length; i++) { args[i] = arguments[i] } var ret = fn.apply(this, args) var cb = args[args.length-1] if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k] }) } return ret } } /***/ }), /***/ 1354: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const createWebSocketStream = __nccwpck_require__(6412); const extension = __nccwpck_require__(1335); const PerMessageDeflate = __nccwpck_require__(4376); const Receiver = __nccwpck_require__(893); const Sender = __nccwpck_require__(7389); const subprotocol = __nccwpck_require__(3332); const WebSocket = __nccwpck_require__(6681); const WebSocketServer = __nccwpck_require__(129); WebSocket.createWebSocketStream = createWebSocketStream; WebSocket.extension = extension; WebSocket.PerMessageDeflate = PerMessageDeflate; WebSocket.Receiver = Receiver; WebSocket.Sender = Sender; WebSocket.Server = WebSocketServer; WebSocket.subprotocol = subprotocol; WebSocket.WebSocket = WebSocket; WebSocket.WebSocketServer = WebSocketServer; module.exports = WebSocket; /***/ }), /***/ 5803: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { EMPTY_BUFFER } = __nccwpck_require__(1791); const FastBuffer = Buffer[Symbol.species]; /** * Merges an array of buffers into a new buffer. * * @param {Buffer[]} list The array of buffers to concat * @param {Number} totalLength The total length of buffers in the list * @return {Buffer} The resulting buffer * @public */ function concat(list, totalLength) { if (list.length === 0) return EMPTY_BUFFER; if (list.length === 1) return list[0]; const target = Buffer.allocUnsafe(totalLength); let offset = 0; for (let i = 0; i < list.length; i++) { const buf = list[i]; target.set(buf, offset); offset += buf.length; } if (offset < totalLength) { return new FastBuffer(target.buffer, target.byteOffset, offset); } return target; } /** * Masks a buffer using the given mask. * * @param {Buffer} source The buffer to mask * @param {Buffer} mask The mask to use * @param {Buffer} output The buffer where to store the result * @param {Number} offset The offset at which to start writing * @param {Number} length The number of bytes to mask. * @public */ function _mask(source, mask, output, offset, length) { for (let i = 0; i < length; i++) { output[offset + i] = source[i] ^ mask[i & 3]; } } /** * Unmasks a buffer using the given mask. * * @param {Buffer} buffer The buffer to unmask * @param {Buffer} mask The mask to use * @public */ function _unmask(buffer, mask) { for (let i = 0; i < buffer.length; i++) { buffer[i] ^= mask[i & 3]; } } /** * Converts a buffer to an `ArrayBuffer`. * * @param {Buffer} buf The buffer to convert * @return {ArrayBuffer} Converted buffer * @public */ function toArrayBuffer(buf) { if (buf.length === buf.buffer.byteLength) { return buf.buffer; } return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); } /** * Converts `data` to a `Buffer`. * * @param {*} data The data to convert * @return {Buffer} The buffer * @throws {TypeError} * @public */ function toBuffer(data) { toBuffer.readOnly = true; if (Buffer.isBuffer(data)) return data; let buf; if (data instanceof ArrayBuffer) { buf = new FastBuffer(data); } else if (ArrayBuffer.isView(data)) { buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); } else { buf = Buffer.from(data); toBuffer.readOnly = false; } return buf; } module.exports = { concat, mask: _mask, toArrayBuffer, toBuffer, unmask: _unmask }; /* istanbul ignore else */ if (!process.env.WS_NO_BUFFER_UTIL) { try { const bufferUtil = __nccwpck_require__(8327); module.exports.mask = function (source, mask, output, offset, length) { if (length < 48) _mask(source, mask, output, offset, length); else bufferUtil.mask(source, mask, output, offset, length); }; module.exports.unmask = function (buffer, mask) { if (buffer.length < 32) _unmask(buffer, mask); else bufferUtil.unmask(buffer, mask); }; } catch (e) { // Continue regardless of the error. } } /***/ }), /***/ 1791: /***/ ((module) => { "use strict"; const BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments']; const hasBlob = typeof Blob !== 'undefined'; if (hasBlob) BINARY_TYPES.push('blob'); module.exports = { BINARY_TYPES, CLOSE_TIMEOUT: 30000, EMPTY_BUFFER: Buffer.alloc(0), GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', hasBlob, kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), kListener: Symbol('kListener'), kStatusCode: Symbol('status-code'), kWebSocket: Symbol('websocket'), NOOP: () => {} }; /***/ }), /***/ 4634: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { kForOnEventAttribute, kListener } = __nccwpck_require__(1791); const kCode = Symbol('kCode'); const kData = Symbol('kData'); const kError = Symbol('kError'); const kMessage = Symbol('kMessage'); const kReason = Symbol('kReason'); const kTarget = Symbol('kTarget'); const kType = Symbol('kType'); const kWasClean = Symbol('kWasClean'); /** * Class representing an event. */ class Event { /** * Create a new `Event`. * * @param {String} type The name of the event * @throws {TypeError} If the `type` argument is not specified */ constructor(type) { this[kTarget] = null; this[kType] = type; } /** * @type {*} */ get target() { return this[kTarget]; } /** * @type {String} */ get type() { return this[kType]; } } Object.defineProperty(Event.prototype, 'target', { enumerable: true }); Object.defineProperty(Event.prototype, 'type', { enumerable: true }); /** * Class representing a close event. * * @extends Event */ class CloseEvent extends Event { /** * Create a new `CloseEvent`. * * @param {String} type The name of the event * @param {Object} [options] A dictionary object that allows for setting * attributes via object members of the same name * @param {Number} [options.code=0] The status code explaining why the * connection was closed * @param {String} [options.reason=''] A human-readable string explaining why * the connection was closed * @param {Boolean} [options.wasClean=false] Indicates whether or not the * connection was cleanly closed */ constructor(type, options = {}) { super(type); this[kCode] = options.code === undefined ? 0 : options.code; this[kReason] = options.reason === undefined ? '' : options.reason; this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; } /** * @type {Number} */ get code() { return this[kCode]; } /** * @type {String} */ get reason() { return this[kReason]; } /** * @type {Boolean} */ get wasClean() { return this[kWasClean]; } } Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); /** * Class representing an error event. * * @extends Event */ class ErrorEvent extends Event { /** * Create a new `ErrorEvent`. * * @param {String} type The name of the event * @param {Object} [options] A dictionary object that allows for setting * attributes via object members of the same name * @param {*} [options.error=null] The error that generated this event * @param {String} [options.message=''] The error message */ constructor(type, options = {}) { super(type); this[kError] = options.error === undefined ? null : options.error; this[kMessage] = options.message === undefined ? '' : options.message; } /** * @type {*} */ get error() { return this[kError]; } /** * @type {String} */ get message() { return this[kMessage]; } } Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); /** * Class representing a message event. * * @extends Event */ class MessageEvent extends Event { /** * Create a new `MessageEvent`. * * @param {String} type The name of the event * @param {Object} [options] A dictionary object that allows for setting * attributes via object members of the same name * @param {*} [options.data=null] The message content */ constructor(type, options = {}) { super(type); this[kData] = options.data === undefined ? null : options.data; } /** * @type {*} */ get data() { return this[kData]; } } Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); /** * This provides methods for emulating the `EventTarget` interface. It's not * meant to be used directly. * * @mixin */ const EventTarget = { /** * Register an event listener. * * @param {String} type A string representing the event type to listen for * @param {(Function|Object)} handler The listener to add * @param {Object} [options] An options object specifies characteristics about * the event listener * @param {Boolean} [options.once=false] A `Boolean` indicating that the * listener should be invoked at most once after being added. If `true`, * the listener would be automatically removed when invoked. * @public */ addEventListener(type, handler, options = {}) { for (const listener of this.listeners(type)) { if ( !options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute] ) { return; } } let wrapper; if (type === 'message') { wrapper = function onMessage(data, isBinary) { const event = new MessageEvent('message', { data: isBinary ? data : data.toString() }); event[kTarget] = this; callListener(handler, this, event); }; } else if (type === 'close') { wrapper = function onClose(code, message) { const event = new CloseEvent('close', { code, reason: message.toString(), wasClean: this._closeFrameReceived && this._closeFrameSent }); event[kTarget] = this; callListener(handler, this, event); }; } else if (type === 'error') { wrapper = function onError(error) { const event = new ErrorEvent('error', { error, message: error.message }); event[kTarget] = this; callListener(handler, this, event); }; } else if (type === 'open') { wrapper = function onOpen() { const event = new Event('open'); event[kTarget] = this; callListener(handler, this, event); }; } else { return; } wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; wrapper[kListener] = handler; if (options.once) { this.once(type, wrapper); } else { this.on(type, wrapper); } }, /** * Remove an event listener. * * @param {String} type A string representing the event type to remove * @param {(Function|Object)} handler The listener to remove * @public */ removeEventListener(type, handler) { for (const listener of this.listeners(type)) { if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { this.removeListener(type, listener); break; } } } }; module.exports = { CloseEvent, ErrorEvent, Event, EventTarget, MessageEvent }; /** * Call an event listener * * @param {(Function|Object)} listener The listener to call * @param {*} thisArg The value to use as `this`` when calling the listener * @param {Event} event The event to pass to the listener * @private */ function callListener(listener, thisArg, event) { if (typeof listener === 'object' && listener.handleEvent) { listener.handleEvent.call(listener, event); } else { listener.call(thisArg, event); } } /***/ }), /***/ 1335: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { tokenChars } = __nccwpck_require__(6615); /** * Adds an offer to the map of extension offers or a parameter to the map of * parameters. * * @param {Object} dest The map of extension offers or parameters * @param {String} name The extension or parameter name * @param {(Object|Boolean|String)} elem The extension parameters or the * parameter value * @private */ function push(dest, name, elem) { if (dest[name] === undefined) dest[name] = [elem]; else dest[name].push(elem); } /** * Parses the `Sec-WebSocket-Extensions` header into an object. * * @param {String} header The field value of the header * @return {Object} The parsed object * @public */ function parse(header) { const offers = Object.create(null); let params = Object.create(null); let mustUnescape = false; let isEscaping = false; let inQuotes = false; let extensionName; let paramName; let start = -1; let code = -1; let end = -1; let i = 0; for (; i < header.length; i++) { code = header.charCodeAt(i); if (extensionName === undefined) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if ( i !== 0 && (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ ) { if (end === -1 && start !== -1) end = i; } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; const name = header.slice(start, end); if (code === 0x2c) { push(offers, name, params); params = Object.create(null); } else { extensionName = name; } start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else if (paramName === undefined) { if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 0x20 || code === 0x09) { if (end === -1 && start !== -1) end = i; } else if (code === 0x3b || code === 0x2c) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; push(params, header.slice(start, end), true); if (code === 0x2c) { push(offers, extensionName, params); params = Object.create(null); extensionName = undefined; } start = end = -1; } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { paramName = header.slice(start, i); start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else { // // The value of a quoted-string after unescaping must conform to the // token ABNF, so only token characters are valid. // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 // if (isEscaping) { if (tokenChars[code] !== 1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (start === -1) start = i; else if (!mustUnescape) mustUnescape = true; isEscaping = false; } else if (inQuotes) { if (tokenChars[code] === 1) { if (start === -1) start = i; } else if (code === 0x22 /* '"' */ && start !== -1) { inQuotes = false; end = i; } else if (code === 0x5c /* '\' */) { isEscaping = true; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { inQuotes = true; } else if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if (start !== -1 && (code === 0x20 || code === 0x09)) { if (end === -1) end = i; } else if (code === 0x3b || code === 0x2c) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; let value = header.slice(start, end); if (mustUnescape) { value = value.replace(/\\/g, ''); mustUnescape = false; } push(params, paramName, value); if (code === 0x2c) { push(offers, extensionName, params); params = Object.create(null); extensionName = undefined; } paramName = undefined; start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } } if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { throw new SyntaxError('Unexpected end of input'); } if (end === -1) end = i; const token = header.slice(start, end); if (extensionName === undefined) { push(offers, token, params); } else { if (paramName === undefined) { push(params, token, true); } else if (mustUnescape) { push(params, paramName, token.replace(/\\/g, '')); } else { push(params, paramName, token); } push(offers, extensionName, params); } return offers; } /** * Builds the `Sec-WebSocket-Extensions` header field value. * * @param {Object} extensions The map of extensions and parameters to format * @return {String} A string representing the given object * @public */ function format(extensions) { return Object.keys(extensions) .map((extension) => { let configurations = extensions[extension]; if (!Array.isArray(configurations)) configurations = [configurations]; return configurations .map((params) => { return [extension] .concat( Object.keys(params).map((k) => { let values = params[k]; if (!Array.isArray(values)) values = [values]; return values .map((v) => (v === true ? k : `${k}=${v}`)) .join('; '); }) ) .join('; '); }) .join(', '); }) .join(', '); } module.exports = { format, parse }; /***/ }), /***/ 958: /***/ ((module) => { "use strict"; const kDone = Symbol('kDone'); const kRun = Symbol('kRun'); /** * A very simple job queue with adjustable concurrency. Adapted from * https://github.com/STRML/async-limiter */ class Limiter { /** * Creates a new `Limiter`. * * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed * to run concurrently */ constructor(concurrency) { this[kDone] = () => { this.pending--; this[kRun](); }; this.concurrency = concurrency || Infinity; this.jobs = []; this.pending = 0; } /** * Adds a job to the queue. * * @param {Function} job The job to run * @public */ add(job) { this.jobs.push(job); this[kRun](); } /** * Removes a job from the queue and runs it if possible. * * @private */ [kRun]() { if (this.pending === this.concurrency) return; if (this.jobs.length) { const job = this.jobs.shift(); this.pending++; job(this[kDone]); } } } module.exports = Limiter; /***/ }), /***/ 4376: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const zlib = __nccwpck_require__(3106); const bufferUtil = __nccwpck_require__(5803); const Limiter = __nccwpck_require__(958); const { kStatusCode } = __nccwpck_require__(1791); const FastBuffer = Buffer[Symbol.species]; const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); const kPerMessageDeflate = Symbol('permessage-deflate'); const kTotalLength = Symbol('total-length'); const kCallback = Symbol('callback'); const kBuffers = Symbol('buffers'); const kError = Symbol('error'); // // We limit zlib concurrency, which prevents severe memory fragmentation // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 // and https://github.com/websockets/ws/issues/1202 // // Intentionally global; it's the global thread pool that's an issue. // let zlibLimiter; /** * permessage-deflate implementation. */ class PerMessageDeflate { /** * Creates a PerMessageDeflate instance. * * @param {Object} [options] Configuration options * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support * for, or request, a custom client window size * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ * acknowledge disabling of client context takeover * @param {Number} [options.concurrencyLimit=10] The number of concurrent * calls to zlib * @param {Boolean} [options.isServer=false] Create the instance in either * server or client mode * @param {Number} [options.maxPayload=0] The maximum allowed message length * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the * use of a custom server window size * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept * disabling of server context takeover * @param {Number} [options.threshold=1024] Size (in bytes) below which * messages should not be compressed if context takeover is disabled * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on * deflate * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on * inflate */ constructor(options) { this._options = options || {}; this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024; this._maxPayload = this._options.maxPayload | 0; this._isServer = !!this._options.isServer; this._deflate = null; this._inflate = null; this.params = null; if (!zlibLimiter) { const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10; zlibLimiter = new Limiter(concurrency); } } /** * @type {String} */ static get extensionName() { return 'permessage-deflate'; } /** * Create an extension negotiation offer. * * @return {Object} Extension parameters * @public */ offer() { const params = {}; if (this._options.serverNoContextTakeover) { params.server_no_context_takeover = true; } if (this._options.clientNoContextTakeover) { params.client_no_context_takeover = true; } if (this._options.serverMaxWindowBits) { params.server_max_window_bits = this._options.serverMaxWindowBits; } if (this._options.clientMaxWindowBits) { params.client_max_window_bits = this._options.clientMaxWindowBits; } else if (this._options.clientMaxWindowBits == null) { params.client_max_window_bits = true; } return params; } /** * Accept an extension negotiation offer/response. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Object} Accepted configuration * @public */ accept(configurations) { configurations = this.normalizeParams(configurations); this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); return this.params; } /** * Releases all resources used by the extension. * * @public */ cleanup() { if (this._inflate) { this._inflate.close(); this._inflate = null; } if (this._deflate) { const callback = this._deflate[kCallback]; this._deflate.close(); this._deflate = null; if (callback) { callback( new Error( 'The deflate stream was closed while data was being processed' ) ); } } } /** * Accept an extension negotiation offer. * * @param {Array} offers The extension negotiation offers * @return {Object} Accepted configuration * @private */ acceptAsServer(offers) { const opts = this._options; const accepted = offers.find((params) => { if ( (opts.serverNoContextTakeover === false && params.server_no_context_takeover) || (params.server_max_window_bits && (opts.serverMaxWindowBits === false || (typeof opts.serverMaxWindowBits === 'number' && opts.serverMaxWindowBits > params.server_max_window_bits))) || (typeof opts.clientMaxWindowBits === 'number' && !params.client_max_window_bits) ) { return false; } return true; }); if (!accepted) { throw new Error('None of the extension offers can be accepted'); } if (opts.serverNoContextTakeover) { accepted.server_no_context_takeover = true; } if (opts.clientNoContextTakeover) { accepted.client_no_context_takeover = true; } if (typeof opts.serverMaxWindowBits === 'number') { accepted.server_max_window_bits = opts.serverMaxWindowBits; } if (typeof opts.clientMaxWindowBits === 'number') { accepted.client_max_window_bits = opts.clientMaxWindowBits; } else if ( accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false ) { delete accepted.client_max_window_bits; } return accepted; } /** * Accept the extension negotiation response. * * @param {Array} response The extension negotiation response * @return {Object} Accepted configuration * @private */ acceptAsClient(response) { const params = response[0]; if ( this._options.clientNoContextTakeover === false && params.client_no_context_takeover ) { throw new Error('Unexpected parameter "client_no_context_takeover"'); } if (!params.client_max_window_bits) { if (typeof this._options.clientMaxWindowBits === 'number') { params.client_max_window_bits = this._options.clientMaxWindowBits; } } else if ( this._options.clientMaxWindowBits === false || (typeof this._options.clientMaxWindowBits === 'number' && params.client_max_window_bits > this._options.clientMaxWindowBits) ) { throw new Error( 'Unexpected or invalid parameter "client_max_window_bits"' ); } return params; } /** * Normalize parameters. * * @param {Array} configurations The extension negotiation offers/reponse * @return {Array} The offers/response with normalized parameters * @private */ normalizeParams(configurations) { configurations.forEach((params) => { Object.keys(params).forEach((key) => { let value = params[key]; if (value.length > 1) { throw new Error(`Parameter "${key}" must have only a single value`); } value = value[0]; if (key === 'client_max_window_bits') { if (value !== true) { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if (!this._isServer) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else if (key === 'server_max_window_bits') { const num = +value; if (!Number.isInteger(num) || num < 8 || num > 15) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } value = num; } else if ( key === 'client_no_context_takeover' || key === 'server_no_context_takeover' ) { if (value !== true) { throw new TypeError( `Invalid value for parameter "${key}": ${value}` ); } } else { throw new Error(`Unknown parameter "${key}"`); } params[key] = value; }); }); return configurations; } /** * Decompress data. Concurrency limited. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ decompress(data, fin, callback) { zlibLimiter.add((done) => { this._decompress(data, fin, (err, result) => { done(); callback(err, result); }); }); } /** * Compress data. Concurrency limited. * * @param {(Buffer|String)} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @public */ compress(data, fin, callback) { zlibLimiter.add((done) => { this._compress(data, fin, (err, result) => { done(); callback(err, result); }); }); } /** * Decompress data. * * @param {Buffer} data Compressed data * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _decompress(data, fin, callback) { const endpoint = this._isServer ? 'client' : 'server'; if (!this._inflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== 'number' ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; this._inflate = zlib.createInflateRaw({ ...this._options.zlibInflateOptions, windowBits }); this._inflate[kPerMessageDeflate] = this; this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; this._inflate.on('error', inflateOnError); this._inflate.on('data', inflateOnData); } this._inflate[kCallback] = callback; this._inflate.write(data); if (fin) this._inflate.write(TRAILER); this._inflate.flush(() => { const err = this._inflate[kError]; if (err) { this._inflate.close(); this._inflate = null; callback(err); return; } const data = bufferUtil.concat( this._inflate[kBuffers], this._inflate[kTotalLength] ); if (this._inflate._readableState.endEmitted) { this._inflate.close(); this._inflate = null; } else { this._inflate[kTotalLength] = 0; this._inflate[kBuffers] = []; if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._inflate.reset(); } } callback(null, data); }); } /** * Compress data. * * @param {(Buffer|String)} data Data to compress * @param {Boolean} fin Specifies whether or not this is the last fragment * @param {Function} callback Callback * @private */ _compress(data, fin, callback) { const endpoint = this._isServer ? 'server' : 'client'; if (!this._deflate) { const key = `${endpoint}_max_window_bits`; const windowBits = typeof this.params[key] !== 'number' ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; this._deflate = zlib.createDeflateRaw({ ...this._options.zlibDeflateOptions, windowBits }); this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; this._deflate.on('data', deflateOnData); } this._deflate[kCallback] = callback; this._deflate.write(data); this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { if (!this._deflate) { // // The deflate stream was closed while data was being processed. // return; } let data = bufferUtil.concat( this._deflate[kBuffers], this._deflate[kTotalLength] ); if (fin) { data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4); } // // Ensure that the callback will not be called again in // `PerMessageDeflate#cleanup()`. // this._deflate[kCallback] = null; this._deflate[kTotalLength] = 0; this._deflate[kBuffers] = []; if (fin && this.params[`${endpoint}_no_context_takeover`]) { this._deflate.reset(); } callback(null, data); }); } } module.exports = PerMessageDeflate; /** * The listener of the `zlib.DeflateRaw` stream `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function deflateOnData(chunk) { this[kBuffers].push(chunk); this[kTotalLength] += chunk.length; } /** * The listener of the `zlib.InflateRaw` stream `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function inflateOnData(chunk) { this[kTotalLength] += chunk.length; if ( this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload ) { this[kBuffers].push(chunk); return; } this[kError] = new RangeError('Max payload size exceeded'); this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; this[kError][kStatusCode] = 1009; this.removeListener('data', inflateOnData); // // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the // fact that in Node.js versions prior to 13.10.0, the callback for // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing // `zlib.reset()` ensures that either the callback is invoked or an error is // emitted. // this.reset(); } /** * The listener of the `zlib.InflateRaw` stream `'error'` event. * * @param {Error} err The emitted error * @private */ function inflateOnError(err) { // // There is no need to call `Zlib#close()` as the handle is automatically // closed when an error is emitted. // this[kPerMessageDeflate]._inflate = null; if (this[kError]) { this[kCallback](this[kError]); return; } err[kStatusCode] = 1007; this[kCallback](err); } /***/ }), /***/ 893: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { Writable } = __nccwpck_require__(2203); const PerMessageDeflate = __nccwpck_require__(4376); const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = __nccwpck_require__(1791); const { concat, toArrayBuffer, unmask } = __nccwpck_require__(5803); const { isValidStatusCode, isValidUTF8 } = __nccwpck_require__(6615); const FastBuffer = Buffer[Symbol.species]; const GET_INFO = 0; const GET_PAYLOAD_LENGTH_16 = 1; const GET_PAYLOAD_LENGTH_64 = 2; const GET_MASK = 3; const GET_DATA = 4; const INFLATING = 5; const DEFER_EVENT = 6; /** * HyBi Receiver implementation. * * @extends Writable */ class Receiver extends Writable { /** * Creates a Receiver instance. * * @param {Object} [options] Options object * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted * multiple times in the same tick * @param {String} [options.binaryType=nodebuffer] The type for binary data * @param {Object} [options.extensions] An object containing the negotiated * extensions * @param {Boolean} [options.isServer=false] Specifies whether to operate in * client or server mode * @param {Number} [options.maxPayload=0] The maximum allowed message length * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages */ constructor(options = {}) { super(); this._allowSynchronousEvents = options.allowSynchronousEvents !== undefined ? options.allowSynchronousEvents : true; this._binaryType = options.binaryType || BINARY_TYPES[0]; this._extensions = options.extensions || {}; this._isServer = !!options.isServer; this._maxPayload = options.maxPayload | 0; this._skipUTF8Validation = !!options.skipUTF8Validation; this[kWebSocket] = undefined; this._bufferedBytes = 0; this._buffers = []; this._compressed = false; this._payloadLength = 0; this._mask = undefined; this._fragmented = 0; this._masked = false; this._fin = false; this._opcode = 0; this._totalPayloadLength = 0; this._messageLength = 0; this._fragments = []; this._errored = false; this._loop = false; this._state = GET_INFO; } /** * Implements `Writable.prototype._write()`. * * @param {Buffer} chunk The chunk of data to write * @param {String} encoding The character encoding of `chunk` * @param {Function} cb Callback * @private */ _write(chunk, encoding, cb) { if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); this._bufferedBytes += chunk.length; this._buffers.push(chunk); this.startLoop(cb); } /** * Consumes `n` bytes from the buffered data. * * @param {Number} n The number of bytes to consume * @return {Buffer} The consumed bytes * @private */ consume(n) { this._bufferedBytes -= n; if (n === this._buffers[0].length) return this._buffers.shift(); if (n < this._buffers[0].length) { const buf = this._buffers[0]; this._buffers[0] = new FastBuffer( buf.buffer, buf.byteOffset + n, buf.length - n ); return new FastBuffer(buf.buffer, buf.byteOffset, n); } const dst = Buffer.allocUnsafe(n); do { const buf = this._buffers[0]; const offset = dst.length - n; if (n >= buf.length) { dst.set(this._buffers.shift(), offset); } else { dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); this._buffers[0] = new FastBuffer( buf.buffer, buf.byteOffset + n, buf.length - n ); } n -= buf.length; } while (n > 0); return dst; } /** * Starts the parsing loop. * * @param {Function} cb Callback * @private */ startLoop(cb) { this._loop = true; do { switch (this._state) { case GET_INFO: this.getInfo(cb); break; case GET_PAYLOAD_LENGTH_16: this.getPayloadLength16(cb); break; case GET_PAYLOAD_LENGTH_64: this.getPayloadLength64(cb); break; case GET_MASK: this.getMask(); break; case GET_DATA: this.getData(cb); break; case INFLATING: case DEFER_EVENT: this._loop = false; return; } } while (this._loop); if (!this._errored) cb(); } /** * Reads the first two bytes of a frame. * * @param {Function} cb Callback * @private */ getInfo(cb) { if (this._bufferedBytes < 2) { this._loop = false; return; } const buf = this.consume(2); if ((buf[0] & 0x30) !== 0x00) { const error = this.createError( RangeError, 'RSV2 and RSV3 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_2_3' ); cb(error); return; } const compressed = (buf[0] & 0x40) === 0x40; if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { const error = this.createError( RangeError, 'RSV1 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_1' ); cb(error); return; } this._fin = (buf[0] & 0x80) === 0x80; this._opcode = buf[0] & 0x0f; this._payloadLength = buf[1] & 0x7f; if (this._opcode === 0x00) { if (compressed) { const error = this.createError( RangeError, 'RSV1 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_1' ); cb(error); return; } if (!this._fragmented) { const error = this.createError( RangeError, 'invalid opcode 0', true, 1002, 'WS_ERR_INVALID_OPCODE' ); cb(error); return; } this._opcode = this._fragmented; } else if (this._opcode === 0x01 || this._opcode === 0x02) { if (this._fragmented) { const error = this.createError( RangeError, `invalid opcode ${this._opcode}`, true, 1002, 'WS_ERR_INVALID_OPCODE' ); cb(error); return; } this._compressed = compressed; } else if (this._opcode > 0x07 && this._opcode < 0x0b) { if (!this._fin) { const error = this.createError( RangeError, 'FIN must be set', true, 1002, 'WS_ERR_EXPECTED_FIN' ); cb(error); return; } if (compressed) { const error = this.createError( RangeError, 'RSV1 must be clear', true, 1002, 'WS_ERR_UNEXPECTED_RSV_1' ); cb(error); return; } if ( this._payloadLength > 0x7d || (this._opcode === 0x08 && this._payloadLength === 1) ) { const error = this.createError( RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' ); cb(error); return; } } else { const error = this.createError( RangeError, `invalid opcode ${this._opcode}`, true, 1002, 'WS_ERR_INVALID_OPCODE' ); cb(error); return; } if (!this._fin && !this._fragmented) this._fragmented = this._opcode; this._masked = (buf[1] & 0x80) === 0x80; if (this._isServer) { if (!this._masked) { const error = this.createError( RangeError, 'MASK must be set', true, 1002, 'WS_ERR_EXPECTED_MASK' ); cb(error); return; } } else if (this._masked) { const error = this.createError( RangeError, 'MASK must be clear', true, 1002, 'WS_ERR_UNEXPECTED_MASK' ); cb(error); return; } if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; else this.haveLength(cb); } /** * Gets extended payload length (7+16). * * @param {Function} cb Callback * @private */ getPayloadLength16(cb) { if (this._bufferedBytes < 2) { this._loop = false; return; } this._payloadLength = this.consume(2).readUInt16BE(0); this.haveLength(cb); } /** * Gets extended payload length (7+64). * * @param {Function} cb Callback * @private */ getPayloadLength64(cb) { if (this._bufferedBytes < 8) { this._loop = false; return; } const buf = this.consume(8); const num = buf.readUInt32BE(0); // // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned // if payload length is greater than this number. // if (num > Math.pow(2, 53 - 32) - 1) { const error = this.createError( RangeError, 'Unsupported WebSocket frame: payload length > 2^53 - 1', false, 1009, 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' ); cb(error); return; } this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); this.haveLength(cb); } /** * Payload length has been read. * * @param {Function} cb Callback * @private */ haveLength(cb) { if (this._payloadLength && this._opcode < 0x08) { this._totalPayloadLength += this._payloadLength; if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { const error = this.createError( RangeError, 'Max payload size exceeded', false, 1009, 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' ); cb(error); return; } } if (this._masked) this._state = GET_MASK; else this._state = GET_DATA; } /** * Reads mask bytes. * * @private */ getMask() { if (this._bufferedBytes < 4) { this._loop = false; return; } this._mask = this.consume(4); this._state = GET_DATA; } /** * Reads data bytes. * * @param {Function} cb Callback * @private */ getData(cb) { let data = EMPTY_BUFFER; if (this._payloadLength) { if (this._bufferedBytes < this._payloadLength) { this._loop = false; return; } data = this.consume(this._payloadLength); if ( this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 ) { unmask(data, this._mask); } } if (this._opcode > 0x07) { this.controlMessage(data, cb); return; } if (this._compressed) { this._state = INFLATING; this.decompress(data, cb); return; } if (data.length) { // // This message is not compressed so its length is the sum of the payload // length of all fragments. // this._messageLength = this._totalPayloadLength; this._fragments.push(data); } this.dataMessage(cb); } /** * Decompresses data. * * @param {Buffer} data Compressed data * @param {Function} cb Callback * @private */ decompress(data, cb) { const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; perMessageDeflate.decompress(data, this._fin, (err, buf) => { if (err) return cb(err); if (buf.length) { this._messageLength += buf.length; if (this._messageLength > this._maxPayload && this._maxPayload > 0) { const error = this.createError( RangeError, 'Max payload size exceeded', false, 1009, 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' ); cb(error); return; } this._fragments.push(buf); } this.dataMessage(cb); if (this._state === GET_INFO) this.startLoop(cb); }); } /** * Handles a data message. * * @param {Function} cb Callback * @private */ dataMessage(cb) { if (!this._fin) { this._state = GET_INFO; return; } const messageLength = this._messageLength; const fragments = this._fragments; this._totalPayloadLength = 0; this._messageLength = 0; this._fragmented = 0; this._fragments = []; if (this._opcode === 2) { let data; if (this._binaryType === 'nodebuffer') { data = concat(fragments, messageLength); } else if (this._binaryType === 'arraybuffer') { data = toArrayBuffer(concat(fragments, messageLength)); } else if (this._binaryType === 'blob') { data = new Blob(fragments); } else { data = fragments; } if (this._allowSynchronousEvents) { this.emit('message', data, true); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit('message', data, true); this._state = GET_INFO; this.startLoop(cb); }); } } else { const buf = concat(fragments, messageLength); if (!this._skipUTF8Validation && !isValidUTF8(buf)) { const error = this.createError( Error, 'invalid UTF-8 sequence', true, 1007, 'WS_ERR_INVALID_UTF8' ); cb(error); return; } if (this._state === INFLATING || this._allowSynchronousEvents) { this.emit('message', buf, false); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit('message', buf, false); this._state = GET_INFO; this.startLoop(cb); }); } } } /** * Handles a control message. * * @param {Buffer} data Data to handle * @return {(Error|RangeError|undefined)} A possible error * @private */ controlMessage(data, cb) { if (this._opcode === 0x08) { if (data.length === 0) { this._loop = false; this.emit('conclude', 1005, EMPTY_BUFFER); this.end(); } else { const code = data.readUInt16BE(0); if (!isValidStatusCode(code)) { const error = this.createError( RangeError, `invalid status code ${code}`, true, 1002, 'WS_ERR_INVALID_CLOSE_CODE' ); cb(error); return; } const buf = new FastBuffer( data.buffer, data.byteOffset + 2, data.length - 2 ); if (!this._skipUTF8Validation && !isValidUTF8(buf)) { const error = this.createError( Error, 'invalid UTF-8 sequence', true, 1007, 'WS_ERR_INVALID_UTF8' ); cb(error); return; } this._loop = false; this.emit('conclude', code, buf); this.end(); } this._state = GET_INFO; return; } if (this._allowSynchronousEvents) { this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); this._state = GET_INFO; } else { this._state = DEFER_EVENT; setImmediate(() => { this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); this._state = GET_INFO; this.startLoop(cb); }); } } /** * Builds an error object. * * @param {function(new:Error|RangeError)} ErrorCtor The error constructor * @param {String} message The error message * @param {Boolean} prefix Specifies whether or not to add a default prefix to * `message` * @param {Number} statusCode The status code * @param {String} errorCode The exposed error code * @return {(Error|RangeError)} The error * @private */ createError(ErrorCtor, message, prefix, statusCode, errorCode) { this._loop = false; this._errored = true; const err = new ErrorCtor( prefix ? `Invalid WebSocket frame: ${message}` : message ); Error.captureStackTrace(err, this.createError); err.code = errorCode; err[kStatusCode] = statusCode; return err; } } module.exports = Receiver; /***/ }), /***/ 7389: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */ const { Duplex } = __nccwpck_require__(2203); const { randomFillSync } = __nccwpck_require__(6982); const PerMessageDeflate = __nccwpck_require__(4376); const { EMPTY_BUFFER, kWebSocket, NOOP } = __nccwpck_require__(1791); const { isBlob, isValidStatusCode } = __nccwpck_require__(6615); const { mask: applyMask, toBuffer } = __nccwpck_require__(5803); const kByteLength = Symbol('kByteLength'); const maskBuffer = Buffer.alloc(4); const RANDOM_POOL_SIZE = 8 * 1024; let randomPool; let randomPoolPointer = RANDOM_POOL_SIZE; const DEFAULT = 0; const DEFLATING = 1; const GET_BLOB_DATA = 2; /** * HyBi Sender implementation. */ class Sender { /** * Creates a Sender instance. * * @param {Duplex} socket The connection socket * @param {Object} [extensions] An object containing the negotiated extensions * @param {Function} [generateMask] The function used to generate the masking * key */ constructor(socket, extensions, generateMask) { this._extensions = extensions || {}; if (generateMask) { this._generateMask = generateMask; this._maskBuffer = Buffer.alloc(4); } this._socket = socket; this._firstFragment = true; this._compress = false; this._bufferedBytes = 0; this._queue = []; this._state = DEFAULT; this.onerror = NOOP; this[kWebSocket] = undefined; } /** * Frames a piece of data according to the HyBi WebSocket protocol. * * @param {(Buffer|String)} data The data to frame * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @return {(Buffer|String)[]} The framed data * @public */ static frame(data, options) { let mask; let merge = false; let offset = 2; let skipMasking = false; if (options.mask) { mask = options.maskBuffer || maskBuffer; if (options.generateMask) { options.generateMask(mask); } else { if (randomPoolPointer === RANDOM_POOL_SIZE) { /* istanbul ignore else */ if (randomPool === undefined) { // // This is lazily initialized because server-sent frames must not // be masked so it may never be used. // randomPool = Buffer.alloc(RANDOM_POOL_SIZE); } randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); randomPoolPointer = 0; } mask[0] = randomPool[randomPoolPointer++]; mask[1] = randomPool[randomPoolPointer++]; mask[2] = randomPool[randomPoolPointer++]; mask[3] = randomPool[randomPoolPointer++]; } skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; offset = 6; } let dataLength; if (typeof data === 'string') { if ( (!options.mask || skipMasking) && options[kByteLength] !== undefined ) { dataLength = options[kByteLength]; } else { data = Buffer.from(data); dataLength = data.length; } } else { dataLength = data.length; merge = options.mask && options.readOnly && !skipMasking; } let payloadLength = dataLength; if (dataLength >= 65536) { offset += 8; payloadLength = 127; } else if (dataLength > 125) { offset += 2; payloadLength = 126; } const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); target[0] = options.fin ? options.opcode | 0x80 : options.opcode; if (options.rsv1) target[0] |= 0x40; target[1] = payloadLength; if (payloadLength === 126) { target.writeUInt16BE(dataLength, 2); } else if (payloadLength === 127) { target[2] = target[3] = 0; target.writeUIntBE(dataLength, 4, 6); } if (!options.mask) return [target, data]; target[1] |= 0x80; target[offset - 4] = mask[0]; target[offset - 3] = mask[1]; target[offset - 2] = mask[2]; target[offset - 1] = mask[3]; if (skipMasking) return [target, data]; if (merge) { applyMask(data, mask, target, offset, dataLength); return [target]; } applyMask(data, mask, data, 0, dataLength); return [target, data]; } /** * Sends a close message to the other peer. * * @param {Number} [code] The status code component of the body * @param {(String|Buffer)} [data] The message component of the body * @param {Boolean} [mask=false] Specifies whether or not to mask the message * @param {Function} [cb] Callback * @public */ close(code, data, mask, cb) { let buf; if (code === undefined) { buf = EMPTY_BUFFER; } else if (typeof code !== 'number' || !isValidStatusCode(code)) { throw new TypeError('First argument must be a valid error code number'); } else if (data === undefined || !data.length) { buf = Buffer.allocUnsafe(2); buf.writeUInt16BE(code, 0); } else { const length = Buffer.byteLength(data); if (length > 123) { throw new RangeError('The message must not be greater than 123 bytes'); } buf = Buffer.allocUnsafe(2 + length); buf.writeUInt16BE(code, 0); if (typeof data === 'string') { buf.write(data, 2); } else { buf.set(data, 2); } } const options = { [kByteLength]: buf.length, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 0x08, readOnly: false, rsv1: false }; if (this._state !== DEFAULT) { this.enqueue([this.dispatch, buf, false, options, cb]); } else { this.sendFrame(Sender.frame(buf, options), cb); } } /** * Sends a ping message to the other peer. * * @param {*} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Function} [cb] Callback * @public */ ping(data, mask, cb) { let byteLength; let readOnly; if (typeof data === 'string') { byteLength = Buffer.byteLength(data); readOnly = false; } else if (isBlob(data)) { byteLength = data.size; readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (byteLength > 125) { throw new RangeError('The data size must not be greater than 125 bytes'); } const options = { [kByteLength]: byteLength, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 0x09, readOnly, rsv1: false }; if (isBlob(data)) { if (this._state !== DEFAULT) { this.enqueue([this.getBlobData, data, false, options, cb]); } else { this.getBlobData(data, false, options, cb); } } else if (this._state !== DEFAULT) { this.enqueue([this.dispatch, data, false, options, cb]); } else { this.sendFrame(Sender.frame(data, options), cb); } } /** * Sends a pong message to the other peer. * * @param {*} data The message to send * @param {Boolean} [mask=false] Specifies whether or not to mask `data` * @param {Function} [cb] Callback * @public */ pong(data, mask, cb) { let byteLength; let readOnly; if (typeof data === 'string') { byteLength = Buffer.byteLength(data); readOnly = false; } else if (isBlob(data)) { byteLength = data.size; readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (byteLength > 125) { throw new RangeError('The data size must not be greater than 125 bytes'); } const options = { [kByteLength]: byteLength, fin: true, generateMask: this._generateMask, mask, maskBuffer: this._maskBuffer, opcode: 0x0a, readOnly, rsv1: false }; if (isBlob(data)) { if (this._state !== DEFAULT) { this.enqueue([this.getBlobData, data, false, options, cb]); } else { this.getBlobData(data, false, options, cb); } } else if (this._state !== DEFAULT) { this.enqueue([this.dispatch, data, false, options, cb]); } else { this.sendFrame(Sender.frame(data, options), cb); } } /** * Sends a data message to the other peer. * * @param {*} data The message to send * @param {Object} options Options object * @param {Boolean} [options.binary=false] Specifies whether `data` is binary * or text * @param {Boolean} [options.compress=false] Specifies whether or not to * compress `data` * @param {Boolean} [options.fin=false] Specifies whether the fragment is the * last one * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Function} [cb] Callback * @public */ send(data, options, cb) { const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; let opcode = options.binary ? 2 : 1; let rsv1 = options.compress; let byteLength; let readOnly; if (typeof data === 'string') { byteLength = Buffer.byteLength(data); readOnly = false; } else if (isBlob(data)) { byteLength = data.size; readOnly = false; } else { data = toBuffer(data); byteLength = data.length; readOnly = toBuffer.readOnly; } if (this._firstFragment) { this._firstFragment = false; if ( rsv1 && perMessageDeflate && perMessageDeflate.params[ perMessageDeflate._isServer ? 'server_no_context_takeover' : 'client_no_context_takeover' ] ) { rsv1 = byteLength >= perMessageDeflate._threshold; } this._compress = rsv1; } else { rsv1 = false; opcode = 0; } if (options.fin) this._firstFragment = true; const opts = { [kByteLength]: byteLength, fin: options.fin, generateMask: this._generateMask, mask: options.mask, maskBuffer: this._maskBuffer, opcode, readOnly, rsv1 }; if (isBlob(data)) { if (this._state !== DEFAULT) { this.enqueue([this.getBlobData, data, this._compress, opts, cb]); } else { this.getBlobData(data, this._compress, opts, cb); } } else if (this._state !== DEFAULT) { this.enqueue([this.dispatch, data, this._compress, opts, cb]); } else { this.dispatch(data, this._compress, opts, cb); } } /** * Gets the contents of a blob as binary data. * * @param {Blob} blob The blob * @param {Boolean} [compress=false] Specifies whether or not to compress * the data * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @param {Function} [cb] Callback * @private */ getBlobData(blob, compress, options, cb) { this._bufferedBytes += options[kByteLength]; this._state = GET_BLOB_DATA; blob .arrayBuffer() .then((arrayBuffer) => { if (this._socket.destroyed) { const err = new Error( 'The socket was closed while the blob was being read' ); // // `callCallbacks` is called in the next tick to ensure that errors // that might be thrown in the callbacks behave like errors thrown // outside the promise chain. // process.nextTick(callCallbacks, this, err, cb); return; } this._bufferedBytes -= options[kByteLength]; const data = toBuffer(arrayBuffer); if (!compress) { this._state = DEFAULT; this.sendFrame(Sender.frame(data, options), cb); this.dequeue(); } else { this.dispatch(data, compress, options, cb); } }) .catch((err) => { // // `onError` is called in the next tick for the same reason that // `callCallbacks` above is. // process.nextTick(onError, this, err, cb); }); } /** * Dispatches a message. * * @param {(Buffer|String)} data The message to send * @param {Boolean} [compress=false] Specifies whether or not to compress * `data` * @param {Object} options Options object * @param {Boolean} [options.fin=false] Specifies whether or not to set the * FIN bit * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Boolean} [options.mask=false] Specifies whether or not to mask * `data` * @param {Buffer} [options.maskBuffer] The buffer used to store the masking * key * @param {Number} options.opcode The opcode * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be * modified * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the * RSV1 bit * @param {Function} [cb] Callback * @private */ dispatch(data, compress, options, cb) { if (!compress) { this.sendFrame(Sender.frame(data, options), cb); return; } const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; this._bufferedBytes += options[kByteLength]; this._state = DEFLATING; perMessageDeflate.compress(data, options.fin, (_, buf) => { if (this._socket.destroyed) { const err = new Error( 'The socket was closed while data was being compressed' ); callCallbacks(this, err, cb); return; } this._bufferedBytes -= options[kByteLength]; this._state = DEFAULT; options.readOnly = false; this.sendFrame(Sender.frame(buf, options), cb); this.dequeue(); }); } /** * Executes queued send operations. * * @private */ dequeue() { while (this._state === DEFAULT && this._queue.length) { const params = this._queue.shift(); this._bufferedBytes -= params[3][kByteLength]; Reflect.apply(params[0], this, params.slice(1)); } } /** * Enqueues a send operation. * * @param {Array} params Send operation parameters. * @private */ enqueue(params) { this._bufferedBytes += params[3][kByteLength]; this._queue.push(params); } /** * Sends a frame. * * @param {(Buffer | String)[]} list The frame to send * @param {Function} [cb] Callback * @private */ sendFrame(list, cb) { if (list.length === 2) { this._socket.cork(); this._socket.write(list[0]); this._socket.write(list[1], cb); this._socket.uncork(); } else { this._socket.write(list[0], cb); } } } module.exports = Sender; /** * Calls queued callbacks with an error. * * @param {Sender} sender The `Sender` instance * @param {Error} err The error to call the callbacks with * @param {Function} [cb] The first callback * @private */ function callCallbacks(sender, err, cb) { if (typeof cb === 'function') cb(err); for (let i = 0; i < sender._queue.length; i++) { const params = sender._queue[i]; const callback = params[params.length - 1]; if (typeof callback === 'function') callback(err); } } /** * Handles a `Sender` error. * * @param {Sender} sender The `Sender` instance * @param {Error} err The error * @param {Function} [cb] The first pending callback * @private */ function onError(sender, err, cb) { callCallbacks(sender, err, cb); sender.onerror(err); } /***/ }), /***/ 6412: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^WebSocket$" }] */ const WebSocket = __nccwpck_require__(6681); const { Duplex } = __nccwpck_require__(2203); /** * Emits the `'close'` event on a stream. * * @param {Duplex} stream The stream. * @private */ function emitClose(stream) { stream.emit('close'); } /** * The listener of the `'end'` event. * * @private */ function duplexOnEnd() { if (!this.destroyed && this._writableState.finished) { this.destroy(); } } /** * The listener of the `'error'` event. * * @param {Error} err The error * @private */ function duplexOnError(err) { this.removeListener('error', duplexOnError); this.destroy(); if (this.listenerCount('error') === 0) { // Do not suppress the throwing behavior. this.emit('error', err); } } /** * Wraps a `WebSocket` in a duplex stream. * * @param {WebSocket} ws The `WebSocket` to wrap * @param {Object} [options] The options for the `Duplex` constructor * @return {Duplex} The duplex stream * @public */ function createWebSocketStream(ws, options) { let terminateOnDestroy = true; const duplex = new Duplex({ ...options, autoDestroy: false, emitClose: false, objectMode: false, writableObjectMode: false }); ws.on('message', function message(msg, isBinary) { const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; if (!duplex.push(data)) ws.pause(); }); ws.once('error', function error(err) { if (duplex.destroyed) return; // Prevent `ws.terminate()` from being called by `duplex._destroy()`. // // - If the `'error'` event is emitted before the `'open'` event, then // `ws.terminate()` is a noop as no socket is assigned. // - Otherwise, the error is re-emitted by the listener of the `'error'` // event of the `Receiver` object. The listener already closes the // connection by calling `ws.close()`. This allows a close frame to be // sent to the other peer. If `ws.terminate()` is called right after this, // then the close frame might not be sent. terminateOnDestroy = false; duplex.destroy(err); }); ws.once('close', function close() { if (duplex.destroyed) return; duplex.push(null); }); duplex._destroy = function (err, callback) { if (ws.readyState === ws.CLOSED) { callback(err); process.nextTick(emitClose, duplex); return; } let called = false; ws.once('error', function error(err) { called = true; callback(err); }); ws.once('close', function close() { if (!called) callback(err); process.nextTick(emitClose, duplex); }); if (terminateOnDestroy) ws.terminate(); }; duplex._final = function (callback) { if (ws.readyState === ws.CONNECTING) { ws.once('open', function open() { duplex._final(callback); }); return; } // If the value of the `_socket` property is `null` it means that `ws` is a // client websocket and the handshake failed. In fact, when this happens, a // socket is never assigned to the websocket. Wait for the `'error'` event // that will be emitted by the websocket. if (ws._socket === null) return; if (ws._socket._writableState.finished) { callback(); if (duplex._readableState.endEmitted) duplex.destroy(); } else { ws._socket.once('finish', function finish() { // `duplex` is not destroyed here because the `'end'` event will be // emitted on `duplex` after this `'finish'` event. The EOF signaling // `null` chunk is, in fact, pushed when the websocket emits `'close'`. callback(); }); ws.close(); } }; duplex._read = function () { if (ws.isPaused) ws.resume(); }; duplex._write = function (chunk, encoding, callback) { if (ws.readyState === ws.CONNECTING) { ws.once('open', function open() { duplex._write(chunk, encoding, callback); }); return; } ws.send(chunk, callback); }; duplex.on('end', duplexOnEnd); duplex.on('error', duplexOnError); return duplex; } module.exports = createWebSocketStream; /***/ }), /***/ 3332: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { tokenChars } = __nccwpck_require__(6615); /** * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. * * @param {String} header The field value of the header * @return {Set} The subprotocol names * @public */ function parse(header) { const protocols = new Set(); let start = -1; let end = -1; let i = 0; for (i; i < header.length; i++) { const code = header.charCodeAt(i); if (end === -1 && tokenChars[code] === 1) { if (start === -1) start = i; } else if ( i !== 0 && (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ ) { if (end === -1 && start !== -1) end = i; } else if (code === 0x2c /* ',' */) { if (start === -1) { throw new SyntaxError(`Unexpected character at index ${i}`); } if (end === -1) end = i; const protocol = header.slice(start, end); if (protocols.has(protocol)) { throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); } protocols.add(protocol); start = end = -1; } else { throw new SyntaxError(`Unexpected character at index ${i}`); } } if (start === -1 || end !== -1) { throw new SyntaxError('Unexpected end of input'); } const protocol = header.slice(start, i); if (protocols.has(protocol)) { throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); } protocols.add(protocol); return protocols; } module.exports = { parse }; /***/ }), /***/ 6615: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const { isUtf8 } = __nccwpck_require__(181); const { hasBlob } = __nccwpck_require__(1791); // // Allowed token characters: // // '!', '#', '$', '%', '&', ''', '*', '+', '-', // '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' // // tokenChars[32] === 0 // ' ' // tokenChars[33] === 1 // '!' // tokenChars[34] === 0 // '"' // ... // // prettier-ignore const tokenChars = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 ]; /** * Checks if a status code is allowed in a close frame. * * @param {Number} code The status code * @return {Boolean} `true` if the status code is valid, else `false` * @public */ function isValidStatusCode(code) { return ( (code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006) || (code >= 3000 && code <= 4999) ); } /** * Checks if a given buffer contains only correct UTF-8. * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by * Markus Kuhn. * * @param {Buffer} buf The buffer to check * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` * @public */ function _isValidUTF8(buf) { const len = buf.length; let i = 0; while (i < len) { if ((buf[i] & 0x80) === 0) { // 0xxxxxxx i++; } else if ((buf[i] & 0xe0) === 0xc0) { // 110xxxxx 10xxxxxx if ( i + 1 === len || (buf[i + 1] & 0xc0) !== 0x80 || (buf[i] & 0xfe) === 0xc0 // Overlong ) { return false; } i += 2; } else if ((buf[i] & 0xf0) === 0xe0) { // 1110xxxx 10xxxxxx 10xxxxxx if ( i + 2 >= len || (buf[i + 1] & 0xc0) !== 0x80 || (buf[i + 2] & 0xc0) !== 0x80 || (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) ) { return false; } i += 3; } else if ((buf[i] & 0xf8) === 0xf0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx if ( i + 3 >= len || (buf[i + 1] & 0xc0) !== 0x80 || (buf[i + 2] & 0xc0) !== 0x80 || (buf[i + 3] & 0xc0) !== 0x80 || (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || buf[i] > 0xf4 // > U+10FFFF ) { return false; } i += 4; } else { return false; } } return true; } /** * Determines whether a value is a `Blob`. * * @param {*} value The value to be tested * @return {Boolean} `true` if `value` is a `Blob`, else `false` * @private */ function isBlob(value) { return ( hasBlob && typeof value === 'object' && typeof value.arrayBuffer === 'function' && typeof value.type === 'string' && typeof value.stream === 'function' && (value[Symbol.toStringTag] === 'Blob' || value[Symbol.toStringTag] === 'File') ); } module.exports = { isBlob, isValidStatusCode, isValidUTF8: _isValidUTF8, tokenChars }; if (isUtf8) { module.exports.isValidUTF8 = function (buf) { return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); }; } /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) { try { const isValidUTF8 = __nccwpck_require__(2414); module.exports.isValidUTF8 = function (buf) { return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); }; } catch (e) { // Continue regardless of the error. } } /***/ }), /***/ 129: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */ const EventEmitter = __nccwpck_require__(4434); const http = __nccwpck_require__(8611); const { Duplex } = __nccwpck_require__(2203); const { createHash } = __nccwpck_require__(6982); const extension = __nccwpck_require__(1335); const PerMessageDeflate = __nccwpck_require__(4376); const subprotocol = __nccwpck_require__(3332); const WebSocket = __nccwpck_require__(6681); const { CLOSE_TIMEOUT, GUID, kWebSocket } = __nccwpck_require__(1791); const keyRegex = /^[+/0-9A-Za-z]{22}==$/; const RUNNING = 0; const CLOSING = 1; const CLOSED = 2; /** * Class representing a WebSocket server. * * @extends EventEmitter */ class WebSocketServer extends EventEmitter { /** * Create a `WebSocketServer` instance. * * @param {Object} options Configuration options * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted * multiple times in the same tick * @param {Boolean} [options.autoPong=true] Specifies whether or not to * automatically send a pong in response to a ping * @param {Number} [options.backlog=511] The maximum length of the queue of * pending connections * @param {Boolean} [options.clientTracking=true] Specifies whether or not to * track clients * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to * wait for the closing handshake to finish after `websocket.close()` is * called * @param {Function} [options.handleProtocols] A hook to handle protocols * @param {String} [options.host] The hostname where to bind the server * @param {Number} [options.maxPayload=104857600] The maximum allowed message * size * @param {Boolean} [options.noServer=false] Enable no server mode * @param {String} [options.path] Accept only connections matching this path * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable * permessage-deflate * @param {Number} [options.port] The port where to bind the server * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S * server to use * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @param {Function} [options.verifyClient] A hook to reject connections * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` * class to use. It must be the `WebSocket` class or class that extends it * @param {Function} [callback] A listener for the `listening` event */ constructor(options, callback) { super(); options = { allowSynchronousEvents: true, autoPong: true, maxPayload: 100 * 1024 * 1024, skipUTF8Validation: false, perMessageDeflate: false, handleProtocols: null, clientTracking: true, closeTimeout: CLOSE_TIMEOUT, verifyClient: null, noServer: false, backlog: null, // use default (511 as implemented in net.js) server: null, host: null, path: null, port: null, WebSocket, ...options }; if ( (options.port == null && !options.server && !options.noServer) || (options.port != null && (options.server || options.noServer)) || (options.server && options.noServer) ) { throw new TypeError( 'One and only one of the "port", "server", or "noServer" options ' + 'must be specified' ); } if (options.port != null) { this._server = http.createServer((req, res) => { const body = http.STATUS_CODES[426]; res.writeHead(426, { 'Content-Length': body.length, 'Content-Type': 'text/plain' }); res.end(body); }); this._server.listen( options.port, options.host, options.backlog, callback ); } else if (options.server) { this._server = options.server; } if (this._server) { const emitConnection = this.emit.bind(this, 'connection'); this._removeListeners = addListeners(this._server, { listening: this.emit.bind(this, 'listening'), error: this.emit.bind(this, 'error'), upgrade: (req, socket, head) => { this.handleUpgrade(req, socket, head, emitConnection); } }); } if (options.perMessageDeflate === true) options.perMessageDeflate = {}; if (options.clientTracking) { this.clients = new Set(); this._shouldEmitClose = false; } this.options = options; this._state = RUNNING; } /** * Returns the bound address, the address family name, and port of the server * as reported by the operating system if listening on an IP socket. * If the server is listening on a pipe or UNIX domain socket, the name is * returned as a string. * * @return {(Object|String|null)} The address of the server * @public */ address() { if (this.options.noServer) { throw new Error('The server is operating in "noServer" mode'); } if (!this._server) return null; return this._server.address(); } /** * Stop the server from accepting new connections and emit the `'close'` event * when all existing connections are closed. * * @param {Function} [cb] A one-time listener for the `'close'` event * @public */ close(cb) { if (this._state === CLOSED) { if (cb) { this.once('close', () => { cb(new Error('The server is not running')); }); } process.nextTick(emitClose, this); return; } if (cb) this.once('close', cb); if (this._state === CLOSING) return; this._state = CLOSING; if (this.options.noServer || this.options.server) { if (this._server) { this._removeListeners(); this._removeListeners = this._server = null; } if (this.clients) { if (!this.clients.size) { process.nextTick(emitClose, this); } else { this._shouldEmitClose = true; } } else { process.nextTick(emitClose, this); } } else { const server = this._server; this._removeListeners(); this._removeListeners = this._server = null; // // The HTTP/S server was created internally. Close it, and rely on its // `'close'` event. // server.close(() => { emitClose(this); }); } } /** * See if a given request should be handled by this server instance. * * @param {http.IncomingMessage} req Request object to inspect * @return {Boolean} `true` if the request is valid, else `false` * @public */ shouldHandle(req) { if (this.options.path) { const index = req.url.indexOf('?'); const pathname = index !== -1 ? req.url.slice(0, index) : req.url; if (pathname !== this.options.path) return false; } return true; } /** * Handle a HTTP Upgrade request. * * @param {http.IncomingMessage} req The request object * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @public */ handleUpgrade(req, socket, head, cb) { socket.on('error', socketOnError); const key = req.headers['sec-websocket-key']; const upgrade = req.headers.upgrade; const version = +req.headers['sec-websocket-version']; if (req.method !== 'GET') { const message = 'Invalid HTTP method'; abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); return; } if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { const message = 'Invalid Upgrade header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (key === undefined || !keyRegex.test(key)) { const message = 'Missing or invalid Sec-WebSocket-Key header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } if (version !== 13 && version !== 8) { const message = 'Missing or invalid Sec-WebSocket-Version header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, { 'Sec-WebSocket-Version': '13, 8' }); return; } if (!this.shouldHandle(req)) { abortHandshake(socket, 400); return; } const secWebSocketProtocol = req.headers['sec-websocket-protocol']; let protocols = new Set(); if (secWebSocketProtocol !== undefined) { try { protocols = subprotocol.parse(secWebSocketProtocol); } catch (err) { const message = 'Invalid Sec-WebSocket-Protocol header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } } const secWebSocketExtensions = req.headers['sec-websocket-extensions']; const extensions = {}; if ( this.options.perMessageDeflate && secWebSocketExtensions !== undefined ) { const perMessageDeflate = new PerMessageDeflate({ ...this.options.perMessageDeflate, isServer: true, maxPayload: this.options.maxPayload }); try { const offers = extension.parse(secWebSocketExtensions); if (offers[PerMessageDeflate.extensionName]) { perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } } catch (err) { const message = 'Invalid or unacceptable Sec-WebSocket-Extensions header'; abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); return; } } // // Optionally call external client verification handler. // if (this.options.verifyClient) { const info = { origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], secure: !!(req.socket.authorized || req.socket.encrypted), req }; if (this.options.verifyClient.length === 2) { this.options.verifyClient(info, (verified, code, message, headers) => { if (!verified) { return abortHandshake(socket, code || 401, message, headers); } this.completeUpgrade( extensions, key, protocols, req, socket, head, cb ); }); return; } if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); } this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); } /** * Upgrade the connection to WebSocket. * * @param {Object} extensions The accepted extensions * @param {String} key The value of the `Sec-WebSocket-Key` header * @param {Set} protocols The subprotocols * @param {http.IncomingMessage} req The request object * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Function} cb Callback * @throws {Error} If called more than once with the same socket * @private */ completeUpgrade(extensions, key, protocols, req, socket, head, cb) { // // Destroy the socket if the client has already sent a FIN packet. // if (!socket.readable || !socket.writable) return socket.destroy(); if (socket[kWebSocket]) { throw new Error( 'server.handleUpgrade() was called more than once with the same ' + 'socket, possibly due to a misconfiguration' ); } if (this._state > RUNNING) return abortHandshake(socket, 503); const digest = createHash('sha1') .update(key + GUID) .digest('base64'); const headers = [ 'HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Accept: ${digest}` ]; const ws = new this.options.WebSocket(null, undefined, this.options); if (protocols.size) { // // Optionally call external protocol selection handler. // const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value; if (protocol) { headers.push(`Sec-WebSocket-Protocol: ${protocol}`); ws._protocol = protocol; } } if (extensions[PerMessageDeflate.extensionName]) { const params = extensions[PerMessageDeflate.extensionName].params; const value = extension.format({ [PerMessageDeflate.extensionName]: [params] }); headers.push(`Sec-WebSocket-Extensions: ${value}`); ws._extensions = extensions; } // // Allow external modification/inspection of handshake headers. // this.emit('headers', headers, req); socket.write(headers.concat('\r\n').join('\r\n')); socket.removeListener('error', socketOnError); ws.setSocket(socket, head, { allowSynchronousEvents: this.options.allowSynchronousEvents, maxPayload: this.options.maxPayload, skipUTF8Validation: this.options.skipUTF8Validation }); if (this.clients) { this.clients.add(ws); ws.on('close', () => { this.clients.delete(ws); if (this._shouldEmitClose && !this.clients.size) { process.nextTick(emitClose, this); } }); } cb(ws, req); } } module.exports = WebSocketServer; /** * Add event listeners on an `EventEmitter` using a map of * pairs. * * @param {EventEmitter} server The event emitter * @param {Object.} map The listeners to add * @return {Function} A function that will remove the added listeners when * called * @private */ function addListeners(server, map) { for (const event of Object.keys(map)) server.on(event, map[event]); return function removeListeners() { for (const event of Object.keys(map)) { server.removeListener(event, map[event]); } }; } /** * Emit a `'close'` event on an `EventEmitter`. * * @param {EventEmitter} server The event emitter * @private */ function emitClose(server) { server._state = CLOSED; server.emit('close'); } /** * Handle socket errors. * * @private */ function socketOnError() { this.destroy(); } /** * Close the connection when preconditions are not fulfilled. * * @param {Duplex} socket The socket of the upgrade request * @param {Number} code The HTTP response status code * @param {String} [message] The HTTP response body * @param {Object} [headers] Additional HTTP response headers * @private */ function abortHandshake(socket, code, message, headers) { // // The socket is writable unless the user destroyed or ended it before calling // `server.handleUpgrade()` or in the `verifyClient` function, which is a user // error. Handling this does not make much sense as the worst that can happen // is that some of the data written by the user might be discarded due to the // call to `socket.end()` below, which triggers an `'error'` event that in // turn causes the socket to be destroyed. // message = message || http.STATUS_CODES[code]; headers = { Connection: 'close', 'Content-Type': 'text/html', 'Content-Length': Buffer.byteLength(message), ...headers }; socket.once('finish', socket.destroy); socket.end( `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + Object.keys(headers) .map((h) => `${h}: ${headers[h]}`) .join('\r\n') + '\r\n\r\n' + message ); } /** * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least * one listener for it, otherwise call `abortHandshake()`. * * @param {WebSocketServer} server The WebSocket server * @param {http.IncomingMessage} req The request object * @param {Duplex} socket The socket of the upgrade request * @param {Number} code The HTTP response status code * @param {String} message The HTTP response body * @param {Object} [headers] The HTTP response headers * @private */ function abortHandshakeOrEmitwsClientError( server, req, socket, code, message, headers ) { if (server.listenerCount('wsClientError')) { const err = new Error(message); Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); server.emit('wsClientError', err, socket, req); } else { abortHandshake(socket, code, message, headers); } } /***/ }), /***/ 6681: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */ const EventEmitter = __nccwpck_require__(4434); const https = __nccwpck_require__(5692); const http = __nccwpck_require__(8611); const net = __nccwpck_require__(9278); const tls = __nccwpck_require__(4756); const { randomBytes, createHash } = __nccwpck_require__(6982); const { Duplex, Readable } = __nccwpck_require__(2203); const { URL } = __nccwpck_require__(7016); const PerMessageDeflate = __nccwpck_require__(4376); const Receiver = __nccwpck_require__(893); const Sender = __nccwpck_require__(7389); const { isBlob } = __nccwpck_require__(6615); const { BINARY_TYPES, CLOSE_TIMEOUT, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = __nccwpck_require__(1791); const { EventTarget: { addEventListener, removeEventListener } } = __nccwpck_require__(4634); const { format, parse } = __nccwpck_require__(1335); const { toBuffer } = __nccwpck_require__(5803); const kAborted = Symbol('kAborted'); const protocolVersions = [8, 13]; const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; /** * Class representing a WebSocket. * * @extends EventEmitter */ class WebSocket extends EventEmitter { /** * Create a new `WebSocket`. * * @param {(String|URL)} address The URL to which to connect * @param {(String|String[])} [protocols] The subprotocols * @param {Object} [options] Connection options */ constructor(address, protocols, options) { super(); this._binaryType = BINARY_TYPES[0]; this._closeCode = 1006; this._closeFrameReceived = false; this._closeFrameSent = false; this._closeMessage = EMPTY_BUFFER; this._closeTimer = null; this._errorEmitted = false; this._extensions = {}; this._paused = false; this._protocol = ''; this._readyState = WebSocket.CONNECTING; this._receiver = null; this._sender = null; this._socket = null; if (address !== null) { this._bufferedAmount = 0; this._isServer = false; this._redirects = 0; if (protocols === undefined) { protocols = []; } else if (!Array.isArray(protocols)) { if (typeof protocols === 'object' && protocols !== null) { options = protocols; protocols = []; } else { protocols = [protocols]; } } initAsClient(this, address, protocols, options); } else { this._autoPong = options.autoPong; this._closeTimeout = options.closeTimeout; this._isServer = true; } } /** * For historical reasons, the custom "nodebuffer" type is used by the default * instead of "blob". * * @type {String} */ get binaryType() { return this._binaryType; } set binaryType(type) { if (!BINARY_TYPES.includes(type)) return; this._binaryType = type; // // Allow to change `binaryType` on the fly. // if (this._receiver) this._receiver._binaryType = type; } /** * @type {Number} */ get bufferedAmount() { if (!this._socket) return this._bufferedAmount; return this._socket._writableState.length + this._sender._bufferedBytes; } /** * @type {String} */ get extensions() { return Object.keys(this._extensions).join(); } /** * @type {Boolean} */ get isPaused() { return this._paused; } /** * @type {Function} */ /* istanbul ignore next */ get onclose() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onerror() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onopen() { return null; } /** * @type {Function} */ /* istanbul ignore next */ get onmessage() { return null; } /** * @type {String} */ get protocol() { return this._protocol; } /** * @type {Number} */ get readyState() { return this._readyState; } /** * @type {String} */ get url() { return this._url; } /** * Set up the socket and the internal resources. * * @param {Duplex} socket The network socket between the server and client * @param {Buffer} head The first packet of the upgraded stream * @param {Object} options Options object * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted * multiple times in the same tick * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Number} [options.maxPayload=0] The maximum allowed message size * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @private */ setSocket(socket, head, options) { const receiver = new Receiver({ allowSynchronousEvents: options.allowSynchronousEvents, binaryType: this.binaryType, extensions: this._extensions, isServer: this._isServer, maxPayload: options.maxPayload, skipUTF8Validation: options.skipUTF8Validation }); const sender = new Sender(socket, this._extensions, options.generateMask); this._receiver = receiver; this._sender = sender; this._socket = socket; receiver[kWebSocket] = this; sender[kWebSocket] = this; socket[kWebSocket] = this; receiver.on('conclude', receiverOnConclude); receiver.on('drain', receiverOnDrain); receiver.on('error', receiverOnError); receiver.on('message', receiverOnMessage); receiver.on('ping', receiverOnPing); receiver.on('pong', receiverOnPong); sender.onerror = senderOnError; // // These methods may not be available if `socket` is just a `Duplex`. // if (socket.setTimeout) socket.setTimeout(0); if (socket.setNoDelay) socket.setNoDelay(); if (head.length > 0) socket.unshift(head); socket.on('close', socketOnClose); socket.on('data', socketOnData); socket.on('end', socketOnEnd); socket.on('error', socketOnError); this._readyState = WebSocket.OPEN; this.emit('open'); } /** * Emit the `'close'` event. * * @private */ emitClose() { if (!this._socket) { this._readyState = WebSocket.CLOSED; this.emit('close', this._closeCode, this._closeMessage); return; } if (this._extensions[PerMessageDeflate.extensionName]) { this._extensions[PerMessageDeflate.extensionName].cleanup(); } this._receiver.removeAllListeners(); this._readyState = WebSocket.CLOSED; this.emit('close', this._closeCode, this._closeMessage); } /** * Start a closing handshake. * * +----------+ +-----------+ +----------+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - * | +----------+ +-----------+ +----------+ | * +----------+ +-----------+ | * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING * +----------+ +-----------+ | * | | | +---+ | * +------------------------+-->|fin| - - - - * | +---+ | +---+ * - - - - -|fin|<---------------------+ * +---+ * * @param {Number} [code] Status code explaining why the connection is closing * @param {(String|Buffer)} [data] The reason why the connection is * closing * @public */ close(code, data) { if (this.readyState === WebSocket.CLOSED) return; if (this.readyState === WebSocket.CONNECTING) { const msg = 'WebSocket was closed before the connection was established'; abortHandshake(this, this._req, msg); return; } if (this.readyState === WebSocket.CLOSING) { if ( this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted) ) { this._socket.end(); } return; } this._readyState = WebSocket.CLOSING; this._sender.close(code, data, !this._isServer, (err) => { // // This error is handled by the `'error'` listener on the socket. We only // want to know if the close frame has been sent here. // if (err) return; this._closeFrameSent = true; if ( this._closeFrameReceived || this._receiver._writableState.errorEmitted ) { this._socket.end(); } }); setCloseTimer(this); } /** * Pause the socket. * * @public */ pause() { if ( this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED ) { return; } this._paused = true; this._socket.pause(); } /** * Send a ping. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the ping is sent * @public */ ping(data, mask, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof data === 'function') { cb = data; data = mask = undefined; } else if (typeof mask === 'function') { cb = mask; mask = undefined; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === undefined) mask = !this._isServer; this._sender.ping(data || EMPTY_BUFFER, mask, cb); } /** * Send a pong. * * @param {*} [data] The data to send * @param {Boolean} [mask] Indicates whether or not to mask `data` * @param {Function} [cb] Callback which is executed when the pong is sent * @public */ pong(data, mask, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof data === 'function') { cb = data; data = mask = undefined; } else if (typeof mask === 'function') { cb = mask; mask = undefined; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } if (mask === undefined) mask = !this._isServer; this._sender.pong(data || EMPTY_BUFFER, mask, cb); } /** * Resume the socket. * * @public */ resume() { if ( this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED ) { return; } this._paused = false; if (!this._receiver._writableState.needDrain) this._socket.resume(); } /** * Send a data message. * * @param {*} data The message to send * @param {Object} [options] Options object * @param {Boolean} [options.binary] Specifies whether `data` is binary or * text * @param {Boolean} [options.compress] Specifies whether or not to compress * `data` * @param {Boolean} [options.fin=true] Specifies whether the fragment is the * last one * @param {Boolean} [options.mask] Specifies whether or not to mask `data` * @param {Function} [cb] Callback which is executed when data is written out * @public */ send(data, options, cb) { if (this.readyState === WebSocket.CONNECTING) { throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); } if (typeof options === 'function') { cb = options; options = {}; } if (typeof data === 'number') data = data.toString(); if (this.readyState !== WebSocket.OPEN) { sendAfterClose(this, data, cb); return; } const opts = { binary: typeof data !== 'string', mask: !this._isServer, compress: true, fin: true, ...options }; if (!this._extensions[PerMessageDeflate.extensionName]) { opts.compress = false; } this._sender.send(data || EMPTY_BUFFER, opts, cb); } /** * Forcibly close the connection. * * @public */ terminate() { if (this.readyState === WebSocket.CLOSED) return; if (this.readyState === WebSocket.CONNECTING) { const msg = 'WebSocket was closed before the connection was established'; abortHandshake(this, this._req, msg); return; } if (this._socket) { this._readyState = WebSocket.CLOSING; this._socket.destroy(); } } } /** * @constant {Number} CONNECTING * @memberof WebSocket */ Object.defineProperty(WebSocket, 'CONNECTING', { enumerable: true, value: readyStates.indexOf('CONNECTING') }); /** * @constant {Number} CONNECTING * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket.prototype, 'CONNECTING', { enumerable: true, value: readyStates.indexOf('CONNECTING') }); /** * @constant {Number} OPEN * @memberof WebSocket */ Object.defineProperty(WebSocket, 'OPEN', { enumerable: true, value: readyStates.indexOf('OPEN') }); /** * @constant {Number} OPEN * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket.prototype, 'OPEN', { enumerable: true, value: readyStates.indexOf('OPEN') }); /** * @constant {Number} CLOSING * @memberof WebSocket */ Object.defineProperty(WebSocket, 'CLOSING', { enumerable: true, value: readyStates.indexOf('CLOSING') }); /** * @constant {Number} CLOSING * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket.prototype, 'CLOSING', { enumerable: true, value: readyStates.indexOf('CLOSING') }); /** * @constant {Number} CLOSED * @memberof WebSocket */ Object.defineProperty(WebSocket, 'CLOSED', { enumerable: true, value: readyStates.indexOf('CLOSED') }); /** * @constant {Number} CLOSED * @memberof WebSocket.prototype */ Object.defineProperty(WebSocket.prototype, 'CLOSED', { enumerable: true, value: readyStates.indexOf('CLOSED') }); [ 'binaryType', 'bufferedAmount', 'extensions', 'isPaused', 'protocol', 'readyState', 'url' ].forEach((property) => { Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); }); // // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface // ['open', 'error', 'close', 'message'].forEach((method) => { Object.defineProperty(WebSocket.prototype, `on${method}`, { enumerable: true, get() { for (const listener of this.listeners(method)) { if (listener[kForOnEventAttribute]) return listener[kListener]; } return null; }, set(handler) { for (const listener of this.listeners(method)) { if (listener[kForOnEventAttribute]) { this.removeListener(method, listener); break; } } if (typeof handler !== 'function') return; this.addEventListener(method, handler, { [kForOnEventAttribute]: true }); } }); }); WebSocket.prototype.addEventListener = addEventListener; WebSocket.prototype.removeEventListener = removeEventListener; module.exports = WebSocket; /** * Initialize a WebSocket client. * * @param {WebSocket} websocket The client to initialize * @param {(String|URL)} address The URL to which to connect * @param {Array} protocols The subprotocols * @param {Object} [options] Connection options * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple * times in the same tick * @param {Boolean} [options.autoPong=true] Specifies whether or not to * automatically send a pong in response to a ping * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait * for the closing handshake to finish after `websocket.close()` is called * @param {Function} [options.finishRequest] A function which can be used to * customize the headers of each http request before it is sent * @param {Boolean} [options.followRedirects=false] Whether or not to follow * redirects * @param {Function} [options.generateMask] The function used to generate the * masking key * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the * handshake request * @param {Number} [options.maxPayload=104857600] The maximum allowed message * size * @param {Number} [options.maxRedirects=10] The maximum number of redirects * allowed * @param {String} [options.origin] Value of the `Origin` or * `Sec-WebSocket-Origin` header * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable * permessage-deflate * @param {Number} [options.protocolVersion=13] Value of the * `Sec-WebSocket-Version` header * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or * not to skip UTF-8 validation for text and close messages * @private */ function initAsClient(websocket, address, protocols, options) { const opts = { allowSynchronousEvents: true, autoPong: true, closeTimeout: CLOSE_TIMEOUT, protocolVersion: protocolVersions[1], maxPayload: 100 * 1024 * 1024, skipUTF8Validation: false, perMessageDeflate: true, followRedirects: false, maxRedirects: 10, ...options, socketPath: undefined, hostname: undefined, protocol: undefined, timeout: undefined, method: 'GET', host: undefined, path: undefined, port: undefined }; websocket._autoPong = opts.autoPong; websocket._closeTimeout = opts.closeTimeout; if (!protocolVersions.includes(opts.protocolVersion)) { throw new RangeError( `Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(', ')})` ); } let parsedUrl; if (address instanceof URL) { parsedUrl = address; } else { try { parsedUrl = new URL(address); } catch { throw new SyntaxError(`Invalid URL: ${address}`); } } if (parsedUrl.protocol === 'http:') { parsedUrl.protocol = 'ws:'; } else if (parsedUrl.protocol === 'https:') { parsedUrl.protocol = 'wss:'; } websocket._url = parsedUrl.href; const isSecure = parsedUrl.protocol === 'wss:'; const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; let invalidUrlMessage; if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { invalidUrlMessage = 'The URL\'s protocol must be one of "ws:", "wss:", ' + '"http:", "https:", or "ws+unix:"'; } else if (isIpcUrl && !parsedUrl.pathname) { invalidUrlMessage = "The URL's pathname is empty"; } else if (parsedUrl.hash) { invalidUrlMessage = 'The URL contains a fragment identifier'; } if (invalidUrlMessage) { const err = new SyntaxError(invalidUrlMessage); if (websocket._redirects === 0) { throw err; } else { emitErrorAndClose(websocket, err); return; } } const defaultPort = isSecure ? 443 : 80; const key = randomBytes(16).toString('base64'); const request = isSecure ? https.request : http.request; const protocolSet = new Set(); let perMessageDeflate; opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect); opts.defaultPort = opts.defaultPort || defaultPort; opts.port = parsedUrl.port || defaultPort; opts.host = parsedUrl.hostname.startsWith('[') ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; opts.headers = { ...opts.headers, 'Sec-WebSocket-Version': opts.protocolVersion, 'Sec-WebSocket-Key': key, Connection: 'Upgrade', Upgrade: 'websocket' }; opts.path = parsedUrl.pathname + parsedUrl.search; opts.timeout = opts.handshakeTimeout; if (opts.perMessageDeflate) { perMessageDeflate = new PerMessageDeflate({ ...opts.perMessageDeflate, isServer: false, maxPayload: opts.maxPayload }); opts.headers['Sec-WebSocket-Extensions'] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() }); } if (protocols.length) { for (const protocol of protocols) { if ( typeof protocol !== 'string' || !subprotocolRegex.test(protocol) || protocolSet.has(protocol) ) { throw new SyntaxError( 'An invalid or duplicated subprotocol was specified' ); } protocolSet.add(protocol); } opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); } if (opts.origin) { if (opts.protocolVersion < 13) { opts.headers['Sec-WebSocket-Origin'] = opts.origin; } else { opts.headers.Origin = opts.origin; } } if (parsedUrl.username || parsedUrl.password) { opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; } if (isIpcUrl) { const parts = opts.path.split(':'); opts.socketPath = parts[0]; opts.path = parts[1]; } let req; if (opts.followRedirects) { if (websocket._redirects === 0) { websocket._originalIpc = isIpcUrl; websocket._originalSecure = isSecure; websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host; const headers = options && options.headers; // // Shallow copy the user provided options so that headers can be changed // without mutating the original object. // options = { ...options, headers: {} }; if (headers) { for (const [key, value] of Object.entries(headers)) { options.headers[key.toLowerCase()] = value; } } } else if (websocket.listenerCount('redirect') === 0) { const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath; if (!isSameHost || (websocket._originalSecure && !isSecure)) { // // Match curl 7.77.0 behavior and drop the following headers. These // headers are also dropped when following a redirect to a subdomain. // delete opts.headers.authorization; delete opts.headers.cookie; if (!isSameHost) delete opts.headers.host; opts.auth = undefined; } } // // Match curl 7.77.0 behavior and make the first `Authorization` header win. // If the `Authorization` header is set, then there is nothing to do as it // will take precedence. // if (opts.auth && !options.headers.authorization) { options.headers.authorization = 'Basic ' + Buffer.from(opts.auth).toString('base64'); } req = websocket._req = request(opts); if (websocket._redirects) { // // Unlike what is done for the `'upgrade'` event, no early exit is // triggered here if the user calls `websocket.close()` or // `websocket.terminate()` from a listener of the `'redirect'` event. This // is because the user can also call `request.destroy()` with an error // before calling `websocket.close()` or `websocket.terminate()` and this // would result in an error being emitted on the `request` object with no // `'error'` event listeners attached. // websocket.emit('redirect', websocket.url, req); } } else { req = websocket._req = request(opts); } if (opts.timeout) { req.on('timeout', () => { abortHandshake(websocket, req, 'Opening handshake has timed out'); }); } req.on('error', (err) => { if (req === null || req[kAborted]) return; req = websocket._req = null; emitErrorAndClose(websocket, err); }); req.on('response', (res) => { const location = res.headers.location; const statusCode = res.statusCode; if ( location && opts.followRedirects && statusCode >= 300 && statusCode < 400 ) { if (++websocket._redirects > opts.maxRedirects) { abortHandshake(websocket, req, 'Maximum redirects exceeded'); return; } req.abort(); let addr; try { addr = new URL(location, address); } catch (e) { const err = new SyntaxError(`Invalid URL: ${location}`); emitErrorAndClose(websocket, err); return; } initAsClient(websocket, addr, protocols, options); } else if (!websocket.emit('unexpected-response', req, res)) { abortHandshake( websocket, req, `Unexpected server response: ${res.statusCode}` ); } }); req.on('upgrade', (res, socket, head) => { websocket.emit('upgrade', res); // // The user may have closed the connection from a listener of the // `'upgrade'` event. // if (websocket.readyState !== WebSocket.CONNECTING) return; req = websocket._req = null; const upgrade = res.headers.upgrade; if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { abortHandshake(websocket, socket, 'Invalid Upgrade header'); return; } const digest = createHash('sha1') .update(key + GUID) .digest('base64'); if (res.headers['sec-websocket-accept'] !== digest) { abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); return; } const serverProt = res.headers['sec-websocket-protocol']; let protError; if (serverProt !== undefined) { if (!protocolSet.size) { protError = 'Server sent a subprotocol but none was requested'; } else if (!protocolSet.has(serverProt)) { protError = 'Server sent an invalid subprotocol'; } } else if (protocolSet.size) { protError = 'Server sent no subprotocol'; } if (protError) { abortHandshake(websocket, socket, protError); return; } if (serverProt) websocket._protocol = serverProt; const secWebSocketExtensions = res.headers['sec-websocket-extensions']; if (secWebSocketExtensions !== undefined) { if (!perMessageDeflate) { const message = 'Server sent a Sec-WebSocket-Extensions header but no extension ' + 'was requested'; abortHandshake(websocket, socket, message); return; } let extensions; try { extensions = parse(secWebSocketExtensions); } catch (err) { const message = 'Invalid Sec-WebSocket-Extensions header'; abortHandshake(websocket, socket, message); return; } const extensionNames = Object.keys(extensions); if ( extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName ) { const message = 'Server indicated an extension that was not requested'; abortHandshake(websocket, socket, message); return; } try { perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); } catch (err) { const message = 'Invalid Sec-WebSocket-Extensions header'; abortHandshake(websocket, socket, message); return; } websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } websocket.setSocket(socket, head, { allowSynchronousEvents: opts.allowSynchronousEvents, generateMask: opts.generateMask, maxPayload: opts.maxPayload, skipUTF8Validation: opts.skipUTF8Validation }); }); if (opts.finishRequest) { opts.finishRequest(req, websocket); } else { req.end(); } } /** * Emit the `'error'` and `'close'` events. * * @param {WebSocket} websocket The WebSocket instance * @param {Error} The error to emit * @private */ function emitErrorAndClose(websocket, err) { websocket._readyState = WebSocket.CLOSING; // // The following assignment is practically useless and is done only for // consistency. // websocket._errorEmitted = true; websocket.emit('error', err); websocket.emitClose(); } /** * Create a `net.Socket` and initiate a connection. * * @param {Object} options Connection options * @return {net.Socket} The newly created socket used to start the connection * @private */ function netConnect(options) { options.path = options.socketPath; return net.connect(options); } /** * Create a `tls.TLSSocket` and initiate a connection. * * @param {Object} options Connection options * @return {tls.TLSSocket} The newly created socket used to start the connection * @private */ function tlsConnect(options) { options.path = undefined; if (!options.servername && options.servername !== '') { options.servername = net.isIP(options.host) ? '' : options.host; } return tls.connect(options); } /** * Abort the handshake and emit an error. * * @param {WebSocket} websocket The WebSocket instance * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to * abort or the socket to destroy * @param {String} message The error message * @private */ function abortHandshake(websocket, stream, message) { websocket._readyState = WebSocket.CLOSING; const err = new Error(message); Error.captureStackTrace(err, abortHandshake); if (stream.setHeader) { stream[kAborted] = true; stream.abort(); if (stream.socket && !stream.socket.destroyed) { // // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if // called after the request completed. See // https://github.com/websockets/ws/issues/1869. // stream.socket.destroy(); } process.nextTick(emitErrorAndClose, websocket, err); } else { stream.destroy(err); stream.once('error', websocket.emit.bind(websocket, 'error')); stream.once('close', websocket.emitClose.bind(websocket)); } } /** * Handle cases where the `ping()`, `pong()`, or `send()` methods are called * when the `readyState` attribute is `CLOSING` or `CLOSED`. * * @param {WebSocket} websocket The WebSocket instance * @param {*} [data] The data to send * @param {Function} [cb] Callback * @private */ function sendAfterClose(websocket, data, cb) { if (data) { const length = isBlob(data) ? data.size : toBuffer(data).length; // // The `_bufferedAmount` property is used only when the peer is a client and // the opening handshake fails. Under these circumstances, in fact, the // `setSocket()` method is not called, so the `_socket` and `_sender` // properties are set to `null`. // if (websocket._socket) websocket._sender._bufferedBytes += length; else websocket._bufferedAmount += length; } if (cb) { const err = new Error( `WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})` ); process.nextTick(cb, err); } } /** * The listener of the `Receiver` `'conclude'` event. * * @param {Number} code The status code * @param {Buffer} reason The reason for closing * @private */ function receiverOnConclude(code, reason) { const websocket = this[kWebSocket]; websocket._closeFrameReceived = true; websocket._closeMessage = reason; websocket._closeCode = code; if (websocket._socket[kWebSocket] === undefined) return; websocket._socket.removeListener('data', socketOnData); process.nextTick(resume, websocket._socket); if (code === 1005) websocket.close(); else websocket.close(code, reason); } /** * The listener of the `Receiver` `'drain'` event. * * @private */ function receiverOnDrain() { const websocket = this[kWebSocket]; if (!websocket.isPaused) websocket._socket.resume(); } /** * The listener of the `Receiver` `'error'` event. * * @param {(RangeError|Error)} err The emitted error * @private */ function receiverOnError(err) { const websocket = this[kWebSocket]; if (websocket._socket[kWebSocket] !== undefined) { websocket._socket.removeListener('data', socketOnData); // // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See // https://github.com/websockets/ws/issues/1940. // process.nextTick(resume, websocket._socket); websocket.close(err[kStatusCode]); } if (!websocket._errorEmitted) { websocket._errorEmitted = true; websocket.emit('error', err); } } /** * The listener of the `Receiver` `'finish'` event. * * @private */ function receiverOnFinish() { this[kWebSocket].emitClose(); } /** * The listener of the `Receiver` `'message'` event. * * @param {Buffer|ArrayBuffer|Buffer[])} data The message * @param {Boolean} isBinary Specifies whether the message is binary or not * @private */ function receiverOnMessage(data, isBinary) { this[kWebSocket].emit('message', data, isBinary); } /** * The listener of the `Receiver` `'ping'` event. * * @param {Buffer} data The data included in the ping frame * @private */ function receiverOnPing(data) { const websocket = this[kWebSocket]; if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP); websocket.emit('ping', data); } /** * The listener of the `Receiver` `'pong'` event. * * @param {Buffer} data The data included in the pong frame * @private */ function receiverOnPong(data) { this[kWebSocket].emit('pong', data); } /** * Resume a readable stream * * @param {Readable} stream The readable stream * @private */ function resume(stream) { stream.resume(); } /** * The `Sender` error event handler. * * @param {Error} The error * @private */ function senderOnError(err) { const websocket = this[kWebSocket]; if (websocket.readyState === WebSocket.CLOSED) return; if (websocket.readyState === WebSocket.OPEN) { websocket._readyState = WebSocket.CLOSING; setCloseTimer(websocket); } // // `socket.end()` is used instead of `socket.destroy()` to allow the other // peer to finish sending queued data. There is no need to set a timer here // because `CLOSING` means that it is already set or not needed. // this._socket.end(); if (!websocket._errorEmitted) { websocket._errorEmitted = true; websocket.emit('error', err); } } /** * Set a timer to destroy the underlying raw socket of a WebSocket. * * @param {WebSocket} websocket The WebSocket instance * @private */ function setCloseTimer(websocket) { websocket._closeTimer = setTimeout( websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout ); } /** * The listener of the socket `'close'` event. * * @private */ function socketOnClose() { const websocket = this[kWebSocket]; this.removeListener('close', socketOnClose); this.removeListener('data', socketOnData); this.removeListener('end', socketOnEnd); websocket._readyState = WebSocket.CLOSING; // // The close frame might not have been received or the `'end'` event emitted, // for example, if the socket was destroyed due to an error. Ensure that the // `receiver` stream is closed after writing any remaining buffered data to // it. If the readable side of the socket is in flowing mode then there is no // buffered data as everything has been already written. If instead, the // socket is paused, any possible buffered data will be read as a single // chunk. // if ( !this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0 ) { const chunk = this.read(this._readableState.length); websocket._receiver.write(chunk); } websocket._receiver.end(); this[kWebSocket] = undefined; clearTimeout(websocket._closeTimer); if ( websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted ) { websocket.emitClose(); } else { websocket._receiver.on('error', receiverOnFinish); websocket._receiver.on('finish', receiverOnFinish); } } /** * The listener of the socket `'data'` event. * * @param {Buffer} chunk A chunk of data * @private */ function socketOnData(chunk) { if (!this[kWebSocket]._receiver.write(chunk)) { this.pause(); } } /** * The listener of the socket `'end'` event. * * @private */ function socketOnEnd() { const websocket = this[kWebSocket]; websocket._readyState = WebSocket.CLOSING; websocket._receiver.end(); this.end(); } /** * The listener of the socket `'error'` event. * * @private */ function socketOnError() { const websocket = this[kWebSocket]; this.removeListener('error', socketOnError); this.on('error', NOOP); if (websocket) { websocket._readyState = WebSocket.CLOSING; this.destroy(); } } /***/ }), /***/ 869: /***/ ((module) => { module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (hasOwnProperty.call(source, key)) { target[key] = source[key] } } } return target } /***/ }), /***/ 8327: /***/ ((module) => { module.exports = eval("require")("bufferutil"); /***/ }), /***/ 2414: /***/ ((module) => { module.exports = eval("require")("utf-8-validate"); /***/ }), /***/ 2613: /***/ ((module) => { "use strict"; module.exports = require("assert"); /***/ }), /***/ 181: /***/ ((module) => { "use strict"; module.exports = require("buffer"); /***/ }), /***/ 6982: /***/ ((module) => { "use strict"; module.exports = require("crypto"); /***/ }), /***/ 2250: /***/ ((module) => { "use strict"; module.exports = require("dns"); /***/ }), /***/ 4434: /***/ ((module) => { "use strict"; module.exports = require("events"); /***/ }), /***/ 9896: /***/ ((module) => { "use strict"; module.exports = require("fs"); /***/ }), /***/ 8611: /***/ ((module) => { "use strict"; module.exports = require("http"); /***/ }), /***/ 5692: /***/ ((module) => { "use strict"; module.exports = require("https"); /***/ }), /***/ 9278: /***/ ((module) => { "use strict"; module.exports = require("net"); /***/ }), /***/ 857: /***/ ((module) => { "use strict"; module.exports = require("os"); /***/ }), /***/ 6928: /***/ ((module) => { "use strict"; module.exports = require("path"); /***/ }), /***/ 2203: /***/ ((module) => { "use strict"; module.exports = require("stream"); /***/ }), /***/ 5574: /***/ ((module) => { "use strict"; module.exports = require("string_decoder"); /***/ }), /***/ 4756: /***/ ((module) => { "use strict"; module.exports = require("tls"); /***/ }), /***/ 2018: /***/ ((module) => { "use strict"; module.exports = require("tty"); /***/ }), /***/ 7016: /***/ ((module) => { "use strict"; module.exports = require("url"); /***/ }), /***/ 9023: /***/ ((module) => { "use strict"; module.exports = require("util"); /***/ }), /***/ 3106: /***/ ((module) => { "use strict"; module.exports = require("zlib"); /***/ }), /***/ 6027: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { EventEmitter } = __nccwpck_require__(4434); class AliyunService { constructor(config = {}, logger = console, options = {}) { this.config = config; this.logger = logger; this.fetchImpl = options.fetchImpl || global.fetch; this.aliyunSdk = options.aliyunSdk || null; this.contexts = new Map(); this.started = false; } start() { if (!this.config.enabled) { this.logger.info('[ALIYUN] 阿里云发送未启用'); this.started = false; return; } if (typeof this.fetchImpl !== 'function') { throw new Error('当前 Node 环境不支持 fetch,无法调用三元组接口'); } this.started = true; this.logger.info(`[ALIYUN] 阿里云服务已启用 tupleApi=${this.getTupleUrl()} autoRegister=${this.config.autoRegister === false ? 0 : 1} retryMs=${this.config.registerRetryMs || 60000}`); } async stop() { const closeTasks = []; this.logger.info(`[ALIYUN] 开始停止阿里云服务 contexts=${this.contexts.size}`); for (const context of this.contexts.values()) { this.clearConnectWaiter(context); context.tuplePromise = null; if (context.iotDevice && typeof context.iotDevice.end === 'function') { closeTasks.push(new Promise((resolve) => { try { context.iotDevice.end(false, resolve); } catch (_error) { resolve(); } })); } } await Promise.all(closeTasks); this.contexts.clear(); this.started = false; this.logger.info('[ALIYUN] 阿里云服务已停止'); } normalizeEventPayload(payload) { if (Array.isArray(payload) && payload.length === 1) { return payload[0]; } return payload; } formatErrorMessage(errorLike) { const normalized = this.normalizeEventPayload(errorLike); if (normalized instanceof Error) { return normalized.message || normalized.name || 'unknown-error'; } if (Array.isArray(normalized)) { const parts = normalized .map((item) => this.formatErrorMessage(item)) .filter(Boolean); return parts.length > 0 ? parts.join(' | ') : 'unknown-error'; } if (normalized && typeof normalized === 'object') { if (typeof normalized.message === 'string' && normalized.message) { return normalized.message; } try { return JSON.stringify(normalized); } catch (_error) { return String(normalized); } } if (normalized === undefined || normalized === null || normalized === '') { return 'unknown-error'; } return String(normalized); } shouldLogClose(context) { const throttleMs = this.config.closeLogThrottleMs || 5000; const now = Date.now(); if (context.lastCloseLogAt > 0 && (now - context.lastCloseLogAt) < throttleMs) { return false; } context.lastCloseLogAt = now; return true; } formatSuedtime(date = new Date()) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hour = String(date.getHours()).padStart(2, '0'); const minute = String(date.getMinutes()).padStart(2, '0'); const second = String(date.getSeconds()).padStart(2, '0'); return `${year}-${month}-${day} ${hour}:${minute}:${second}`; } buildPayload(message) { return { ...(message || {}), suedtime: this.formatSuedtime(), }; } getTupleUrl() { if (this.config.tupleApiUrl) { return this.config.tupleApiUrl; } const baseUrl = (this.config.tupleApiBaseUrl || '').replace(/\/$/, ''); const apiPath = this.config.tupleApiPath || '/device/info/getAliyunDeviceSecret'; return `${baseUrl}${apiPath}`; } getAliyunSdk() { if (this.aliyunSdk) { return this.aliyunSdk; } // eslint-disable-next-line global-require this.aliyunSdk = __nccwpck_require__(9871); return this.aliyunSdk; } getContext(device) { const deviceId = device.deviceId; if (!this.contexts.has(deviceId)) { this.contexts.set(deviceId, { deviceId, tuple: null, tuplePromise: null, iotDevice: null, connected: false, hasConnectedOnce: false, connectPromise: null, resolveConnectPromise: null, rejectConnectPromise: null, connectTimer: null, lastRegisterAttempt: 0, lastRegisterError: '', lastPropsError: '', lastCloseLogAt: 0, }); this.logger.info(`[ALIYUN] 创建设备上下文 deviceId=${deviceId}`); } return this.contexts.get(deviceId); } extractTuple(responseBody, deviceId) { const data = responseBody && typeof responseBody === 'object' ? (responseBody.data || responseBody.result || responseBody) : null; if (!data || typeof data !== 'object') { throw new Error('三元组接口返回为空'); } const tuple = { productKey: data.productKey || data.ProductKey || '', deviceName: data.deviceName || data.DeviceName || deviceId, deviceSecret: data.deviceSecret || data.DeviceSecret || '', }; if (!tuple.productKey || !tuple.deviceName || !tuple.deviceSecret) { throw new Error('三元组字段不完整'); } return tuple; } async requestTuple(deviceId) { const url = this.getTupleUrl(); const formData = new URLSearchParams(); formData.set('isAutoRegister', this.config.autoRegister === false ? '0' : '1'); formData.set('deviceName', deviceId); this.logger.info(`[ALIYUN] 开始请求三元组 deviceId=${deviceId} url=${url}`); const response = await this.fetchImpl(url, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: formData.toString(), }); if (!response.ok) { throw new Error(`三元组接口请求失败 HTTP ${response.status}`); } const rawText = await response.text(); let responseBody = null; try { responseBody = JSON.parse(rawText); } catch (_error) { throw new Error('三元组接口返回不是有效 JSON'); } return this.extractTuple(responseBody, deviceId); } async ensureTuple(context, device) { if (context.tuple) { this.logger.info(`[ALIYUN] 复用已缓存三元组 deviceId=${device.deviceId} deviceName=${context.tuple.deviceName}`); return context.tuple; } if (context.tuplePromise) { this.logger.info(`[ALIYUN] 复用三元组请求中的会话 deviceId=${device.deviceId}`); return context.tuplePromise; } const retryMs = this.config.registerRetryMs || 60000; const now = Date.now(); if (context.lastRegisterAttempt > 0 && (now - context.lastRegisterAttempt) < retryMs && context.lastRegisterError) { this.logger.warn(`[ALIYUN] 三元组请求冷却中 deviceId=${device.deviceId} retryMs=${retryMs} lastError=${context.lastRegisterError}`); throw new Error(`阿里云三元组重试冷却中 ${context.lastRegisterError}`); } context.lastRegisterAttempt = now; context.tuplePromise = (async () => { try { const tuple = await this.requestTuple(device.deviceId); context.tuple = tuple; context.lastRegisterError = ''; this.logger.info(`[ALIYUN] 三元组获取成功 deviceId=${device.deviceId} deviceName=${tuple.deviceName}`); return tuple; } catch (error) { context.lastRegisterError = error.message; this.logger.error(`[ALIYUN] 三元组获取失败 deviceId=${device.deviceId}: ${error.message}`); throw error; } finally { context.tuplePromise = null; } })(); return context.tuplePromise; } createIotDevice(tuple) { const sdk = this.getAliyunSdk(); if (!sdk || typeof sdk.device !== 'function') { throw new Error('aliyun-iot-device-sdk 不可用'); } return sdk.device({ ProductKey: tuple.productKey, DeviceName: tuple.deviceName, DeviceSecret: tuple.deviceSecret, }); } clearConnectWaiter(context) { if (context.connectTimer) { clearTimeout(context.connectTimer); } context.connectPromise = null; context.resolveConnectPromise = null; context.rejectConnectPromise = null; context.connectTimer = null; } resolveConnectWaiter(context, iotDevice) { if (!context.connectPromise || typeof context.resolveConnectPromise !== 'function') { return false; } const resolve = context.resolveConnectPromise; this.clearConnectWaiter(context); resolve(iotDevice); return true; } rejectConnectWaiter(context, error) { if (!context.connectPromise || typeof context.rejectConnectPromise !== 'function') { return false; } const reject = context.rejectConnectPromise; this.clearConnectWaiter(context); reject(error instanceof Error ? error : new Error(this.formatErrorMessage(error))); return true; } ensureConnectWaiter(context, device) { if (context.connectPromise) { return context.connectPromise; } const connectTimeoutMs = this.config.connectTimeoutMs || 15000; context.connectPromise = new Promise((resolve, reject) => { context.resolveConnectPromise = resolve; context.rejectConnectPromise = reject; context.connectTimer = setTimeout(() => { this.rejectConnectWaiter(context, new Error('阿里云连接超时')); }, connectTimeoutMs); }); if (context.iotDevice && !context.connected) { this.logger.info(`[ALIYUN] 等待现有设备连接恢复 deviceId=${device.deviceId}`); } return context.connectPromise; } bindIotDeviceEvents(context, device, iotDevice) { const isCurrentDevice = () => context.iotDevice === iotDevice; iotDevice.on('connect', () => { if (!isCurrentDevice()) { return; } const wasConnected = context.connected; const hadConnectedOnce = context.hasConnectedOnce; context.connected = true; context.hasConnectedOnce = true; context.lastCloseLogAt = 0; const resolvedPending = this.resolveConnectWaiter(context, iotDevice); if (resolvedPending) { this.logger.info(`[ALIYUN] ${hadConnectedOnce ? '设备重新连接成功' : '设备连接成功'} deviceId=${device.deviceId}`); return; } if (!wasConnected) { this.logger.info(`[ALIYUN] 设备重新连接成功 deviceId=${device.deviceId}`); } }); iotDevice.on('error', (error) => { if (!isCurrentDevice()) { return; } context.connected = false; this.logger.error(`[ALIYUN] 连接错误 deviceId=${device.deviceId}: ${this.formatErrorMessage(error)}`); this.rejectConnectWaiter(context, error); }); iotDevice.on('reconnect', () => { if (!isCurrentDevice()) { return; } this.logger.info(`[ALIYUN] 正在重连 deviceId=${device.deviceId}`); }); iotDevice.on('offline', () => { if (!isCurrentDevice()) { return; } context.connected = false; this.logger.warn(`[ALIYUN] 连接离线 deviceId=${device.deviceId}`); }); iotDevice.on('close', () => { if (!isCurrentDevice()) { return; } context.connected = false; if (this.shouldLogClose(context)) { this.logger.info(`[ALIYUN] 连接关闭 deviceId=${device.deviceId}`); } }); } async ensureIotDevice(context, device) { if (context.iotDevice && context.connected) { this.logger.info(`[ALIYUN] 复用已连接设备 deviceId=${device.deviceId}`); return context.iotDevice; } if (context.connectPromise) { this.logger.info(`[ALIYUN] 复用连接中的设备会话 deviceId=${device.deviceId}`); return context.connectPromise; } if (!context.iotDevice) { const tuple = await this.ensureTuple(context, device); if (!context.iotDevice) { this.logger.info(`[ALIYUN] 开始创建设备连接 deviceId=${device.deviceId} deviceName=${tuple.deviceName}`); const iotDevice = this.createIotDevice(tuple); context.iotDevice = iotDevice; this.bindIotDeviceEvents(context, device, iotDevice); } } if (context.connected) { return context.iotDevice; } return this.ensureConnectWaiter(context, device); } async postProps(context, device, payload) { const iotDevice = await this.ensureIotDevice(context, device); this.logger.info(`[ALIYUN] 开始属性上报 deviceId=${device.deviceId} keys=${Object.keys(payload).join(',')}`); return new Promise((resolve, reject) => { iotDevice.postProps(payload, (result) => { if (result && (result.message === 'success' || result.success === true || result.code === 200)) { context.lastPropsError = ''; this.logger.info(`[ALIYUN] 属性上报成功 deviceId=${device.deviceId} payload=${JSON.stringify(payload)}`); resolve(result); return; } const errorMessage = result && (result.message || result.code) ? String(result.message || result.code) : '阿里云返回未知错误'; context.lastPropsError = errorMessage; reject(new Error(errorMessage)); }); }); } async publish(device, message) { if (!this.started || !this.config.enabled) { this.logger.warn(`[ALIYUN] 跳过发送 deviceId=${device.deviceId} reason=aliyun-disabled`); return { skipped: true, reason: 'aliyun-disabled' }; } const context = this.getContext(device); const payload = this.buildPayload(message); this.logger.info(`[ALIYUN] 收到发送请求 deviceId=${device.deviceId} payload=${JSON.stringify(payload)}`); try { await this.postProps(context, device, payload); return { ok: true, payload }; } catch (error) { this.logger.error(`[ALIYUN] 属性上报失败 deviceId=${device.deviceId}: ${error.message}`); return { ok: false, reason: error.message, payload }; } } } class FakeAliyunDevice extends EventEmitter { postProps(payload, callback) { callback({ message: 'success', payload }); } } module.exports = { AliyunService, FakeAliyunDevice, }; /***/ }), /***/ 6742: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const fs = __nccwpck_require__(9896); const path = __nccwpck_require__(6928); const { TcpService } = __nccwpck_require__(2632); const { MqttService } = __nccwpck_require__(2189); const { AliyunService } = __nccwpck_require__(6027); const { MetricAggregator } = __nccwpck_require__(7235); const { getDefaultConfigPath } = __nccwpck_require__(9640); const LOG_LEVELS = { debug: 10, info: 20, warn: 30, error: 40, }; function formatLocalTimestamp(date = new Date()) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hour = String(date.getHours()).padStart(2, '0'); const minute = String(date.getMinutes()).padStart(2, '0'); const second = String(date.getSeconds()).padStart(2, '0'); const millisecond = String(date.getMilliseconds()).padStart(3, '0'); return `${year}-${month}-${day} ${hour}:${minute}:${second}.${millisecond}`; } function normalizeLogLevel(level) { const normalized = String(level || 'info').trim().toLowerCase(); return LOG_LEVELS[normalized] ? normalized : 'info'; } function createLogger(loggingConfig = {}) { const settings = { enabled: loggingConfig.enabled !== false, console: loggingConfig.console !== false, dir: loggingConfig.dir || __nccwpck_require__.ab + "logs", filePrefix: loggingConfig.filePrefix || 'jhm-service', level: normalizeLogLevel(loggingConfig.level), }; let currentDate = ''; let currentFilePath = ''; function getDatePart(date = new Date()) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}${month}${day}`; } function ensureLogFilePath() { if (!settings.enabled) { return null; } const today = getDatePart(); if (currentFilePath && currentDate === today) { return currentFilePath; } fs.mkdirSync(settings.dir, { recursive: true }); currentDate = today; currentFilePath = path.join(settings.dir, `${settings.filePrefix}-${today}.log`); return currentFilePath; } function shouldWrite(level) { return LOG_LEVELS[level] >= LOG_LEVELS[settings.level]; } function format(level, message) { return `[${formatLocalTimestamp()}] [${level.toUpperCase()}] ${message}`; } function write(level, message) { const normalizedLevel = normalizeLogLevel(level); if (!shouldWrite(normalizedLevel)) { return; } const line = format(normalizedLevel, message); if (settings.console) { if (normalizedLevel === 'error') { console.error(line); } else if (normalizedLevel === 'warn') { console.warn(line); } else { console.log(line); } } const logFilePath = ensureLogFilePath(); if (logFilePath) { try { fs.appendFileSync(logFilePath, `${line}\n`, 'utf8'); } catch (error) { console.error(`[LOGGER] Failed to append log file: ${error.message}`); } } } return { debug(message) { write('debug', message); }, info(message) { write('info', message); }, warn(message) { write('warn', message); }, error(message) { write('error', message); }, getLogFilePath() { ensureLogFilePath(); return currentFilePath; }, async close() { currentDate = ''; }, }; } function parseArgs(argv) { const options = { configPath: getDefaultConfigPath(), }; for (let index = 2; index < argv.length; index += 1) { const arg = argv[index]; const value = argv[index + 1]; if (arg === '--config' && value) { options.configPath = path.resolve(value); index += 1; } else if (arg === '--help' || arg === '-h') { options.help = true; } } return options; } function printHelp() { console.log(`JHM TCP Socket Gateway Usage: node app.js node app.js --config ./config.json jhm-service.exe --config .\\runtime\\config.json ./jhm-service --config ./runtime/config.json Options: --config set config file path --help, -h show help `); } function loadConfig(configPath) { if (!fs.existsSync(configPath)) { throw new Error(`config file not found: ${configPath}`); } const content = fs.readFileSync(configPath, 'utf8'); const config = JSON.parse(content); validateConfig(config); return config; } function getSendChannels(config) { const channels = Array.isArray(config.send && config.send.channels) ? config.send.channels : ['mqtt']; return Array.from(new Set(channels .map((item) => String(item || '').trim().toLowerCase()) .filter(Boolean))); } function getSendOptions(config) { const send = config.send || {}; const mode = ['immediate', 'batch'].includes(String(send.mode || '').trim().toLowerCase()) ? String(send.mode).trim().toLowerCase() : 'batch'; return { mode, flushIntervalMs: Number(send.flushIntervalMs) > 0 ? Number(send.flushIntervalMs) : 60000, alignToMinute: send.alignToMinute !== false, includeDeviceIdField: send.includeDeviceIdField !== false, deviceIdField: send.deviceIdField || 'n', publishOnShutdown: send.publishOnShutdown !== false, }; } function getBloodPressureOptions(config) { const bloodPressure = config.protocol && config.protocol.bloodPressure; return { publishTime: bloodPressure ? bloodPressure.publishTime !== false : true, }; } function validateConfig(config) { if (!config.tcp || !Array.isArray(config.devices)) { throw new Error('config.json must include tcp and devices'); } if (!config.tcp.host || !config.tcp.port) { throw new Error('config.json must include tcp.host and tcp.port'); } const channels = getSendChannels(config); if (channels.length === 0) { throw new Error('config.json send.channels must enable at least one channel'); } if (channels.includes('mqtt')) { if (!config.mqtt) { throw new Error('config.json enabled mqtt but missing mqtt config'); } const hasBrokerUrl = Boolean(config.mqtt.brokerUrl); const hasHostMode = Boolean(config.mqtt.protocol && config.mqtt.host && config.mqtt.port); if (!hasBrokerUrl && !hasHostMode) { throw new Error('config.json mqtt requires brokerUrl or protocol/host/port'); } if (!config.mqtt.topicTemplate && !config.mqtt.defaultTopicPrefix) { throw new Error('config.json mqtt requires topicTemplate or defaultTopicPrefix'); } } if (channels.includes('aliyun')) { if (!config.aliyun) { throw new Error('config.json enabled aliyun but missing aliyun config'); } if (!config.aliyun.tupleApiBaseUrl && !config.aliyun.tupleApiUrl) { throw new Error('config.json aliyun requires tupleApiBaseUrl or tupleApiUrl'); } } if (!config.protocol || !config.protocol.alModelPath) { throw new Error('config.json protocol.alModelPath is required'); } const sendOptions = getSendOptions(config); if (sendOptions.flushIntervalMs <= 0) { throw new Error('config.json send.flushIntervalMs must be > 0'); } if (config.logging && config.logging.level) { const supportedLevels = ['debug', 'info', 'warn', 'error']; if (!supportedLevels.includes(String(config.logging.level).toLowerCase())) { throw new Error(`config.json logging.level only supports ${supportedLevels.join(', ')}`); } } } function resolveConfigPath(configFilePath, targetPath) { if (path.isAbsolute(targetPath)) { return targetPath; } return path.join(path.dirname(configFilePath), targetPath); } async function main() { const options = parseArgs(process.argv); if (options.help) { printHelp(); return; } const bootstrapLogger = createLogger({ enabled: false, console: true, }); bootstrapLogger.info(`[APP] Startup arguments parsed config=${options.configPath}`); const config = loadConfig(options.configPath); const logDir = resolveConfigPath(options.configPath, (config.logging && config.logging.dir) || './logs'); const logger = createLogger({ ...(config.logging || {}), dir: logDir, }); const sendChannels = getSendChannels(config); const sendOptions = getSendOptions(config); const bloodPressureOptions = getBloodPressureOptions(config); const alModelPath = resolveConfigPath(options.configPath, config.protocol.alModelPath); if (config.logging && config.logging.enabled === false) { logger.info('[APP] File logging is disabled; console output only'); } else { logger.info(`[APP] Local logging enabled dir=${logDir} file=${logger.getLogFilePath()} level=${normalizeLogLevel(config.logging && config.logging.level)}`); } logger.info(`[APP] Config loaded tcp=${config.tcp.host}:${config.tcp.port} devices=${config.devices.length} channels=${sendChannels.join(',')} sendMode=${sendOptions.mode} flushIntervalMs=${sendOptions.flushIntervalMs} alModel=${alModelPath}`); const mqttService = sendChannels.includes('mqtt') ? new MqttService(config.mqtt, logger) : null; const aliyunService = sendChannels.includes('aliyun') ? new AliyunService(config.aliyun, logger) : null; const aggregator = new MetricAggregator({ logger, ...sendOptions, onFlush: async (device, payload, meta) => { logger.info(`[APP] Batch dispatch deviceId=${device.deviceId} channels=${sendChannels.join(',')} reason=${meta.reason} payload=${JSON.stringify(payload)}`); let ok = true; if (mqttService) { try { mqttService.publish(device, payload); } catch (error) { ok = false; logger.error(`[APP] MQTT batch dispatch failed deviceId=${device.deviceId}: ${error.message}`); } } if (aliyunService) { try { const result = await aliyunService.publish(device, payload); if (result && result.skipped) { ok = false; logger.warn(`[APP] Aliyun batch dispatch skipped deviceId=${device.deviceId} reason=${result.reason}`); } else if (result && result.ok === false) { ok = false; logger.error(`[APP] Aliyun batch dispatch failed deviceId=${device.deviceId}: ${result.reason}`); } } catch (error) { ok = false; logger.error(`[APP] Aliyun batch dispatch exception deviceId=${device.deviceId}: ${error.message}`); } } return ok; }, }); const tcpService = new TcpService({ tcpConfig: config.tcp, devices: config.devices, alModelPath, publishBloodPressureTime: bloodPressureOptions.publishTime, logger, onMetric(device, metric) { logger.info(`[APP] Metric cached deviceId=${device.deviceId} mode=${sendOptions.mode} metric=${JSON.stringify(metric)}`); aggregator.ingest(device, metric).catch((error) => { logger.error(`[APP] Metric cache failed deviceId=${device.deviceId}: ${error.message}`); }); }, }); if (mqttService) { logger.info('[APP] Starting MQTT channel'); mqttService.start(); } if (aliyunService) { logger.info('[APP] Starting Aliyun channel'); aliyunService.start(); } aggregator.start(); await tcpService.start(); logger.info('[APP] All services started'); let shuttingDown = false; async function shutdown(signal) { if (shuttingDown) { return; } shuttingDown = true; logger.warn(`[APP] Received ${signal}, shutting down`); await tcpService.stop(); await aggregator.stop(); if (mqttService) { await mqttService.stop(); } if (aliyunService) { await aliyunService.stop(); } logger.info('[APP] Service shutdown completed'); await logger.close(); process.exit(0); } process.on('SIGINT', () => { shutdown('SIGINT'); }); process.on('SIGTERM', () => { shutdown('SIGTERM'); }); process.on('uncaughtException', (error) => { logger.error(`[APP] Uncaught exception: ${error.stack || error.message}`); }); process.on('unhandledRejection', (reason) => { logger.error(`[APP] Unhandled promise rejection: ${reason}`); }); } if (require.main === require.cache[eval('__filename')]) { main().catch((error) => { console.error(error.message); process.exit(1); }); } module.exports = { createLogger, formatLocalTimestamp, getBloodPressureOptions, getSendChannels, getSendOptions, loadConfig, main, normalizeLogLevel, parseArgs, printHelp, resolveConfigPath, validateConfig, }; /***/ }), /***/ 3825: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const fs = __nccwpck_require__(9896); const path = __nccwpck_require__(6928); const JHM_HEADER_1 = 0xEE; const JHM_HEADER_2 = 0x55; const JHM_FRAME_LENGTH = 8; const BP_HEADER_1 = 0xAA; const BP_HEADER_2 = 0x55; const BP_COMMAND = 0xBA; const MIN_HEADER_LENGTH = 2; const COMMAND_RULES = { 0x01: { identifier: 'F', decode: (payload) => uint32BE(payload) / 10 }, 0x02: { identifier: null, decode: (payload) => uint32BE(payload) / 10 }, 0x03: { identifier: 'A', decode: (payload) => mlToL(uint32BE(payload)) }, 0x04: { identifier: 'sysj', decode: (payload) => (uint16BE(payload[0], payload[1]) * 60) + uint16BE(payload[2], payload[3]) }, 0x05: { identifier: 'C', decode: (payload) => mlToL(uint32BE(payload)) }, 0x06: { identifier: 'B', decode: (payload) => mlToL(uint32BE(payload)) }, 0x07: { identifier: 'L', decode: (payload) => uint32BE(payload) }, 0x08: { identifier: 'D', decode: (payload) => uint32BE(payload) }, 0x09: { identifier: 'H', decode: (payload) => signed24WithFlag(payload[0], payload.slice(1)) }, 0x0A: { identifier: 'o', decode: (payload) => signed24WithFlag(payload[0], payload.slice(1)) }, 0x0B: { identifier: 'J', decode: (payload) => signed24WithFlag(payload[0], payload.slice(1)) }, 0x0C: { identifier: 'U', decode: (payload) => uint32BE(payload) }, 0x0D: { identifier: 'G', decode: (payload) => uint24BE(payload.slice(1)) / 10 }, 0x0E: { identifier: 'Na', decode: (payload) => uint32BE(payload) }, 0x0F: { identifier: 'HCO3', decode: (payload) => uint32BE(payload) }, }; function toHex(value) { return `0x${value.toString(16).toUpperCase().padStart(2, '0')}`; } function bytesToHex(buffer) { return Array.from(buffer, toHex).join(' '); } function checksum(command, payload) { return (command + payload[0] + payload[1] + payload[2] + payload[3]) & 0xFF; } function additiveChecksum(bytes) { let sum = 0; for (const value of bytes) { sum = (sum + value) & 0xFF; } return sum; } function uint32BE(bytes) { return ((bytes[0] * 0x1000000) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3]) >>> 0; } function uint24BE(bytes) { return ((bytes[0] << 16) + (bytes[1] << 8) + bytes[2]) >>> 0; } function uint16BE(high, low) { return ((high << 8) | low) >>> 0; } function mlToL(valueInMl) { return Number((valueInMl / 1000).toFixed(3)); } function signed24WithFlag(flag, bytes) { const rawValue = uint24BE(bytes); return flag === 0x01 ? -rawValue : rawValue; } function resolveFilePath(filePath) { if (path.isAbsolute(filePath)) { return filePath; } return path.join(process.cwd(), filePath); } function loadAlModelMap(filePath) { const resolvedPath = resolveFilePath(filePath); const fileContent = fs.readFileSync(resolvedPath, 'utf8'); const model = JSON.parse(fileContent); const map = new Map(); for (const item of model.properties || []) { map.set(item.identifier, item.name); } return map; } class JhmDecoder { constructor(options = {}) { this.buffer = Buffer.alloc(0); this.maxBufferBytes = options.maxBufferBytes || 8192; this.alModelMap = loadAlModelMap(options.alModelPath || './alModel.json'); } push(chunk) { if (!Buffer.isBuffer(chunk) || chunk.length === 0) { return []; } this.buffer = Buffer.concat([this.buffer, chunk]); if (this.buffer.length > this.maxBufferBytes) { this.buffer = Buffer.alloc(0); return [{ ok: false, publish: false, reason: 'buffer-overflow' }]; } const results = []; while (this.buffer.length >= MIN_HEADER_LENGTH) { const header = this.findHeader(); if (!header) { this.buffer = this.buffer.slice(Math.max(0, this.buffer.length - 1)); break; } if (header.index > 0) { this.buffer = this.buffer.slice(header.index); } if (header.protocol === 'jhm') { if (this.buffer.length < JHM_FRAME_LENGTH) { break; } const frame = this.buffer.slice(0, JHM_FRAME_LENGTH); this.buffer = this.buffer.slice(JHM_FRAME_LENGTH); results.push(this.parseJhmFrame(frame)); continue; } if (this.buffer.length < 3) { break; } const frameLength = this.buffer[2]; if (frameLength < 6) { this.buffer = this.buffer.slice(1); continue; } if (this.buffer.length < frameLength) { break; } const frame = this.buffer.slice(0, frameLength); this.buffer = this.buffer.slice(frameLength); results.push(this.parseBloodPressureFrame(frame)); } return results; } findHeader() { for (let index = 0; index <= this.buffer.length - 2; index += 1) { if (this.buffer[index] === JHM_HEADER_1 && this.buffer[index + 1] === JHM_HEADER_2) { return { index, protocol: 'jhm' }; } if (this.buffer[index] === BP_HEADER_1 && this.buffer[index + 1] === BP_HEADER_2) { return { index, protocol: 'blood-pressure' }; } } return null; } buildMetricResult({ command, rawHex, metric, extra = {} }) { const publishedEntries = Object.entries(metric || {}) .filter(([, value]) => value !== undefined && value !== null) .filter(([identifier]) => this.alModelMap.has(identifier)); if (publishedEntries.length === 0) { return { ok: true, publish: false, reason: 'identifier-not-in-almodel', command, commandHex: toHex(command), rawHex, ...extra, }; } const publishedMetric = Object.fromEntries(publishedEntries); const identifiers = publishedEntries.map(([identifier]) => identifier); const result = { ok: true, publish: true, reason: 'ok', command, commandHex: toHex(command), rawHex, metric: publishedMetric, identifiers, ...extra, }; if (identifiers.length === 1) { const [identifier] = identifiers; result.identifier = identifier; result.name = this.alModelMap.get(identifier); result.value = publishedMetric[identifier]; } return result; } parseJhmFrame(frame) { const command = frame[2]; const payload = frame.slice(3, 7); const receivedChecksum = frame[7]; const expectedChecksum = checksum(command, payload); const rawHex = bytesToHex(frame); if (receivedChecksum !== expectedChecksum) { return { ok: false, publish: false, reason: 'checksum-invalid', command, commandHex: toHex(command), rawHex, }; } const rule = COMMAND_RULES[command]; if (!rule) { return { ok: true, publish: false, reason: 'unsupported-command', command, commandHex: toHex(command), rawHex, }; } if (!rule.identifier) { return { ok: true, publish: false, reason: 'identifier-missing', command, commandHex: toHex(command), rawHex, }; } if (!this.alModelMap.has(rule.identifier)) { return { ok: true, publish: false, reason: 'identifier-not-in-almodel', command, commandHex: toHex(command), rawHex, identifier: rule.identifier, }; } const value = rule.decode(payload); return this.buildMetricResult({ command, rawHex, metric: { [rule.identifier]: value, }, }); } parseBloodPressureFrame(frame) { const frameLength = frame[2]; const command = frame[3]; const payload = frame.slice(4, frame.length - 1); const receivedChecksum = frame[frame.length - 1]; const expectedChecksum = additiveChecksum(frame.slice(0, -1)); const rawHex = bytesToHex(frame); if (frameLength !== frame.length) { return { ok: false, publish: false, reason: 'length-invalid', command, commandHex: toHex(command), rawHex, protocol: 'blood-pressure', }; } if (receivedChecksum !== expectedChecksum) { return { ok: false, publish: false, reason: 'checksum-invalid', command, commandHex: toHex(command), rawHex, protocol: 'blood-pressure', }; } if (command !== BP_COMMAND) { return { ok: true, publish: false, reason: 'unsupported-command', command, commandHex: toHex(command), rawHex, protocol: 'blood-pressure', }; } if (payload.length < 4) { return { ok: false, publish: false, reason: 'payload-too-short', command, commandHex: toHex(command), rawHex, protocol: 'blood-pressure', }; } const metric = { N: uint16BE(payload[0], payload[1]), O: payload[2], P: payload[3], }; return this.buildMetricResult({ command, rawHex, metric, extra: { protocol: 'blood-pressure', }, }); } } module.exports = { BP_COMMAND, BP_HEADER_1, BP_HEADER_2, COMMAND_RULES, FRAME_LENGTH: JHM_FRAME_LENGTH, JHM_FRAME_LENGTH, JHM_HEADER_1, JHM_HEADER_2, JhmDecoder, additiveChecksum, bytesToHex, checksum, loadAlModelMap, signed24WithFlag, toHex, uint16BE, uint24BE, uint32BE, }; /***/ }), /***/ 7235: /***/ ((module) => { class MetricAggregator { constructor(options = {}) { this.logger = options.logger || console; this.onFlush = typeof options.onFlush === 'function' ? options.onFlush : async () => true; this.mode = String(options.mode || 'batch').trim().toLowerCase(); this.flushIntervalMs = Number(options.flushIntervalMs) > 0 ? Number(options.flushIntervalMs) : 60000; this.alignToMinute = options.alignToMinute !== false; this.includeDeviceIdField = options.includeDeviceIdField !== false; this.deviceIdField = options.deviceIdField || 'n'; this.publishOnShutdown = options.publishOnShutdown !== false; this.cache = new Map(); this.timer = null; this.started = false; this.flushing = false; this.flushQueued = false; } start() { if (this.started) { return; } this.started = true; if (this.mode === 'batch') { this.scheduleNextFlush(); } } async stop() { this.started = false; if (this.timer) { clearTimeout(this.timer); this.timer = null; } if (this.mode === 'batch' && this.publishOnShutdown) { await this.flush({ reason: 'shutdown' }); } } ingest(device, metric = {}) { if (!device || !device.deviceId || !metric || typeof metric !== 'object') { return Promise.resolve(false); } const entry = this.getOrCreateEntry(device); entry.device = device; entry.dirty = true; entry.lastUpdateAt = Date.now(); if (this.includeDeviceIdField) { entry.payload[this.deviceIdField] = device.deviceId; } Object.assign(entry.payload, metric); if (this.mode === 'immediate') { return this.flush({ reason: 'immediate', deviceId: device.deviceId }); } return Promise.resolve(true); } getOrCreateEntry(device) { if (!this.cache.has(device.deviceId)) { this.cache.set(device.deviceId, { device, payload: {}, dirty: false, firstSeenAt: Date.now(), lastUpdateAt: 0, lastFlushAt: 0, }); } return this.cache.get(device.deviceId); } computeDelayMs() { if (!this.alignToMinute) { return this.flushIntervalMs; } const remainder = Date.now() % this.flushIntervalMs; return remainder === 0 ? this.flushIntervalMs : this.flushIntervalMs - remainder; } scheduleNextFlush() { if (!this.started || this.mode !== 'batch') { return; } if (this.timer) { clearTimeout(this.timer); } this.timer = setTimeout(() => { this.flush({ reason: 'timer' }).catch((error) => { this.logger.error(`[APP] Aggregator flush failed: ${error.message}`); }); }, this.computeDelayMs()); if (typeof this.timer.unref === 'function') { this.timer.unref(); } } async flush(options = {}) { const reason = options.reason || 'manual'; const deviceId = options.deviceId || ''; if (this.flushing) { this.flushQueued = true; return false; } this.flushing = true; if (this.timer) { clearTimeout(this.timer); this.timer = null; } try { const entries = Array.from(this.cache.values()).filter((entry) => { if (!entry.dirty) { return false; } if (deviceId && entry.device.deviceId !== deviceId) { return false; } return true; }); for (const entry of entries) { const payload = { ...entry.payload, }; if (this.includeDeviceIdField) { payload[this.deviceIdField] = entry.device.deviceId; } try { const result = await this.onFlush(entry.device, payload, { reason, firstSeenAt: entry.firstSeenAt, lastUpdateAt: entry.lastUpdateAt, lastFlushAt: entry.lastFlushAt, }); if (result === false) { continue; } entry.dirty = false; entry.lastFlushAt = Date.now(); } catch (error) { this.logger.error(`[APP] Aggregator device flush failed deviceId=${entry.device.deviceId}: ${error.message}`); } } return true; } finally { this.flushing = false; if (this.started && this.mode === 'batch') { this.scheduleNextFlush(); } if (this.flushQueued) { this.flushQueued = false; await this.flush({ reason: 'queued' }); } } } getSnapshot(deviceId) { if (!deviceId) { return Array.from(this.cache.values()).map((entry) => ({ deviceId: entry.device.deviceId, payload: { ...entry.payload }, dirty: entry.dirty, })); } const entry = this.cache.get(deviceId); if (!entry) { return null; } return { deviceId: entry.device.deviceId, payload: { ...entry.payload }, dirty: entry.dirty, }; } } module.exports = { MetricAggregator, }; /***/ }), /***/ 2189: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const mqtt = __nccwpck_require__(4825); // MQTT 服务负责建立连接、处理重连,并按设备编号发布消息。 class MqttService { constructor(config, logger = console) { this.config = config; this.logger = logger; this.client = null; this.connected = false; } // 把时间格式化为 yyyy-mm-dd hh:MM:ss,供上报字段 suedtime 使用。 formatSuedtime(date = new Date()) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hour = String(date.getHours()).padStart(2, '0'); const minute = String(date.getMinutes()).padStart(2, '0'); const second = String(date.getSeconds()).padStart(2, '0'); return `${year}-${month}-${day} ${hour}:${minute}:${second}`; } // 在原始指标对象上追加上传时间字段,保证每次发送都有 suedtime。 buildPayload(message) { return { ...(message || {}), suedtime: this.formatSuedtime(), }; } // 根据配置拼接 MQTT 连接地址,兼容 brokerUrl 和 protocol/host/port 两种写法。 getBrokerUrl() { if (this.config.brokerUrl) { return this.config.brokerUrl; } const protocol = this.config.protocol || 'mqtt'; const host = this.config.host; const port = this.config.port; return `${protocol}://${host}:${port}`; } // 为当前实例生成一个客户端标识,未配置时自动生成默认值。 getClientId() { if (this.config.clientId) { return this.config.clientId; } const hostName = (this.config.host || 'broker').replace(/[^a-zA-Z0-9]/g, '_'); return `jhm_tcp_gateway_${hostName}`; } // 启动 MQTT 客户端连接。 start() { const brokerUrl = this.getBrokerUrl(); const clientId = this.getClientId(); this.logger.info(`[MQTT] 准备连接 broker=${brokerUrl} clientId=${clientId} qos=${this.config.qos || 0} retain=${Boolean(this.config.retain)}`); this.client = mqtt.connect(brokerUrl, { clientId, username: this.config.username || undefined, password: this.config.password || undefined, reconnectPeriod: this.config.reconnectPeriod || 5000, connectTimeout: this.config.connectTimeoutMs || 30000, }); // 连接成功后标记状态,便于日志和故障判断。 this.client.on('connect', () => { this.connected = true; this.logger.info(`[MQTT] 已连接到 ${brokerUrl}`); }); // 重连时输出提示,方便现场排查网络波动问题。 this.client.on('reconnect', () => { this.connected = false; this.logger.warn('[MQTT] 正在重连...'); }); // 断开连接时更新状态。 this.client.on('close', () => { this.connected = false; this.logger.warn('[MQTT] 连接已关闭'); }); // 出现错误时只记录日志,不让主进程直接崩溃。 this.client.on('error', (error) => { this.logger.error(`[MQTT] 错误: ${error.message}`); }); } // 根据配置模板生成设备专属 topic。 buildTopic(device) { // 优先使用完整模板;如果只配置了默认前缀,则按 前缀/设备编号 组织 topic。 if (this.config.topicTemplate) { return this.config.topicTemplate .replace('{deviceId}', device.deviceId) .replace('{ip}', device.ip) .replace('{name}', device.name || device.deviceId); } const topicPrefix = this.config.defaultTopicPrefix || 'device'; return `${topicPrefix}/${device.deviceId}`; } // 发布一条最小指标对象,例如 { F: 37.5 }。 publish(device, message) { if (!this.client) { throw new Error('MQTT 服务尚未启动'); } const topic = this.buildTopic(device); const payloadObject = this.buildPayload(message); const payload = JSON.stringify(payloadObject); // 如果 MQTT 当前还未连上,则消息会由 mqtt 客户端排队,日志中做提示。 if (!this.connected) { this.logger.warn(`[MQTT] 当前未连接,消息将等待发送: ${topic}`); } this.client.publish(topic, payload, { qos: this.config.qos || 0, retain: Boolean(this.config.retain), }, (error) => { if (error) { this.logger.error(`[MQTT] 发布失败 ${topic}: ${error.message}`); return; } this.logger.info(`[MQTT] 发布成功 ${topic} ${payload}`); }); } // 关闭 MQTT 连接,便于优雅停机。 async stop() { if (!this.client) { return; } this.logger.info('[MQTT] 开始关闭连接'); await new Promise((resolve) => { this.client.end(false, resolve); }); this.connected = false; this.client = null; this.logger.info('[MQTT] MQTT 服务已停止'); } } module.exports = { MqttService, }; /***/ }), /***/ 1211: /***/ ((module) => { function _OverloadYield(e, d) { this.v = e, this.k = d; } module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 9754: /***/ ((module) => { function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 1474: /***/ ((module) => { function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 7228: /***/ ((module) => { function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 5300: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var toPropertyKey = __nccwpck_require__(3963); function _defineProperty(e, r, t) { return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 9597: /***/ ((module) => { function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 5843: /***/ ((module) => { function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 3774: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var regeneratorDefine = __nccwpck_require__(9077); function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return regeneratorDefine(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (regeneratorDefine(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), regeneratorDefine(u), regeneratorDefine(u, o, "Generator"), regeneratorDefine(u, n, function () { return this; }), regeneratorDefine(u, "toString", function () { return "[object Generator]"; }), (module.exports = _regenerator = function _regenerator() { return { w: i, m: f }; }, module.exports.__esModule = true, module.exports["default"] = module.exports)(); } module.exports = _regenerator, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 2916: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var regeneratorAsyncGen = __nccwpck_require__(8264); function _regeneratorAsync(n, e, r, t, o) { var a = regeneratorAsyncGen(n, e, r, t, o); return a.next().then(function (n) { return n.done ? n.value : a.next(); }); } module.exports = _regeneratorAsync, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 8264: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var regenerator = __nccwpck_require__(3774); var regeneratorAsyncIterator = __nccwpck_require__(9246); function _regeneratorAsyncGen(r, e, t, o, n) { return new regeneratorAsyncIterator(regenerator().w(r, e, t, o), n || Promise); } module.exports = _regeneratorAsyncGen, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 9246: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var OverloadYield = __nccwpck_require__(1211); var regeneratorDefine = __nccwpck_require__(9077); function AsyncIterator(t, e) { function n(r, o, i, f) { try { var c = t[r](o), u = c.value; return u instanceof OverloadYield ? e.resolve(u.v).then(function (t) { n("next", t, i, f); }, function (t) { n("throw", t, i, f); }) : e.resolve(u).then(function (t) { c.value = t, i(c); }, function (t) { return n("throw", t, i, f); }); } catch (t) { f(t); } } var r; this.next || (regeneratorDefine(AsyncIterator.prototype), regeneratorDefine(AsyncIterator.prototype, "function" == typeof Symbol && Symbol.asyncIterator || "@asyncIterator", function () { return this; })), regeneratorDefine(this, "_invoke", function (t, o, i) { function f() { return new e(function (e, r) { n(t, i, e, r); }); } return r = r ? r.then(f, f) : f(); }, !0); } module.exports = AsyncIterator, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 9077: /***/ ((module) => { function _regeneratorDefine(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } module.exports = _regeneratorDefine = function regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, module.exports.__esModule = true, module.exports["default"] = module.exports, _regeneratorDefine(e, r, n, t); } module.exports = _regeneratorDefine, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 9742: /***/ ((module) => { function _regeneratorKeys(e) { var n = Object(e), r = []; for (var t in n) r.unshift(t); return function e() { for (; r.length;) if ((t = r.pop()) in n) return e.value = t, e.done = !1, e; return e.done = !0, e; }; } module.exports = _regeneratorKeys, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 4408: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var OverloadYield = __nccwpck_require__(1211); var regenerator = __nccwpck_require__(3774); var regeneratorAsync = __nccwpck_require__(2916); var regeneratorAsyncGen = __nccwpck_require__(8264); var regeneratorAsyncIterator = __nccwpck_require__(9246); var regeneratorKeys = __nccwpck_require__(9742); var regeneratorValues = __nccwpck_require__(4232); function _regeneratorRuntime() { "use strict"; var r = regenerator(), e = r.m(_regeneratorRuntime), t = (Object.getPrototypeOf ? Object.getPrototypeOf(e) : e.__proto__).constructor; function n(r) { var e = "function" == typeof r && r.constructor; return !!e && (e === t || "GeneratorFunction" === (e.displayName || e.name)); } var o = { "throw": 1, "return": 2, "break": 3, "continue": 3 }; function a(r) { var e, t; return function (n) { e || (e = { stop: function stop() { return t(n.a, 2); }, "catch": function _catch() { return n.v; }, abrupt: function abrupt(r, e) { return t(n.a, o[r], e); }, delegateYield: function delegateYield(r, o, a) { return e.resultName = o, t(n.d, regeneratorValues(r), a); }, finish: function finish(r) { return t(n.f, r); } }, t = function t(r, _t, o) { n.p = e.prev, n.n = e.next; try { return r(_t, o); } finally { e.next = n.n; } }), e.resultName && (e[e.resultName] = n.v, e.resultName = void 0), e.sent = n.v, e.next = n.n; try { return r.call(this, e); } finally { n.p = e.prev, n.n = e.next; } }; } return (module.exports = _regeneratorRuntime = function _regeneratorRuntime() { return { wrap: function wrap(e, t, n, o) { return r.w(a(e), t, n, o && o.reverse()); }, isGeneratorFunction: n, mark: r.m, awrap: function awrap(r, e) { return new OverloadYield(r, e); }, AsyncIterator: regeneratorAsyncIterator, async: function async(r, e, t, o, u) { return (n(e) ? regeneratorAsyncGen : regeneratorAsync)(a(r), e, t, o, u); }, keys: regeneratorKeys, values: regeneratorValues }; }, module.exports.__esModule = true, module.exports["default"] = module.exports)(); } module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 4232: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var _typeof = (__nccwpck_require__(7087)["default"]); function _regeneratorValues(e) { if (null != e) { var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"], r = 0; if (t) return t.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) return { next: function next() { return e && r >= e.length && (e = void 0), { value: e && e[r++], done: !e }; } }; } throw new TypeError(_typeof(e) + " is not iterable"); } module.exports = _regeneratorValues, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 8208: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var arrayWithHoles = __nccwpck_require__(1474); var iterableToArrayLimit = __nccwpck_require__(9597); var unsupportedIterableToArray = __nccwpck_require__(4643); var nonIterableRest = __nccwpck_require__(5843); function _slicedToArray(r, e) { return arrayWithHoles(r) || iterableToArrayLimit(r, e) || unsupportedIterableToArray(r, e) || nonIterableRest(); } module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 9558: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var _typeof = (__nccwpck_require__(7087)["default"]); function toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } module.exports = toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 3963: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var _typeof = (__nccwpck_require__(7087)["default"]); var toPrimitive = __nccwpck_require__(9558); function toPropertyKey(t) { var i = toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } module.exports = toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 7087: /***/ ((module) => { function _typeof(o) { "@babel/helpers - typeof"; return module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o); } module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 4643: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var arrayLikeToArray = __nccwpck_require__(9754); function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? arrayLikeToArray(r, a) : void 0; } } module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; /***/ }), /***/ 215: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // TODO(Babel 8): Remove this file. var runtime = __nccwpck_require__(4408)(); module.exports = runtime; // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736= try { regeneratorRuntime = runtime; } catch (accidentalStrictMode) { if (typeof globalThis === "object") { globalThis.regeneratorRuntime = runtime; } else { Function("r", "regeneratorRuntime = r")(runtime); } } /***/ }), /***/ 2477: /***/ ((__unused_webpack_module, exports) => { "use strict"; /** * @module LRUCache */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LRUCache = void 0; const perf = typeof performance === 'object' && performance && typeof performance.now === 'function' ? performance : Date; const warned = new Set(); /* c8 ignore start */ const PROCESS = (typeof process === 'object' && !!process ? process : {}); /* c8 ignore start */ const emitWarning = (msg, type, code, fn) => { typeof PROCESS.emitWarning === 'function' ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`); }; let AC = globalThis.AbortController; let AS = globalThis.AbortSignal; /* c8 ignore start */ if (typeof AC === 'undefined') { //@ts-ignore AS = class AbortSignal { onabort; _onabort = []; reason; aborted = false; addEventListener(_, fn) { this._onabort.push(fn); } }; //@ts-ignore AC = class AbortController { constructor() { warnACPolyfill(); } signal = new AS(); abort(reason) { if (this.signal.aborted) return; //@ts-ignore this.signal.reason = reason; //@ts-ignore this.signal.aborted = true; //@ts-ignore for (const fn of this.signal._onabort) { fn(reason); } this.signal.onabort?.(reason); } }; let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'; const warnACPolyfill = () => { if (!printACPolyfillWarning) return; printACPolyfillWarning = false; emitWarning('AbortController is not defined. If using lru-cache in ' + 'node 14, load an AbortController polyfill from the ' + '`node-abort-controller` package. A minimal polyfill is ' + 'provided for use by LRUCache.fetch(), but it should not be ' + 'relied upon in other contexts (eg, passing it to other APIs that ' + 'use AbortController/AbortSignal might have undesirable effects). ' + 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill); }; } /* c8 ignore stop */ const shouldWarn = (code) => !warned.has(code); const TYPE = Symbol('type'); const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n); /* c8 ignore start */ // This is a little bit ridiculous, tbh. // The maximum array length is 2^32-1 or thereabouts on most JS impls. // And well before that point, you're caching the entire world, I mean, // that's ~32GB of just integers for the next/prev links, plus whatever // else to hold that many keys and values. Just filling the memory with // zeroes at init time is brutal when you get that big. // But why not be complete? // Maybe in the future, these limits will have expanded. const getUintArray = (max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null; /* c8 ignore stop */ class ZeroArray extends Array { constructor(size) { super(size); this.fill(0); } } class Stack { heap; length; // private constructor static #constructing = false; static create(max) { const HeapCls = getUintArray(max); if (!HeapCls) return []; Stack.#constructing = true; const s = new Stack(max, HeapCls); Stack.#constructing = false; return s; } constructor(max, HeapCls) { /* c8 ignore start */ if (!Stack.#constructing) { throw new TypeError('instantiate Stack using Stack.create(n)'); } /* c8 ignore stop */ this.heap = new HeapCls(max); this.length = 0; } push(n) { this.heap[this.length++] = n; } pop() { return this.heap[--this.length]; } } /** * Default export, the thing you're using this module to get. * * The `K` and `V` types define the key and value types, respectively. The * optional `FC` type defines the type of the `context` object passed to * `cache.fetch()` and `cache.memo()`. * * Keys and values **must not** be `null` or `undefined`. * * All properties from the options object (with the exception of `max`, * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are * added as normal public members. (The listed options are read-only getters.) * * Changing any of these will alter the defaults for subsequent method calls. */ class LRUCache { // options that cannot be changed without disaster #max; #maxSize; #dispose; #disposeAfter; #fetchMethod; #memoMethod; /** * {@link LRUCache.OptionsBase.ttl} */ ttl; /** * {@link LRUCache.OptionsBase.ttlResolution} */ ttlResolution; /** * {@link LRUCache.OptionsBase.ttlAutopurge} */ ttlAutopurge; /** * {@link LRUCache.OptionsBase.updateAgeOnGet} */ updateAgeOnGet; /** * {@link LRUCache.OptionsBase.updateAgeOnHas} */ updateAgeOnHas; /** * {@link LRUCache.OptionsBase.allowStale} */ allowStale; /** * {@link LRUCache.OptionsBase.noDisposeOnSet} */ noDisposeOnSet; /** * {@link LRUCache.OptionsBase.noUpdateTTL} */ noUpdateTTL; /** * {@link LRUCache.OptionsBase.maxEntrySize} */ maxEntrySize; /** * {@link LRUCache.OptionsBase.sizeCalculation} */ sizeCalculation; /** * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection} */ noDeleteOnFetchRejection; /** * {@link LRUCache.OptionsBase.noDeleteOnStaleGet} */ noDeleteOnStaleGet; /** * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort} */ allowStaleOnFetchAbort; /** * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} */ allowStaleOnFetchRejection; /** * {@link LRUCache.OptionsBase.ignoreFetchAbort} */ ignoreFetchAbort; // computed properties #size; #calculatedSize; #keyMap; #keyList; #valList; #next; #prev; #head; #tail; #free; #disposed; #sizes; #starts; #ttls; #hasDispose; #hasFetchMethod; #hasDisposeAfter; /** * Do not call this method unless you need to inspect the * inner workings of the cache. If anything returned by this * object is modified in any way, strange breakage may occur. * * These fields are private for a reason! * * @internal */ static unsafeExposeInternals(c) { return { // properties starts: c.#starts, ttls: c.#ttls, sizes: c.#sizes, keyMap: c.#keyMap, keyList: c.#keyList, valList: c.#valList, next: c.#next, prev: c.#prev, get head() { return c.#head; }, get tail() { return c.#tail; }, free: c.#free, // methods isBackgroundFetch: (p) => c.#isBackgroundFetch(p), backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context), moveToTail: (index) => c.#moveToTail(index), indexes: (options) => c.#indexes(options), rindexes: (options) => c.#rindexes(options), isStale: (index) => c.#isStale(index), }; } // Protected read-only members /** * {@link LRUCache.OptionsBase.max} (read-only) */ get max() { return this.#max; } /** * {@link LRUCache.OptionsBase.maxSize} (read-only) */ get maxSize() { return this.#maxSize; } /** * The total computed size of items in the cache (read-only) */ get calculatedSize() { return this.#calculatedSize; } /** * The number of items stored in the cache (read-only) */ get size() { return this.#size; } /** * {@link LRUCache.OptionsBase.fetchMethod} (read-only) */ get fetchMethod() { return this.#fetchMethod; } get memoMethod() { return this.#memoMethod; } /** * {@link LRUCache.OptionsBase.dispose} (read-only) */ get dispose() { return this.#dispose; } /** * {@link LRUCache.OptionsBase.disposeAfter} (read-only) */ get disposeAfter() { return this.#disposeAfter; } constructor(options) { const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options; if (max !== 0 && !isPosInt(max)) { throw new TypeError('max option must be a nonnegative integer'); } const UintArray = max ? getUintArray(max) : Array; if (!UintArray) { throw new Error('invalid max value: ' + max); } this.#max = max; this.#maxSize = maxSize; this.maxEntrySize = maxEntrySize || this.#maxSize; this.sizeCalculation = sizeCalculation; if (this.sizeCalculation) { if (!this.#maxSize && !this.maxEntrySize) { throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize'); } if (typeof this.sizeCalculation !== 'function') { throw new TypeError('sizeCalculation set to non-function'); } } if (memoMethod !== undefined && typeof memoMethod !== 'function') { throw new TypeError('memoMethod must be a function if defined'); } this.#memoMethod = memoMethod; if (fetchMethod !== undefined && typeof fetchMethod !== 'function') { throw new TypeError('fetchMethod must be a function if specified'); } this.#fetchMethod = fetchMethod; this.#hasFetchMethod = !!fetchMethod; this.#keyMap = new Map(); this.#keyList = new Array(max).fill(undefined); this.#valList = new Array(max).fill(undefined); this.#next = new UintArray(max); this.#prev = new UintArray(max); this.#head = 0; this.#tail = 0; this.#free = Stack.create(max); this.#size = 0; this.#calculatedSize = 0; if (typeof dispose === 'function') { this.#dispose = dispose; } if (typeof disposeAfter === 'function') { this.#disposeAfter = disposeAfter; this.#disposed = []; } else { this.#disposeAfter = undefined; this.#disposed = undefined; } this.#hasDispose = !!this.#dispose; this.#hasDisposeAfter = !!this.#disposeAfter; this.noDisposeOnSet = !!noDisposeOnSet; this.noUpdateTTL = !!noUpdateTTL; this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection; this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection; this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort; this.ignoreFetchAbort = !!ignoreFetchAbort; // NB: maxEntrySize is set to maxSize if it's set if (this.maxEntrySize !== 0) { if (this.#maxSize !== 0) { if (!isPosInt(this.#maxSize)) { throw new TypeError('maxSize must be a positive integer if specified'); } } if (!isPosInt(this.maxEntrySize)) { throw new TypeError('maxEntrySize must be a positive integer if specified'); } this.#initializeSizeTracking(); } this.allowStale = !!allowStale; this.noDeleteOnStaleGet = !!noDeleteOnStaleGet; this.updateAgeOnGet = !!updateAgeOnGet; this.updateAgeOnHas = !!updateAgeOnHas; this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1; this.ttlAutopurge = !!ttlAutopurge; this.ttl = ttl || 0; if (this.ttl) { if (!isPosInt(this.ttl)) { throw new TypeError('ttl must be a positive integer if specified'); } this.#initializeTTLTracking(); } // do not allow completely unbounded caches if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) { throw new TypeError('At least one of max, maxSize, or ttl is required'); } if (!this.ttlAutopurge && !this.#max && !this.#maxSize) { const code = 'LRU_CACHE_UNBOUNDED'; if (shouldWarn(code)) { warned.add(code); const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' + 'result in unbounded memory consumption.'; emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache); } } } /** * Return the number of ms left in the item's TTL. If item is not in cache, * returns `0`. Returns `Infinity` if item is in cache without a defined TTL. */ getRemainingTTL(key) { return this.#keyMap.has(key) ? Infinity : 0; } #initializeTTLTracking() { const ttls = new ZeroArray(this.#max); const starts = new ZeroArray(this.#max); this.#ttls = ttls; this.#starts = starts; this.#setItemTTL = (index, ttl, start = perf.now()) => { starts[index] = ttl !== 0 ? start : 0; ttls[index] = ttl; if (ttl !== 0 && this.ttlAutopurge) { const t = setTimeout(() => { if (this.#isStale(index)) { this.#delete(this.#keyList[index], 'expire'); } }, ttl + 1); // unref() not supported on all platforms /* c8 ignore start */ if (t.unref) { t.unref(); } /* c8 ignore stop */ } }; this.#updateItemAge = index => { starts[index] = ttls[index] !== 0 ? perf.now() : 0; }; this.#statusTTL = (status, index) => { if (ttls[index]) { const ttl = ttls[index]; const start = starts[index]; /* c8 ignore next */ if (!ttl || !start) return; status.ttl = ttl; status.start = start; status.now = cachedNow || getNow(); const age = status.now - start; status.remainingTTL = ttl - age; } }; // debounce calls to perf.now() to 1s so we're not hitting // that costly call repeatedly. let cachedNow = 0; const getNow = () => { const n = perf.now(); if (this.ttlResolution > 0) { cachedNow = n; const t = setTimeout(() => (cachedNow = 0), this.ttlResolution); // not available on all platforms /* c8 ignore start */ if (t.unref) { t.unref(); } /* c8 ignore stop */ } return n; }; this.getRemainingTTL = key => { const index = this.#keyMap.get(key); if (index === undefined) { return 0; } const ttl = ttls[index]; const start = starts[index]; if (!ttl || !start) { return Infinity; } const age = (cachedNow || getNow()) - start; return ttl - age; }; this.#isStale = index => { const s = starts[index]; const t = ttls[index]; return !!t && !!s && (cachedNow || getNow()) - s > t; }; } // conditionally set private methods related to TTL #updateItemAge = () => { }; #statusTTL = () => { }; #setItemTTL = () => { }; /* c8 ignore stop */ #isStale = () => false; #initializeSizeTracking() { const sizes = new ZeroArray(this.#max); this.#calculatedSize = 0; this.#sizes = sizes; this.#removeItemSize = index => { this.#calculatedSize -= sizes[index]; sizes[index] = 0; }; this.#requireSize = (k, v, size, sizeCalculation) => { // provisionally accept background fetches. // actual value size will be checked when they return. if (this.#isBackgroundFetch(v)) { return 0; } if (!isPosInt(size)) { if (sizeCalculation) { if (typeof sizeCalculation !== 'function') { throw new TypeError('sizeCalculation must be a function'); } size = sizeCalculation(v, k); if (!isPosInt(size)) { throw new TypeError('sizeCalculation return invalid (expect positive integer)'); } } else { throw new TypeError('invalid size value (must be positive integer). ' + 'When maxSize or maxEntrySize is used, sizeCalculation ' + 'or size must be set.'); } } return size; }; this.#addItemSize = (index, size, status) => { sizes[index] = size; if (this.#maxSize) { const maxSize = this.#maxSize - sizes[index]; while (this.#calculatedSize > maxSize) { this.#evict(true); } } this.#calculatedSize += sizes[index]; if (status) { status.entrySize = size; status.totalCalculatedSize = this.#calculatedSize; } }; } #removeItemSize = _i => { }; #addItemSize = (_i, _s, _st) => { }; #requireSize = (_k, _v, size, sizeCalculation) => { if (size || sizeCalculation) { throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache'); } return 0; }; *#indexes({ allowStale = this.allowStale } = {}) { if (this.#size) { for (let i = this.#tail; true;) { if (!this.#isValidIndex(i)) { break; } if (allowStale || !this.#isStale(i)) { yield i; } if (i === this.#head) { break; } else { i = this.#prev[i]; } } } } *#rindexes({ allowStale = this.allowStale } = {}) { if (this.#size) { for (let i = this.#head; true;) { if (!this.#isValidIndex(i)) { break; } if (allowStale || !this.#isStale(i)) { yield i; } if (i === this.#tail) { break; } else { i = this.#next[i]; } } } } #isValidIndex(index) { return (index !== undefined && this.#keyMap.get(this.#keyList[index]) === index); } /** * Return a generator yielding `[key, value]` pairs, * in order from most recently used to least recently used. */ *entries() { for (const i of this.#indexes()) { if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield [this.#keyList[i], this.#valList[i]]; } } } /** * Inverse order version of {@link LRUCache.entries} * * Return a generator yielding `[key, value]` pairs, * in order from least recently used to most recently used. */ *rentries() { for (const i of this.#rindexes()) { if (this.#valList[i] !== undefined && this.#keyList[i] !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield [this.#keyList[i], this.#valList[i]]; } } } /** * Return a generator yielding the keys in the cache, * in order from most recently used to least recently used. */ *keys() { for (const i of this.#indexes()) { const k = this.#keyList[i]; if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield k; } } } /** * Inverse order version of {@link LRUCache.keys} * * Return a generator yielding the keys in the cache, * in order from least recently used to most recently used. */ *rkeys() { for (const i of this.#rindexes()) { const k = this.#keyList[i]; if (k !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield k; } } } /** * Return a generator yielding the values in the cache, * in order from most recently used to least recently used. */ *values() { for (const i of this.#indexes()) { const v = this.#valList[i]; if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield this.#valList[i]; } } } /** * Inverse order version of {@link LRUCache.values} * * Return a generator yielding the values in the cache, * in order from least recently used to most recently used. */ *rvalues() { for (const i of this.#rindexes()) { const v = this.#valList[i]; if (v !== undefined && !this.#isBackgroundFetch(this.#valList[i])) { yield this.#valList[i]; } } } /** * Iterating over the cache itself yields the same results as * {@link LRUCache.entries} */ [Symbol.iterator]() { return this.entries(); } /** * A String value that is used in the creation of the default string * description of an object. Called by the built-in method * `Object.prototype.toString`. */ [Symbol.toStringTag] = 'LRUCache'; /** * Find a value for which the supplied fn method returns a truthy value, * similar to `Array.find()`. fn is called as `fn(value, key, cache)`. */ find(fn, getOptions = {}) { for (const i of this.#indexes()) { const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) continue; if (fn(value, this.#keyList[i], this)) { return this.get(this.#keyList[i], getOptions); } } } /** * Call the supplied function on each item in the cache, in order from most * recently used to least recently used. * * `fn` is called as `fn(value, key, cache)`. * * If `thisp` is provided, function will be called in the `this`-context of * the provided object, or the cache if no `thisp` object is provided. * * Does not update age or recenty of use, or iterate over stale values. */ forEach(fn, thisp = this) { for (const i of this.#indexes()) { const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) continue; fn.call(thisp, value, this.#keyList[i], this); } } /** * The same as {@link LRUCache.forEach} but items are iterated over in * reverse order. (ie, less recently used items are iterated over first.) */ rforEach(fn, thisp = this) { for (const i of this.#rindexes()) { const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) continue; fn.call(thisp, value, this.#keyList[i], this); } } /** * Delete any stale entries. Returns true if anything was removed, * false otherwise. */ purgeStale() { let deleted = false; for (const i of this.#rindexes({ allowStale: true })) { if (this.#isStale(i)) { this.#delete(this.#keyList[i], 'expire'); deleted = true; } } return deleted; } /** * Get the extended info about a given entry, to get its value, size, and * TTL info simultaneously. Returns `undefined` if the key is not present. * * Unlike {@link LRUCache#dump}, which is designed to be portable and survive * serialization, the `start` value is always the current timestamp, and the * `ttl` is a calculated remaining time to live (negative if expired). * * Always returns stale values, if their info is found in the cache, so be * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl}) * if relevant. */ info(key) { const i = this.#keyMap.get(key); if (i === undefined) return undefined; const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined) return undefined; const entry = { value }; if (this.#ttls && this.#starts) { const ttl = this.#ttls[i]; const start = this.#starts[i]; if (ttl && start) { const remain = ttl - (perf.now() - start); entry.ttl = remain; entry.start = Date.now(); } } if (this.#sizes) { entry.size = this.#sizes[i]; } return entry; } /** * Return an array of [key, {@link LRUCache.Entry}] tuples which can be * passed to {@link LRLUCache#load}. * * The `start` fields are calculated relative to a portable `Date.now()` * timestamp, even if `performance.now()` is available. * * Stale entries are always included in the `dump`, even if * {@link LRUCache.OptionsBase.allowStale} is false. * * Note: this returns an actual array, not a generator, so it can be more * easily passed around. */ dump() { const arr = []; for (const i of this.#indexes({ allowStale: true })) { const key = this.#keyList[i]; const v = this.#valList[i]; const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; if (value === undefined || key === undefined) continue; const entry = { value }; if (this.#ttls && this.#starts) { entry.ttl = this.#ttls[i]; // always dump the start relative to a portable timestamp // it's ok for this to be a bit slow, it's a rare operation. const age = perf.now() - this.#starts[i]; entry.start = Math.floor(Date.now() - age); } if (this.#sizes) { entry.size = this.#sizes[i]; } arr.unshift([key, entry]); } return arr; } /** * Reset the cache and load in the items in entries in the order listed. * * The shape of the resulting cache may be different if the same options are * not used in both caches. * * The `start` fields are assumed to be calculated relative to a portable * `Date.now()` timestamp, even if `performance.now()` is available. */ load(arr) { this.clear(); for (const [key, entry] of arr) { if (entry.start) { // entry.start is a portable timestamp, but we may be using // node's performance.now(), so calculate the offset, so that // we get the intended remaining TTL, no matter how long it's // been on ice. // // it's ok for this to be a bit slow, it's a rare operation. const age = Date.now() - entry.start; entry.start = perf.now() - age; } this.set(key, entry.value, entry); } } /** * Add a value to the cache. * * Note: if `undefined` is specified as a value, this is an alias for * {@link LRUCache#delete} * * Fields on the {@link LRUCache.SetOptions} options param will override * their corresponding values in the constructor options for the scope * of this single `set()` operation. * * If `start` is provided, then that will set the effective start * time for the TTL calculation. Note that this must be a previous * value of `performance.now()` if supported, or a previous value of * `Date.now()` if not. * * Options object may also include `size`, which will prevent * calling the `sizeCalculation` function and just use the specified * number if it is a positive integer, and `noDisposeOnSet` which * will prevent calling a `dispose` function in the case of * overwrites. * * If the `size` (or return value of `sizeCalculation`) for a given * entry is greater than `maxEntrySize`, then the item will not be * added to the cache. * * Will update the recency of the entry. * * If the value is `undefined`, then this is an alias for * `cache.delete(key)`. `undefined` is never stored in the cache. */ set(k, v, setOptions = {}) { if (v === undefined) { this.delete(k); return this; } const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; let { noUpdateTTL = this.noUpdateTTL } = setOptions; const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation); // if the item doesn't fit, don't do anything // NB: maxEntrySize set to maxSize by default if (this.maxEntrySize && size > this.maxEntrySize) { if (status) { status.set = 'miss'; status.maxEntrySizeExceeded = true; } // have to delete, in case something is there already. this.#delete(k, 'set'); return this; } let index = this.#size === 0 ? undefined : this.#keyMap.get(k); if (index === undefined) { // addition index = (this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size); this.#keyList[index] = k; this.#valList[index] = v; this.#keyMap.set(k, index); this.#next[this.#tail] = index; this.#prev[index] = this.#tail; this.#tail = index; this.#size++; this.#addItemSize(index, size, status); if (status) status.set = 'add'; noUpdateTTL = false; } else { // update this.#moveToTail(index); const oldVal = this.#valList[index]; if (v !== oldVal) { if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) { oldVal.__abortController.abort(new Error('replaced')); const { __staleWhileFetching: s } = oldVal; if (s !== undefined && !noDisposeOnSet) { if (this.#hasDispose) { this.#dispose?.(s, k, 'set'); } if (this.#hasDisposeAfter) { this.#disposed?.push([s, k, 'set']); } } } else if (!noDisposeOnSet) { if (this.#hasDispose) { this.#dispose?.(oldVal, k, 'set'); } if (this.#hasDisposeAfter) { this.#disposed?.push([oldVal, k, 'set']); } } this.#removeItemSize(index); this.#addItemSize(index, size, status); this.#valList[index] = v; if (status) { status.set = 'replace'; const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal; if (oldValue !== undefined) status.oldValue = oldValue; } } else if (status) { status.set = 'update'; } } if (ttl !== 0 && !this.#ttls) { this.#initializeTTLTracking(); } if (this.#ttls) { if (!noUpdateTTL) { this.#setItemTTL(index, ttl, start); } if (status) this.#statusTTL(status, index); } if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) { const dt = this.#disposed; let task; while ((task = dt?.shift())) { this.#disposeAfter?.(...task); } } return this; } /** * Evict the least recently used item, returning its value or * `undefined` if cache is empty. */ pop() { try { while (this.#size) { const val = this.#valList[this.#head]; this.#evict(true); if (this.#isBackgroundFetch(val)) { if (val.__staleWhileFetching) { return val.__staleWhileFetching; } } else if (val !== undefined) { return val; } } } finally { if (this.#hasDisposeAfter && this.#disposed) { const dt = this.#disposed; let task; while ((task = dt?.shift())) { this.#disposeAfter?.(...task); } } } } #evict(free) { const head = this.#head; const k = this.#keyList[head]; const v = this.#valList[head]; if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) { v.__abortController.abort(new Error('evicted')); } else if (this.#hasDispose || this.#hasDisposeAfter) { if (this.#hasDispose) { this.#dispose?.(v, k, 'evict'); } if (this.#hasDisposeAfter) { this.#disposed?.push([v, k, 'evict']); } } this.#removeItemSize(head); // if we aren't about to use the index, then null these out if (free) { this.#keyList[head] = undefined; this.#valList[head] = undefined; this.#free.push(head); } if (this.#size === 1) { this.#head = this.#tail = 0; this.#free.length = 0; } else { this.#head = this.#next[head]; } this.#keyMap.delete(k); this.#size--; return head; } /** * Check if a key is in the cache, without updating the recency of use. * Will return false if the item is stale, even though it is technically * in the cache. * * Check if a key is in the cache, without updating the recency of * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set * to `true` in either the options or the constructor. * * Will return `false` if the item is stale, even though it is technically in * the cache. The difference can be determined (if it matters) by using a * `status` argument, and inspecting the `has` field. * * Will not update item age unless * {@link LRUCache.OptionsBase.updateAgeOnHas} is set. */ has(k, hasOptions = {}) { const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions; const index = this.#keyMap.get(k); if (index !== undefined) { const v = this.#valList[index]; if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === undefined) { return false; } if (!this.#isStale(index)) { if (updateAgeOnHas) { this.#updateItemAge(index); } if (status) { status.has = 'hit'; this.#statusTTL(status, index); } return true; } else if (status) { status.has = 'stale'; this.#statusTTL(status, index); } } else if (status) { status.has = 'miss'; } return false; } /** * Like {@link LRUCache#get} but doesn't update recency or delete stale * items. * * Returns `undefined` if the item is stale, unless * {@link LRUCache.OptionsBase.allowStale} is set. */ peek(k, peekOptions = {}) { const { allowStale = this.allowStale } = peekOptions; const index = this.#keyMap.get(k); if (index === undefined || (!allowStale && this.#isStale(index))) { return; } const v = this.#valList[index]; // either stale and allowed, or forcing a refresh of non-stale value return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; } #backgroundFetch(k, index, options, context) { const v = index === undefined ? undefined : this.#valList[index]; if (this.#isBackgroundFetch(v)) { return v; } const ac = new AC(); const { signal } = options; // when/if our AC signals, then stop listening to theirs. signal?.addEventListener('abort', () => ac.abort(signal.reason), { signal: ac.signal, }); const fetchOpts = { signal: ac.signal, options, context, }; const cb = (v, updateCache = false) => { const { aborted } = ac.signal; const ignoreAbort = options.ignoreFetchAbort && v !== undefined; if (options.status) { if (aborted && !updateCache) { options.status.fetchAborted = true; options.status.fetchError = ac.signal.reason; if (ignoreAbort) options.status.fetchAbortIgnored = true; } else { options.status.fetchResolved = true; } } if (aborted && !ignoreAbort && !updateCache) { return fetchFail(ac.signal.reason); } // either we didn't abort, and are still here, or we did, and ignored const bf = p; if (this.#valList[index] === p) { if (v === undefined) { if (bf.__staleWhileFetching) { this.#valList[index] = bf.__staleWhileFetching; } else { this.#delete(k, 'fetch'); } } else { if (options.status) options.status.fetchUpdated = true; this.set(k, v, fetchOpts.options); } } return v; }; const eb = (er) => { if (options.status) { options.status.fetchRejected = true; options.status.fetchError = er; } return fetchFail(er); }; const fetchFail = (er) => { const { aborted } = ac.signal; const allowStaleAborted = aborted && options.allowStaleOnFetchAbort; const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection; const noDelete = allowStale || options.noDeleteOnFetchRejection; const bf = p; if (this.#valList[index] === p) { // if we allow stale on fetch rejections, then we need to ensure that // the stale value is not removed from the cache when the fetch fails. const del = !noDelete || bf.__staleWhileFetching === undefined; if (del) { this.#delete(k, 'fetch'); } else if (!allowStaleAborted) { // still replace the *promise* with the stale value, // since we are done with the promise at this point. // leave it untouched if we're still waiting for an // aborted background fetch that hasn't yet returned. this.#valList[index] = bf.__staleWhileFetching; } } if (allowStale) { if (options.status && bf.__staleWhileFetching !== undefined) { options.status.returnedStale = true; } return bf.__staleWhileFetching; } else if (bf.__returned === bf) { throw er; } }; const pcall = (res, rej) => { const fmp = this.#fetchMethod?.(k, v, fetchOpts); if (fmp && fmp instanceof Promise) { fmp.then(v => res(v === undefined ? undefined : v), rej); } // ignored, we go until we finish, regardless. // defer check until we are actually aborting, // so fetchMethod can override. ac.signal.addEventListener('abort', () => { if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) { res(undefined); // when it eventually resolves, update the cache. if (options.allowStaleOnFetchAbort) { res = v => cb(v, true); } } }); }; if (options.status) options.status.fetchDispatched = true; const p = new Promise(pcall).then(cb, eb); const bf = Object.assign(p, { __abortController: ac, __staleWhileFetching: v, __returned: undefined, }); if (index === undefined) { // internal, don't expose status. this.set(k, bf, { ...fetchOpts.options, status: undefined }); index = this.#keyMap.get(k); } else { this.#valList[index] = bf; } return bf; } #isBackgroundFetch(p) { if (!this.#hasFetchMethod) return false; const b = p; return (!!b && b instanceof Promise && b.hasOwnProperty('__staleWhileFetching') && b.__abortController instanceof AC); } async fetch(k, fetchOptions = {}) { const { // get options allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, // set options ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL, // fetch exclusive options noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions; if (!this.#hasFetchMethod) { if (status) status.fetch = 'get'; return this.get(k, { allowStale, updateAgeOnGet, noDeleteOnStaleGet, status, }); } const options = { allowStale, updateAgeOnGet, noDeleteOnStaleGet, ttl, noDisposeOnSet, size, sizeCalculation, noUpdateTTL, noDeleteOnFetchRejection, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, status, signal, }; let index = this.#keyMap.get(k); if (index === undefined) { if (status) status.fetch = 'miss'; const p = this.#backgroundFetch(k, index, options, context); return (p.__returned = p); } else { // in cache, maybe already fetching const v = this.#valList[index]; if (this.#isBackgroundFetch(v)) { const stale = allowStale && v.__staleWhileFetching !== undefined; if (status) { status.fetch = 'inflight'; if (stale) status.returnedStale = true; } return stale ? v.__staleWhileFetching : (v.__returned = v); } // if we force a refresh, that means do NOT serve the cached value, // unless we are already in the process of refreshing the cache. const isStale = this.#isStale(index); if (!forceRefresh && !isStale) { if (status) status.fetch = 'hit'; this.#moveToTail(index); if (updateAgeOnGet) { this.#updateItemAge(index); } if (status) this.#statusTTL(status, index); return v; } // ok, it is stale or a forced refresh, and not already fetching. // refresh the cache. const p = this.#backgroundFetch(k, index, options, context); const hasStale = p.__staleWhileFetching !== undefined; const staleVal = hasStale && allowStale; if (status) { status.fetch = isStale ? 'stale' : 'refresh'; if (staleVal && isStale) status.returnedStale = true; } return staleVal ? p.__staleWhileFetching : (p.__returned = p); } } async forceFetch(k, fetchOptions = {}) { const v = await this.fetch(k, fetchOptions); if (v === undefined) throw new Error('fetch() returned undefined'); return v; } memo(k, memoOptions = {}) { const memoMethod = this.#memoMethod; if (!memoMethod) { throw new Error('no memoMethod provided to constructor'); } const { context, forceRefresh, ...options } = memoOptions; const v = this.get(k, options); if (!forceRefresh && v !== undefined) return v; const vv = memoMethod(k, v, { options, context, }); this.set(k, vv, options); return vv; } /** * Return a value from the cache. Will update the recency of the cache * entry found. * * If the key is not found, get() will return `undefined`. */ get(k, getOptions = {}) { const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions; const index = this.#keyMap.get(k); if (index !== undefined) { const value = this.#valList[index]; const fetching = this.#isBackgroundFetch(value); if (status) this.#statusTTL(status, index); if (this.#isStale(index)) { if (status) status.get = 'stale'; // delete only if not an in-flight background fetch if (!fetching) { if (!noDeleteOnStaleGet) { this.#delete(k, 'expire'); } if (status && allowStale) status.returnedStale = true; return allowStale ? value : undefined; } else { if (status && allowStale && value.__staleWhileFetching !== undefined) { status.returnedStale = true; } return allowStale ? value.__staleWhileFetching : undefined; } } else { if (status) status.get = 'hit'; // if we're currently fetching it, we don't actually have it yet // it's not stale, which means this isn't a staleWhileRefetching. // If it's not stale, and fetching, AND has a __staleWhileFetching // value, then that means the user fetched with {forceRefresh:true}, // so it's safe to return that value. if (fetching) { return value.__staleWhileFetching; } this.#moveToTail(index); if (updateAgeOnGet) { this.#updateItemAge(index); } return value; } } else if (status) { status.get = 'miss'; } } #connect(p, n) { this.#prev[n] = p; this.#next[p] = n; } #moveToTail(index) { // if tail already, nothing to do // if head, move head to next[index] // else // move next[prev[index]] to next[index] (head has no prev) // move prev[next[index]] to prev[index] // prev[index] = tail // next[tail] = index // tail = index if (index !== this.#tail) { if (index === this.#head) { this.#head = this.#next[index]; } else { this.#connect(this.#prev[index], this.#next[index]); } this.#connect(this.#tail, index); this.#tail = index; } } /** * Deletes a key out of the cache. * * Returns true if the key was deleted, false otherwise. */ delete(k) { return this.#delete(k, 'delete'); } #delete(k, reason) { let deleted = false; if (this.#size !== 0) { const index = this.#keyMap.get(k); if (index !== undefined) { deleted = true; if (this.#size === 1) { this.#clear(reason); } else { this.#removeItemSize(index); const v = this.#valList[index]; if (this.#isBackgroundFetch(v)) { v.__abortController.abort(new Error('deleted')); } else if (this.#hasDispose || this.#hasDisposeAfter) { if (this.#hasDispose) { this.#dispose?.(v, k, reason); } if (this.#hasDisposeAfter) { this.#disposed?.push([v, k, reason]); } } this.#keyMap.delete(k); this.#keyList[index] = undefined; this.#valList[index] = undefined; if (index === this.#tail) { this.#tail = this.#prev[index]; } else if (index === this.#head) { this.#head = this.#next[index]; } else { const pi = this.#prev[index]; this.#next[pi] = this.#next[index]; const ni = this.#next[index]; this.#prev[ni] = this.#prev[index]; } this.#size--; this.#free.push(index); } } } if (this.#hasDisposeAfter && this.#disposed?.length) { const dt = this.#disposed; let task; while ((task = dt?.shift())) { this.#disposeAfter?.(...task); } } return deleted; } /** * Clear the cache entirely, throwing away all values. */ clear() { return this.#clear('delete'); } #clear(reason) { for (const index of this.#rindexes({ allowStale: true })) { const v = this.#valList[index]; if (this.#isBackgroundFetch(v)) { v.__abortController.abort(new Error('deleted')); } else { const k = this.#keyList[index]; if (this.#hasDispose) { this.#dispose?.(v, k, reason); } if (this.#hasDisposeAfter) { this.#disposed?.push([v, k, reason]); } } } this.#keyMap.clear(); this.#valList.fill(undefined); this.#keyList.fill(undefined); if (this.#ttls && this.#starts) { this.#ttls.fill(0); this.#starts.fill(0); } if (this.#sizes) { this.#sizes.fill(0); } this.#head = 0; this.#tail = 0; this.#free.length = 0; this.#calculatedSize = 0; this.#size = 0; if (this.#hasDisposeAfter && this.#disposed) { const dt = this.#disposed; let task; while ((task = dt?.shift())) { this.#disposeAfter?.(...task); } } } } exports.LRUCache = LRUCache; //# sourceMappingURL=index.js.map /***/ }), /***/ 9640: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const fs = __nccwpck_require__(9896); const path = __nccwpck_require__(6928); function fileExists(filePath) { try { return fs.statSync(filePath).isFile(); } catch (_error) { return false; } } function getDefaultConfigCandidates(options = {}) { const packaged = options.packaged !== undefined ? options.packaged : Boolean(process.pkg); const cwd = options.cwd || process.cwd(); const appDir = options.appDir || __dirname; const execPath = options.execPath || process.execPath; if (packaged) { const execDir = path.dirname(execPath); return [ path.join(execDir, 'runtime', 'config.json'), path.join(execDir, 'config.json'), path.join(cwd, 'config.json'), ]; } return [ path.join(cwd, 'config.json'), path.join(appDir, 'config.json'), ]; } function getDefaultConfigPath(options = {}) { const candidates = getDefaultConfigCandidates(options); return candidates.find(fileExists) || candidates[0]; } module.exports = { fileExists, getDefaultConfigCandidates, getDefaultConfigPath, }; /***/ }), /***/ 2632: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const net = __nccwpck_require__(9278); const { JhmDecoder } = __nccwpck_require__(3825); function normalizeIp(address) { if (!address) { return ''; } if (address.startsWith('::ffff:')) { return address.slice(7); } return address; } function formatReceivedTimestamp(date = new Date()) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hour = String(date.getHours()).padStart(2, '0'); const minute = String(date.getMinutes()).padStart(2, '0'); const second = String(date.getSeconds()).padStart(2, '0'); return `${year}-${month}-${day} ${hour}:${minute}:${second}`; } class TcpService { constructor(options) { this.tcpConfig = options.tcpConfig; this.devices = options.devices || []; this.alModelPath = options.alModelPath; this.publishBloodPressureTime = options.publishBloodPressureTime !== false; this.logger = options.logger || console; this.onMetric = typeof options.onMetric === 'function' ? options.onMetric : () => {}; this.server = null; this.sessions = new Map(); this.deviceMap = this.buildDeviceMap(this.devices); } buildDeviceMap(devices) { const map = new Map(); for (const device of devices) { if (!device || !device.ip || !device.deviceId) { continue; } map.set(normalizeIp(device.ip), { ...device, name: device.name || device['备注'] || device.deviceId, }); } return map; } getReceivedMetricTime() { return formatReceivedTimestamp(); } async start() { this.server = net.createServer((socket) => { this.handleConnection(socket); }); this.server.maxConnections = this.tcpConfig.maxConnections || 100; this.server.on('error', (error) => { this.logger.error(`[TCP] 服务错误: ${error.message}`); }); await new Promise((resolve, reject) => { this.server.once('listening', resolve); this.server.once('error', reject); this.server.listen({ host: this.tcpConfig.host, port: this.tcpConfig.port, backlog: this.tcpConfig.backlog || 128, }); }); this.logger.info(`[TCP] 已监听 ${this.tcpConfig.host}:${this.tcpConfig.port} devices=${this.deviceMap.size} maxConnections=${this.server.maxConnections}`); } handleConnection(socket) { const clientIp = normalizeIp(socket.remoteAddress); const device = this.deviceMap.get(clientIp); if (!device) { this.logger.warn(`[TCP] 未配置设备接入,ip=${clientIp} port=${socket.remotePort},连接将被关闭`); socket.destroy(); return; } const decoder = new JhmDecoder({ alModelPath: this.alModelPath, maxBufferBytes: this.tcpConfig.maxBufferBytes || 8192, }); this.sessions.set(socket, { clientIp, device, decoder, }); if (this.tcpConfig.keepAlive) { socket.setKeepAlive(true, this.tcpConfig.keepAliveDelayMs || 10000); } socket.setNoDelay(Boolean(this.tcpConfig.noDelay)); socket.setTimeout(this.tcpConfig.socketTimeoutMs || 120000); this.logger.info(`[TCP] 设备已连接 deviceId=${device.deviceId} ip=${clientIp} port=${socket.remotePort} activeSessions=${this.sessions.size}`); socket.on('data', (chunk) => { this.handleData(socket, chunk); }); socket.on('timeout', () => { this.logger.warn(`[TCP] 连接超时 deviceId=${device.deviceId} ip=${clientIp}`); socket.destroy(); }); socket.on('error', (error) => { this.logger.error(`[TCP] 连接异常 deviceId=${device.deviceId} ip=${clientIp}: ${error.message}`); }); socket.on('close', () => { this.sessions.delete(socket); this.logger.info(`[TCP] 设备已断开 deviceId=${device.deviceId} ip=${clientIp} activeSessions=${this.sessions.size}`); }); } handleData(socket, chunk) { const session = this.sessions.get(socket); if (!session) { return; } this.logger.info(`[TCP] 收到原始数据 deviceId=${session.device.deviceId} bytes=${chunk.length}`); const results = session.decoder.push(chunk); if (results.length === 0) { this.logger.warn(`[TCP] 当前数据片段未形成完整报文 deviceId=${session.device.deviceId} bytes=${chunk.length}`); } for (const result of results) { if (!result.publish) { if (!result.ok) { this.logger.warn(`[TCP] 丢弃无效报文 deviceId=${session.device.deviceId} reason=${result.reason}`); } else { this.logger.warn(`[TCP] 跳过未发布报文 deviceId=${session.device.deviceId} reason=${result.reason || 'publish-disabled'} raw=${result.rawHex || ''}`); } continue; } if (result.protocol === 'blood-pressure' && this.publishBloodPressureTime) { result.metric = { ...result.metric, M: this.getReceivedMetricTime(), }; } this.logger.info(`[TCP] 收到指标 deviceId=${session.device.deviceId} metric=${JSON.stringify(result.metric)} raw=${result.rawHex}`); this.onMetric(session.device, result.metric, result); } } async stop() { this.logger.info(`[TCP] 开始停止 TCP 服务 activeSessions=${this.sessions.size}`); for (const socket of this.sessions.keys()) { socket.destroy(); } this.sessions.clear(); if (!this.server) { return; } await new Promise((resolve) => { this.server.close(resolve); }); this.server = null; this.logger.info('[TCP] TCP 服务已停止'); } } module.exports = { formatReceivedTimestamp, TcpService, normalizeIp, }; /***/ }), /***/ 9417: /***/ ((module) => { "use strict"; module.exports = {"rE":"2.18.9"}; /***/ }), /***/ 5055: /***/ ((module) => { "use strict"; module.exports = /*#__PURE__*/JSON.parse('{"name":"aliyun-iot-device-sdk","version":"1.0.1","description":"aliyun iot device sdk","keywords":["iot","mqtt","linkPlatform","linkKit","linkEdge","aliyun-iot-mqtt","aliyun","aliyunIot","iothub","linkdevelop","alink","device","sdk","iot-sdk"],"main":"lib/index.js","scripts":{"broker":"node broker.js","lib":"babel src -d lib","dev":"babel src -w -d lib","test":"jest --coverage ./test/","test:dev":"jest --coverage --watch ./test/","rap":"npm run lib && rm -rf rap && mkdir rap && cp -R lib rap && cp package.json rap && sed \'s/npm/rap/g\' README.md > rap/README.md && cd rap && rap publish","dist":"npm run lib && rm -rf dist/ && mkdir dist && browserify lib/index.js | uglifyjs -c > dist/aliyun-iot-device-sdk.min.js","pubus":"rm -rf unstabitily && mkdir unstabitily && cp package.unstabitily.json unstabitily/ && mv ./unstabitily/package.unstabitily.json ./unstabitily/package.json && cp README.md ./unstabitily && cp -r lib/ ./unstabitily && npm publish ./unstabitily/"},"jest":{"verbose":true,"testEnvironment":"node","moduleDirectories":["node_modules"]},"author":"玄彦,饭鱼","license":"MIT","devDependencies":{"aedes":"^0.35.3","babel-cli":"^6.26.0","babel-preset-env":"^1.6.1","browserify":"^16.2.2","jest":"^22.0.4","mosca":"^2.8.3","uglify-js":"^3.4.5"},"dependencies":{"axios":"^0.18.0","mqtt":"^2.15.0","qs":"^6.6.0"},"ruff":{"dependencies":{"mqtt":"^0.1.3"}}}'); /***/ }), /***/ 4198: /***/ ((module) => { "use strict"; module.exports = /*#__PURE__*/JSON.parse('{"name":"axios","version":"0.18.1","description":"Promise based HTTP client for the browser and node.js","main":"index.js","scripts":{"test":"grunt test && bundlesize","start":"node ./sandbox/server.js","build":"NODE_ENV=production grunt build","preversion":"npm test","version":"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json","postversion":"git push && git push --tags","examples":"node ./examples/server.js","coveralls":"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js"},"repository":{"type":"git","url":"https://github.com/axios/axios.git"},"keywords":["xhr","http","ajax","promise","node"],"author":"Matt Zabriskie","license":"MIT","bugs":{"url":"https://github.com/axios/axios/issues"},"homepage":"https://github.com/axios/axios","devDependencies":{"bundlesize":"^0.5.7","coveralls":"^2.11.9","es6-promise":"^4.0.5","grunt":"^1.0.1","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.0.0","grunt-contrib-nodeunit":"^1.0.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^19.0.0","grunt-karma":"^2.0.0","grunt-ts":"^6.0.0-beta.3","grunt-webpack":"^1.0.18","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1","karma":"^1.3.0","karma-chrome-launcher":"^2.0.0","karma-coverage":"^1.0.0","karma-firefox-launcher":"^1.0.0","karma-jasmine":"^1.0.2","karma-jasmine-ajax":"^0.1.13","karma-opera-launcher":"^1.0.0","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^1.1.0","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.7","karma-webpack":"^1.7.0","load-grunt-tasks":"^3.5.2","minimist":"^1.2.0","sinon":"^1.17.4","webpack":"^1.13.1","webpack-dev-server":"^1.14.1","url-search-params":"^0.6.1","typescript":"^2.0.3"},"browser":{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},"typings":"./index.d.ts","dependencies":{"follow-redirects":"1.5.10","is-buffer":"^2.0.2"},"bundlesize":[{"path":"./dist/axios.min.js","threshold":"5kB"}]}'); /***/ }), /***/ 2860: /***/ ((module) => { "use strict"; module.exports = {"version":"5.15.1"}; /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __nccwpck_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ var threw = true; /******/ try { /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); /******/ threw = false; /******/ } finally { /******/ if(threw) delete __webpack_module_cache__[moduleId]; /******/ } /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // expose the module cache /******/ __nccwpck_require__.c = __webpack_module_cache__; /******/ /************************************************************************/ /******/ /* webpack/runtime/compat */ /******/ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; /******/ /************************************************************************/ /******/ /******/ // module cache are used so entry inlining is disabled /******/ // startup /******/ // Load entry module and return exports /******/ var __webpack_exports__ = __nccwpck_require__(__nccwpck_require__.s = 6742); /******/ module.exports = __webpack_exports__; /******/ /******/ })() ;