From 6f37cc4e5de887c747198d81d22688bb913c9948 Mon Sep 17 00:00:00 2001 From: teamdocs Date: Wed, 16 Oct 2024 20:50:34 +0200 Subject: [PATCH] V9.3.3 --- dist/_locales/de/messages.json | 4 +- dist/_locales/en/messages.json | 6 +- dist/_locales/zh_CN/messages.json | 4 +- dist/content_script.js | 48429 ++++++++++++-------- dist/csv_editor.html | 2 +- dist/csv_editor.js | 597 +- dist/inject.js | 2023 +- dist/manifest.json | 18 +- dist/popup.html | 2 +- dist/popup.js | 54530 ++++++++++------------- dist/vision_editor.html | 2 +- dist/vision_editor.js | 2937 +- extension/_locales/de/messages.json | 4 +- extension/_locales/en/messages.json | 6 +- extension/_locales/zh_CN/messages.json | 4 +- extension/csv_editor.html | 2 +- extension/manifest.json | 3 +- extension/popup.html | 2 +- extension/sidepanel.html | 2 +- src/common/convert_utils.js | 4 +- src/common/utils.js | 2 +- src/common/web_extension.js | 2 +- src/components/header.js | 8 +- src/config/preinstall_macros.js | 6 +- src/containers/dashboard/index.js | 2 +- src/ext/bg.js | 18 +- src/ext/content_script/index.js | 18 +- src/ext/popup/run_command.ts | 19 +- src/init_player.js | 26 +- 29 files changed, 54120 insertions(+), 54562 deletions(-) diff --git a/dist/_locales/de/messages.json b/dist/_locales/de/messages.json index a3bbce5..eef930a 100644 --- a/dist/_locales/de/messages.json +++ b/dist/_locales/de/messages.json @@ -1,6 +1,6 @@ { "name": { - "message": "UI.Vision RPA", + "message": "Ui.Vision", "description": "extension name" }, "description": { @@ -8,7 +8,7 @@ "description": "extension description" }, "short_name": { - "message": "UIVision RPA", + "message": "Ui.Vision", "description": "extension short_name" } } diff --git a/dist/_locales/en/messages.json b/dist/_locales/en/messages.json index 35f32a0..32e6767 100644 --- a/dist/_locales/en/messages.json +++ b/dist/_locales/en/messages.json @@ -1,14 +1,14 @@ { "name": { - "message": "UI.Vision RPA", + "message": "Ui.Vision", "description": "extension name" }, "description": { - "message": "Universal AI-powered task and UI test automation. RPA combines Visual Web Automation, Visual Desktop Automation and Selenium IDE++.", + "message": "Task and UI test automation with Computer Vision/OCR. Ui.Vision combines browser automation and desktop automation.", "description": "extension description" }, "short_name": { - "message": "UIVision RPA", + "message": "Ui.Vision", "description": "extension short_name" } } diff --git a/dist/_locales/zh_CN/messages.json b/dist/_locales/zh_CN/messages.json index d2ca2f8..becc39b 100644 --- a/dist/_locales/zh_CN/messages.json +++ b/dist/_locales/zh_CN/messages.json @@ -1,6 +1,6 @@ { "name": { - "message": "UI.Vision RPA 浏览器自动化工具", + "message": "Ui.Vision RPA 浏览器自动化工具", "description": "extension name" }, "description": { @@ -8,7 +8,7 @@ "description": "extension description" }, "short_name": { - "message": "UI.Vision自动化", + "message": "Ui.Vision", "description": "extension short_name" } } diff --git a/dist/content_script.js b/dist/content_script.js index defa4a7..77f86b5 100644 --- a/dist/content_script.js +++ b/dist/content_script.js @@ -1,7 +1,7 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 78826: +/***/ 33836: /***/ (function(module) { /*! MIT License. Copyright 2015-2018 Richard Moore . See LICENSE.txt. */ @@ -799,8 +799,8 @@ /***/ }), -/***/ 10431: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 81909: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -808,358 +808,1405 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Box = exports.getAnchorRects = exports.genGetAnchorRects = exports.diagonalPoint = exports.diagonalPos = exports.pointAtPos = exports.calcRectAndAnchor = exports.fitSquarePoint = exports.BOX_ANCHOR_POS = undefined; - -var _extends2 = __webpack_require__(88239); +exports.base64 = void 0; +var base64; +(function (_base) { + // prettier-ignore + var encodingTable = new Uint8Array([65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47]); + + // prettier-ignore + var decodingTable = new Uint8Array([-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]); + var paddingChar = 61; + function calculateEncodedLength(length) { + var result = Math.trunc(length / 3) * 4; + result += length % 3 != 0 ? 4 : 0; + return result; + } + function readWord(input, i, maxLength) { + if (maxLength > 4) { + throw new Error("maxLength should be in range [0, 4]."); + } + var t = new Uint8Array(4); + for (var k = 0; k < maxLength; ++k) { + var c = input.charCodeAt(i + k); + var b = decodingTable[c]; + if (b === 0xff) { + return undefined; + } + t[k] = b; + } + return (t[0] << 3 * 6) + (t[1] << 2 * 6) + (t[2] << 1 * 6) + (t[3] << 0 * 6); + } + function writeWord(output, i, triple) { + output[i + 0] = triple >> 16 & 0xff; + output[i + 1] = triple >> 8 & 0xff; + output[i + 2] = triple & 0xff; + } + function encode(input) { + var inLen = input.length; + var outLen = calculateEncodedLength(inLen); + var lengthMod3 = inLen % 3; + var calcLength = inLen - lengthMod3; + var output = new Uint8Array(outLen); + var i; + var j = 0; + for (i = 0; i < calcLength; i += 3) { + output[j + 0] = encodingTable[(input[i] & 0xfc) >> 2]; + output[j + 1] = encodingTable[(input[i] & 0x03) << 4 | (input[i + 1] & 0xf0) >> 4]; + output[j + 2] = encodingTable[(input[i + 1] & 0x0f) << 2 | (input[i + 2] & 0xc0) >> 6]; + output[j + 3] = encodingTable[input[i + 2] & 0x3f]; + j += 4; + } + i = calcLength; + switch (lengthMod3) { + case 2: + // One character padding needed + output[j + 0] = encodingTable[(input[i] & 0xfc) >> 2]; + output[j + 1] = encodingTable[(input[i] & 0x03) << 4 | (input[i + 1] & 0xf0) >> 4]; + output[j + 2] = encodingTable[(input[i + 1] & 0x0f) << 2]; + output[j + 3] = paddingChar; + j += 4; + break; + case 1: + // Two character padding needed + output[j + 0] = encodingTable[(input[i] & 0xfc) >> 2]; + output[j + 1] = encodingTable[(input[i] & 0x03) << 4]; + output[j + 2] = paddingChar; + output[j + 3] = paddingChar; + j += 4; + break; + } + var decoder = new TextDecoder("ascii"); + return decoder.decode(output); + } + _base.encode = encode; + function decode(input) { + var inLen = input.length; + if (inLen % 4 != 0) { + return undefined; + } + var padding = 0; + if (inLen > 0 && input.charCodeAt(inLen - 1) == paddingChar) { + ++padding; + if (inLen > 1 && input.charCodeAt(inLen - 2) == paddingChar) { + ++padding; + } + } + var encodedLen = inLen - padding; + var completeLen = encodedLen & ~3; + var outLen = 6 * inLen / 8 - padding; + var output = new Uint8Array(outLen); + var triple; + var i = 0; + var j = 0; + while (i < completeLen) { + triple = readWord(input, i, 4); + if (typeof triple === "undefined") { + return undefined; + } + writeWord(output, j, triple); + i += 4; + j += 3; + } + if (padding > 0) { + triple = readWord(input, i, 4 - padding); + if (typeof triple === "undefined") { + return undefined; + } + switch (padding) { + case 1: + output[j + 0] = triple >> 16 & 0xff; + output[j + 1] = triple >> 8 & 0xff; + break; + case 2: + output[j + 0] = triple >> 16 & 0xff; + break; + } + } + return output; + } + _base.decode = decode; +})(base64 || (exports.base64 = base64 = {})); -var _extends3 = _interopRequireDefault(_extends2); +/***/ }), -var _classCallCheck2 = __webpack_require__(99663); +/***/ 6329: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); +"use strict"; -var _createClass2 = __webpack_require__(22600); -var _createClass3 = _interopRequireDefault(_createClass2); +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.captureClientAPI = exports.CaptureScreenshotService = void 0; +exports.getScreenshotRatio = getScreenshotRatio; +exports.imageSizeFromDataURI = imageSizeFromDataURI; +exports.scaleDataURI = scaleDataURI; +var _web_extension = _interopRequireDefault(__webpack_require__(41953)); +var _utils = __webpack_require__(46580); +var _ts_utils = __webpack_require__(1601); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +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), !0).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; } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +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."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +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; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /* globals chrome */ +function imageSizeFromDataURI(dataURI) { + return createImageBitmap((0, _utils.dataURItoBlob)(dataURI)).then(function (img) { + return { + width: img.width, + height: img.height + }; + }); +} +function getScreenshotRatio(dataURI, tabId, devicePixelRatio) { + return Promise.all([imageSizeFromDataURI(dataURI), _web_extension["default"].tabs.get(tabId)]).then(function (tuple) { + var _tuple = _slicedToArray(tuple, 2), + size = _tuple[0], + tab = _tuple[1]; + return tab.width * devicePixelRatio / size.width; + }); +} +function scaleDataURI(dataURI, scale) { + if (scale === 1) return Promise.resolve(dataURI); + return imageSizeFromDataURI(dataURI).then(function (size) { + var canvas = createCanvas(size.width, size.height, scale); + return drawOnCanvas({ + canvas: canvas, + dataURI: dataURI, + x: 0, + y: 0, + width: size.width * scale, + height: size.height * scale + }).then(function () { + return canvas.toDataURL(); + }); + }); +} +function pCompose(list) { + return list.reduce(function (prev, fn) { + return prev.then(fn); + }, Promise.resolve()); +} +var CaptureScreenshotService = exports.CaptureScreenshotService = /*#__PURE__*/function () { + function CaptureScreenshotService(params) { + _classCallCheck(this, CaptureScreenshotService); + this.params = params; + this.captureVisibleTab = typeof chrome !== 'undefined' && typeof chrome.tabs !== 'undefined' && typeof chrome.tabs.MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND === 'number' ? (0, _ts_utils.throttlePromiseFunc)(this.params.captureVisibleTab, chrome.tabs.MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND * 1000 + 100) : this.params.captureVisibleTab; + } + _createClass(CaptureScreenshotService, [{ + key: "saveScreen", + value: function saveScreen(screenshotStorage, tabId, fileName, devicePixelRatio) { + return this.captureScreenBlob(tabId, devicePixelRatio).then(function (screenBlob) { + return screenshotStorage.overwrite(fileName, screenBlob).then(function () { + return screenshotStorage.getLink(fileName); + }).then(function (url) { + return { + url: url, + fileName: fileName + }; + }, function (e) { + return Promise.reject(e); + }); + }); + } + }, { + key: "saveFullScreen", + value: function saveFullScreen(screenshotStorage, tabId, fileName, clientAPI) { + return this.captureFullScreen(tabId, clientAPI, { + blob: true + }).then(function (screenBlob) { + return screenshotStorage.overwrite(fileName, screenBlob).then(function () { + return screenshotStorage.getLink(fileName); + }).then(function (url) { + return { + url: url, + fileName: fileName + }; + }); + }); + } + }, { + key: "captureScreen", + value: function captureScreen(tabId, devicePixelRatio, presetScreenshotRatio) { + var is2ndArgFunction = typeof presetScreenshotRatio === 'function'; + var hasScreenshotRatio = !!presetScreenshotRatio && !is2ndArgFunction; + var pDataURI = this.captureVisibleTab(null, { + format: 'png' + }); + var pRatio = hasScreenshotRatio ? Promise.resolve(presetScreenshotRatio) : pDataURI.then(function (dataURI) { + return getScreenshotRatio(dataURI, tabId, devicePixelRatio); + }); + return Promise.all([pDataURI, pRatio]).then(function (tuple) { + var _tuple2 = _slicedToArray(tuple, 2), + dataURI = _tuple2[0], + screenshotRatio = _tuple2[1]; + // Note: leak the info about screenshotRatio on purpose + if (!hasScreenshotRatio && is2ndArgFunction) presetScreenshotRatio(screenshotRatio); + if (screenshotRatio === 1) return dataURI; + return scaleDataURI(dataURI, screenshotRatio); + }); + } + }, { + key: "captureFullScreen", + value: function captureFullScreen(tabId) { + var _this = this; + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : captureClientAPI, + startCapture = _ref.startCapture, + scrollPage = _ref.scrollPage, + endCapture = _ref.endCapture; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var opts = _objectSpread({ + blob: false + }, options); + return withPageInfo(startCapture, endCapture, function (pageInfo) { + var devicePixelRatio = pageInfo.devicePixelRatio; + + // Note: cut down page width and height + // reference: https://stackoverflow.com/questions/6081483/maximum-size-of-a-canvas-element/11585939#11585939 + var maxSide = Math.floor(32767 / devicePixelRatio); + pageInfo.pageWidth = Math.min(maxSide, pageInfo.pageWidth); + pageInfo.pageHeight = Math.min(maxSide, pageInfo.pageHeight); + var captureScreen = _this.createCaptureScreenWithCachedScreenshotRatio(devicePixelRatio); + var canvas = createCanvas(pageInfo.pageWidth, pageInfo.pageHeight, devicePixelRatio); + var scrollOffsets = getAllScrollOffsets(pageInfo); + var todos = scrollOffsets.map(function (offset, i) { + return function () { + return scrollPage(offset, { + index: i, + total: scrollOffsets.length + }).then(function (realOffset) { + return captureScreen(tabId).then(function (dataURI) { + return drawOnCanvas({ + canvas: canvas, + dataURI: dataURI, + x: realOffset.x * devicePixelRatio, + y: realOffset.y * devicePixelRatio, + width: pageInfo.windowWidth * devicePixelRatio, + height: pageInfo.windowHeight * devicePixelRatio + }); + }); + }); + }; + }); + var convert = opts.blob ? _utils.dataURItoBlob : function (x) { + return x; + }; + return pCompose(todos).then(function () { + return convert(canvas.toDataURL()); + }); + }); + } + }, { + key: "captureScreenInSelectionSimple", + value: function captureScreenInSelectionSimple(tabId, _ref2) { + var rect = _ref2.rect, + devicePixelRatio = _ref2.devicePixelRatio; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var opts = _objectSpread({ + blob: false + }, options); + var convert = opts.blob ? _utils.dataURItoBlob : function (x) { + return x; + }; + var canvas = createCanvas(rect.width, rect.height, devicePixelRatio); + return this.captureScreen(tabId, devicePixelRatio).then(function (dataURI) { + return drawOnCanvas({ + canvas: canvas, + dataURI: dataURI, + x: -1 * rect.x * devicePixelRatio, + y: -1 * rect.y * devicePixelRatio + }); + }).then(function () { + return convert(canvas.toDataURL()); + }); + } + }, { + key: "captureScreenInSelection", + value: function captureScreenInSelection(tabId, _ref3, _ref4) { + var _this2 = this; + var rect = _ref3.rect, + devicePixelRatio = _ref3.devicePixelRatio; + var startCapture = _ref4.startCapture, + scrollPage = _ref4.scrollPage, + endCapture = _ref4.endCapture; + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var opts = _objectSpread({ + blob: false + }, options); + var convert = opts.blob ? _utils.dataURItoBlob : function (x) { + return x; + }; + return withPageInfo(startCapture, endCapture, function (pageInfo) { + var maxSide = Math.floor(32767 / devicePixelRatio); + pageInfo.pageWidth = Math.min(maxSide, pageInfo.pageWidth); + pageInfo.pageHeight = Math.min(maxSide, pageInfo.pageHeight); + var captureScreen = _this2.createCaptureScreenWithCachedScreenshotRatio(devicePixelRatio); + var canvas = createCanvas(rect.width, rect.height, devicePixelRatio); + var scrollOffsets = getAllScrollOffsetsForRect(rect, pageInfo); + var todos = scrollOffsets.map(function (offset, i) { + return function () { + return scrollPage(offset, { + index: i, + total: scrollOffsets.length + }).then(function (realOffset) { + return captureScreen(tabId).then(function (dataURI) { + return drawOnCanvas({ + canvas: canvas, + dataURI: dataURI, + x: (realOffset.x - rect.x) * devicePixelRatio, + y: (realOffset.y - rect.y) * devicePixelRatio, + width: pageInfo.windowWidth * devicePixelRatio, + height: pageInfo.windowHeight * devicePixelRatio + }); + }); + }); + }; + }); + return pCompose(todos).then(function () { + return convert(canvas.toDataURL()); + }); + }); + } + }, { + key: "createCaptureScreenWithCachedScreenshotRatio", + value: function createCaptureScreenWithCachedScreenshotRatio(devicePixelRatio) { + var _this3 = this; + var screenshotRatio; + return function (tabId) { + return _this3.captureScreen(tabId, devicePixelRatio, screenshotRatio || function (ratio) { + screenshotRatio = ratio; + }); + }; + } + }, { + key: "captureScreenBlob", + value: function captureScreenBlob(tabId, devicePixelRatio) { + return this.captureScreen(tabId, devicePixelRatio).then(_utils.dataURItoBlob); + } + }]); + return CaptureScreenshotService; +}(); +function getAllScrollOffsets(_ref5) { + var pageWidth = _ref5.pageWidth, + pageHeight = _ref5.pageHeight, + windowWidth = _ref5.windowWidth, + windowHeight = _ref5.windowHeight, + _ref5$topPadding = _ref5.topPadding, + topPadding = _ref5$topPadding === void 0 ? 150 : _ref5$topPadding; + var topPad = windowHeight > topPadding ? topPadding : 0; + var xStep = windowWidth; + var yStep = windowHeight - topPad; + var result = []; -var _keys = __webpack_require__(88902); + // Note: bottom comes first so that when we render those screenshots one by one to the final canvas, + // those at top will overwrite top padding part of those at bottom, it is useful if that page has some fixed header + for (var y = pageHeight - windowHeight; y > -1 * yStep; y -= yStep) { + for (var x = 0; x < pageWidth; x += xStep) { + result.push({ + x: x, + y: y + }); + } + } + return result; +} +function getAllScrollOffsetsForRect(_ref6, _ref7) { + var x = _ref6.x, + y = _ref6.y, + width = _ref6.width, + height = _ref6.height; + var windowWidth = _ref7.windowWidth, + windowHeight = _ref7.windowHeight, + _ref7$topPadding = _ref7.topPadding, + topPadding = _ref7$topPadding === void 0 ? 150 : _ref7$topPadding; + var topPad = windowHeight > topPadding ? topPadding : 0; + var xStep = windowWidth; + var yStep = windowHeight - topPad; + var result = []; + for (var sy = y + height - windowHeight; sy > y - yStep; sy -= yStep) { + for (var sx = x; sx < x + width; sx += xStep) { + result.push({ + x: sx, + y: sy + }); + } + } + if (result.length === 0) { + result.push({ + x: x, + y: y + height - windowHeight + }); + } + return result; +} +function createCanvas(width, height) { + var pixelRatio = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + if (typeof window === 'undefined') { + return new self.OffscreenCanvas(width * pixelRatio, height * pixelRatio); + } + var canvas = document.createElement('canvas'); + canvas.width = width * pixelRatio; + canvas.height = height * pixelRatio; + return canvas; +} +function drawOnCanvas(_ref8) { + var canvas = _ref8.canvas, + dataURI = _ref8.dataURI, + x = _ref8.x, + y = _ref8.y, + width = _ref8.width, + height = _ref8.height; + return createImageBitmap((0, _utils.dataURItoBlob)(dataURI)).then(function (image) { + canvas.getContext('2d').drawImage(image, 0, 0, image.width, image.height, x, y, width || image.width, height || image.height); + return { + x: x, + y: y, + width: width, + height: height + }; + }); +} +function withPageInfo(startCapture, endCapture, callback) { + return startCapture().then(function (pageInfo) { + // Note: in case sender contains any non-serializable data + delete pageInfo.sender; + return callback(pageInfo).then(function (result) { + endCapture(pageInfo); + return result; + }); + }); +} +var captureClientAPI = exports.captureClientAPI = { + getPageInfo: function getPageInfo() { + var body = document.body; + var widths = [document.documentElement.clientWidth, document.documentElement.scrollWidth, document.documentElement.offsetWidth, body ? body.scrollWidth : 0, body ? body.offsetWidth : 0]; + var heights = [document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight, body ? body.scrollHeight : 0, body ? body.offsetHeight : 0]; + var data = { + pageWidth: Math.max.apply(Math, widths), + pageHeight: Math.max.apply(Math, heights), + windowWidth: window.innerWidth, + windowHeight: window.innerHeight, + hasBody: !!body, + originalX: window.scrollX, + originalY: window.scrollY, + originalOverflowStyle: document.documentElement.style.overflow, + originalBodyOverflowYStyle: body && body.style.overflowY, + devicePixelRatio: window.devicePixelRatio + }; + return data; + }, + startCapture: function startCapture() { + var _ref9 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref9$hideScrollbar = _ref9.hideScrollbar, + hideScrollbar = _ref9$hideScrollbar === void 0 ? true : _ref9$hideScrollbar; + var body = document.body; + var pageInfo = captureClientAPI.getPageInfo(); + + // Note: try to make pages with bad scrolling work, e.g., ones with + // `body { overflow-y: scroll; }` can break `window.scrollTo` + if (body) { + body.style.overflowY = 'visible'; + } + if (hideScrollbar) { + // Disable all scrollbars. We'll restore the scrollbar state when we're done + // taking the screenshots. + document.documentElement.style.overflow = 'hidden'; + } + return Promise.resolve(pageInfo); + }, + scrollPage: function scrollPage(_ref10, opts) { + var x = _ref10.x, + y = _ref10.y; + window.scrollTo(x, y); + return (0, _utils.delay)(function () { + return { + x: window.scrollX, + y: window.scrollY + }; + }, 100); + }, + endCapture: function endCapture(pageInfo) { + var originalX = pageInfo.originalX, + originalY = pageInfo.originalY, + hasBody = pageInfo.hasBody, + originalOverflowStyle = pageInfo.originalOverflowStyle, + originalBodyOverflowYStyle = pageInfo.originalBodyOverflowYStyle; + if (hasBody) { + document.body.style.overflowY = originalBodyOverflowYStyle !== null && originalBodyOverflowYStyle !== void 0 ? originalBodyOverflowYStyle : ''; + } + document.documentElement.style.overflow = originalOverflowStyle; + window.scrollTo(originalX, originalY); + return Promise.resolve(true); + } +}; -var _keys2 = _interopRequireDefault(_keys); +/***/ }), -var _sign = __webpack_require__(39730); +/***/ 62042: +/***/ ((__unused_webpack_module, exports) => { -var _sign2 = _interopRequireDefault(_sign); +"use strict"; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var BOX_ANCHOR_POS = exports.BOX_ANCHOR_POS = { - TOP_LEFT: 1, - TOP_RIGHT: 2, - BOTTOM_RIGHT: 3, - BOTTOM_LEFT: 4 +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.consecutive = consecutive; +exports.withConsecutive = withConsecutive; +function consecutive(c) { + if (typeof c === 'boolean') { + return { + interval: 0, + count: c ? 1 : 0 + }; + } + return c; +} +var timeout = function timeout(duration) { + return new Promise(function (resolve) { + setTimeout(resolve, duration); + }); }; - -var fitSquarePoint = exports.fitSquarePoint = function fitSquarePoint(movingPoint, fixedPoint) { - var mp = movingPoint; - var fp = fixedPoint; - var xlen = Math.abs(mp.x - fp.x); - var ylen = Math.abs(mp.y - fp.y); - var len = Math.min(xlen, ylen); - - return { - x: fp.x + (0, _sign2.default)(mp.x - fp.x) * len, - y: fp.y + (0, _sign2.default)(mp.y - fp.y) * len +function withConsecutive(c, fn) { + var _consecutive = consecutive(c), + interval = _consecutive.interval, + count = _consecutive.count; + var counter = count; + var next = function next(pass) { + if (!pass) throw new Error('failed to run consecutive'); + if (counter-- <= 0) return Promise.resolve(true); + return timeout(interval).then(fn).then(next); }; -}; + return fn().then(next); +} -var calcRectAndAnchor = exports.calcRectAndAnchor = function calcRectAndAnchor(movingPoint, fixedPoint) { - var mp = movingPoint; - var fp = fixedPoint; - var pos = null; - var tlp = null; +/***/ }), - if (mp.x <= fp.x && mp.y <= fp.y) { - pos = BOX_ANCHOR_POS.TOP_LEFT; - tlp = mp; - } else if (mp.x > fp.x && mp.y > fp.y) { - pos = BOX_ANCHOR_POS.BOTTOM_RIGHT; - tlp = fp; - } else if (mp.x > fp.x) { - pos = BOX_ANCHOR_POS.TOP_RIGHT; - tlp = { x: fp.x, y: mp.y }; - } else if (mp.y > fp.y) { - pos = BOX_ANCHOR_POS.BOTTOM_LEFT; - tlp = { x: mp.x, y: fp.y }; - } +/***/ 95902: +/***/ ((__unused_webpack_module, exports) => { - return { - rect: { - x: tlp.x, - y: tlp.y, - width: Math.abs(mp.x - fp.x), - height: Math.abs(mp.y - fp.y) - }, - anchorPos: pos - }; -}; +"use strict"; -var pointAtPos = exports.pointAtPos = function pointAtPos(rect, pos) { - switch (pos) { - case BOX_ANCHOR_POS.TOP_LEFT: - return { - x: rect.x, - y: rect.y - }; - case BOX_ANCHOR_POS.TOP_RIGHT: - return { - x: rect.x + rect.width, - y: rect.y - }; - case BOX_ANCHOR_POS.BOTTOM_RIGHT: - return { - x: rect.x + rect.width, - y: rect.y + rect.height - }; - case BOX_ANCHOR_POS.BOTTOM_LEFT: - return { - x: rect.x, - y: rect.y + rect.height - }; - } -}; -var diagonalPos = exports.diagonalPos = function diagonalPos(pos) { - switch (pos) { - case BOX_ANCHOR_POS.TOP_LEFT: - return BOX_ANCHOR_POS.BOTTOM_RIGHT; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.UNTITLED_ID = exports.TEST_CASE_STATUS = exports.STATE_STORAGE_KEY = exports.SCREENSHOT_DELAY = exports.RECORDER_STATUS = exports.PLAYER_STATUS = exports.PLAYER_MODE = exports.LAST_SCREENSHOT_FILE_NAME = exports.LAST_DESKTOP_SCREENSHOT_FILE_NAME = exports.INSPECTOR_STATUS = exports.CS_IPC_TIMEOUT = exports.CONTENT_SCRIPT_STATUS = exports.APP_STATUS = void 0; +var mk = function mk(list) { + return list.reduce(function (prev, key) { + prev[key] = key; + return prev; + }, {}); +}; +var APP_STATUS = exports.APP_STATUS = mk(['NORMAL', 'INSPECTOR', 'RECORDER', 'PLAYER']); +var INSPECTOR_STATUS = exports.INSPECTOR_STATUS = mk(['PENDING', 'INSPECTING', 'STOPPED']); +var RECORDER_STATUS = exports.RECORDER_STATUS = mk(['PENDING', 'RECORDING', 'STOPPED']); +var PLAYER_STATUS = exports.PLAYER_STATUS = mk(['PLAYING', 'PAUSED', 'STOPPED']); +var PLAYER_MODE = exports.PLAYER_MODE = mk(['TEST_CASE', 'TEST_SUITE']); +var CONTENT_SCRIPT_STATUS = exports.CONTENT_SCRIPT_STATUS = mk(['NORMAL', 'RECORDING', 'INSPECTING', 'PLAYING']); +var TEST_CASE_STATUS = exports.TEST_CASE_STATUS = mk(['NORMAL', 'SUCCESS', 'ERROR', 'ERROR_IN_SUB']); +var LAST_SCREENSHOT_FILE_NAME = exports.LAST_SCREENSHOT_FILE_NAME = '__lastscreenshot'; +var LAST_DESKTOP_SCREENSHOT_FILE_NAME = exports.LAST_DESKTOP_SCREENSHOT_FILE_NAME = '__last_desktop_screenshot'; +var UNTITLED_ID = exports.UNTITLED_ID = '__untitled__'; - case BOX_ANCHOR_POS.TOP_RIGHT: - return BOX_ANCHOR_POS.BOTTOM_LEFT; +// Note: in Ubuntu, you have to take some delay after activating some tab, otherwise there are chances +// Chrome still think the panel is the window you want to take screenshot, and weird enough in Ubuntu, +// You can't take screenshot of tabs with 'chrome-extension://' schema, even if it's your own extension +var SCREENSHOT_DELAY = exports.SCREENSHOT_DELAY = /Linux/i.test(self.navigator.userAgent) ? 200 : 0; +var CS_IPC_TIMEOUT = exports.CS_IPC_TIMEOUT = 3000; +var STATE_STORAGE_KEY = exports.STATE_STORAGE_KEY = 'background_state'; - case BOX_ANCHOR_POS.BOTTOM_RIGHT: - return BOX_ANCHOR_POS.TOP_LEFT; +/***/ }), - case BOX_ANCHOR_POS.BOTTOM_LEFT: - return BOX_ANCHOR_POS.TOP_RIGHT; - } -}; +/***/ 92950: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -var diagonalPoint = exports.diagonalPoint = function diagonalPoint(rect, anchorPos) { - return pointAtPos(rect, diagonalPos(anchorPos)); -}; +"use strict"; -var genGetAnchorRects = exports.genGetAnchorRects = function genGetAnchorRects(ANCHOR_POS, pointAtPos) { - return function (_ref) { - var rect = _ref.rect, - _ref$size = _ref.size, - size = _ref$size === undefined ? 5 : _ref$size; - var values = function values(obj) { - return (0, _keys2.default)(obj).map(function (key) { - return obj[key]; - }); - }; - var createRect = function createRect(point, size) { - return { - x: point.x - size, - y: point.y - size, - width: size * 2, - height: size * 2 - }; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.accurateOffset = accurateOffset; +exports.assertLocator = assertLocator; +exports.bindDrag = exports.bindContentEditableChange = void 0; +exports.canvasFromSVG = canvasFromSVG; +exports.domText = exports.cssSelector = void 0; +exports.elementByElementFromPoint = elementByElementFromPoint; +exports.getAncestor = getAncestor; +exports.getElementByLocator = getElementByLocator; +exports.getElementByXPath = getElementByXPath; +exports.getElementsByXPath = getElementsByXPath; +exports.getPixel = getPixel; +exports.getStyle = void 0; +exports.hasAncestor = hasAncestor; +exports.imageBlobFromSVG = imageBlobFromSVG; +exports.imageDataFromUrl = imageDataFromUrl; +exports.isEditable = isEditable; +exports.isElementFromPoint = isElementFromPoint; +exports.isFirefox = isFirefox; +exports.isLocator = isLocator; +exports.pixel = exports.offset = exports.isVisible = exports.isPositionFixed = void 0; +exports.preloadImage = preloadImage; +exports.rgbToHex = rgbToHex; +exports.scaleRect = scaleRect; +exports.setStyle = exports.scrollTop = exports.scrollLeft = void 0; +exports.subImage = subImage; +exports.svgNodetoString = svgNodetoString; +exports.svgToBase64 = svgToBase64; +exports.viewportCoordinateByElementFromPoint = viewportCoordinateByElementFromPoint; +var _glob = __webpack_require__(42143); +var _utils = __webpack_require__(46580); +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +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."); } +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; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +var getStyle = exports.getStyle = function getStyle(dom) { + if (!dom) throw new Error('getStyle: dom does not exist'); + return getComputedStyle(dom); +}; +var setStyle = exports.setStyle = function setStyle(dom, style) { + if (!dom) throw new Error('setStyle: dom does not exist'); + for (var i = 0, keys = Object.keys(style), len = keys.length; i < len; i++) { + dom.style[keys[i]] = style[keys[i]]; + } + return dom; +}; +var pixel = exports.pixel = function pixel(num) { + if ((num + '').indexOf('px') !== -1) return num; + return (num || 0) + 'px'; +}; +var bindDrag = exports.bindDrag = function bindDrag(options) { + var onDragStart = options.onDragStart, + onDragEnd = options.onDragEnd, + onDrag = options.onDrag, + $el = options.$el, + _options$preventGloba = options.preventGlobalClick, + preventGlobalClick = _options$preventGloba === void 0 ? true : _options$preventGloba, + _options$doc = options.doc, + doc = _options$doc === void 0 ? document : _options$doc; + var isDragging = false; + var startPos = { + x: 0, + y: 0 + }; + var onMouseDown = function onMouseDown(e) { + isDragging = true; + startPos = { + x: e.screenX, + y: e.screenY }; - - return values(ANCHOR_POS).map(function (pos) { - return { - anchorPos: pos, - rect: createRect(pointAtPos(rect, pos), size) - }; + onDragStart(e); + }; + var onMouseUp = function onMouseUp(e) { + if (!isDragging) return; + isDragging = false; + var dx = e.screenX - startPos.x; + var dy = e.screenY - startPos.y; + onDragEnd(e, { + dx: dx, + dy: dy + }); + }; + var onMouseMove = function onMouseMove(e) { + if (!isDragging) return; + var dx = e.screenX - startPos.x; + var dy = e.screenY - startPos.y; + onDrag(e, { + dx: dx, + dy: dy }); + e.preventDefault(); + e.stopPropagation(); + }; + var onClick = function onClick(e) { + e.preventDefault(); + e.stopPropagation(); + }; + if (preventGlobalClick) { + doc.addEventListener('click', onClick, true); + } + doc.addEventListener('mousemove', onMouseMove, true); + doc.addEventListener('mouseup', onMouseUp, true); + $el.addEventListener('mousedown', onMouseDown, true); + return function () { + doc.removeEventListener('click', onClick, true); + doc.removeEventListener('mousemove', onMouseMove, true); + doc.removeEventListener('mouseup', onMouseUp, true); + $el.removeEventListener('mousedown', onMouseDown, true); }; }; +var bindContentEditableChange = exports.bindContentEditableChange = function bindContentEditableChange(options) { + var onChange = options.onChange, + _options$doc2 = options.doc, + doc = _options$doc2 === void 0 ? document : _options$doc2; + var currentCE = null; + var oldContent = null; + var onFocus = function onFocus(e) { + if (!e.target || e.target.contentEditable !== 'true') return; + currentCE = e.target; + oldContent = currentCE.innerHTML; + }; + var onBlur = function onBlur(e) { + if (e.target !== currentCE) { + // Do nothing + } else if (currentCE && currentCE.innerHTML !== oldContent) { + onChange(e); + } + currentCE = null; + oldContent = null; + }; + doc.addEventListener('focus', onFocus, true); + doc.addEventListener('blur', onBlur, true); + return function () { + doc.removeEventListener('focus', onFocus, true); + doc.removeEventListener('blur', onBlur, true); + }; +}; +var scrollLeft = exports.scrollLeft = function scrollLeft(document) { + return document.documentElement.scrollLeft; +}; +var scrollTop = exports.scrollTop = function scrollTop(document) { + return document.documentElement.scrollTop; +}; +var domText = exports.domText = function domText($dom) { + var it = $dom.innerText ? $dom.innerText.trim() : ''; + var tc = $dom.textContent; + var pos = tc.toUpperCase().indexOf(it.toUpperCase()); + return pos === -1 ? it : tc.substr(pos, it.length); +}; +var isVisible = exports.isVisible = function isVisible(el) { + if (el === window.document) return true; + if (!el) return true; + var style = window.getComputedStyle(el); + if (style.display === 'none' || style.opacity === '0' || style.visibility === 'hidden') return false; + return isVisible(el.parentNode); +}; +var cssSelector = exports.cssSelector = function cssSelector(dom) { + if (!dom) return ''; + if (dom.nodeType !== 1) return ''; + if (dom.tagName === 'BODY') return 'body'; + if (dom.id) return '#' + dom.id; + var classes = dom.className.split(/\s+/g).filter(function (item) { + return item && item.length; + }); + var children = Array.from(dom.parentNode ? dom.parentNode.childNodes : []).filter(function ($el) { + return $el.nodeType === 1; + }); + var sameTag = children.filter(function ($el) { + return $el.tagName === dom.tagName; + }); + var sameClass = children.filter(function ($el) { + var cs = typeof $el.className === 'string' ? $el.className.split(/\s+/g) : []; + return _utils.and.apply(void 0, _toConsumableArray(classes.map(function (c) { + return cs.indexOf(c) !== -1; + }))); + }); + var extra = ''; + if (sameTag.length === 1) { + extra = ''; + } else if (classes.length && sameClass.length === 1) { + extra = '.' + classes.join('.'); + } else { + extra = ':nth-child(' + (1 + children.findIndex(function (item) { + return item === dom; + })) + ')'; + } + var me = dom.tagName.toLowerCase() + extra; -var getAnchorRects = exports.getAnchorRects = genGetAnchorRects(BOX_ANCHOR_POS, pointAtPos); - -var Box = exports.Box = function () { - function Box(options) { - (0, _classCallCheck3.default)(this, Box); - this.state = { - type: 'box', - data: null, - style: {}, - rect: { - x: 0, - y: 0, - width: 0, - height: 0 + // Note: browser will add an extra 'tbody' when tr directly in table, which will cause an wrong selector, + // so the hack is to remove all tbody here + var ret = cssSelector(dom.parentNode) + ' > ' + me; + return ret; + // return ret.replace(/\s*>\s*tbody\s*>?/g, ' ') +}; +var isPositionFixed = exports.isPositionFixed = function isPositionFixed($dom) { + if (!$dom || $dom === document.documentElement || $dom === document.body) return false; + return getComputedStyle($dom)['position'] === 'fixed' || isPositionFixed($dom.parentNode); +}; +var offset = exports.offset = function offset(dom) { + if (!dom) return { + left: 0, + top: 0 + }; + var rect = dom.getBoundingClientRect(); + return { + left: rect.left + window.scrollX, + top: rect.top + window.scrollY + }; +}; +function accurateOffset(dom) { + if (!dom) return { + left: 0, + top: 0 + }; + var doc = dom.ownerDocument; + if (!doc || dom === doc.documentElement) return { + left: 0, + top: 0 + }; + var parentOffset = accurateOffset(dom.offsetParent); + return { + left: parentOffset.left + dom.offsetLeft, + top: parentOffset.top + dom.offsetTop + }; +} +function preloadImage(url) { + return new Promise(function (resolve, reject) { + var $img = new Image(); + $img.onload = function () { + resolve({ + $img: $img, + width: $img.width, + height: $img.height + }); + }; + $img.onerror = function (e) { + reject(e); + }; + $img.src = url; + }); +} +function isFirefox() { + return /Firefox/.test(window.navigator.userAgent); +} +function svgNodetoString(svgNode) { + return svgNode.outerHTML; +} +function svgToBase64(str) { + return 'data:image/svg+xml;base64,' + window.btoa(str); +} +function canvasFromSVG(str) { + return new Promise(function (resolve, reject) { + var c = document.createElement('canvas'); + var ctx = c.getContext('2d'); + var img = document.createElement('img'); + var b64 = svgToBase64(str); + var mw = str.match(/ 1 && arguments[1] !== undefined ? arguments[1] : 'image/png'; + var quality = arguments.length > 2 ? arguments[2] : undefined; + return canvasFromSVG(str).then(function (canvas) { + var p = new Promise(function (resolve, reject) { + try { + canvas.toBlob(resolve, mimeType, quality); + } catch (e) { + reject(e); } + }); + return p; + }); +} +function imageDataFromUrl(url) { + return preloadImage(url).then(function (_ref) { + var $img = _ref.$img, + width = _ref.width, + height = _ref.height; + var canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + var context = canvas.getContext('2d'); + context.drawImage($img, 0, 0, width, height); + return context.getImageData(0, 0, width, height); + }); +} +function subImage(imageUrl, rect) { + return new Promise(function (resolve, reject) { + var $img = new Image(); + $img.onload = function () { + var canvas = document.createElement('canvas'); + canvas.width = rect.width; + canvas.height = rect.height; + var context = canvas.getContext('2d'); + context.drawImage($img, 0, 0, $img.width, $img.height, -1 * rect.x, -1 * rect.y, $img.width, $img.height); + resolve(canvas.toDataURL()); }; - this.local = {}; - - var opts = (0, _extends3.default)({ - firstSilence: true, - transform: function transform(x) { - return x; - }, - onStateChange: function onStateChange() {} - }, options); - - this.transform = opts.transform; - this.onStateChange = opts.onStateChange; - this.normalizeRect = opts.normalizeRect || function (x) { - return x; + $img.src = imageUrl; + }); +} +function rgbToHex(r, g, b) { + if (r > 255 || g > 255 || b > 255) { + throw 'Invalid color component'; + } + return (r << 16 | g << 8 | b).toString(16); +} +function getPixel(params) { + var x = params.x, + y = params.y, + dataUrl = params.dataUrl; + return new Promise(function (resolve, reject) { + var $img = new Image(); + $img.onload = function () { + var imgWidth = $img.width; + var imgHeight = $img.height; + if (x < 0 || y < 0 || x > imgWidth || y > imgHeight) { + return reject(new Error("".concat(x, ", ").concat(y, " is out of screenshot bound 0, 0 ~ ").concat(imgWidth, ", ").concat(imgHeight))); + } + var canvas = document.createElement('canvas'); + canvas.width = x + 5; + canvas.height = y + 5; + var context = canvas.getContext('2d'); + context.drawImage($img, 0, 0, x + 5, y + 5, 0, 0, x + 5, y + 5); + var hex; + try { + var p = context.getImageData(x, y, 1, 1).data; + hex = '#' + ('000000' + rgbToHex(p[0], p[1], p[2])).slice(-6); + resolve(hex); + } catch (err) { + var e = err; + reject(new Error("Failed to get pixel color" + (e !== null && e !== void 0 && e.message ? ": ".concat(e.message, ".") : '.'))); + } }; + $img.src = dataUrl; + }); +} +function scaleRect(rect, scale) { + return { + x: scale * rect.x, + y: scale * rect.y, + width: scale * rect.width, + height: scale * rect.height + }; +} +function isEditable(el) { + if (el.contentEditable === 'true') { + return true; + } + var tag = (el.tagName || '').toLowerCase(); + if (['input', 'textarea'].indexOf(tag) === -1) { + return false; + } + var disabled = el.disabled; + var readOnly = el.readOnly; + return !disabled && !readOnly; +} +function hasAncestor(el, checkAncestor) { + var node = el; + while (node) { + if (checkAncestor(node)) { + return true; + } + node = node.parentNode; + } + return false; +} +function getAncestor(el, checkAncestor) { + var node = el; + while (node) { + if (checkAncestor(node)) { + return node; + } + node = node.parentNode; + } + return null; +} +function getElementsByXPath(xpath) { + var snapshot = document.evaluate(xpath, document.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + var list = []; + for (var i = 0, len = snapshot.snapshotLength; i < len; i++) { + list.push(snapshot.snapshotItem(i)); + } + return list; +} +function getElementByXPath(xpath) { + return getElementsByXPath(xpath)[0]; +} +function assertLocator(str) { + var i = str.indexOf('='); - this.__setState({ - id: opts.id, - data: opts.data, - type: this.getType(), - style: this.getDefaultStyle(), - category: this.getCategory(), - rect: { - x: opts.x, - y: opts.y, - width: opts.width || 0, - height: opts.height || 0 - } - }, { silent: opts.firstSilence }); + // xpath + if (/^\//.test(str)) return true; + // efp + if (/^#elementfrompoint/i.test(str)) return true; + // Above is all locators that doesn't require '=' + if (i === -1) throw new Error('invalid locator, ' + str); + var method = str.substr(0, i); + var value = str.substr(i + 1); + if (!value || !value.length) throw new Error('invalid locator, ' + str); + switch (method && method.toLowerCase()) { + case 'id': + case 'name': + case 'identifier': + case 'link': + case 'linktext': + case 'partiallinktext': + case 'css': + case 'xpath': + return true; + default: + throw new Error('invalid locator, ' + str); } - // Note: possible settings +} +function isLocator(str) { + try { + assertLocator(str); + return true; + } catch (e) { + return false; + } +} +// Note: parse the locator and return the element found accordingly +function getElementByLocator(str, shouldWaitForVisible) { + var i = str.indexOf('='); + var el; + if (/^\//.test(str)) { + el = getElementByXPath(str); + } else if (/^#elementfrompoint/i.test(str.trim())) { + el = elementByElementFromPoint(str); + } else if (i === -1) { + throw new Error('getElementByLocator: invalid locator, ' + str); + } else { + var method = str.substr(0, i); + var value = str.substr(i + 1); + var lowerMethod = method && method.toLowerCase(); + switch (lowerMethod) { + case 'id': + el = document.getElementById(value); + break; + case 'name': + el = document.getElementsByName(value)[0]; + break; + case 'identifier': + el = document.getElementById(value) || document.getElementsByName(value)[0]; + break; + case 'link-notused': + { + var links = [].slice.call(document.getElementsByTagName('a')); + // Note: there are cases such as 'link=exact:xxx' + var realVal = value.replace(/^exact:/, ''); + // Note: position support. eg. link=Download@POS=3 + var match = realVal.match(/^(.+)@POS=(\d+)$/i); + var index = 0; + if (match) { + realVal = match[1]; + index = parseInt(match[2]) - 1; + } - (0, _createClass3.default)(Box, [{ - key: 'getType', - value: function getType() { - return 'box'; - } - }, { - key: 'getCategory', - value: function getCategory() { - return Box.category; - } - }, { - key: 'getDefaultAnchorPos', - value: function getDefaultAnchorPos() { - return BOX_ANCHOR_POS.BOTTOM_RIGHT; + // Note: use textContent instead of innerText to avoid influence from text-transform + var candidates = links.filter(function (a) { + return (0, _glob.globMatch)(realVal, domText(a)); + }); + el = candidates[index]; + break; + } + case 'link': + case 'linktext': + case 'partiallinktext': + { + var _links = [].slice.call(document.getElementsByTagName('a')); + // Note: position support. eg. link=Download@POS=3 + var _match = value.match(/^(.+)@POS=(\d+)$/i); + var _realVal = value; + var _index = 0; + if (_match) { + _realVal = _match[1]; + _index = parseInt(_match[2]) - 1; + } + var pattern = lowerMethod === 'partiallinktext' ? "*".concat(_realVal, "*") : _realVal; + var _candidates = _links.filter(function (link) { + return (0, _glob.globMatch)(pattern, domText(link), { + flags: 'im' + }); + }); + el = _candidates[_index]; + break; + } + case 'css': + el = document.querySelector(value); + break; + case 'xpath': + el = getElementByXPath(value); + break; + default: + throw new Error('getElementByLocator: unsupported locator method, ' + method); } - }, { - key: 'getDefaultStyle', - value: function getDefaultStyle() { - return {}; + } + if (!el) { + throw new Error('getElementByLocator: fail to find element based on the locator, ' + str); + } + if (shouldWaitForVisible && !isVisible(el)) { + throw new Error('getElementByLocator: element is found but not visible yet'); + } + return el; +} +function isElementFromPoint(str) { + return /^#elementfrompoint/i.test(str.trim()); +} +function viewportCoordinateByElementFromPoint(str) { + var reg = /^#elementfrompoint\s*\((\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\)/i; + var m = str.trim().match(reg); + if (!m) { + throw new Error("Invalid '#elementfrompoint' expression"); + } + var viewportX = parseFloat(m[1]); + var viewportY = parseFloat(m[2]); + if (viewportX <= 0 || viewportY <= 0) { + throw new Error("'#elementfrompoint' only accepts positive numbers"); + } + return [viewportX, viewportY]; +} +function elementByElementFromPoint(str) { + var _viewportCoordinateBy = viewportCoordinateByElementFromPoint(str), + _viewportCoordinateBy2 = _slicedToArray(_viewportCoordinateBy, 2), + x = _viewportCoordinateBy2[0], + y = _viewportCoordinateBy2[1]; + var el = document.elementFromPoint(x, y); + return el; +} + +/***/ }), + +/***/ 36447: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = interceptLog; +/** + * + * @description + * it is used to intercept log in production environment + */ +function interceptLog() { + var isProduction = "production" === 'production'; + if (isProduction) { + var noop = function noop() {}; + console.log = noop; + console.info = noop; + console.warn = noop; + console.error = noop; + } +} + +/***/ }), + +/***/ 75866: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getIpcCache = exports.IpcCache = void 0; +var _ts_utils = __webpack_require__(1601); +var _consecutive = __webpack_require__(62042); +var _storage = _interopRequireDefault(__webpack_require__(88555)); +var _ipc_bg_cs = __webpack_require__(59711); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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 _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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +var IpcStatus = /*#__PURE__*/function (IpcStatus) { + IpcStatus[IpcStatus["Off"] = 0] = "Off"; + IpcStatus[IpcStatus["On"] = 1] = "On"; + return IpcStatus; +}(IpcStatus || {}); +var ipcCacheStorageKey = 'ipc_cache'; +var IpcCache = exports.IpcCache = /*#__PURE__*/function () { + function IpcCache() { + _classCallCheck(this, IpcCache); + _defineProperty(this, "cuidIpcMap", {}); + } + _createClass(IpcCache, [{ + key: "fetch", + value: function fetch() { + return _storage["default"].get(ipcCacheStorageKey).then(function (cache) { + return cache || {}; + }); } }, { - key: 'getId', - value: function getId() { - return this.state.id; + key: "has", + value: function has(tabId, cuid) { + return this.fetch().then(function (cache) { + var item = cache[tabId]; + return !!item && (!cuid || item.cuid == cuid); + }); } }, { - key: 'getState', - value: function getState() { - return this.transform(this.state); + key: "get", + value: function get(tabId) { + var _this = this; + var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2000; + var before = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Infinity; + return (0, _ts_utils.until)('ipc by tab id', function () { + return _this.fetch().then(function (cache) { + var ipcObj = cache[tabId]; + var enabled = ipcObj && ipcObj.status === IpcStatus.On; + var valid = enabled && (before === Infinity || before > ipcObj.timestamp); + if (!valid) { + return { + pass: false, + result: null + }; + } + return { + pass: true, + result: _this.getCachedIpc("".concat(ipcObj.cuid), tabId) + }; + }); + }, 100, timeout); } }, { - key: 'processIncomingStyle', - value: function processIncomingStyle(style) { - return style; + key: "domReadyGet", + value: function domReadyGet(tabId) { + var _this2 = this; + var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 60 * 1000; + var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + return (0, _ts_utils.retry)(function () { + return _this2.get(tabId).then(function (ipc) { + // Note: must respond to DOM READY for multiple times in line, + // before we can be sure that it's ready + return (0, _consecutive.withConsecutive)(c, function () { + return ipc.ask('DOM_READY', {}, 1000).then(function () { + return true; + }, function () { + return false; + }); + }).then(function () { + return ipc; + }); + }); + }, { + timeout: timeout, + retryInterval: 1000, + shouldRetry: function shouldRetry(e) { + return true; + } + })(); } }, { - key: 'setStyle', - value: function setStyle(obj) { - this.__setState({ - style: (0, _extends3.default)({}, this.state.style, this.processIncomingStyle(obj)) + key: "set", + value: function set(tabId, ipc, cuid) { + return this.fetch().then(function (cache) { + cache[tabId] = { + ipc: ipc, + cuid: cuid, + status: 1, + timestamp: new Date().getTime() + }; + // remove functions from cache object to avoid errors in saving object in storage in firefox + var cacheObj = JSON.parse(JSON.stringify(cache)); + return _storage["default"].set(ipcCacheStorageKey, cacheObj).then(function () {}); }); } }, { - key: 'setData', - value: function setData(data) { - this.__setState({ data: data }); - } - }, { - key: 'moveAnchorStart', - value: function moveAnchorStart(_ref2) { - var anchorPos = _ref2.anchorPos; - - this.__setLocal({ - oldPoint: pointAtPos(this.state.rect, anchorPos), - oldAnchorPos: anchorPos, - anchorPos: anchorPos + key: "setStatus", + value: function setStatus(tabId, status) { + var updateTimestamp = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + return this.fetch().then(function (cache) { + var found = cache[tabId]; + if (!found) return false; + found.status = status; + if (updateTimestamp) { + found.timestamp = new Date().getTime(); + } + return _storage["default"].set(ipcCacheStorageKey, cache); }); } }, { - key: 'moveAnchor', - value: function moveAnchor(_ref3) { - var x = _ref3.x, - y = _ref3.y; - - var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - fit = _ref4.fit; - - var old = this.state.rect; - var pos = this.local.anchorPos; - var fixed = diagonalPoint(old, pos); - var moving = !fit ? { x: x, y: y } : fitSquarePoint({ x: x, y: y }, fixed); - var res = calcRectAndAnchor(moving, fixed); - - this.__setLocal({ anchorPos: res.anchorPos }); - this.__setState({ rect: this.normalizeRect(res.rect, 'moveAnchor') }); + key: "enable", + value: function enable(tabId) { + return this.setStatus(tabId, IpcStatus.On, true); } }, { - key: 'moveAnchorEnd', - value: function moveAnchorEnd() { - this.__setLocal({ - oldPoint: null, - oldAnchorPos: null, - anchorPos: null - }); + key: "disable", + value: function disable(tabId) { + return this.setStatus(tabId, IpcStatus.Off); } }, { - key: 'moveBoxStart', - value: function moveBoxStart() { - this.__setLocal({ - oldRect: (0, _extends3.default)({}, this.state.rect) + key: "getCuid", + value: function getCuid(tabId) { + return this.fetch().then(function (cache) { + var found = cache[tabId]; + if (!found) return null; + return found.cuid; }); } }, { - key: 'moveBox', - value: function moveBox(_ref5) { - var dx = _ref5.dx, - dy = _ref5.dy; - - var old = this.local.oldRect; - var upd = (0, _extends3.default)({}, old, { - x: old.x + dx, - y: old.y + dy + key: "del", + value: function del(tabId) { + return this.fetch().then(function (cache) { + delete cache[tabId]; + return _storage["default"].set(ipcCacheStorageKey, cache).then(function () {}); }); - - this.__setState({ rect: this.normalizeRect(upd, 'moveBox') }); } }, { - key: 'moveBoxEnd', - value: function moveBoxEnd() { - this.__setLocal({ - oldRect: null + key: "cleanup", + value: function cleanup(tabIdDict) { + return this.fetch().then(function (cache) { + Object.keys(cache).forEach(function (tabId) { + if (!tabIdDict[tabId]) { + delete cache[tabId]; + } + }); + return _storage["default"].set(ipcCacheStorageKey, cache).then(function () { + return cache; + }); }); } }, { - key: '__setState', - value: function __setState(obj) { - var _this = this; - - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var last = this.getState(); - - this.state = (0, _extends3.default)({}, this.state, obj); - - if (opts.silent) return; - - var fn = function fn() { - return _this.onStateChange(_this.getState(), last); - }; - var invoke = opts.nextTick ? function (fn) { - return setTimeout(fn, 0); - } : function (fn) { - return fn(); - }; - - invoke(fn); - } - }, { - key: '__setLocal', - value: function __setLocal(obj) { - this.local = (0, _extends3.default)({}, this.local, obj); + key: "getCachedIpc", + value: function getCachedIpc(cuid, tabId) { + if (!this.cuidIpcMap[cuid]) { + this.cuidIpcMap[cuid] = (0, _ipc_bg_cs.openBgWithCs)(cuid).ipcBg(tabId); + } + return this.cuidIpcMap[cuid]; } }]); - return Box; + return IpcCache; }(); - -Box.settings = []; -Box.category = 'rect'; -Box.defaultAnchorPos = BOX_ANCHOR_POS.BOTTOM_RIGHT; +var getIpcCache = exports.getIpcCache = (0, _ts_utils.singletonGetter)(function () { + return new IpcCache(); +}); /***/ }), -/***/ 77930: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 89130: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -1167,131 +2214,41 @@ Box.defaultAnchorPos = BOX_ANCHOR_POS.BOTTOM_RIGHT; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.decryptIfNeeded = exports.encryptIfNeeded = exports.decrypt = exports.encrypt = exports.aesDecrypt = exports.aesEncrypt = undefined; - -var _promise = __webpack_require__(46593); - -var _promise2 = _interopRequireDefault(_promise); - -var _pbkdf = __webpack_require__(25632); - -var _pbkdf2 = _interopRequireDefault(_pbkdf); - -var _aesJs = __webpack_require__(78826); - -var _aesJs2 = _interopRequireDefault(_aesJs); - -var _web_extension = __webpack_require__(61171); - -var _web_extension2 = _interopRequireDefault(_web_extension); - -var _storage = __webpack_require__(67585); - -var _storage2 = _interopRequireDefault(_storage); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var RAW_PREFIX = '@_KANTU_@'; -var DEPRECATED_CIPHER_PREFIX = '__KANTU_ENCRYPTED__'; -var CIPHER_PREFIX = '__RPA_ENCRYPTED__'; -var RAW_PREFIX_REG = new RegExp('^' + RAW_PREFIX); -var CIPHER_PREFIX_REG = new RegExp('^(' + CIPHER_PREFIX + '|' + DEPRECATED_CIPHER_PREFIX + ')'); +exports["default"] = void 0; +exports.logFactory = logFactory; +// Log factory is quite simple, just a wrapper on console.log +// so that you can use the same API, at the same, achieve following features +// 1. Hide all logs in production +// 2. Extend it to save logs in local storage / or send it back to you backend (for debug or analysis) -var getEncryptConfig = function getEncryptConfig() { - return _storage2.default.get('config').then(function (config) { - return { - shouldEncrypt: config.shouldEncryptPassword === 'master_password', - masterPassword: config.masterPassword +function logFactory(enabled) { + var isEnabled = !!enabled; + var obj = ['log', 'info', 'warn', 'error'].reduce(function (prev, method) { + prev[method] = function () { + var _console; + if (!isEnabled) return; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + (_console = console)[method].apply(_console, [new Date().toISOString(), ' - '].concat(args)); }; + return prev; + }, {}); + return Object.assign(obj.log, obj, { + enable: function enable() { + isEnabled = true; + }, + disable: function disable() { + isEnabled = false; + } }); -}; - -var aesEncrypt = exports.aesEncrypt = function aesEncrypt(text, password) { - var key = _pbkdf2.default.pbkdf2Sync(password, 'salt', 1, 256 / 8, 'sha512'); - var engine = new _aesJs2.default.ModeOfOperation.ctr(key); - - return _aesJs2.default.utils.hex.fromBytes(engine.encrypt(_aesJs2.default.utils.utf8.toBytes(text))); -}; - -var aesDecrypt = exports.aesDecrypt = function aesDecrypt(text, password) { - var key = _pbkdf2.default.pbkdf2Sync(password, 'salt', 1, 256 / 8, 'sha512'); - var engine = new _aesJs2.default.ModeOfOperation.ctr(key); - - return _aesJs2.default.utils.utf8.fromBytes(engine.decrypt(_aesJs2.default.utils.hex.toBytes(text))); -}; - -var encrypt = exports.encrypt = function encrypt(text) { - return getEncryptConfig().then(function (_ref) { - var shouldEncrypt = _ref.shouldEncrypt, - masterPassword = _ref.masterPassword; - - if (!shouldEncrypt) return text; - return '' + CIPHER_PREFIX + aesEncrypt(RAW_PREFIX + text, masterPassword); - }); -}; - -var decrypt = exports.decrypt = function decrypt(text) { - return getEncryptConfig().then(function (_ref2) { - var shouldEncrypt = _ref2.shouldEncrypt, - masterPassword = _ref2.masterPassword; - - if (!shouldEncrypt) return text; - var raw = aesDecrypt(text.replace(CIPHER_PREFIX_REG, ''), masterPassword); - if (raw.indexOf(RAW_PREFIX) !== 0) throw new Error('Wrong master password'); - return raw.replace(RAW_PREFIX_REG, ''); - }).catch(function (e) { - throw new Error('password string invalid'); - }); -}; - -var encryptIfNeeded = exports.encryptIfNeeded = function encryptIfNeeded(text, dom) { - if (dom && dom.tagName.toUpperCase() === 'INPUT' && dom.type === 'password') { - return encrypt(text); - } - - return _promise2.default.resolve(text); -}; - -var decryptIfNeeded = exports.decryptIfNeeded = function decryptIfNeeded(text, dom) { - if (!CIPHER_PREFIX_REG.test(text)) { - return _promise2.default.resolve(text); - } - - if (!dom || ['INPUT', 'TEXTAREA'].indexOf(dom.tagName.toUpperCase()) !== -1) { - return decrypt(text); - } - - return _promise2.default.resolve(text); -}; - -/***/ }), - -/***/ 64341: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.globMatch = globMatch; - -var _kdGlobToRegexp = __webpack_require__(33733); - -var _kdGlobToRegexp2 = _interopRequireDefault(_kdGlobToRegexp); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function globMatch(pattern, text, opts) { - var reg = (0, _kdGlobToRegexp2.default)(pattern, opts || {}); - var res = reg.test(text); - return res; } +var logger = logFactory("production" !== 'production'); +var _default = exports["default"] = logger; /***/ }), -/***/ 14537: +/***/ 1601: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; @@ -1300,738 +2257,1196 @@ function globMatch(pattern, text, opts) { Object.defineProperty(exports, "__esModule", ({ value: true })); - -var _typeof2 = __webpack_require__(72444); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _keys = __webpack_require__(88902); - -var _keys2 = _interopRequireDefault(_keys); - -var _from = __webpack_require__(24043); - -var _from2 = _interopRequireDefault(_from); - -var _log = __webpack_require__(77242); - -var _log2 = _interopRequireDefault(_log); - -var _dom_utils = __webpack_require__(24874); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/* - * Basic tool function - */ - -var extend = function extend() { - var args = (0, _from2.default)(arguments); - var len = args.length; - - if (len <= 0) return {}; - if (len === 1) return args[0]; - - var head = args[0]; - var rest = args.slice(1); - - return rest.reduce(function (prev, cur) { - for (var i = 0, keys = (0, _keys2.default)(cur), len = keys.length; i < len; i++) { - prev[keys[i]] = cur[keys[i]]; - } - - return prev; - }, head); -}; - -var isArray = Array.isArray; - -var id = function id(x) { +exports.TraverseTreeResult = void 0; +exports.addInBetween = addInBetween; +exports.ancestorsInNode = ancestorsInNode; +exports.ancestorsInNodesList = ancestorsInNodesList; +exports.and = void 0; +exports.assertExhausted = assertExhausted; +exports.capitalInitial = capitalInitial; +exports.clone = clone; +exports.compose = void 0; +exports.concatUint8Array = concatUint8Array; +exports.concurrent = void 0; +exports.consecutive = consecutive; +exports.countDown = countDown; +exports.delay = void 0; +exports.errorClassFactory = errorClassFactory; +exports.findNodeInForest = findNodeInForest; +exports.findNodeInTree = findNodeInTree; +exports.flatten = void 0; +exports.flattenTreeWithPaths = flattenTreeWithPaths; +exports.flatternTree = flatternTree; +exports.flow = flow; +exports.forestSlice = forestSlice; +exports.getExtName = getExtName; +exports.getIn = void 0; +exports.guardVoidPromise = guardVoidPromise; +exports.id = id; +exports.isForestEqual = isForestEqual; +exports.isMac = isMac; +exports.isTreeEqual = isTreeEqual; +exports.map = void 0; +exports.milliSecondsToStringInSecond = milliSecondsToStringInSecond; +exports.nodeByOffset = nodeByOffset; +exports.nodeCount = nodeCount; +exports.normalizeHtmlId = normalizeHtmlId; +exports.or = exports.on = exports.objMap = exports.objFilter = void 0; +exports.pad2digits = pad2digits; +exports.parseBoolLike = parseBoolLike; +exports.partial = void 0; +exports.pathsInNode = pathsInNode; +exports.pathsInNodeList = pathsInNodeList; +exports.pickIfExist = exports.pick = void 0; +exports.pointToFitRect = pointToFitRect; +exports.range = void 0; +exports.readFileAsText = readFileAsText; +exports.reduceRight = void 0; +exports.repeatStr = repeatStr; +exports.resolvePath = resolvePath; +exports.retry = void 0; +exports.retryWithCount = retryWithCount; +exports.setIn = exports.safeUpdateIn = exports.safeSetIn = exports.safeOn = exports.safeMap = void 0; +exports.singletonGetter = singletonGetter; +exports.singletonGetterByKey = singletonGetterByKey; +exports.snakeToCamel = snakeToCamel; +exports.strictParseBoolLike = strictParseBoolLike; +exports.sum = sum; +exports.throttle = throttle; +exports.throttlePromiseFunc = throttlePromiseFunc; +exports.toArray = toArray; +exports.traverseTree = traverseTree; +exports.treeFilter = treeFilter; +exports.treeMap = treeMap; +exports.treeSlice = treeSlice; +exports.updateIn = exports.until = exports.uniqueStrings = exports.uniqueName = exports.unique = exports.uid = void 0; +exports.urlWithQueries = urlWithQueries; +exports.withConsecutive = withConsecutive; +exports.withPostfix = exports.withFileExtension = exports.withCountDown = void 0; +exports.withPromise = withPromise; +exports.zipWith = exports.without = void 0; +var _log = _interopRequireDefault(__webpack_require__(89130)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } +function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _isNativeFunction(fn) { try { return Function.toString.call(fn).indexOf("[native code]") !== -1; } catch (e) { return typeof fn === "function"; } } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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), !0).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; } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +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 singletonGetter(factoryFn) { + var instance = null; + return function () { + if (instance) return instance; + instance = factoryFn.apply(void 0, arguments); + return instance; + }; +} +function singletonGetterByKey(getKey, factoryFn) { + var cache = {}; + return function () { + var key = getKey.apply(void 0, arguments); + if (cache[key]) return cache[key]; + cache[key] = factoryFn.apply(void 0, arguments); + return cache[key]; + }; +} +function id(x) { return x; +} +function capitalInitial(str) { + return str.charAt(0).toUpperCase() + str.substr(1); +} +function snakeToCamel(kebabStr) { + var list = kebabStr.split('_'); + return list[0] + list.slice(1).map(capitalInitial).join(''); +} +var delay = exports.delay = function delay(fn, timeout) { + return new Promise(function (resolve, reject) { + setTimeout(function () { + try { + resolve(fn()); + } catch (e) { + reject(e); + } + }, timeout); + }); }; - -var trim = function trim(str) { - return str.replace(/^\s*|\s*$/g, ''); -}; - -var flatten = function flatten(list) { - return [].concat.apply([], list); -}; - -var sum = function sum() { - var list = (0, _from2.default)(arguments); - return list.reduce(function (prev, cur) { - return prev + cur; - }, 0); -}; - -var last = function last(list) { - return list[list.length - 1]; +var until = exports.until = function until(name, check) { + var interval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1000; + var expire = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 10000; + var start = new Date().getTime(); + var go = /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var _yield$Promise$resolv, pass, result; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(expire && new Date().getTime() - start >= expire)) { + _context.next = 2; + break; + } + throw new Error("until: ".concat(name, " expired!")); + case 2: + _context.next = 4; + return Promise.resolve(check()); + case 4: + _yield$Promise$resolv = _context.sent; + pass = _yield$Promise$resolv.pass; + result = _yield$Promise$resolv.result; + if (!pass) { + _context.next = 9; + break; + } + return _context.abrupt("return", Promise.resolve(result)); + case 9: + return _context.abrupt("return", delay(go, interval)); + case 10: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function go() { + return _ref.apply(this, arguments); + }; + }(); + return new Promise(function (resolve, reject) { + try { + resolve(go()); + } catch (e) { + reject(e); + } + }); }; - -var or = function or(list) { - return (list || []).reduce(function (prev, cur) { - return prev || cur; - }, false); +var range = exports.range = function range(start, end) { + var step = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var ret = []; + for (var _i = start; _i < end; _i += step) { + ret.push(_i); + } + return ret; }; - -var and = function and(list) { - return (list || []).reduce(function (prev, cur) { - return prev && cur; - }, true); +var partial = exports.partial = function partial(fn) { + var len = fn.length; + var _arbitary; + _arbitary = function arbitary(curArgs, leftArgCnt) { + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (args.length >= leftArgCnt) { + return fn.apply(null, curArgs.concat(args)); + } + return _arbitary(curArgs.concat(args), leftArgCnt - args.length); + }; + }; + return _arbitary([], len); }; - -var zipWith = function zipWith(fn) { - if (arguments.length < 3) return null; - - var list = (0, _from2.default)(arguments).slice(1); - var len = list.reduce(function (min, cur) { - return cur.length < min ? cur.length : min; - }, Infinity); - var ret = []; - - for (var i = 0; i < len; i++) { - ret.push(fn.apply(null, list.map(function (item) { - return item[i]; - }))); +var reduceRight = exports.reduceRight = function reduceRight(fn, initial, list) { + var ret = initial; + for (var _i2 = list.length - 1; _i2 >= 0; _i2--) { + ret = fn(list[_i2], ret); } - return ret; }; - -var intersect = function intersect() { - var list = (0, _from2.default)(arguments); - var len = Math.max.apply(null, list.map(function (item) { - return item.length; - })); +var compose = exports.compose = function compose() { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + return reduceRight(function (cur, prev) { + return function (x) { + return cur(prev(x)); + }; + }, function (x) { + return x; + }, args); +}; +var map = exports.map = partial(function (fn, list) { var result = []; - - for (var i = 0; i < len; i++) { - var val = list[0][i]; - var no = list.filter(function (item) { - return item[i] !== val; - }); - - if (no && no.length) break; - - result.push(val); + for (var _i3 = 0, len = list.length; _i3 < len; _i3++) { + result.push(fn(list[_i3])); } - return result; -}; - -var deepEqual = function deepEqual(a, b) { - if (isArray(a) && isArray(b)) { - return a.length === b.length && and(zipWith(deepEqual, a, b)); +}); +var on = exports.on = partial(function (key, fn, dict) { + if (Array.isArray(dict)) { + return [].concat(_toConsumableArray(dict.slice(0, key)), [fn(dict[key])], _toConsumableArray(dict.slice(key + 1))); } - - if ((typeof a === 'undefined' ? 'undefined' : (0, _typeof3.default)(a)) === 'object' && (typeof b === 'undefined' ? 'undefined' : (0, _typeof3.default)(b)) === 'object') { - // TODO - return false; + return Object.assign({}, dict, _defineProperty({}, key, fn(dict[key]))); +}); +var updateIn = exports.updateIn = partial(function (keys, fn, obj) { + var updater = compose.apply(null, keys.map(function (key) { + return key === '[]' ? map : on(key); + })); + return updater(fn)(obj); +}); +var setIn = exports.setIn = partial(function (keys, value, obj) { + var updater = compose.apply(null, keys.map(function (key) { + return key === '[]' ? map : on(key); + })); + return updater(function () { + return value; + })(obj); +}); +var getIn = exports.getIn = partial(function (keys, obj) { + return keys.reduce(function (prev, key) { + if (!prev) return prev; + return prev[key]; + }, obj); +}); +var safeMap = exports.safeMap = partial(function (fn, list) { + var result = []; + var safeList = list || []; + for (var _i4 = 0, len = safeList.length; _i4 < len; _i4++) { + result.push(fn(safeList[_i4])); } - - return a === b; -}; - -/* - * Dom helper function - */ - -var pixel = function pixel(num) { - if ((num + '').indexOf('px') !== -1) return num; - return (num || 0) + 'px'; -}; - -var getStyle = function getStyle(dom, styleName) { - if (!dom) throw new Error('getStyle: dom does not exist'); - return getComputedStyle(dom)[styleName]; -}; - -var setStyle = function setStyle(dom, style) { - if (!dom) throw new Error('setStyle: dom does not exist'); - - for (var i = 0, keys = (0, _keys2.default)(style), len = keys.length; i < len; i++) { - dom.style[keys[i]] = style[keys[i]]; + return result; +}); +var safeOn = exports.safeOn = partial(function (key, fn, dict) { + if (Array.isArray(dict)) { + return [].concat(_toConsumableArray(dict.slice(0, key)), [fn(dict[key])], _toConsumableArray(dict.slice(key + 1))); } - - return dom; -}; - -var cssSum = function cssSum(dom, list) { - var isInline = getStyle(dom, 'display') === 'inline'; - - return list.reduce(function (prev, cur) { - var val = isInline && ['width', 'height'].indexOf(cur) !== -1 ? dom.getClientRects()[0][cur] : getStyle(dom, cur); - - return prev + parseInt(val || '0', 10); - }, 0); + return Object.assign({}, dict, _defineProperty({}, key, fn((dict || {})[key]))); +}); +var safeUpdateIn = exports.safeUpdateIn = partial(function (keys, fn, obj) { + var updater = compose.apply(null, keys.map(function (key) { + return key === '[]' ? safeMap : safeOn(key); + })); + return updater(fn)(obj); +}); +var safeSetIn = exports.safeSetIn = partial(function (keys, value, obj) { + var updater = compose.apply(null, keys.map(function (key) { + return key === '[]' ? safeMap : safeOn(key); + })); + return updater(function () { + return value; + })(obj); +}); +var pick = exports.pick = function pick(keys, obj) { + return keys.reduce(function (prev, key) { + prev[key] = obj[key]; + return prev; + }, {}); }; - -var offset = function offset(dom, noPx) { - if (!dom) return { left: 0, top: 0 }; - - var rect = dom.getBoundingClientRect(); - var fn = noPx ? id : pixel; - - return { - left: fn(rect.left + window.scrollX), - top: fn(rect.top + window.scrollY) - }; +var pickIfExist = exports.pickIfExist = function pickIfExist(keys, obj) { + return keys.reduce(function (prev, key) { + if (obj[key] !== undefined) { + prev[key] = obj[key]; + } + return prev; + }, {}); }; - -var rect = function rect(dom, noPx) { - var pos = offset(dom, noPx); - var isInline = getStyle(dom, 'display') === 'inline'; - var w = isInline ? dom.getClientRects()[0]['width'] : getStyle(dom, 'width'); - var h = isInline ? dom.getClientRects()[0]['height'] : getStyle(dom, 'height'); - var fn = noPx ? id : pixel; - - return extend({ width: fn(w), height: fn(h) }, pos); +var without = exports.without = function without(keys, obj) { + return Object.keys(obj).reduce(function (prev, key) { + if (keys.indexOf(key) === -1) { + prev[key] = obj[key]; + } + return prev; + }, {}); }; - -// Reference: http://ryanve.com/lab/dimensions/ -var clientWidth = function clientWidth(document) { - return document.documentElement.clientWidth; +var uid = exports.uid = function uid() { + return '' + new Date().getTime() + '.' + Math.floor(Math.random() * 10000000).toString(16); }; - -var clientHeight = function clientHeight(document) { - return document.documentElement.clientHeight; +var flatten = exports.flatten = function flatten(list) { + return [].concat.apply([], list); }; - -var removeChildren = function removeChildren(dom, predicate) { - var pred = predicate || function () { - return true; +var zipWith = exports.zipWith = function zipWith(fn) { + for (var _len3 = arguments.length, listOfList = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + listOfList[_key3 - 1] = arguments[_key3]; + } + var len = Math.min.apply(Math, _toConsumableArray(listOfList.map(function (list) { + return list.length; + }))); + var res = []; + var _loop = function _loop(_i5) { + res.push(fn.apply(void 0, _toConsumableArray(listOfList.map(function (list) { + return list[_i5]; + })))); }; - var children = dom.childNodes; - - for (var i = children.length - 1; i >= 0; i--) { - if (pred(children[i])) { - dom.removeChild(children[i]); - } + for (var _i5 = 0; _i5 < len; _i5++) { + _loop(_i5); } + return res; }; - -var inDom = function inDom($outer, $el) { - if (!$el) return false; - if ($outer === $el) return true; - return inDom($outer, $el.parentNode); -}; - -var inDomList = function inDomList(list, $el) { - return or(list.map(function ($outer) { - return inDom($outer, $el); - })); -}; - -var parentWithTag = function parentWithTag(tag, $el) { - var lowerTag = tag.toLowerCase(); - var $dom = $el; - - while ($dom) { - if ($dom.tagName.toLowerCase() === lowerTag) { - return $dom; - } - - $dom = $dom.parentNode; +var and = exports.and = function and() { + for (var _len4 = arguments.length, list = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + list[_key4] = arguments[_key4]; } - - return null; + return list.reduce(function (prev, cur) { + return prev && cur; + }, true); }; - -var parentWithClass = function parentWithClass(className, $el) { - var $dom = $el; - - while ($dom) { - // Note: In Firefox, HTML Document object doesn't have `classList` property - if ($dom.classList !== undefined && $dom.classList.contains(className)) { - return $dom; - } - - $dom = $dom.parentNode; +var or = exports.or = function or() { + for (var _len5 = arguments.length, list = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + list[_key5] = arguments[_key5]; } - - return null; + return list.reduce(function (prev, cur) { + return prev || cur; + }, false); }; - -var selector = function selector(dom) { - if (dom.nodeType !== 1) return ''; - if (dom.tagName === 'BODY') return 'body'; - if (dom.id) return '#' + dom.id; - - var classes = (dom.getAttribute('class') || '').split(/\s+/g).filter(function (item) { - return item && item.length; - }); - - var children = (0, _from2.default)(dom.parentNode.childNodes).filter(function ($el) { - return $el.nodeType === 1; - }); - - var sameTag = children.filter(function ($el) { - return $el.tagName === dom.tagName; - }); - - var sameClass = children.filter(function ($el) { - var cs = ($el.getAttribute('class') || '').split(/\s+/g); - - return and(classes.map(function (c) { - return cs.indexOf(c) !== -1; - })); +var withPostfix = exports.withPostfix = function withPostfix(options) { + var reg = options.reg, + str = options.str, + fn = options.fn; + var m = str.match(reg); + var extName = m ? m[0] : ''; + var baseName = m ? str.replace(reg, '') : str; + var result = fn(baseName, function (name) { + return name + extName; }); - - var extra = ''; - - if (sameTag.length === 1) { - extra = ''; - } else if (classes.length && sameClass.length === 1) { - extra = '.' + classes.join('.'); - } else { - extra = ':nth-child(' + (1 + children.findIndex(function (item) { - return item === dom; - })) + ')'; + if (result === null || result === undefined) { + throw new Error('withPostfix: should not return null/undefined'); } - - var me = dom.tagName.toLowerCase() + extra; - - // Note: browser will add an extra 'tbody' when tr directly in table, which will cause an wrong selector, - // so the hack is to remove all tbody here - var ret = selector(dom.parentNode) + ' > ' + me; - return ret; - // return ret.replace(/\s*>\s*tbody\s*>?/g, ' ') -}; - -var getTagIndex = function getTagIndex(dom) { - return (0, _from2.default)(dom.parentNode.childNodes).filter(function (item) { - return item.nodeType === dom.nodeType && item.tagName === dom.tagName; - }).reduce(function (prev, node, i) { - if (prev !== null) return prev; - return node === dom ? i + 1 : prev; - }, null); + if (typeof result.then === 'function') { + return result.then(function (name) { + return name + extName; + }); + } + return result + extName; }; - -var relativeXPath = function relativeXPath(dom) { - if (!dom) return null; - if (dom.nodeType === 3) return '@text'; - - var index = getTagIndex(dom); - var count = (0, _from2.default)(dom.parentNode.childNodes).filter(function (item) { - return item.nodeType === dom.nodeType && item.tagName === dom.tagName; - }).length; - var tag = dom.tagName.toLowerCase(); - - return index > 1 ? tag + '[' + index + ']' : tag; +var withFileExtension = exports.withFileExtension = function withFileExtension(origName, fn) { + return withPostfix({ + fn: fn, + str: origName, + reg: /\.\w+$/ + }); }; - -var xpath = function xpath(dom, cur, list) { - var helper = function helper(dom, cur, list) { - if (!dom) return null; - - if (!cur) { - if (dom.nodeType === 3) { - return helper(dom.parentNode); - } else { - return helper(dom, dom, []); - } +function getExtName(fileName) { + return withFileExtension(fileName, function () { + return ''; + }); +} +var uniqueName = exports.uniqueName = function uniqueName(name, options) { + var opts = _objectSpread({ + generate: function generate(old) { + var step = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + var reg = /_(\d+)$/; + var m = old.match(reg); + if (!m) return "".concat(old, "_").concat(step); + return old.replace(reg, function (_, n) { + return "_".concat(parseInt(n, 10) + step); + }); + }, + check: function check() { + return Promise.resolve(true); + }, + postfixReg: /\.\w+$/ + }, options || {}); + var generate = opts.generate, + check = opts.check, + postfixReg = opts.postfixReg; + return withPostfix({ + str: name, + reg: postfixReg, + fn: function fn(baseName, getFullName) { + var go = function go(fileName, step) { + return Promise.resolve(check(getFullName(fileName))).then(function (pass) { + if (pass) return fileName; + return go(generate(fileName, step), step); + }); + }; + return go(baseName, 1); } - - if (!cur.parentNode) { - return ['html'].concat(list); + }); +}; +var objFilter = exports.objFilter = function objFilter(filter, obj) { + return Object.keys(obj).reduce(function (prev, key, i) { + if (filter(obj[key], key, i)) { + prev[key] = obj[key]; } - - if (cur.tagName === 'BODY') { - return ['html', 'body'].concat(list); + return prev; + }, {}); +}; +function throttle(fn, timeout) { + var lastTime = 0; + return function () { + var now = new Date().getTime(); + if (now - lastTime < timeout) return; + lastTime = now; + return fn.apply(void 0, arguments); + }; +} +var retry = exports.retry = function retry(fn, options) { + return function () { + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; } - - if (cur.id) { - return ['*[@id="' + cur.id + '"]'].concat(list); - } - - return helper(dom, cur.parentNode, [relativeXPath(cur)].concat(list)); - }; - - var parts = helper(dom, cur, list); - var prefix = parts[0] === 'html' ? '/' : '//'; - var ret = prefix + parts.join('/'); - - return ret; -}; - -var xpathPosition = function xpathPosition(dom) { - var path = ''; - var current = dom; - - try { - while (current !== null) { - var currentPath = void 0; - - if (current.parentNode != null) { - currentPath = '/' + relativeXPath(current); - } else if (current.tagName === 'BODY') { - currentPath = 'html/body'; - } else { - currentPath = '/' + current.nodeName.toLowerCase(); + var _timeout$retryInterva = _objectSpread({ + timeout: 5000, + retryInterval: 1000, + onFirstFail: function onFirstFail() {}, + onFinal: function onFinal() {}, + shouldRetry: function shouldRetry(e) { + return false; + } + }, options), + timeout = _timeout$retryInterva.timeout, + onFirstFail = _timeout$retryInterva.onFirstFail, + onFinal = _timeout$retryInterva.onFinal, + shouldRetry = _timeout$retryInterva.shouldRetry, + retryInterval = _timeout$retryInterva.retryInterval; + var retryCount = 0; + var lastError; + var timerToClear; + var done = false; + var wrappedOnFinal = function wrappedOnFinal() { + done = true; + if (timerToClear) { + clearTimeout(timerToClear); } - - path = currentPath + path; - var locator = '/' + path; - - if (dom === (0, _dom_utils.getElementByXPath)(locator)) { - return locator; + return onFinal.apply(void 0, arguments); + }; + var intervalMan = function () { + var lastInterval; + var intervalFactory = function () { + switch (_typeof(retryInterval)) { + case 'function': + return retryInterval; + case 'number': + return function (retryCount, lastInterval) { + return retryInterval; + }; + default: + throw new Error('retryInterval must be either a number or a function'); + } + }(); + return { + getLastInterval: function getLastInterval() { + return lastInterval; + }, + getInterval: function getInterval() { + var interval = intervalFactory(retryCount, lastInterval); + lastInterval = interval; + return interval; + } + }; + }(); + var onError = function onError(e, _throwErr) { + var throwErr = _throwErr || function (e) { + return Promise.reject(e); + }; + if (retryCount === 0) { + onFirstFail(e); } - - current = current.parentNode; - } - } catch (e) {} - - return null; + return new Promise(function (resolve) { + resolve(shouldRetry(e)); + }).then(function (should) { + if (!should) { + wrappedOnFinal(e); + return throwErr(e); + } + lastError = e; + var p = new Promise(function (resolve, reject) { + if (retryCount++ === 0) { + timerToClear = setTimeout(function () { + wrappedOnFinal(lastError); + reject(lastError); + }, timeout); + } + if (done) return; + delay(run, intervalMan.getInterval()).then(resolve, function (e) { + return resolve(onError(e, function (err) { + return reject(e); + })); + }); + }); + return p; + }); + }; + var run = function run() { + return new Promise(function (resolve, reject) { + try { + var res = fn.apply(void 0, args.concat([{ + retryCount: retryCount, + retryInterval: intervalMan.getLastInterval() + }])); + resolve(res); + } catch (e) { + reject(e); + } + })["catch"](onError); + }; + return run().then(function (result) { + wrappedOnFinal(null, result); + return result; + }); + }; }; - -var attributeValue = function attributeValue(value) { - if (value.indexOf("'") < 0) { - return "'" + value + "'"; - } else if (value.indexOf('"') < 0) { - return '"' + value + '"'; - } else { - var result = 'concat('; - var part = ''; - var didReachEndOfValue = false; - while (!didReachEndOfValue) { - var apos = value.indexOf("'"); - var quot = value.indexOf('"'); - if (apos < 0) { - result += "'" + value + "'"; - didReachEndOfValue = true; - break; - } else if (quot < 0) { - result += '"' + value + '"'; - didReachEndOfValue = true; - break; - } else if (quot < apos) { - part = value.substring(0, apos); - result += "'" + part + "'"; - value = value.substring(part.length); - } else { - part = value.substring(0, quot); - result += '"' + part + '"'; - value = value.substring(part.length); - } - result += ','; +function retryWithCount(options, fn) { + var n = 0; + return retry(fn, { + timeout: 99999, + retryInterval: options.interval, + shouldRetry: function shouldRetry() { + return ++n <= options.count; } - result += ')'; - return result; + }); +} +function flow() { + for (var _len7 = arguments.length, fns = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { + fns[_key7] = arguments[_key7]; } -}; - -var xpathAttr = function xpathAttr(dom) { - function attributesXPath(name, attNames, attributes) { - var locator = '//' + name + '['; - for (var i = 0; i < attNames.length; i++) { + var result = new Array(fns.length); + var finalPromise = fns.reduce(function (prev, fn, i) { + return prev.then(function (res) { if (i > 0) { - locator += ' and '; + result[i - 1] = res; } - var attName = attNames[i]; - locator += '@' + attName + '=' + attributeValue(attributes[attName]); + return fn(res); + }); + }, Promise.resolve()); + return finalPromise.then(function (res) { + result[fns.length - 1] = res; + return result; + }); +} +function guardVoidPromise(fn) { + return function () { + for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { + args[_key8] = arguments[_key8]; } - locator += ']'; - return locator; + return new Promise(function (resolve, reject) { + try { + resolve(fn.apply(void 0, args)); + } catch (e) { + reject(e); + } + }).then(function () {}, function (e) { + _log["default"].error(e); + }); + }; +} +function parseBoolLike(value) { + var fallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + if (typeof value === 'boolean') { + return value; + } + if (typeof value === 'number') { + return !!value; + } + if (value === undefined) { + return fallback; } - try { - var PREFERRED_ATTRIBUTES = ['id', 'name', 'value', 'type', 'action', 'onclick']; - var i = 0; - - if (dom.attributes) { - var atts = dom.attributes; - var attsMap = {}; - for (i = 0; i < atts.length; i++) { - var att = atts[i]; - attsMap[att.name] = att.value; - } - var names = []; - // try preferred attributes - for (i = 0; i < PREFERRED_ATTRIBUTES.length; i++) { - var name = PREFERRED_ATTRIBUTES[i]; - - if (attsMap[name] != null) { - names.push(name); - - var locator = attributesXPath(dom.nodeName.toLowerCase(), names, attsMap); - - if (dom === (0, _dom_utils.getElementByXPath)(locator)) { - return locator; - } - } - } - } - } catch (e) {} - - return null; + var val = JSON.parse(value.toLowerCase()); + return !!val; + } catch (e) { + return fallback; + } +} +function strictParseBoolLike(value) { + if (typeof value === 'boolean') { + return value; + } + var result = JSON.parse(value.toLowerCase()); + if (typeof result !== 'boolean') { + throw new Error('Not a boolean'); + } + return result; +} +function sum() { + for (var _len9 = arguments.length, list = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { + list[_key9] = arguments[_key9]; + } + return list.reduce(function (x, y) { + return x + y; + }, 0); +} +function concatUint8Array() { + for (var _len10 = arguments.length, arrays = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) { + arrays[_key10] = arguments[_key10]; + } + var totalLength = sum.apply(void 0, _toConsumableArray(arrays.map(function (arr) { + return arr.length; + }))); + var result = new Uint8Array(totalLength); + for (var _i6 = 0, offset = 0, len = arrays.length; _i6 < len; _i6 += 1) { + result.set(arrays[_i6], offset); + offset += arrays[_i6].length; + } + return result; +} +function withPromise(factory) { + return new Promise(function (resolve) { + resolve(factory()); + }); +} +function clone(data) { + if (data === undefined) return undefined; + return JSON.parse(JSON.stringify(data)); +} +var objMap = exports.objMap = function objMap(fn, obj) { + var keys = _typeof(obj) === 'object' ? Object.keys(obj) : []; + return keys.reduce(function (prev, key, i) { + prev[key] = fn(obj[key], key, i, obj); + return prev; + }, {}); }; - -var atXPath = function atXPath(xpath, document) { - var lower = function lower(str) { - return str && str.toLowerCase(); +function milliSecondsToStringInSecond(ms) { + return (ms / 1000).toFixed(2) + 's'; +} +var concurrent = exports.concurrent = function concurrent(max) { + var queue = []; + var running = 0; + var free = function free() { + running--; + check(); }; - var reg = /^([a-zA-Z0-9]+)(\[(\d+)\])?$/; - - return xpath.reduce(function (prev, cur) { - if (!prev) return prev; - if (!prev.childNodes || !prev.childNodes.length) return null; - - var match = cur.match(reg); - var tag = match[1]; - var index = match[3] ? parseInt(match[3], 10) : 1; - var list = (0, _from2.default)(prev.childNodes).filter(function (item) { - return item.nodeType === 1 && lower(item.tagName) === lower(tag); + var check = function check() { + if (running >= max || queue.length <= 0) return; + var tuple = queue.shift(); + var resolve = tuple.resolve; + running++; + resolve(free); + }; + var wait = function wait() { + return new Promise(function (resolve, reject) { + queue.push({ + resolve: resolve, + reject: reject + }); + check(); }); - - return list[index - 1]; - }, document); -}; - -var domText = function domText($dom) { - var it = $dom.innerText && $dom.innerText.trim(); - var tc = $dom.textContent; - var pos = tc.toUpperCase().indexOf(it.toUpperCase()); - - return tc.substr(pos, it.length); + }; + var wrap = function wrap(fn, context) { + return function () { + var args = [].slice.apply(arguments); + return wait().then(function (done) { + return fn.apply(context, args).then(function (ret) { + done(); + return ret; + }, function (error) { + done(); + throw error; + }); + }); + }; + }; + return wrap; }; - -var getFirstWorkingLocator = function getFirstWorkingLocator(locators, $el) { - var _loop = function _loop(i, len) { - var $match = function () { - try { - return (0, _dom_utils.getElementByLocator)(locators[i]); - } catch (e) { - return null; +function errorClassFactory(name) { + return /*#__PURE__*/function (_Error) { + _inherits(_class, _Error); + function _class() { + var _this; + _classCallCheck(this, _class); + for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) { + args[_key11] = arguments[_key11]; } - }(); - - if ($el === $match) { - return { - v: locators[i] - }; + _this = _callSuper(this, _class, [].concat(args)); + _this.code = name; + if (_this.message) { + _this.message = name + ': ' + _this.message; + } else { + _this.message = name; + } + return _this; } - }; - - for (var i = 0, len = locators.length; i < len; i++) { - var _ret = _loop(i, len); - - if ((typeof _ret === 'undefined' ? 'undefined' : (0, _typeof3.default)(_ret)) === "object") return _ret.v; + return _createClass(_class); + }( /*#__PURE__*/_wrapNativeSuper(Error)); +} +function treeMap(mapper, tree) { + var paths = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + return _objectSpread(_objectSpread({}, mapper(tree, paths)), {}, { + children: tree.children.map(function (subnode, i) { + return treeMap(mapper, subnode, [].concat(_toConsumableArray(paths), [i])); + }) + }); +} +function treeFilter(predicate, tree) { + var paths = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + if (predicate(tree, paths)) { + return tree; } - - return null; -}; - -// Note: get the locator of a DOM -var getLocator = function getLocator($dom, withAllOptions) { - var id = $dom.getAttribute('id'); - var name = $dom.getAttribute('name'); - var isLink = $dom.tagName.toLowerCase() === 'a'; - var text = function () { - try { - return domText($dom); - } catch (e) { - return null; - } - }(); - var classes = (0, _from2.default)($dom.classList); - var candidates = []; - - // link - if (isLink && text && text.length) { - var links = [].slice.call(document.getElementsByTagName('a')); - var matches = links.filter(function ($el) { - return domText($el) === text; - }); - var index = matches.findIndex(function ($el) { - return $el === $dom; - }); - - if (index !== -1) { - candidates.push(index === 0 ? 'linkText=' + text : 'linkText=' + text + '@POS=' + (index + 1)); + var children = tree.children.map(function (subnode, i) { + return treeFilter(predicate, subnode, [].concat(_toConsumableArray(paths), [i])); + }); + var validChildren = children.filter(function (item) { + return item; + }); + return validChildren.length === 0 ? null : _objectSpread(_objectSpread({}, tree), {}, { + children: validChildren + }); +} +function treeSlice(max, tree) { + var root = null; + var count = 0; + traverseTree(function (data, paths) { + if (++count > max) { + return TraverseTreeResult.Stop; + } + if (paths.length === 0) { + root = _objectSpread(_objectSpread({}, data), {}, { + children: [] + }); + } else { + var finalIndex = paths[paths.length - 1]; + var parent = paths.slice(0, -1).reduce(function (node, index) { + return node.children[index]; + }, root); + parent.children[finalIndex] = _objectSpread(_objectSpread({}, data), {}, { + children: [] + }); } + return TraverseTreeResult.Normal; + }, tree); + return root; +} +function forestSlice(max, forest) { + var newTree = { + children: forest + }; + var result = treeSlice(max + 1, newTree); + return result ? result.children : []; +} +function isTreeEqual(isNodeEqual, a, b) { + var aChildren = a.children || []; + var bChildren = b.children || []; + var alen = aChildren.length; + var blen = bChildren.length; + if (alen !== blen) { + return false; } - - // id - if (id && id.length) { - candidates.push('id=' + id); - } - - // name - if (name && name.length) { - candidates.push('name=' + name); + if (!isNodeEqual(a, b)) { + return false; } - - // xpath - candidates.push('xpath=' + xpath($dom)); - - var attrXPath = xpathAttr($dom); - - if (attrXPath) { - candidates.push('xpath=' + attrXPath); + for (var _i7 = 0; _i7 < alen; _i7++) { + if (!isTreeEqual(isNodeEqual, a.children[_i7], b.children[_i7])) { + return false; + } } - - var positionXPath = xpathPosition($dom); - - if (positionXPath) { - candidates.push('xpath=' + positionXPath); + return true; +} +function isForestEqual(isNodeEqual, a, b) { + if (a.length !== b.length) { + return false; } - - // css - // Try with simple css selector first. If not unqiue, use full css selector - /** - * Below is the old logic with a shorter css selector - * - let sel = null - if (classes.length > 0) { - sel = $dom.tagName.toLowerCase() + classes.map(c => '.' + c).join('') - if ($dom !== document.querySelectorAll(sel)[0]) { - sel = null + for (var _i8 = 0, len = a.length; _i8 < len; _i8++) { + if (!isTreeEqual(isNodeEqual, a[_i8], b[_i8])) { + return false; } } - if (!sel) { - sel = selector($dom) - } - */ - candidates.push('css=' + selector($dom)); - - // Get the first one working - var chosen = getFirstWorkingLocator(candidates, $dom); - - if (withAllOptions) { - return { - target: chosen, - targetOptions: candidates - }; + return true; +} +function nodeCount(tree) { + var count = 0; + traverseTree(function () { + count++; + return TraverseTreeResult.Normal; + }, tree); + return count; +} +var TraverseTreeResult = exports.TraverseTreeResult = /*#__PURE__*/function (TraverseTreeResult) { + TraverseTreeResult[TraverseTreeResult["Normal"] = 0] = "Normal"; + TraverseTreeResult[TraverseTreeResult["Skip"] = 1] = "Skip"; + TraverseTreeResult[TraverseTreeResult["Stop"] = 2] = "Stop"; + return TraverseTreeResult; +}({}); +function traverseTree(fn, node) { + var paths = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + var intent = fn(node, paths); + if (intent !== TraverseTreeResult.Normal) { + return intent; + } + var childCount = node.children ? node.children.length : 0; + var children = node.children || []; + for (var _i9 = 0; _i9 < childCount; _i9++) { + if (traverseTree(fn, children[_i9], [].concat(_toConsumableArray(paths), [_i9])) === TraverseTreeResult.Stop) { + return TraverseTreeResult.Stop; + } + } + return TraverseTreeResult.Normal; +} +function pathsInNode(predicate, root) { + var result = null; + traverseTree(function (node, paths) { + if (predicate(node, paths)) { + result = paths; + return TraverseTreeResult.Stop; + } + return TraverseTreeResult.Normal; + }, root); + return result ? result : null; +} +function ancestorsInNode(predicate, root) { + var paths = pathsInNode(predicate, root); + if (paths === null) { + return null; } - - return chosen; -}; - -var checkIframe = function checkIframe(iframeWin) { - var key = new Date() * 1 + '' + Math.random(); - - try { - iframeWin[key] = 'asd'; - return iframeWin[key] === 'asd'; - } catch (e) { - return false; + var ancestorPaths = paths.slice(0, -1); + var keys = addInBetween('children', ancestorPaths); + return ancestorPaths.map(function (_, index) { + var subKeys = keys.slice(0, index * 2 + 1); + return getIn(subKeys, root.children); + }); +} +function pathsInNodeList(predicate, nodes) { + for (var _i10 = 0, len = nodes.length; _i10 < len; _i10++) { + var _paths = pathsInNode(predicate, nodes[_i10]); + if (_paths !== null) { + return [_i10].concat(_toConsumableArray(_paths)); + } } -}; - -// Note: get the locator for frame -var getFrameLocator = function getFrameLocator(frameWin, win) { - if (checkIframe(frameWin)) { - var frameDom = frameWin.frameElement; - var locator = getLocator(frameDom); - - if (/^id=/.test(locator) || /^name=/.test(locator)) { - return locator; + return null; +} +function ancestorsInNodesList(predicate, nodes) { + for (var _i11 = 0, len = nodes.length; _i11 < len; _i11++) { + var ancestors = ancestorsInNode(predicate, nodes[_i11]); + if (ancestors !== null) { + return [nodes[_i11]].concat(_toConsumableArray(ancestors)); } } - - for (var i = 0, len = win.frames.length; i < len; i++) { - if (win.frames[i] === frameWin) { - return 'index=' + i; + return null; +} +function flattenTreeWithPaths(tree) { + var result = []; + traverseTree(function (node, paths) { + result.push({ + paths: paths, + node: without(['children'], node) + }); + return TraverseTreeResult.Normal; + }, tree); + return result; +} +function flatternTree(tree) { + return flattenTreeWithPaths(tree).map(function (item) { + return item.node; + }); +} +function findNodeInTree(predicate, tree) { + var result = null; + traverseTree(function (node, paths) { + if (predicate(node, paths)) { + result = node; + return TraverseTreeResult.Stop; + } + return TraverseTreeResult.Normal; + }, tree); + return result; +} +function findNodeInForest(predicate, forest) { + for (var _i12 = 0, len = forest.length; _i12 < len; _i12++) { + var result = findNodeInTree(predicate, forest[_i12]); + if (result) { + return result; } } - - throw new Error('Frame locator not found'); -}; - -/* - * Mask related - */ - -var maskFactory = function maskFactory() { + return null; +} +function toArray(list) { + return Array.isArray(list) ? list : [list]; +} +function nodeByOffset(params) { + var tree = params.tree, + isTargetQualified = params.isTargetQualified, + isCandidateQualified = params.isCandidateQualified, + offset = params.offset; + if (Math.floor(offset) !== offset) { + throw new Error("offset must be integer. It's now ".concat(offset)); + } + var ret = null; + var trees = toArray(tree); var cache = []; - var prefix = '__mask__' + new Date() * 1 + Math.round(Math.random() * 1000) + '__'; - var uid = 1; - var defaultStyle = { - position: 'absolute', - zIndex: '999', - display: 'none', - boxSizing: 'border-box', - backgroundColor: 'red', - opacity: 0.5, - pointerEvents: 'none' - }; - - var genMask = function genMask(style, dom) { - var mask = document.createElement('div'); - - if (dom) { - style = extend({}, defaultStyle, style || {}, rect(dom)); - } else { - style = extend({}, defaultStyle, style || {}); - } - - setStyle(mask, style); - mask.id = prefix + uid++; - cache.push(mask); - - return mask; - }; - - var clear = function clear() { - for (var i = 0, len = cache.length; i < len; i++) { - var mask = cache[i]; - - if (mask && mask.parentNode) { - mask.parentNode.removeChild(mask); + var maxCache = 1 + Math.ceil(Math.abs(offset)); + + // Note: if offset is negative, which means you're looking for some item ahead, + // we can get it from cache. Otherwise, use offsetLeft as counter until we reach the item. + // So `found` could only be tree if `offset` is a positive integer + var offsetLeft = Math.max(0, offset); + var found = false; + for (var _i13 = 0, len = trees.length; _i13 < len; _i13++) { + var traverseResult = traverseTree(function (node, paths) { + var qualified = isCandidateQualified(node, paths); + if (!qualified) { + return TraverseTreeResult.Normal; + } + if (offset < 0) { + cache.push(node); + if (cache.length > maxCache) { + cache.shift(); + } + } + if (offset > 0 && found) { + offsetLeft -= 1; + if (offsetLeft === 0) { + ret = node; + return TraverseTreeResult.Stop; + } + } + if (isTargetQualified(node, paths)) { + if (offset <= 0) { + var index = cache.length - 1 + offset; + ret = index >= 0 ? cache[index] : null; + return TraverseTreeResult.Stop; + } else { + found = true; + } } + return TraverseTreeResult.Normal; + }, trees[_i13]); + if (traverseResult === TraverseTreeResult.Stop) { + break; } - }; - + } + return ret; +} +function pointToFitRect(data) { + var bound = data.bound, + size = data.size, + point = data.point; + var lBorder = bound.x; + var rBorder = bound.x + bound.width; + var tBorder = bound.y; + var bBorder = bound.y + bound.height; + var x = function () { + if (point.x + size.width <= rBorder) { + return point.x; + } + if (point.x - size.width >= lBorder) { + return point.x - size.width; + } + return rBorder - size.width; + }(); + var y = function () { + if (point.y + size.height <= bBorder) { + return point.y; + } + if (point.y - size.height >= tBorder) { + return point.y - size.height; + } + return bBorder - size.height; + }(); return { - gen: genMask, - clear: clear + x: x, + y: y }; +} +function addInBetween(item, list) { + var result = []; + for (var _i14 = 0, len = list.length; _i14 < len; _i14++) { + if (_i14 !== 0) { + result.push(item); + } + result.push(list[_i14]); + } + return result; +} +function normalizeHtmlId(str) { + return str.replace(/[^A-Za-z0-9_-]/g, '_'); +} +var unique = exports.unique = function unique(list, getKey) { + var cache = {}; + var result = list.reduce(function (prev, cur) { + var key = getKey(cur); + if (!cache[key]) { + cache[key] = true; + prev.push(cur); + } + return prev; + }, []); + return result; }; - -var showMaskOver = function showMaskOver(mask, el) { - var pos = offset(el); - var w = cssSum(el, ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth']); - var h = cssSum(el, ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', ' borderBottomWidth']); - - setStyle(mask, extend(pos, { - width: pixel(w), - height: pixel(h), - display: 'block' - })); +var uniqueStrings = exports.uniqueStrings = function uniqueStrings() { + for (var _len12 = arguments.length, list = new Array(_len12), _key12 = 0; _key12 < _len12; _key12++) { + list[_key12] = arguments[_key12]; + } + return unique(list, function (x) { + return x; + }); }; - -var isVisible = function isVisible(el) { - if (el === window.document) return true; - if (!el) return true; - - var style = window.getComputedStyle(el); - if (style.display === 'none' || style.opacity === '0' || style.visibility === 'hidden') return false; - - return isVisible(el.parentNode); +function consecutive(c) { + if (typeof c === 'boolean') { + return { + interval: 0, + count: c ? 1 : 0 + }; + } + return c; +} +var timeout = function timeout(duration) { + return new Promise(function (resolve) { + setTimeout(resolve, duration); + }); }; - -exports["default"] = { - offset: offset, - setStyle: setStyle, - selector: selector, - xpath: xpath, - atXPath: atXPath, - domText: domText, - getLocator: getLocator, - getFrameLocator: getFrameLocator, - maskFactory: maskFactory, - showMaskOver: showMaskOver, - inDom: inDom, - isVisible: isVisible, - parentWithTag: parentWithTag, - parentWithClass: parentWithClass +function withConsecutive(c, fn) { + var _consecutive = consecutive(c), + interval = _consecutive.interval, + count = _consecutive.count; + var counter = count; + var next = function next(pass) { + if (!pass) throw new Error('failed to run consecutive'); + if (counter-- <= 0) return Promise.resolve(true); + return timeout(interval || 0).then(fn).then(next); + }; + return fn().then(next); +} +function readFileAsText(file) { + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.onload = function (readerEvent) { + try { + var text = readerEvent.target.result; + resolve(text); + } catch (e) { + reject(e); + } + }; + reader.readAsText(file); + }); +} +function assertExhausted(_, msg) { + throw new Error('switch case not exhausted' + (msg ? ': ' + msg : '')); +} +function pad2digits(n) { + if (n >= 0 && n < 10) { + return '0' + n; + } + return '' + n; +} +function repeatStr(n, str) { + var s = ''; + for (var _i15 = 0; _i15 < n; _i15++) { + s += str; + } + return s; +} +function isMac() { + var userAgent = window.navigator.userAgent; + return !!/macintosh/i.test(userAgent) || /mac os x/i.test(userAgent) && !/like mac os x/i.test(userAgent); +} +function resolvePath(path, basePath, relativePath) { + var dirPath = path.dirname(basePath); + relativePath = relativePath.replace(/\\/g, '/'); + if (relativePath.indexOf('/') === 0) { + return path.normalize(relativePath).replace(/^(\/|\\)/, ''); + } else { + return path.join(dirPath, relativePath); + } +} +function countDown(options) { + var interval = options.interval, + timeout = options.timeout, + onTick = options.onTick, + onTimeout = options.onTimeout; + var past = 0; + var timer = setInterval(function () { + past += interval; + try { + onTick({ + past: past, + total: timeout + }); + } catch (e) { + console.warn(e); + } + if (past >= timeout) { + clearInterval(timer); + if (typeof onTimeout === 'function') { + try { + onTimeout({ + past: past, + total: timeout + }); + } catch (e) { + console.warn(e); + } + } + } + }, options.interval); + return function () { + return clearInterval(timer); + }; +} +var withCountDown = exports.withCountDown = function withCountDown(options) { + var interval = options.interval, + timeout = options.timeout, + onTick = options.onTick; + var past = 0; + return new Promise(function (resolve, reject) { + var timer = setInterval(function () { + past += interval; + try { + onTick({ + cancel: cancel, + past: past, + total: timeout + }); + } catch (e) { + console.error(e); + } + if (past >= timeout) clearInterval(timer); + }, interval); + var cancel = function cancel() { + return clearInterval(timer); + }; + var p = delay(function () {}, timeout).then(function () { + return clearInterval(timer); + }); + resolve(p); + }); }; +function urlWithQueries(url) { + var queries = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var hasQuery = Object.keys(queries).length > 0; + if (!hasQuery) { + return url; + } + var queryStr = Object.keys(queries).map(function (key) { + var _queries$key; + return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent((_queries$key = queries[key]) === null || _queries$key === void 0 ? void 0 : _queries$key.toString())); + }).join('&'); + return "".concat(url, "?").concat(queryStr); +} +function throttlePromiseFunc(fn, interval) { + if (interval <= 0) { + throw new Error("Interval must be positive number"); + } + var p = Promise.resolve(); + var generatedFunc = function generatedFunc() { + for (var _len13 = arguments.length, args = new Array(_len13), _key13 = 0; _key13 < _len13; _key13++) { + args[_key13] = arguments[_key13]; + } + var ret = p.then(function () { + console.log("in generatedFunc...", args); + return fn.apply(void 0, args); + }); + p = ret.then(function () { + return delay(function () {}, interval); + }, function () { + return delay(function () {}, interval); + }); + return ret; + }; + return generatedFunc; +} /***/ }), -/***/ 5116: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 14125: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -2039,123 +3454,141 @@ exports["default"] = { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.onMessage = exports.postMessage = undefined; - -var _extends2 = __webpack_require__(88239); - -var _extends3 = _interopRequireDefault(_extends2); - -var _promise = __webpack_require__(46593); - -var _promise2 = _interopRequireDefault(_promise); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var TYPE = 'SELENIUM_IDE_CS_MSG'; - -var postMessage = exports.postMessage = function postMessage(targetWin, myWin, payload) { - var target = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '*'; - var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 60000; +exports.utf8 = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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 _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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +// Adapted from: http://www.json.org/JSON_checker/utf8_decode.c +var Utf8Decoder = /*#__PURE__*/function () { + function Utf8Decoder(input) { + _classCallCheck(this, Utf8Decoder); + this.input = input; + this.position = 0; + } - return new _promise2.default(function (resolve, reject) { - if (!targetWin || !targetWin.postMessage) { - throw new Error('csPostMessage: targetWin is not a window'); + /** + * Gets the next byte. + * @returns UTF8_END if there are no more bytes, next byte otherwise. + */ + _createClass(Utf8Decoder, [{ + key: "getNextByte", + value: function getNextByte() { + if (this.position >= this.input.length) { + return Utf8Decoder.END; + } + var c = this.input[this.position] & 0xff; + ++this.position; + return c; } - if (!myWin || !myWin.addEventListener || !myWin.removeEventListener) { - throw new Error('csPostMessage: myWin is not a window', myWin); + /** + * Gets the 6-bit payload of the next continuation byte. + * @returns Contination byte if it's valid, UTF8_ERROR otherwise. + */ + }, { + key: "getNextContinuationByte", + value: function getNextContinuationByte() { + var c = this.getNextByte(); + return (c & 0xc0) == 0x80 ? c & 0x3f : Utf8Decoder.ERROR; } - var secret = Math.random(); - var type = TYPE; - - // Note: create a listener with a corresponding secret every time - var onMsg = function onMsg(e) { - if (e.data && e.data.type === TYPE && !e.data.isRequest && e.data.secret === secret) { - myWin.removeEventListener('message', onMsg); - var _e$data = e.data, - _payload = _e$data.payload, - error = _e$data.error; - - - if (error) return reject(new Error(error)); - if (_payload !== undefined) return resolve(_payload); - - reject(new Error('csPostMessage: No payload nor error found')); + /** + * Decodes next codepoint. + * @returns `Utf8Decoder.END` for end of stream, next codepoint if it's valid, `Utf8Decoder.ERROR` otherwise. + */ + }, { + key: "decodeNext", + value: function decodeNext() { + if (this.position >= this.input.length) { + return this.position === this.input.length ? Utf8Decoder.END : Utf8Decoder.ERROR; } - }; - - myWin.addEventListener('message', onMsg); - - // Note: - // * `type` to make sure we check our own msg only - // * `secret` is for 1 to 1 relationship between a msg and a listener - // * `payload` is the real data you want to send - // * `isRequest` is to mark that it's not an answer to some previous request - - targetWin.postMessage({ - type: type, - secret: secret, - payload: payload, - isRequest: true - }, target); - - setTimeout(function () { - reject(new Error('csPostMessage: timeout ' + timeout + ' ms')); - }, timeout); - }); -}; - -var onMessage = exports.onMessage = function onMessage(win, fn) { - if (!win || !win.addEventListener || !win.removeEventListener) { - throw new Error('csOnMessage: not a window', win); - } + var c = this.getNextByte(); - var onMsg = function onMsg(e) { - // Note: only respond to msg with `isRequest` as true - if (e && e.data && e.data.type === TYPE && e.data.isRequest && e.data.secret) { - var tpl = { - type: TYPE, - secret: e.data.secret + // Zero continuation (0 to 127) + if ((c & 0x80) == 0) { + return c; + } - // Note: wrapped with a new Promise to catch any exception during the execution of fn - };new _promise2.default(function (resolve, reject) { - var ret = void 0; + // One continuation (128 to 2047) + if ((c & 0xe0) == 0xc0) { + var c1 = this.getNextContinuationByte(); + if (c1 >= 0) { + var r = (c & 0x1f) << 6 | c1; + if (r >= 128) { + return r; + } + } - try { - ret = fn(e.data.payload, { - source: e.source - }); - } catch (err) { - reject(err); + // Two continuations (2048 to 55295 and 57344 to 65535) + } else if ((c & 0xf0) == 0xe0) { + var _c = this.getNextContinuationByte(); + var c2 = this.getNextContinuationByte(); + if ((_c | c2) >= 0) { + var _r = (c & 0x0f) << 12 | _c << 6 | c2; + if (_r >= 2048 && (_r < 55296 || _r > 57343)) { + return _r; + } } - // Note: only resolve if returned value is not undefined. With this, we can have multiple - // listeners added to onMessage, and each one takes care of what it really cares - if (ret !== undefined) { - resolve(ret); + // Three continuations (65536 to 1114111) + } else if ((c & 0xf8) == 0xf0) { + var _c2 = this.getNextContinuationByte(); + var _c3 = this.getNextContinuationByte(); + var c3 = this.getNextContinuationByte(); + if ((_c2 | _c3 | c3) >= 0) { + var _r2 = (c & 0x07) << 18 | _c2 << 12 | _c3 << 6 | c3; + if (_r2 >= 65536 && _r2 <= 1114111) { + return _r2; + } } - }).then(function (res) { - e.source.postMessage((0, _extends3.default)({}, tpl, { - payload: res - }), '*'); - }, function (err) { - e.source.postMessage((0, _extends3.default)({}, tpl, { - error: err.message - }), '*'); - }); + } + return Utf8Decoder.ERROR; } - }; - - win.addEventListener('message', onMsg); - return function () { - return win.removeEventListener('message', onMsg); - }; -}; + }]); + return Utf8Decoder; +}(); +_defineProperty(Utf8Decoder, "REPLACEMENT_CHARACTER", "\uFFFD"); +_defineProperty(Utf8Decoder, "END", -1); +_defineProperty(Utf8Decoder, "ERROR", -2); +var utf8; +(function (_utf) { + function isValid(input) { + var decoder = new Utf8Decoder(input); + while (true) { + var cp = decoder.decodeNext(); + switch (cp) { + case Utf8Decoder.END: + return true; + case Utf8Decoder.ERROR: + return false; + default: + // ignore + } + } + } + _utf.isValid = isValid; + function decode(input) { + var decoder = new Utf8Decoder(input); + var output = ""; + while (true) { + var cp = decoder.decodeNext(); + if (cp === Utf8Decoder.END) { + break; + } + output += cp !== Utf8Decoder.ERROR ? String.fromCodePoint(cp) : Utf8Decoder.REPLACEMENT_CHARACTER; + } + return output; + } + _utf.decode = decode; +})(utf8 || (exports.utf8 = utf8 = {})); /***/ }), -/***/ 31745: +/***/ 8747: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; @@ -2164,321 +3597,373 @@ var onMessage = exports.onMessage = function onMessage(win, fn) { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.bgInit = exports.csInit = exports.openBgWithCs = undefined; - -var _regenerator = __webpack_require__(94942); - -var _regenerator2 = _interopRequireDefault(_regenerator); - -var _asyncToGenerator2 = __webpack_require__(36803); - -var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); - -var _promise = __webpack_require__(46593); - -var _promise2 = _interopRequireDefault(_promise); - -var _typeof2 = __webpack_require__(72444); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _ipc_promise = __webpack_require__(93671); +exports["default"] = void 0; +var _web_extension = _interopRequireDefault(__webpack_require__(41953)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +var platform = _web_extension["default"].isFirefox() ? 'firefox' : 'chrome'; +var _default = exports["default"] = { + preinstall: { + version: '5.8.8', + macroFolder: '/Demo' + }, + nativeMessaging: { + idleTimeBeforeDisconnect: 1e4 // 10 seconds + }, + urlAfterUpgrade: 'https://goto.ui.vision/x/idehelp?help=k_update', + urlAfterInstall: 'https://goto.ui.vision/x/idehelp?help=k_welcome', + urlAfterUninstall: 'https://goto.ui.vision/x/idehelp?help=k_why', + performanceLimit: { + fileCount: Infinity + }, + xmodulesLimit: { + unregistered: { + ocrCommandCount: 100, + xCommandCount: Infinity, + xFileMacroCount: 10, + proxyExecCount: Infinity, + upgradeUrl: 'https://goto.ui.vision/x/idehelp?help=k_xupgradepro' + }, + free: { + ocrCommandCount: 250, + xCommandCount: Infinity, + xFileMacroCount: 20, + proxyExecCount: Infinity, + upgradeUrl: 'https://goto.ui.vision/x/idehelp?help=k_xupgradepro' + }, + pro: { + ocrCommandCount: 500, + xCommandCount: Infinity, + xFileMacroCount: Infinity, + proxyExecCount: Infinity, + upgradeUrl: 'https://goto.ui.vision/x/idehelp?help=k_xupgrade_contactsupport' + } + }, + xfile: { + minVersionToReadBigFile: '1.0.10' + }, + ocr: { + freeApiEndpoint: 'https://api.ocr.space/parse/image', + proApi1Endpoint: 'https://apipro1.ocr.space/parse/image', + proApi2Endpoint: 'https://apipro2.ocr.space/parse/image', + apiTimeout: 60 * 1000, + singleApiTimeout: 30 * 1000, + apiHealthyResponseTime: 20 * 1000, + resetTime: 24 * 3600 * 1000 + }, + license: { + api: { + url: 'https://license1.ocr.space/api/status' + } + }, + icons: { + normal: 'logo38.png', + inverted: 'inverted_logo_38.png' + }, + forceMigrationRemedy: false, + iframePostMessageTimeout: 500, + ui: { + commandItemHeight: 35 + }, + commandRunner: { + sendKeysMaxCharCount: 1000 + }, + executeScript: { + minimumTimeout: 5000 + } +}; -var _ipc_promise2 = _interopRequireDefault(_ipc_promise); +/***/ }), -var _ipc_cache = __webpack_require__(54105); +/***/ 8327: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -var _web_extension = __webpack_require__(61171); +"use strict"; -var _web_extension2 = _interopRequireDefault(_web_extension); -var _log = __webpack_require__(77242); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getState = getState; +exports.updateState = updateState; +var _storage = _interopRequireDefault(__webpack_require__(88555)); +var C = _interopRequireWildcard(__webpack_require__(95902)); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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), !0).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; } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +var defaultState = { + status: C.APP_STATUS.NORMAL, + tabIds: { + lastActivated: [], + lastInspect: null, + lastRecord: null, + toInspect: null, + firstRecord: null, + toRecord: null, + lastPlay: null, + firstPlay: null, + toPlay: null, + panel: null, + lastPanelWindow: null + }, + pullback: false, + // Note: heartBeatSecret = -1, means no heart beat available, and panel should not retry on heart beat lost + heartBeatSecret: 0, + // Note: disableHeartBeat = true, `checkHeartBeat` will stop working, it's useful for cases like close current tab + disableHeartBeat: false, + // Note: pendingPlayingTab = true, tells `getPlayTab` to wait until the current tab is closed and another tab is focused on + pendingPlayingTab: false, + xClickNeedCalibrationInfo: null, + lastCsIpcSecret: null, + closingAllWindows: false +}; +function getState(optionalKey) { + return _storage["default"].get(C.STATE_STORAGE_KEY).then(function (state) { + var st = state || defaultState; + if (typeof optionalKey === 'string') { + return st[optionalKey]; + } + return st; + }); +} +function updateState(updateFunc) { + var fn = typeof updateFunc === 'function' ? updateFunc : function (state) { + return _objectSpread(_objectSpread({}, state), updateFunc); + }; + return getState().then(function (state) { + var result = fn(state); + return _storage["default"].set(C.STATE_STORAGE_KEY, result).then(function () {}); + }); +} -var _log2 = _interopRequireDefault(_log); +/***/ }), -var _utils = __webpack_require__(63370); +/***/ 20652: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +"use strict"; -var TIMEOUT = -1; -// Note: `cuid` is a kind of unique id so that you can create multiple -// ipc promise instances between the same two end points -var openBgWithCs = exports.openBgWithCs = function openBgWithCs(cuid) { - var wrap = function wrap(str) { - return str + '_' + cuid; - }; - - // factory function to generate ipc promise instance for background - // `tabId` is needed to identify which tab to send messages to - var ipcBg = function ipcBg(tabId) { - var bgListeners = []; - - // `sender` contains tab info. Background may need this to store the corresponding - // relationship between tabId and ipc instance - var addSender = function addSender(obj, sender) { - if (!obj || (typeof obj === 'undefined' ? 'undefined' : (0, _typeof3.default)(obj)) !== 'object') return obj; - - obj.sender = sender; - return obj; - }; - - _web_extension2.default.runtime.onMessage.addListener(function (req, sender, sendResponse) { - if (req.type === wrap('CS_ANSWER_BG') || req.type === wrap('CS_ASK_BG')) { - sendResponse(true); - } - - bgListeners.forEach(function (listener) { - return listener(req, sender); - }); - return true; - }); - - return (0, _ipc_promise2.default)({ - timeout: TIMEOUT, - ask: function ask(uid, cmd, args) { - return _web_extension2.default.tabs.sendMessage(tabId, { - type: wrap('BG_ASK_CS'), - uid: uid, - cmd: cmd, - args: args - }); - }, - onAnswer: function onAnswer(fn) { - bgListeners.push(function (req, sender) { - if (req.type !== wrap('CS_ANSWER_BG')) return; - fn(req.uid, req.err, addSender(req.data, sender)); - }); - }, - onAsk: function onAsk(fn) { - bgListeners.push(function (req, sender) { - if (req.type !== wrap('CS_ASK_BG')) return; - fn(req.uid, req.cmd, addSender(req.args, sender)); - }); - }, - answer: function answer(uid, err, data) { - return _web_extension2.default.tabs.sendMessage(tabId, { - type: wrap('BG_ANSWER_CS'), - uid: uid, - err: err, - data: data - }); - }, - destroy: function destroy() { - bgListeners = []; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.evalViaInject = evalViaInject; +exports.hackAlertInject = hackAlertInject; +exports.untilHackAlertInjected = untilHackAlertInjected; +exports.untilInjected = untilInjected; +var _utils = __webpack_require__(46580); +var _ts_utils = __webpack_require__(1601); +var _web_extension = _interopRequireDefault(__webpack_require__(41953)); +var _log = _interopRequireDefault(__webpack_require__(89130)); +var _cs_postmessage = __webpack_require__(50366); +var _config = _interopRequireDefault(__webpack_require__(8747)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +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); }); }; } +var scriptInjectedOnce; +function evalViaInject(_x) { + return _evalViaInject.apply(this, arguments); +} +function _evalViaInject() { + _evalViaInject = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(code) { + var api; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return untilInjected(); + case 2: + api = _context.sent; + (0, _log["default"])('sending INJECT_RUN_EVAL >>>>>>', code); + return _context.abrupt("return", api.eval(code)); + case 5: + case "end": + return _context.stop(); } - }); - }; - - // factory function to generate ipc promise for content scripts - var ipcCs = function ipcCs(checkReady) { - var csListeners = []; - - _web_extension2.default.runtime.onMessage.addListener(function (req, sender, sendResponse) { - if (req.type === wrap('BG_ANSWER_CS') || req.type === wrap('BG_ASK_CS')) { - sendResponse(true); + }, _callee); + })); + return _evalViaInject.apply(this, arguments); +} +function hackAlertInject(_x2) { + return _hackAlertInject.apply(this, arguments); +} +function _hackAlertInject() { + _hackAlertInject = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(code) { + var api; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return untilHackAlertInjected(); + case 2: + api = _context2.sent; + // old: await untilInjected() // new: await untilHackAlertInjected() + (0, _log["default"])('sending INJECT_RUN_EVAL >>>>>>', code); + return _context2.abrupt("return", api.eval(code)); + case 5: + case "end": + return _context2.stop(); } - - csListeners.forEach(function (listener) { - return listener(req, sender); + }, _callee2); + })); + return _hackAlertInject.apply(this, arguments); +} +function untilHackAlertInjected() { + var api = { + eval: function _eval(code) { + (0, _log["default"])('sending INJECT_RUN_EVAL'); + return (0, _cs_postmessage.postMessage)(window, window, { + cmd: 'INJECT_RUN_EVAL', + args: { + code: code + } + }, '*', 5000).then(function (data) { + (0, _log["default"])('eval result', data); + return data.result; }); - return true; - }); - - return (0, _ipc_promise2.default)({ - timeout: TIMEOUT, - checkReady: checkReady, - ask: function ask(uid, cmd, args) { - // log('cs ask', uid, cmd, args) - return _web_extension2.default.runtime.sendMessage({ - type: wrap('CS_ASK_BG'), - uid: uid, - cmd: cmd, - args: args - }); - }, - onAnswer: function onAnswer(fn) { - csListeners.push(function (req, sender) { - if (req.type !== wrap('BG_ANSWER_CS')) return; - fn(req.uid, req.err, req.data); - }); - }, - onAsk: function onAsk(fn) { - csListeners.push(function (req, sender) { - if (req.type !== wrap('BG_ASK_CS')) return; - fn(req.uid, req.cmd, req.args); - }); - }, - answer: function answer(uid, err, data) { - return _web_extension2.default.runtime.sendMessage({ - type: wrap('CS_ANSWER_BG'), - uid: uid, - err: err, - data: data - }); - }, - destroy: function destroy() { - csListeners = []; - } - }); + } }; - - return { - ipcCs: ipcCs, - ipcBg: ipcBg + var injected = !!document.body.getAttribute('data-injected'); + if (injected) { + return Promise.resolve(api); + } + + // issue #32 + // check against injecting twice + // injecting more than once is causing script to run twice eg: { "Command": "executeScript", "Target": "console.log('test')" } + if (!scriptInjectedOnce) { + scriptInjectedOnce = true; + (0, _utils.insertScript)(_web_extension["default"].runtime.getURL('inject.js')); + } + return (0, _ts_utils.retry)(function () { + (0, _log["default"])('sending INJECT_READY'); + return (0, _cs_postmessage.postMessage)(window, window, { + cmd: 'INJECT_READY' + }, '*', 500); + }, { + shouldRetry: function shouldRetry() { + return true; + }, + timeout: 5000, + retryInterval: 0 + })().then(function () { + return api; + })["catch"](function (e) { + (0, _log["default"])(e.stack); + throw new Error('fail to inject (ha)'); + }); +} +function untilInjected() { + var minTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _config["default"].executeScript.minimumTimeout; + var api = { + eval: function _eval(code) { + (0, _log["default"])('sending INJECT_RUN_EVAL'); + return (0, _cs_postmessage.postMessage)(window, window, { + cmd: 'INJECT_RUN_EVAL', + args: { + code: code + } + }, '*', minTimeout).then(function (data) { + (0, _log["default"])('eval result', data); + return data.result; + }); + } }; -}; - -// Helper function to init ipc promise instance for content scripts -// The idea here is to send CONNECT message to background when initializing -var csInit = exports.csInit = function csInit() { - var noRecover = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - - var cuid = '' + Math.floor(Math.random() * 10000); + var injected = !!document.body.getAttribute('data-injected'); + if (injected) { + return Promise.resolve(api); + } + (0, _utils.insertScript)(_web_extension["default"].runtime.getURL('inject.js')); + return (0, _ts_utils.retry)(function () { + (0, _log["default"])('sending INJECT_READY'); + return (0, _cs_postmessage.postMessage)(window, window, { + cmd: 'INJECT_READY' + }, '*', 500); + }, { + shouldRetry: function shouldRetry() { + return true; + }, + timeout: 5000, + retryInterval: 0 + })().then(function () { + return api; + })["catch"](function (e) { + (0, _log["default"])(e.stack); + throw new Error('fail to inject'); + }); +} - if (noRecover) { - _web_extension2.default.runtime.sendMessage({ - type: 'CONNECT', - cuid: cuid - }); - return openBgWithCs(cuid).ipcCs(); - } +/***/ }), - (0, _log2.default)('sending Connect...'); +/***/ 98272: +/***/ ((__unused_webpack_module, exports) => { - // Note: Ext.runtime.getURL is available in content script, but not injected js - // We use it here to detect whether it is loaded by content script or injected - // Calling runtime.sendMessage in injected js will cause an uncatchable exception - if (!_web_extension2.default.runtime.getURL) return; +"use strict"; - // try this process in case we're in none-src frame - try { - // let connected = false - // const checkReady = () => { - // if (connected) return Promise.resolve(true) - // return Promise.reject(new Error('cs not connected with bg yet')) - // } - var reconnect = function reconnect() { - return (0, _utils.withTimeout)(500, function () { - return _web_extension2.default.runtime.sendMessage({ - type: 'RECONNECT' - }).then(function (cuid) { - (0, _log2.default)('got existing cuid', cuid); - if (cuid) return openBgWithCs(cuid).ipcCs(); - throw new Error('failed to reconnect'); - }); - }); - }; - var connectBg = function connectBg() { - return (0, _utils.withTimeout)(1000, function () { - return _web_extension2.default.runtime.sendMessage({ - type: 'CONNECT', - cuid: cuid - }).then(function (done) { - if (done) return openBgWithCs(cuid).ipcCs(); - throw new Error('not done'); - }); - }); - }; - var tryConnect = (0, _utils.retry)(connectBg, { - shouldRetry: function shouldRetry() { - return true; - }, - retryInterval: 0, - timeout: 5000 - }); - // Note: Strategy here - // 1. Try to recover connection with background (get the existing cuid) - // 2. If cuid not found, try to create new connection (cuid) with background - // 3. Both of these two steps above are async, but this api itself is synchronous, - // so we have to create a mock API and return it first - var enhancedConnect = function enhancedConnect() { - return reconnect().catch(function () { - return tryConnect(); - }).catch(function (e) { - _log2.default.error('Failed to create cs ipc'); - throw e; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.DevicePixelRatioService = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +var DevicePixelRatioService = exports.DevicePixelRatioService = /*#__PURE__*/function () { + function DevicePixelRatioService(params) { + _classCallCheck(this, DevicePixelRatioService); + this.params = params; + } + _createClass(DevicePixelRatioService, [{ + key: "getDevicePixelRatioInfo", + value: function getDevicePixelRatioInfo() { + var _this$params$window; + var win = (_this$params$window = this.params.window) !== null && _this$params$window !== void 0 ? _this$params$window : window; + var currentRatio = win.devicePixelRatio; + return this.params.getZoom().then(function (zoom) { + return { + currentRatio: currentRatio, + baseRatio: currentRatio / zoom, + zoom: zoom + }; }); - }; - - return (0, _utils.mockAPIWith)(enhancedConnect, { - ask: function ask() { - return _promise2.default.reject(new Error('mock ask')); - }, - onAsk: function onAsk() { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - _log2.default.apply(undefined, ['mock onAsk'].concat(args)); - }, - destroy: function destroy() {}, - secret: cuid - }, ['ask']); - } catch (e) { - _log2.default.error(e.stack); - } -}; - -// Helper function to init ipc promise instance for background -// it accepts a `fn` function to handle CONNECT message from content scripts -var bgInit = exports.bgInit = function bgInit(fn) { - _web_extension2.default.runtime.onMessage.addListener(function (req, sender, sendResponse) { - switch (req.type) { - case 'CONNECT': - { - if (req.cuid) { - fn(sender.tab.id, req.cuid, openBgWithCs(req.cuid).ipcBg(sender.tab.id)); - sendResponse(true); - } - break; - } - - case 'RECONNECT': - { - (0, _ipc_cache.getIpcCache)().getCuid(sender.tab.id).then(function () { - var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(cuid) { - return _regenerator2.default.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (!cuid) { - _context.next = 3; - break; - } - - _context.next = 3; - return (0, _ipc_cache.getIpcCache)().enable(sender.tab.id); - - case 3: + } + }]); + return DevicePixelRatioService; +}(); - sendResponse(cuid || null); +/***/ }), - case 4: - case 'end': - return _context.stop(); - } - } - }, _callee, undefined); - })); +/***/ 73632: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - return function (_x2) { - return _ref.apply(this, arguments); - }; - }()); +"use strict"; - break; - } - } - return true; - }); -}; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.PublicMethodTypes = exports.MethodTypeInvocationNames = exports.MethodTypeFriendlyNames = void 0; +var _kantuFileAccess = __webpack_require__(11434); +/** + * Non-external method types which the user can use via UI. + */ +var PublicMethodTypes = exports.PublicMethodTypes = [_kantuFileAccess.KantuFileAccess.MethodType.GetFileSystemEntries, _kantuFileAccess.KantuFileAccess.MethodType.GetDirectories, _kantuFileAccess.KantuFileAccess.MethodType.GetFiles, _kantuFileAccess.KantuFileAccess.MethodType.DirectoryExists, _kantuFileAccess.KantuFileAccess.MethodType.FileExists, _kantuFileAccess.KantuFileAccess.MethodType.CreateDirectory, _kantuFileAccess.KantuFileAccess.MethodType.RemoveDirectory, _kantuFileAccess.KantuFileAccess.MethodType.CopyFile, _kantuFileAccess.KantuFileAccess.MethodType.MoveFile, _kantuFileAccess.KantuFileAccess.MethodType.DeleteFile, _kantuFileAccess.KantuFileAccess.MethodType.ReadAllText, _kantuFileAccess.KantuFileAccess.MethodType.WriteAllText, _kantuFileAccess.KantuFileAccess.MethodType.AppendAllText, _kantuFileAccess.KantuFileAccess.MethodType.ReadAllBytes, _kantuFileAccess.KantuFileAccess.MethodType.WriteAllBytes, _kantuFileAccess.KantuFileAccess.MethodType.AppendAllBytes]; +var MethodTypeFriendlyNames = exports.MethodTypeFriendlyNames = ["GetVersion", "GetFileSystemEntries", "GetDirectories", "GetFiles", "GetFileSystemEntryInfo", "GetSpecialFolderPath", "DirectoryExists", "FileExists", "CreateDirectory", "RemoveDirectory", "CopyFile", "MoveFile", "DeleteFile", "ReadAllText", "WriteAllText", "AppendAllText", "ReadAllBytes", "WriteAllBytes", "AppendAllBytes", "GetMaxFileRange", "GetFileSize", "ReadFileRange", "RunProcess"]; +var MethodTypeInvocationNames = exports.MethodTypeInvocationNames = ["get_version", "get_file_system_entries", "get_directories", "get_files", "get_file_system_entry_info", "get_special_folder_path", "directory_exists", "file_exists", "create_directory", "remove_directory", "copy_file", "move_file", "delete_file", "read_all_text", "write_all_text", "append_all_text", "read_all_bytes", "write_all_bytes", "append_all_bytes", "get_max_file_range", "get_file_size", "read_file_range", "run_process"]; /***/ }), -/***/ 41471: +/***/ 89937: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; @@ -2487,1188 +3972,3061 @@ var bgInit = exports.bgInit = function bgInit(fn) { Object.defineProperty(exports, "__esModule", ({ value: true })); - -var _ipc_bg_cs = __webpack_require__(31745); - -var throwNotTop = function throwNotTop() { - throw new Error('You are not a top window, not allowed to initialize/use csIpc'); -}; - -// Note: csIpc is only available to top window -var ipc = typeof window !== 'undefined' && window.top === window ? (0, _ipc_bg_cs.csInit)() : { - ask: throwNotTop, - send: throwNotTop, - onAsk: throwNotTop, - destroy: throwNotTop - - // Note: one ipc singleton per content script -};exports["default"] = ipc; +exports.getNativeFileSystemAPI = exports.SpecialFolder = void 0; +var _constants = __webpack_require__(73632); +var _kantuFileAccessHost = __webpack_require__(81173); +var _ts_utils = __webpack_require__(1601); +var _log = _interopRequireDefault(__webpack_require__(89130)); +var _path = _interopRequireDefault(__webpack_require__(26513)); +var _utf = __webpack_require__(14125); +var _base = __webpack_require__(81909); +var _utils = __webpack_require__(46580); +var _semver = _interopRequireDefault(__webpack_require__(99589)); +var _config = _interopRequireDefault(__webpack_require__(8747)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +var SpecialFolder = exports.SpecialFolder = /*#__PURE__*/function (SpecialFolder) { + SpecialFolder[SpecialFolder["UserProfile"] = 0] = "UserProfile"; + SpecialFolder[SpecialFolder["UserDesktop"] = 1] = "UserDesktop"; + return SpecialFolder; +}({}); +var getNativeFileSystemAPI = exports.getNativeFileSystemAPI = (0, _ts_utils.singletonGetter)(function () { + var nativeHost = new _kantuFileAccessHost.KantuFileAccessHost(); + var pReady = nativeHost.connectAsync()["catch"](function (e) { + _log["default"].warn('pReady - error', e); + throw e; + }); + var pendingRequestCount = 0; + var api = _constants.MethodTypeInvocationNames.reduce(function (prev, method) { + var camel = (0, _ts_utils.snakeToCamel)(method); + if (prev[camel]) { + return prev; + } + prev[camel] = function () { + var fn = function fn(params) { + return pReady.then(function () { + pendingRequestCount += 1; + return nativeHost.invokeAsync(method, params); + }).then(function (data) { + pendingRequestCount -= 1; + return data; + }, function (e) { + //pendingRequestCount -= 1 // caused ~10s delay if no xmodule installed + pendingRequestCount = 0; + // Note: Looks like for now whenever there is an error, you have to reconnect native host + // otherwise, all commands return "Disconnected" afterwards + var typeSafeAPI = api; + typeSafeAPI.reconnect()["catch"](function () {}); + throw e; + }); + }; + return fn; + }(); + return prev; + }, { + reconnect: function reconnect() { + return (0, _ts_utils.until)('pendingRequestCount === 0', function () { + return { + pass: pendingRequestCount === 0, + result: true + }; + }).then(function () { + (0, _log["default"])("FileSystem - reconnect", new Error().stack); + nativeHost.disconnect(); + pReady = nativeHost.connectAsync(); + return pReady.then(function () { + return api; + }); + }); + }, + getEntries: function getEntries(params) { + var typeSafeAPI = api; + return typeSafeAPI.getFileSystemEntries(params).then(function (res) { + var errorCode = res.errorCode, + entries = res.entries; + if (params.brief) { + return Promise.resolve({ + errorCode: errorCode, + entries: entries.map(function (name) { + return { + name: name, + length: 0, + isDirectory: false, + lastWriteTime: 0 + }; + }) + }); + } + return Promise.all(entries.map(function (name) { + var entryPath = _path["default"].join(params.path, name); + return typeSafeAPI.getFileSystemEntryInfo({ + path: entryPath + }).then(function (info) { + return { + name: name, + length: info.length, + isDirectory: info.isDirectory, + lastWriteTime: info.lastWriteTime + }; + }); + })).then(function (entryInfos) { + return { + errorCode: errorCode, + entries: entryInfos + }; + }); + }); + }, + ensureDir: function ensureDir(params) { + var typeSafeAPI = api; + return typeSafeAPI.directoryExists({ + path: params.path + }).then(function (exists) { + if (exists) return true; + return typeSafeAPI.ensureDir({ + path: _path["default"].dirname(params.path) + }).then(function (done) { + if (!done) return false; + return typeSafeAPI.createDirectory({ + path: params.path + }); + }); + })["catch"](function (e) { + return false; + }); + }, + readBigFile: function readBigFile(params) { + var typeSafeAPI = api; + return typeSafeAPI.getFileSize(params).then(function (fileSize) { + if (fileSize === 0) { + return new Uint8Array(0); + } + var content = []; + var go = function go(pos) { + return typeSafeAPI.readFileRange({ + path: params.path, + rangeStart: pos + }).then(function (result) { + var data = _base.base64.decode(result.buffer); + if (data) { + for (var i = 0; i < data.length; i++) { + content.push(data[i]); + } + } + if (result.rangeEnd <= pos || result.rangeEnd >= fileSize) { + return new Uint8Array(content); + } + return go(result.rangeEnd); + }); + }; + return go(0); + }); + }, + isReadBigFileSupported: function isReadBigFileSupported() { + var typeSafeAPI = api; + return typeSafeAPI.getVersion().then(function (version) { + return !_semver["default"].lt(version, _config["default"].xfile.minVersionToReadBigFile); + }); + }, + readAllTextCompat: function readAllTextCompat(params) { + var typeSafeAPI = api; + return typeSafeAPI.isReadBigFileSupported().then(function (supported) { + if (!supported) { + return typeSafeAPI.readAllText(params); + } + return typeSafeAPI.readBigFile(params).then(function (content) { + var text = _utf.utf8.decode(content); + return { + errorCode: 0, + content: text + }; + }); + }); + }, + readAllBytesCompat: function readAllBytesCompat(params) { + var typeSafeAPI = api; + return typeSafeAPI.isReadBigFileSupported().then(function (supported) { + if (!supported) { + return typeSafeAPI.readAllBytes(params); + } + return typeSafeAPI.readBigFile(params).then(function (content) { + return (0, _utils.blobToDataURL)(new Blob([content])).then(function (dataUrl) { + return { + errorCode: 0, + content: dataUrl + }; + }); + }); + }); + } + }); + return api; +}); /***/ }), -/***/ 93671: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 81173: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -var _stringify = __webpack_require__(63239); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _keys = __webpack_require__(88902); - -var _keys2 = _interopRequireDefault(_keys); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.KantuFileAccessHost = void 0; +var _native_host = __webpack_require__(39356); +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +var KantuFileAccessHost = exports.KantuFileAccessHost = /*#__PURE__*/function (_NativeMessagingHost) { + _inherits(KantuFileAccessHost, _NativeMessagingHost); + function KantuFileAccessHost() { + _classCallCheck(this, KantuFileAccessHost); + return _callSuper(this, KantuFileAccessHost, [KantuFileAccessHost.HOST_NAME]); + } + return _createClass(KantuFileAccessHost); +}(_native_host.NativeMessagingHost); +_defineProperty(KantuFileAccessHost, "HOST_NAME", "com.a9t9.kantu.file_access"); -var _getIterator2 = __webpack_require__(26378); +/***/ }), -var _getIterator3 = _interopRequireDefault(_getIterator2); +/***/ 11434: +/***/ ((__unused_webpack_module, exports) => { -var _promise = __webpack_require__(46593); +"use strict"; -var _promise2 = _interopRequireDefault(_promise); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.KantuFileAccess = void 0; +var KantuFileAccess; +(function (_KantuFileAccess) { + var MethodType = /*#__PURE__*/function (MethodType) { + MethodType[MethodType["GetVersion"] = 0] = "GetVersion"; + MethodType[MethodType["GetFileSystemEntries"] = 1] = "GetFileSystemEntries"; + MethodType[MethodType["GetDirectories"] = 2] = "GetDirectories"; + MethodType[MethodType["GetFiles"] = 3] = "GetFiles"; + MethodType[MethodType["DirectoryExists"] = 4] = "DirectoryExists"; + MethodType[MethodType["FileExists"] = 5] = "FileExists"; + MethodType[MethodType["GetFileSystemEntryInfo"] = 6] = "GetFileSystemEntryInfo"; + MethodType[MethodType["GetSpecialFolderPath"] = 7] = "GetSpecialFolderPath"; + MethodType[MethodType["CreateDirectory"] = 8] = "CreateDirectory"; + MethodType[MethodType["RemoveDirectory"] = 9] = "RemoveDirectory"; + MethodType[MethodType["CopyFile"] = 10] = "CopyFile"; + MethodType[MethodType["MoveFile"] = 11] = "MoveFile"; + MethodType[MethodType["DeleteFile"] = 12] = "DeleteFile"; + MethodType[MethodType["ReadAllText"] = 13] = "ReadAllText"; + MethodType[MethodType["WriteAllText"] = 14] = "WriteAllText"; + MethodType[MethodType["AppendAllText"] = 15] = "AppendAllText"; + MethodType[MethodType["ReadAllBytes"] = 16] = "ReadAllBytes"; + MethodType[MethodType["WriteAllBytes"] = 17] = "WriteAllBytes"; + MethodType[MethodType["AppendAllBytes"] = 18] = "AppendAllBytes"; + MethodType[MethodType["GetMaxFileRange"] = 19] = "GetMaxFileRange"; + MethodType[MethodType["GetFileSize"] = 20] = "GetFileSize"; + MethodType[MethodType["ReadFileRange"] = 21] = "ReadFileRange"; + MethodType[MethodType["RunProcess"] = 22] = "RunProcess"; + return MethodType; + }({}); + _KantuFileAccess.MethodType = MethodType; + var ErrorCode = /*#__PURE__*/function (ErrorCode) { + ErrorCode[ErrorCode["Succeeded"] = 0] = "Succeeded"; + ErrorCode[ErrorCode["Failed"] = 1] = "Failed"; + ErrorCode[ErrorCode["Truncated"] = 2] = "Truncated"; + return ErrorCode; + }({}); + _KantuFileAccess.ErrorCode = ErrorCode; +})(KantuFileAccess || (exports.KantuFileAccess = KantuFileAccess = {})); -var _require = __webpack_require__(63370), - retry = _require.retry; +/***/ }), -var TO_BE_REMOVED = false; +/***/ 39356: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -var log = function log(msg) { - if (console && console.log) console.log(msg); -}; +"use strict"; -var transformError = function transformError(err) { - console.error(err); - if (err instanceof Error) { - return { - isError: true, - name: err.name, - message: err.message, - stack: err.stack +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.NativeMessagingHost = void 0; +var _config = _interopRequireDefault(__webpack_require__(8747)); +var _lodash = _interopRequireDefault(__webpack_require__(20181)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +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 _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } /// +var InvocationQueueItem = /*#__PURE__*/function () { + function InvocationQueueItem(id, method, params, callback) { + _classCallCheck(this, InvocationQueueItem); + this.requestObject = { + id: id, + method: method, + params: params }; + this.callback = callback; } - - return err; -}; - -// Note: The whole idea of ipc promise is about transforming the callback style -// ipc communication API to a Promise style -// -// eg. Orignial: `chrome.runtime.sendMessage({}, () => {})` -// ipcPromise: `ipc.ask({}).then(() => {})` -// -// The benifit is -// 1. You can chain this promise with others -// 2. Create kind of connected channels between two ipc ends -// -// This is a generic interface to define a ipc promise utility -// All you need to declare is 4 functions -// -// e.g. -// ``` -// ipcPromise({ -// ask: function (uid, cmd, args) { ... }, -// answer: function (uid, err, data) { ... }, -// onAsk: function (fn) { ... }, -// onAnswer: function (fn) { ... }, -// }) -// ``` -function ipcPromise(options) { - var ask = options.ask; - var answer = options.answer; - var timeout = options.timeout; - var onAnswer = options.onAnswer; - var onAsk = options.onAsk; - var userDestroy = options.destroy; - var checkReady = options.checkReady || function () { - return _promise2.default.resolve(true); - }; - - var nid = 0; - var askCache = {}; - var unhandledAsk = []; - var markUnhandled = function markUnhandled(uid, cmd, args) { - unhandledAsk.push({ uid: uid, cmd: cmd, args: args }); - }; - var handler = markUnhandled; - - var getNextNid = function getNextNid() { - nid = (nid + 1) % 100000; - return nid; - }; - - var runHandlers = function runHandlers(handlers, cmd, args, resolve, reject) { - for (var i = 0, len = handlers.length; i < len; i++) { - var res; - - try { - res = handlers[i](cmd, args); - } catch (e) { - return reject(e); + _createClass(InvocationQueueItem, [{ + key: "request", + get: function get() { + return this.requestObject; + } + }]); + return InvocationQueueItem; +}(); +var NativeMessagingHost = exports.NativeMessagingHost = /*#__PURE__*/function () { + function NativeMessagingHost(hostName) { + var _this = this; + _classCallCheck(this, NativeMessagingHost); + _defineProperty(this, "ongoingInvocationCount", 0); + _defineProperty(this, "debouncedDisconnectOnIdle", (0, _lodash["default"])(function () { + if (_this.ongoingInvocationCount === 0) { + _this.disconnect(); + } else { + _this.debouncedDisconnectOnIdle(); } - - if (res !== undefined) { - return resolve(res); + }, _config["default"].nativeMessaging.idleTimeBeforeDisconnect)); + this.internalHostName = hostName; + this.nextInvocationId = 1; + this.queue = new Array(); + this.handleMessage = this.handleMessage.bind(this); + this.handleDisconnect = this.handleDisconnect.bind(this); + } + _createClass(NativeMessagingHost, [{ + key: "processResponse", + value: function processResponse(id, result, error) { + var callback = undefined; + for (var i = 0; i < this.queue.length; ++i) { + var entry = this.queue[i]; + if (entry.request.id === id) { + callback = entry.callback; + this.queue.splice(i, 1); + break; + } + } + if (callback) { + callback(result, error); } } - // Note: DO NOT resolve anything if all handlers return undefined - }; - - // both for ask and unhandledAsk - timeout = timeout || -1; - - onAnswer(function (uid, err, data) { - if (uid && askCache[uid] === TO_BE_REMOVED) { - delete askCache[uid]; - return; + }, { + key: "handleMessage", + value: function handleMessage(message) { + var response = message; + if (typeof response.id !== "number") { + return; + } + this.ongoingInvocationCount = Math.max(0, this.ongoingInvocationCount - 1); + this.processResponse(response.id, response.result, response.error); + if (response.error) { + this.disconnect(); + } } - - if (!uid || !askCache[uid]) { - // log('ipcPromise: response uid invalid: ' + uid); - return; + }, { + key: "handleDisconnect", + value: function handleDisconnect() { + this.disconnect(); } - - var resolve = askCache[uid][0]; - var reject = askCache[uid][1]; - - delete askCache[uid]; - - if (err) { - reject(transformError(err)); - } else { - resolve(data); + }, { + key: "hostName", + get: function get() { + return this.internalHostName; } - }); + }, { + key: "connectAsync", + value: function connectAsync() { + // Commented out the following line to keep the connection to native messaging + // to keep the service worker always alive + // note that it only applies to Chrome 100+ + // reference: https://github.com/teamdocs/selenium-ide-chrome-light-2017/issues/884#issuecomment-1088739538 + // + // this.debouncedDisconnectOnIdle(); + + if (this.port) { + return this.invokeAsync("get_version", undefined); + } + this.port = chrome.runtime.connectNative(this.hostName); + this.port.onMessage.addListener(this.handleMessage); + this.port.onDisconnect.addListener(this.handleDisconnect); + this.ongoingInvocationCount = 0; + return this.invokeAsync("get_version", undefined); + } + }, { + key: "disconnect", + value: function disconnect() { + var message = chrome.runtime.lastError && chrome.runtime.lastError.message || "Disconnected"; + if (this.port) { + this.port.disconnect(); + this.port = undefined; + } - onAsk(function (uid, cmd, args) { - if (timeout > 0) { - setTimeout(function () { - var found = unhandledAsk && unhandledAsk.find(function (item) { - return item.uid === uid; + // Discard all queued invocations + var invocationIdArray = this.queue.map(function (x) { + return x.request.id; + }); + var _iterator = _createForOfIteratorHelper(invocationIdArray), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var id = _step.value; + this.processResponse(id, undefined, { + message: message + }); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + this.queue = new Array(); + } + }, { + key: "invoke", + value: function () { + var _invoke = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(method, params, callback) { + var id, item; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (this.port) { + _context.next = 3; + break; + } + _context.next = 3; + return this.connectAsync(); + case 3: + id = this.nextInvocationId++; + item = new InvocationQueueItem(id, method, params, callback); + this.ongoingInvocationCount++; + this.queue.push(item); + this.port.postMessage(item.request); + + // "Chrome 100: native messaging port keeps service worker alive" + // reference: https://developer.chrome.com/docs/extensions/whatsnew/#m100-native-msg-lifetime + // + // Commented out the following line to keep the connection to native messaging + // to keep the service worker always alive + // note that it only applies to Chrome 100+ + // reference: https://github.com/teamdocs/selenium-ide-chrome-light-2017/issues/884#issuecomment-1088739538 + // + // this.debouncedDisconnectOnIdle(); + case 8: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function invoke(_x, _x2, _x3) { + return _invoke.apply(this, arguments); + } + return invoke; + }() + }, { + key: "invokeAsync", + value: function invokeAsync(method, params) { + var _this2 = this; + return new Promise(function (resolve, reject) { + _this2.invoke(method, params, function (result, error) { + if (chrome.runtime.lastError) { + error = new Error(chrome.runtime.lastError.message); + } + if (error) { + reject(error); + } else { + resolve(result); + } }); - - if (!found) return; - - answer(uid, new Error('ipcPromise: answer timeout ' + timeout + ' for cmd "' + cmd + '", args "' + args + '"')); - }, timeout); + }); } + }]); + return NativeMessagingHost; +}(); - if (handler === markUnhandled) { - markUnhandled(uid, cmd, args); - return; - } +/***/ }), - return new _promise2.default(function (resolve, reject) { - runHandlers(handler, cmd, args, resolve, reject); - }).then(function (data) { - // note: handler doens't handle the cmd => return undefined, should wait for timeout - if (data === undefined) return markUnhandled(uid, cmd, args); - answer(uid, null, data); - }, function (err) { - answer(uid, transformError(err), null); - }); - }); +/***/ 56553: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - var wrapAsk = function wrapAsk(cmd, args, timeoutToOverride) { - var uid = 'ipcp_' + new Date() * 1 + '_' + getNextNid(); - var finalTimeout = timeoutToOverride || timeout; - var timer; +"use strict"; - // Note: make it possible to disable timeout - if (finalTimeout > 0) { - timer = setTimeout(function () { - var reject; - if (askCache && askCache[uid]) { - reject = askCache[uid][1]; - askCache[uid] = TO_BE_REMOVED; - reject(new Error('ipcPromise: onAsk timeout ' + finalTimeout + ' for cmd "' + cmd + '", args ' + stringify(args))); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getOrcMatchesHighlighter = exports.OcrMatchesHighlighter = void 0; +var _dom_utils = __webpack_require__(92950); +var _ts_utils = __webpack_require__(1601); +var _global_state = __webpack_require__(8327); +var _types = __webpack_require__(35847); +var _index = __webpack_require__(99998); +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +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."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +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; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +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(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), !0).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; } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +var OcrMatchesHighlighter = exports.OcrMatchesHighlighter = /*#__PURE__*/function () { + function OcrMatchesHighlighter() { + _classCallCheck(this, OcrMatchesHighlighter); + this.$container = this.createContainer(); + this.stores = {}; + } + _createClass(OcrMatchesHighlighter, [{ + key: "clear", + value: function clear() { + //Array.from(this.$container.childNodes).forEach(node => node.remove()) + Array.from(this.$container.childNodes).forEach(function (node) { + if (node.getAttribute('id') !== 'rect-ocr-box') { + node.remove(); } - }, finalTimeout); - } - - return new _promise2.default(function (resolve, reject) { - askCache[uid] = [resolve, reject]; - - _promise2.default.resolve(ask(uid, cmd, args || [])).catch(function (e) { - reject(e); }); - }).then(function (data) { - if (timer) { - clearTimeout(timer); - } - return data; - }, function (e) { - if (timer) { - clearTimeout(timer); - } - throw e; - }); - }; - - var wrapOnAsk = function wrapOnAsk(fn) { - if (Array.isArray(handler)) { - handler.push(fn); - } else { - handler = [fn]; } - - var ps = unhandledAsk.map(function (task) { - return new _promise2.default(function (resolve, reject) { - runHandlers(handler, task.cmd, task.args, resolve, reject); - }).then(function (data) { - // note: handler doens't handle the cmd => return undefined, should wait for timeout - if (data === undefined) return; - answer(task.uid, null, data); - return task.uid; - }, function (err) { - answer(task.uid, err, null); - return task.uid; + }, { + key: "updateStates", + value: function updateStates(store) { + this.stores = store; + } + }, { + key: "highlightRelative", + value: function highlightRelative(rect) { + var $rect = document.createElement('div'); + (0, _dom_utils.setStyle)($rect, _objectSpread({ + boxSizing: 'border-box', + position: 'absolute', + left: "".concat(rect.x, "px"), + top: "".concat(rect.y, "px"), + width: "".concat(rect.width, "px"), + height: "".concat(rect.height, "px"), + border: "2px solid #fe1492", + background: "transparent", + pointerEvents: 'none' + }, {})); + this.$container.appendChild($rect); + } + }, { + key: "highlight", + value: function highlight(matches) { + var _this = this; + var showOcrOverlay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + this.clear(); + matches.forEach(function (match, i) { + _this.createHighlightForMatch(match, i, showOcrOverlay); }); - }); - - _promise2.default.all(ps).then(function (uids) { - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = (0, _getIterator3.default)(uids), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var uid = _step.value; - - if (uid === undefined) continue; - - var index = unhandledAsk.findIndex(function (item) { - return item.uid === uid; + } + }, { + key: "createHighlightForMatch", + value: function createHighlightForMatch(match, matchIndex, showOcrOverlay) { + var _this2 = this; + console.log('match:>> ', match); + console.log('match.words:>> ', match.words); + console.log('matchIndex:>> ', matchIndex); + console.log('showOcrOverlay:>> ==', showOcrOverlay); + + // match.words.forEach((word, i) => { + // this.createHighlightForWord(word, { + // highlight: match.highlight, + // shouldScrollTo: false + // }, matchIndex) + // }) + + if (showOcrOverlay) { + match.words.forEach(function (word, i) { + _this2.createHighlightForWord(word, { + highlight: match.highlight, + shouldScrollTo: false + }, matchIndex, showOcrOverlay); + }); + } else if (matchIndex && match.words.length === 1) { + var singleWord = match.words[0]; + this.createHighlightForWord(singleWord, { + highlight: match.highlight, + shouldScrollTo: false + }, matchIndex); + } else if (matchIndex && match.words.length > 1 && match.highlight !== _types.OcrHighlightType.Identified) { + var isSequential = true; + var lastRightXOnMultipleLines = match.words.reduce(function (lastRight, word) { + if (!isSequential) return lastRight; + if (word.word.Left < lastRight) { + isSequential = false; + return lastRight; + } + lastRight = word.word.Left + word.word.Width; + console.log('lastRight:>> ', lastRight); + return lastRight; + }, 0); + console.log('isSequential:>> ', isSequential); + console.log('lastRightXOnMultipleLines:>> ', lastRightXOnMultipleLines); + var combinedWidth = 0; + if (!isSequential) { + combinedWidth = lastRightXOnMultipleLines - match.words[0].word.Left; + } else { + // if not sequential, calculate the combined width + var leftMostWord = match.words.reduce(function (acc, word) { + return acc.word.Left < word.word.Left ? acc : word; }); - - unhandledAsk.splice(index, 1); + var rightMostWord = match.words.reduce(function (acc, word) { + return acc.word.Left + acc.word.Width > word.word.Left + word.word.Width ? acc : word; + }); + combinedWidth = rightMostWord.word.Left + rightMostWord.word.Width - leftMostWord.word.Left; } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); + console.log('combinedWidth:>> ', combinedWidth); + var combinedWord = { + position: { + pageIndex: match.words[0].position.pageIndex, + lineIndex: match.words[0].position.lineIndex, + wordIndex: match.words[0].position.wordIndex + }, + word: { + WordText: match.words.map(function (word) { + return word.word.WordText; + }).join(' '), + Height: match.words[0].word.Height, + Width: combinedWidth, + Top: match.words[0].word.Top, + Left: match.words[0].word.Left } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } + }; + this.createHighlightForWord(combinedWord, { + highlight: match.highlight, + shouldScrollTo: false + }, matchIndex); + } else { + // grey out the identified words + match.words.forEach(function (word, i) { + _this2.createHighlightForWord(word, { + highlight: match.highlight, + shouldScrollTo: false + }, matchIndex); + }); } - }); - }; - var destroy = function destroy(noReject) { - userDestroy && userDestroy(); - - ask = null; - answer = null; - onAnswer = null; - onAsk = null; - unhandledAsk = null; + // console.log('this.stores:>> ', this.stores) - if (!noReject) { - (0, _keys2.default)(askCache).forEach(function (uid) { - var tuple = askCache[uid]; - var reject = tuple[1]; - reject && reject(new Error('IPC Promise has been Destroyed.')); - delete askCache[uid]; - }); + if (match.highlight === _types.OcrHighlightType.TopMatched || match.highlight === _types.OcrHighlightType.WildcardTopMatched) { + var stores = this.stores; + // if (stores) { + if (stores['curent_cmd'] == "XClickTextRelative" || stores['curent_cmd'] == "XMoveTextRelative") { + this.createRectForMatch(match); + } + if (stores['curent_cmd'] == "OCRExtractbyTextRelative" || stores['curent_cmd'] == "visionLimitSearchAreabyTextRelative") { + this.createRectForMatchOCrExtract(match); + } + // } + } } - }; - - var waitForReady = function waitForReady(checkReady, fn) { - return function () { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + }, { + key: "createHighlightForWord", + value: function createHighlightForWord(pw, options, matchIndex) { + var showOcrOverlayOnly = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var $mark = document.createElement('div'); + $mark.innerText = pw.word.WordText; + + // console.log(`pw.word.WordText matchIndex ${matchIndex} text:>> `, pw.word.WordText) + // console.log('options:>> ', options) + + var styleByType = function () { + switch (options.highlight) { + case _types.OcrHighlightType.Identified: + return { + color: 'rgba(255, 0, 0, 1)', + backgroundColor: 'rgba(200, 200, 200, 0.75)' + }; + case _types.OcrHighlightType.Matched: + return { + color: '#f00', + backgroundColor: 'rgba(255, 215, 15, 0.5)' + }; + case _types.OcrHighlightType.TopMatched: + return { + color: '#fe1492', + backgroundColor: 'rgba(255, 215, 15, 0.5)' + }; + case _types.OcrHighlightType.WildcardMatched: + return { + color: '#fe1492', + backgroundColor: 'rgba(255, 215, 15, 0.5)' + }; + case _types.OcrHighlightType.WildcardTopMatched: + return { + color: '#fe1492', + backgroundColor: 'rgba(255, 215, 15, 0.5)' + }; + } + }(); + (0, _dom_utils.setStyle)($mark, _objectSpread({ + boxSizing: 'border-box', + position: 'absolute', + left: "".concat(pw.word.Left, "px"), + top: "".concat(pw.word.Top, "px"), + width: "".concat(pw.word.Width, "px"), + height: "".concat(pw.word.Height, "px"), + lineHeight: "".concat(pw.word.Height, "px"), + fontSize: "".concat(pw.word.Height * 0.8, "px"), + fontWeight: 'bold', + textAlign: 'center', + pointerEvents: 'none' + }, styleByType)); + this.$container.appendChild($mark); + var showSerial = !showOcrOverlayOnly && (options.highlight === _types.OcrHighlightType.Matched || options.highlight === _types.OcrHighlightType.TopMatched || options.highlight === _types.OcrHighlightType.WildcardMatched || options.highlight === _types.OcrHighlightType.WildcardTopMatched); + + // Highlight match with a match serial + if (showSerial) { + $mark.innerText = ''; + var $serialElement = document.createElement('span'); + $serialElement.innerText = "".concat(matchIndex); + (0, _dom_utils.setStyle)($serialElement, { + position: 'absolute', + top: '-15px', + left: '-15px', + fontSize: '10px', + lineHeight: '10px', + color: '#e31399', + border: '2px solid', + padding: '2px 4px', + borderRadius: '4px' + }); + // append the serial element to the mark + $mark.appendChild($serialElement); + var $circleElement = document.createElement('span'); + (0, _dom_utils.setStyle)($circleElement, { + position: 'absolute', + border: '3px solid #e31399ba', + padding: '3px 3px', + borderRadius: '10px', + right: 'calc(50% - 6px)', + bottom: 'calc(50% - 6px)' + }); + // append the after element to the mark + $mark.appendChild($circleElement); + var $textElement = document.createElement('div'); + $textElement.innerText = pw.word.WordText; + (0, _dom_utils.setStyle)($textElement, { + position: 'absolute', + width: '100%', + top: '100%', + left: '50%', + transform: 'translateX(-50%)', + fontSize: '18px', + fontWeight: 'bold', + color: '#4697fc' + }); + // append the text element to the mark + $mark.appendChild($textElement); } + if (options.shouldScrollTo) { + $mark.scrollIntoView({ + block: 'center' + }); + } + } + }, { + key: "createRectForMatchOCrExtract", + value: function createRectForMatchOCrExtract(match, styles) { + var _this3 = this; + _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var allState, rect, $rect, $rectY, $rectX, $rectBox, markerDiv, stylesY, stylesX, stylesBox, xD, yD, isLeft, isTopY, isXavilable, stores, getCoordinates, cal_tragte, caliberTick, getTickCounter, countCalObj, ocrCalibration, isDesktopMode, x, all_nums, rectTop, rectLeft, rectWidth, rectHeight, yHeight, yTop; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + getTickCounter = function _getTickCounter(str) { + function getNumberSet(num, type) { + if (parseInt(num) > 0 && type == 'X') { + return ['>', parseInt(num)]; + } else if (parseInt(num) < 0 && type == 'X') { + return ['<', parseInt(String(num).replace('-', ''))]; + } else if (parseInt(num) > 0 && type == 'Y') { + return ['^', parseInt(num)]; + } else { + return ['v', parseInt(String(num).replace('-', ''))]; + } + } + var nums = getCoordinates(str); + var _getNumberSet = getNumberSet(nums[0], 'X'), + _getNumberSet2 = _slicedToArray(_getNumberSet, 2), + x1 = _getNumberSet2[0], + y1 = _getNumberSet2[1]; + var _getNumberSet3 = getNumberSet(nums[1], 'Y'), + _getNumberSet4 = _slicedToArray(_getNumberSet3, 2), + x2 = _getNumberSet4[0], + y2 = _getNumberSet4[1]; + ; + var valueObj = {}; + valueObj[x1] = y1; + valueObj[x2] = y2; + return valueObj; + }; + getCoordinates = function _getCoordinates(str) { + //var regex = /TL(-?\d+),(-?\d+)BR(-?\d+),(-?\d+)/; + var regex = /R(-?\d+),(-?\d+)W(-?\d+)H(-?\d+)/; + var matches = str.match(regex); + var x = parseInt(matches[1]); + var y = parseInt(matches[2]); + var W = parseInt(matches[3]); + var H = parseInt(matches[4]); + return [x, y, W, H]; + }; + _context.next = 4; + return (0, _global_state.getState)(); + case 4: + allState = _context.sent; + rect = (0, _index.ocrMatchRect)(match); + $rect = document.createElement('div'); + $rectY = document.createElement('div'); + $rectX = document.createElement('div'); + $rectBox = document.createElement('div'); + $rectBox.setAttribute('id', 'rect-ocr-box'); + $rectY.setAttribute('id', 'rect-ocr-box'); + $rectX.setAttribute('id', 'rect-ocr-box'); + $rect.setAttribute('id', 'rect-ocr-box'); + (0, _dom_utils.setStyle)($rect, _objectSpread({ + boxSizing: 'border-box', + position: 'absolute', + left: "".concat(rect.x, "px"), + top: "".concat(rect.y, "px"), + width: "".concat(rect.width, "px"), + height: "".concat(rect.height, "px"), + border: "2px solid #fe1492", + background: "transparent", + pointerEvents: 'none' + }, styles || {})); + markerDiv = ""; + stylesY = {}; + stylesX = {}; + stylesBox = {}; + xD = 0, yD = 0; + isLeft = false; + isTopY = false; + isXavilable = false; + stores = _this3.stores; + cal_tragte = !!stores['caliber_trget'] ? stores['caliber_trget'] : ''; + caliberTick = cal_tragte; + if (caliberTick.indexOf('W') == -1 || caliberTick.indexOf('H') == -1) { + caliberTick = caliberTick + 'W30H10'; + } + ; + countCalObj = getTickCounter(caliberTick); + ocrCalibration = allState['ocrCalibration'] ? allState['ocrCalibration'] : 6; + isDesktopMode = stores.isDesktopMode; + if (isDesktopMode == "false") { + ocrCalibration = 7; + } + for (x in countCalObj) { + if (x == 'v' || x == 'v') { + yD += rect['y'] + ocrCalibration * countCalObj[x]; //down (add in y offset) + } + if (x == '>') { + xD += rect['x'] + ocrCalibration * countCalObj[x]; //right (add in x offset) + } + if (x == '<') { + xD += rect['x'] - ocrCalibration * countCalObj[x]; //left (minus in x offset) + isLeft = true; + } + if (x == '^') { + yD += rect['y'] - ocrCalibration * countCalObj[x]; //up (minus in y offset) + isTopY = true; + } + } + all_nums = getCoordinates(caliberTick); + rectTop = yD; + rectLeft = xD; + rectWidth = ocrCalibration * all_nums[2]; + rectHeight = ocrCalibration * all_nums[3]; + stylesBox = { + position: 'absolute', + left: rectLeft + 'px', + top: rectTop + 'px', + width: rectWidth + 'px', + height: rectHeight + 'px', + border: "2px solid green" + }; + if (yD != 0) { + stylesY = { + position: 'absolute', + left: "".concat(rectLeft, "px"), + top: "".concat(rect.y, "px"), + height: "".concat(Math.abs(rect.y - yD), "px"), + borderLeft: "2px solid red" + }; + if (isTopY) { + yHeight = stylesY['height']; + yTop = stylesY['top']; + stylesY['top'] = Math.abs(parseFloat(yTop) - parseInt(yHeight)) + 'px'; + } + } else { + yD = rect.y; + } + if (yD) if (xD != 0) { + stylesX = { + position: 'absolute', + left: "".concat(rect.x, "px"), + top: "".concat(rect.y, "px"), + width: "".concat(Math.abs(rect.x - xD), "px"), + borderBottom: "2px solid red" + }; + if (isLeft) { + stylesX['left'] = Math.abs(rect.x - Math.abs(rect.x - xD)) + 'px'; + stylesY['left'] = Math.abs(rect.x - Math.abs(rect.x - xD)) + 'px'; + } + isXavilable = true; + } + (0, _dom_utils.setStyle)($rectX, stylesX); + (0, _dom_utils.setStyle)($rectBox, stylesBox); + (0, _dom_utils.setStyle)($rectY, stylesY); + localStorage.removeItem('curent_cmd'); + localStorage.removeItem('caliber_trget'); + localStorage.removeItem('ocrCalibration'); + _this3.$container.appendChild($rect); + _this3.$container.appendChild($rectY); + _this3.$container.appendChild($rectX); + _this3.$container.appendChild($rectBox); + setTimeout(function () { + var elementsIds = document.querySelectorAll('[id="rect-ocr-box"]'); + elementsIds.forEach(function (element) { + element.removeAttribute('id'); + }); + }, 5000); + case 52: + case "end": + return _context.stop(); + } + }, _callee); + }))(); + } + }, { + key: "createRectForMatch", + value: function createRectForMatch(match, styles) { + var _this4 = this; + _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { + var allState, rect, $rect, $rectY, $rectX, $rectBox, markerDiv, stylesY, stylesX, stylesBox, xD, yD, isLeft, isTopY, isXavilable, stores, getTickCounter, cal_tragte, caliberTick, countCalObj, ocrCalibration, isDesktopMode, x, yHeight, yTop, xWidth, xLeft, leftNewX, yLeft, _yHeight, leftNewY, _yTop, toptNewY; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return (0, _global_state.getState)(); + case 2: + allState = _context2.sent; + rect = (0, _index.ocrMatchRect)(match); + $rect = document.createElement('div'); + $rectY = document.createElement('div'); + $rectX = document.createElement('div'); + $rectBox = document.createElement('div'); + (0, _dom_utils.setStyle)($rect, _objectSpread({ + boxSizing: 'border-box', + position: 'absolute', + left: "".concat(rect.x, "px"), + top: "".concat(rect.y, "px"), + width: "".concat(rect.width, "px"), + height: "".concat(rect.height, "px"), + border: "2px solid #fe1492", + background: "transparent", + pointerEvents: 'none' + }, styles || {})); + markerDiv = ""; + stylesY = {}; + stylesX = {}; + stylesBox = {}; + xD = 0, yD = 0; + isLeft = false; + isTopY = false; + isXavilable = false; + stores = _this4.stores; + if (stores['curent_cmd'] == "XClickTextRelative" || stores['curent_cmd'] == "XMoveTextRelative") { + getTickCounter = function getTickCounter(str) { + function getNumberSet(num, type) { + if (parseInt(num) > 0 && type == 'X') { + return ['>', parseInt(num)]; + } else if (parseInt(num) < 0 && type == 'X') { + return ['<', parseInt(num.replace('-', ''))]; + } else if (parseInt(num) > 0 && type == 'Y') { + return ['^', parseInt(num)]; + } else { + return ['v', parseInt(num.replace('-', ''))]; + } + } + function getAllNumbersWithSign(str) { + var matches = str.match(/-?\d+/g); + if (matches) { + return matches; + } + return null; + } + if (str.indexOf('#R') !== -1) { + //ABC #R-6,3 + var parts = str.split("#R"); + var nums = getAllNumbersWithSign(parts[1]); + var _getNumberSet5 = getNumberSet(nums[0], 'X'), + _getNumberSet6 = _slicedToArray(_getNumberSet5, 2), + x1 = _getNumberSet6[0], + y1 = _getNumberSet6[1]; + var _getNumberSet7 = getNumberSet(nums[1], 'Y'), + _getNumberSet8 = _slicedToArray(_getNumberSet7, 2), + x2 = _getNumberSet8[0], + y2 = _getNumberSet8[1]; + ; // 3 + var valueObj = {}; + valueObj[x1] = y1; + valueObj[x2] = y2; + return valueObj; + } - var makeSureReady = retry(checkReady, { - shouldRetry: function shouldRetry() { - return true; - }, - retryInterval: 100, - timeout: 5000 - }); - - return makeSureReady().then(function () { - return fn.apply(undefined, args); - }); - }; - }; - - return { - ask: waitForReady(checkReady, wrapAsk), - onAsk: wrapOnAsk, - destroy: destroy - }; -} - -ipcPromise.serialize = function (obj) { - return { - ask: function ask(cmd, args, timeout) { - return obj.ask(cmd, (0, _stringify2.default)(args), timeout); - }, - - onAsk: function onAsk(fn) { - return obj.onAsk(function (cmd, args) { - return fn(cmd, JSON.parse(args)); - }); - }, - - destroy: obj.destroy - }; -}; - -function stringify(v) { - return v === undefined ? 'undefined' : (0, _stringify2.default)(v); -} - -module.exports = ipcPromise; + // return str.split('').reduce((total, letter) => { + // total[letter] ? total[letter]++ : total[letter] = 1; + // return total; + // }, {}); + }; + ; + cal_tragte = !!stores['caliber_trget'] ? stores['caliber_trget'] : ''; //const caliberTick = cal_tragte.split('#R')[1];//old methode + caliberTick = cal_tragte; + countCalObj = getTickCounter(caliberTick); //const ocrCalibration:any = !!localStorage.getItem('ocrCalibration') ? localStorage.getItem('ocrCalibration'):6; + ocrCalibration = allState['ocrCalibration'] ? allState['ocrCalibration'] : 6; + isDesktopMode = stores.isDesktopMode; + if (isDesktopMode == "false") { + ocrCalibration = 7; + } + for (x in countCalObj) { + if (x == 'v' || x == 'v') { + yD += rect['y'] + ocrCalibration * countCalObj[x]; //down (add in y offset) + } + if (x == '>') { + xD += rect['x'] + ocrCalibration * countCalObj[x]; //right (add in x offset) + } + if (x == '<') { + xD += rect['x'] - ocrCalibration * countCalObj[x]; //left (minus in x offset) + isLeft = true; + } + if (x == '^') { + yD += rect['y'] - ocrCalibration * countCalObj[x]; //up (minus in y offset) + isTopY = true; + } + } + if (yD != 0) { + stylesY = { + position: 'absolute', + left: "".concat(rect.x + rect.width / 2, "px"), + top: "".concat(rect.y, "px"), + height: "".concat(Math.abs(rect.y - yD), "px"), + borderLeft: "2px solid red" + }; + if (isTopY) { + yHeight = stylesY['height']; + yTop = stylesY['top']; + stylesY['top'] = Math.abs(parseFloat(yTop) - parseInt(yHeight)) + 'px'; + } + (0, _dom_utils.setStyle)($rectY, stylesY); + } else { + yD = rect.y; + } + if (yD) if (xD != 0) { + stylesX = { + position: 'absolute', + left: "".concat(rect.x + rect.width / 2, "px"), + top: "".concat(yD, "px"), + width: "".concat(Math.abs(rect.x - xD), "px"), + borderBottom: "2px solid red" + }; + if (isLeft) { + stylesX['left'] = Math.abs(rect.x + rect.width / 2 - Math.abs(rect.x - xD)) + 'px'; + } + isXavilable = true; + } + (0, _dom_utils.setStyle)($rectX, stylesX); + if (isXavilable) { + xWidth = stylesX['width']; + xLeft = stylesX['left']; + leftNewX = isLeft ? parseFloat(xLeft) - 20 : parseFloat(xLeft) + parseFloat(xWidth); + stylesBox = { + position: 'absolute', + left: "".concat(leftNewX, "px"), + top: "".concat(yD - 20 / 2, "px"), + width: "".concat(20, "px"), + height: "".concat(20, "px"), + border: "2px solid green" + }; + } else { + yLeft = stylesY['left']; + _yHeight = stylesY['height']; + leftNewY = parseFloat(yLeft); + _yTop = stylesY['top']; + toptNewY = isTopY ? parseFloat(_yTop) - 20 : parseFloat(_yTop) + parseFloat(_yHeight); + stylesBox = { + position: 'absolute', + left: "".concat(leftNewY - 20 / 2, "px"), + top: "".concat(toptNewY, "px"), + width: "".concat(20, "px"), + height: "".concat(20, "px"), + border: "2px solid green" + }; + } + (0, _dom_utils.setStyle)($rectBox, stylesBox); + } + localStorage.removeItem('curent_cmd'); + localStorage.removeItem('caliber_trget'); + localStorage.removeItem('ocrCalibration'); + _this4.$container.appendChild($rect); + _this4.$container.appendChild($rectY); + _this4.$container.appendChild($rectX); + _this4.$container.appendChild($rectBox); + case 26: + case "end": + return _context2.stop(); + } + }, _callee2); + }))(); + } + }, { + key: "createContainer", + value: function createContainer() { + var $div = document.createElement('div'); + document.documentElement.appendChild($div); + return $div; + } + }]); + return OcrMatchesHighlighter; +}(); +var getOrcMatchesHighlighter = exports.getOrcMatchesHighlighter = (0, _ts_utils.singletonGetter)(function () { + return new OcrMatchesHighlighter(); +}); /***/ }), -/***/ 3575: +/***/ 99998: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Keyboard = exports.Keystroke = exports.KeyEvents = undefined; - -var _createClass2 = __webpack_require__(22600); - -var _createClass3 = _interopRequireDefault(_createClass2); - -var _classCallCheck2 = __webpack_require__(99663); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _domElementIsNativelyEditable = __webpack_require__(34673); - -var _domElementIsNativelyEditable2 = _interopRequireDefault(_domElementIsNativelyEditable); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var CTRL = 1 << 0; -var META = 1 << 1; -var ALT = 1 << 2; -var SHIFT = 1 << 3; - -// Key Events -var KeyEvents = exports.KeyEvents = { - DOWN: 1 << 0, - PRESS: 1 << 1, - UP: 1 << 2, - INPUT: 1 << 3 -}; -KeyEvents.ALL = KeyEvents.DOWN | KeyEvents.PRESS | KeyEvents.UP | KeyEvents.INPUT; - -/** - * Represents a keystroke, or a single key code with a set of active modifiers. - * - * @class Keystroke - */ - -var Keystroke = -/** - * @param {number} modifiers A bitmask formed by CTRL, META, ALT, and SHIFT. - * @param {number} keyCode - */ -exports.Keystroke = function Keystroke(modifiers, keyCode) { - (0, _classCallCheck3.default)(this, Keystroke); - - this.modifiers = modifiers; - this.ctrlKey = !!(modifiers & CTRL); - this.metaKey = !!(modifiers & META); - this.altKey = !!(modifiers & ALT); - this.shiftKey = !!(modifiers & SHIFT); - this.keyCode = keyCode; -} - -/** - * Gets the bitmask value for the "control" modifier. - * - * @type {number} - */ - - -/** - * Gets the bitmask value for the "meta" modifier. - * - * @return {number} - */ - +exports.WordMatchType = void 0; +exports.allWordsWithPosition = allWordsWithPosition; +exports.getOcrPositionedWordsFromParseResults = getOcrPositionedWordsFromParseResults; +exports.guardOCRResponse = guardOCRResponse; +exports.hasWordMatch = hasWordMatch; +exports.isOcrSpaceFreeKey = isOcrSpaceFreeKey; +exports.isWordEqual = isWordEqual; +exports.isWordPositionEqual = isWordPositionEqual; +exports.iterateThroughParseResults = iterateThroughParseResults; +exports.ocrMatchCenter = ocrMatchCenter; +exports.ocrMatchRect = ocrMatchRect; +exports.runDownloadLog = runDownloadLog; +exports.runOCR = runOCR; +exports.runOCRLocal = runOCRLocal; +exports.runOCRTesseractC = runOCRTesseractC; +exports.scaleOcrParseResultWord = scaleOcrParseResultWord; +exports.scaleOcrResponseCoordinates = scaleOcrResponseCoordinates; +exports.scaleOcrTextSearchMatch = scaleOcrTextSearchMatch; +exports.searchTextInOCRResponse = searchTextInOCRResponse; +exports.testOcrSpaceAPIKey = testOcrSpaceAPIKey; +exports.wordIteratorFromParseResults = wordIteratorFromParseResults; +var _superagent = _interopRequireDefault(__webpack_require__(15734)); +var _types = __webpack_require__(35847); +var _utils = __webpack_require__(46580); +var _ts_utils = __webpack_require__(1601); +var _filesystem = __webpack_require__(89937); +var _xfile = __webpack_require__(63109); +var _path = _interopRequireDefault(__webpack_require__(26513)); +var _tesseract_c = _interopRequireDefault(__webpack_require__(67802)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +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), !0).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; } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +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."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +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; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +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 runDownloadLog(base64result, targetP, osType) { + var fsAPI = (0, _filesystem.getNativeFileSystemAPI)(); + return fsAPI.getSpecialFolderPath({ + folder: _filesystem.SpecialFolder.UserProfile + }).then(function (profilePath) { + var uivision = osType == "mac" ? '/Library/uivision-xmodules/2.2.2/xmodules/' : _path["default"].join(profilePath, "\\AppData\\Roaming\\UI.Vision\\XModules\\ocr"); + return fsAPI.ensureDir({ + path: uivision + }).then(function (Opath) { + var _getXFile$getCachedCo = (0, _xfile.getXFile)().getCachedConfig(), + rootDir = _getXFile$getCachedCo.rootDir; + var path = uivision; + var outputpath = rootDir; + var filepath = '', + targetpath = targetP; + if (osType == "mac") { + filepath = path + '/ocr3'; + //targetpath = outputpath+'/images/image.png'; + } else { + filepath = path + '\\ocrexe\\ocrcl1.exe'; + //targetpath = outputpath+'\\images\\image.png'; + } + var params = { + fileName: filepath, + path: targetpath, + content: base64result, + waitForExit: true + }; + return fsAPI.writeAllText(params).then(function (res) { + if (res != undefined) { + return res; + } + })["catch"](function () { + return console.log({ + result: false + }); + }); + }); + })["catch"](function (e) { + // Ignore host not found error, `initConfig` is supposed to be called on start + // But we can't guarantee that native fs module is already installed + if (!/Specified native messaging host not found/.test(e)) { + throw e; + } + }); +} +function runOCRTesseractC(_x, _x2) { + return _runOCRTesseractC.apply(this, arguments); +} +function _runOCRTesseractC() { + _runOCRTesseractC = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(options, logCB) { + var language, imageDataURL, tesseractWrapper, extractionResult, retVal; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + language = options.language; + imageDataURL = options.imageDataURL; + _context.next = 4; + return _tesseract_c["default"].getInstance(); + case 4: + tesseractWrapper = _context.sent; + tesseractWrapper.setLogger(logCB); + _context.next = 8; + return tesseractWrapper.start(imageDataURL, language); + case 8: + extractionResult = _context.sent; + retVal = { + "ParsedResults": extractionResult.resultData, + "ProcessingTimeInMilliseconds": extractionResult.processingTimeInMilliseconds + }; + return _context.abrupt("return", Promise.resolve(retVal)); + case 11: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _runOCRTesseractC.apply(this, arguments); +} +function runOCRLocal(options) { + var language = options.language; + var base64result = options.image; + var osType = options.os; + var fsAPI = (0, _filesystem.getNativeFileSystemAPI)(); + return fsAPI.getSpecialFolderPath({ + folder: _filesystem.SpecialFolder.UserProfile + }).then(function (profilePath) { + var uivision = osType == "mac" ? '/Library/uivision-xmodules/2.2.2/xmodules/' : _path["default"].join(profilePath, "\\AppData\\Roaming\\UI.Vision\\XModules\\ocr"); + return fsAPI.ensureDir({ + path: uivision + }).then(function (Opath) { + var _getXFile$getCachedCo2 = (0, _xfile.getXFile)().getCachedConfig(), + rootDir = _getXFile$getCachedCo2.rootDir; + var path = uivision; + var outputpath = rootDir; + var filepath = '', + targetpath = ''; + if (osType == "mac") { + filepath = path + '/ocr3'; + //targetpath = outputpath+'/images/image.png'; + targetpath = outputpath + '/image.png'; + } else { + filepath = path + '\\ocrexe\\ocrcl1.exe'; + //targetpath = outputpath+'\\images\\image.png'; + targetpath = outputpath + '/image.png'; + } + var params = { + fileName: filepath, + path: targetpath, + content: base64result, + waitForExit: true + }; + return fsAPI.writeAllBytes(params).then(function (res) { + if (res != undefined) { + var _filepath = ''; + var _params = {}; + if (osType == "mac") { + _filepath = path + '/ocr3'; + _params = { + arguments: '--in ' + outputpath + "/image.png" + " --out " + outputpath + "/ocr_output.json --lang " + language, + //arguments: '--in '+outputpath+"/image.png"+" --out "+outputpath+"/ocr_output.json --lang "+language, + fileName: _filepath, + waitForExit: true + }; + } else { + _filepath = path + '\\ocrexe\\ocrcl1.exe'; + _params = { + arguments: outputpath + "\\image.png" + " " + outputpath + "\\ocr_output.json " + language, + //arguments: outputpath+"\\images\\image.png"+" "+outputpath+"\\logs\\ocr_output.json "+language, + fileName: _filepath, + waitForExit: true + }; + } + return fsAPI.runProcess(_params); + } else { + console.log({ + result: false + }); + } + }).then(function (res) { + if (res != undefined && res.exitCode != null && res.exitCode >= 0) { + var _filepath2 = ''; + var _params2 = {}; + if (osType == "mac") { + _params2 = { + path: outputpath + "/ocr_output.json", + //path: outputpath+"/logs/ocr_output.json", + waitForExit: true + }; + } else { + _params2 = { + path: outputpath + "\\ocr_output.json", + //path: outputpath+"\\logs\\ocr_output.json", + waitForExit: true + }; + } + console.log('params:>> ', _params2); + return fsAPI.readAllBytes(_params2); + } + }).then(function (json) { + if (json) { + if (json.errorCode == 0) { + //console.log(json.content); + return json.content; + } else { + return false; + } + } + })["catch"](function () { + return console.log({ + result: false + }); + }); + }); + })["catch"](function (e) { + // Ignore host not found error, `initConfig` is supposed to be called on start + // But we can't guarantee that native fs module is already installed + if (!/Specified native messaging host not found/.test(e)) { + throw e; + } + }); +} +function runOCR(options) { + var scaleStr = (options.scale + '').toLowerCase(); + var scale = ['true', 'false'].indexOf(scaleStr) !== -1 ? scaleStr : 'true'; + var engine = [1, 2].indexOf(options.engine || 0) !== -1 ? options.engine : 1; + var singleRun = function singleRun() { + return options.getApiUrlAndApiKey().then(function (server) { + var url = server.url, + key = server.key; + var f = new FormData(); + console.log('runOCR url:>> ', url); + console.log('runOCR key:>> ', key); + f.append('apikey', key); + f.append('language', options.language); + f.append('scale', scale); + f.append('OCREngine', '' + engine); + f.append('isOverlayRequired', '' + options.isOverlayRequired); + if (options.isTable !== undefined) { + f.append('isTable', '' + options.isTable); + } + if (typeof options.image === 'string') { + f.append('file', (0, _utils.dataURItoBlob)(options.image), 'unknown.png'); + } else { + f.append('file', options.image.blob, options.image.name); + } + var startTime = new Date().getTime(); + if (options.willSendRequest) { + options.willSendRequest({ + server: server, + startTime: startTime + }); + } + return (0, _utils.withTimeout)(options.singleApiTimeout, function () { + return _superagent["default"].post(url).send(f); + }).then(function (res) { + if (options.didGetResponse) { + return options.didGetResponse({ + server: server, + startTime: startTime, + endTime: new Date().getTime(), + response: res.body, + error: null + }).then(function () { + return res; + }, function () { + return res; + }); + } + return res; + }, function (e) { + var err = getApiError(e); + if (options.didGetResponse) { + return options.didGetResponse({ + server: server, + startTime: startTime, + endTime: new Date().getTime(), + response: null, + error: err + }).then(function () { + throw err; + }, function () { + throw err; + }); + } + throw e; + }).then(onApiReturn, onApiError)["catch"](function (e) { + if (/timeout/i.test(e.message)) { + throw new Error("OCR request timeout ".concat((options.singleApiTimeout / 1000).toFixed(1), "s")); + } else { + throw e; + } + }); + }); + }; + var run = (0, _ts_utils.retry)(singleRun, { + // We don't want timeout mechanism from retry, so just make it big enough + timeout: options.singleApiTimeout * 10, + retryInterval: 0, + shouldRetry: options.shouldRetry || function () { + return false; + } + }); + return (0, _utils.withTimeout)(options.totalTimeout, run)["catch"](function (e) { + if (/timeout/i.test(e.message)) { + throw new Error('OCR timeout'); + } else { + throw e; + } + }); +} +function isOcrSpaceFreeKey(key) { + return !!key && key.startsWith('K8'); +} +function testOcrSpaceAPIKey(_ref) { + var url = _ref.url, + key = _ref.key; + var f = new FormData(); + console.log('runOCR url:>> ', url); + console.log('runOCR key:>> ', key); + f.append('apikey', key); + return (0, _utils.withTimeout)(10 * 1000, function () { + return _superagent["default"].post(url).send(f); + }).then(function (res) { + // if res.body is json object + if (res.body && res.body.ErrorMessage && res.body.ErrorMessage.length > 0 && res.body.ErrorMessage[0] === "Unable to recognize the file type") { + // key is valid + return true; + } else { + return false; + } + })["catch"](function (e) { + console.log('testOcrSpaceAPIKey e:>> ', e); + return false; + }); +} +function getApiError(e) { + if (e.response && typeof e.response.body === 'string') { + return new Error(e.response.body); + } + return e; +} +function onApiError(e) { + console.error(e); + throw getApiError(e); +} +function onApiReturn(res) { + guardOCRResponse(res.body); + return res.body; +} +function guardOCRResponse(data) { + switch (data.OCRExitCode) { + case _types.OCRExitCode.AllParsed: + return; + case _types.OCRExitCode.PartiallyParsed: + throw new Error(['Parsed Partially (Only few pages out of all the pages parsed successfully)', data.ErrorMessage || '', data.ErrorDetails || ''].filter(function (s) { + return s.length > 0; + }).join('; ')); + case _types.OCRExitCode.Failed: + throw new Error(['OCR engine fails to parse an image', data.ErrorMessage || '', data.ErrorDetails || ''].filter(function (s) { + return s.length > 0; + }).join('; ')); + case _types.OCRExitCode.Fatal: + throw new Error(['Fatal error occurs during parsing', data.ErrorMessage || '', data.ErrorDetails || ''].filter(function (s) { + return s.length > 0; + }).join('; ')); + } +} +function wordIteratorFromParseResults(parseResults) { + var pageIndex = 0; + var lineIndex = 0; + var wordIndex = 0; + var next = function next() { + var page = parseResults[pageIndex]; + var currentLines = page ? page.TextOverlay.Lines : []; + var line = page ? page.TextOverlay.Lines[lineIndex] : null; + var currentWords = line ? line.Words : []; + var word = line ? line.Words[wordIndex] : null; + if (!word) { + return { + done: true, + value: null + }; + } + var value = { + word: word, + position: { + pageIndex: pageIndex, + lineIndex: lineIndex, + wordIndex: wordIndex + } + }; + var _ref2 = function () { + var nextWordIndex = wordIndex + 1; + var nextLineIndex = lineIndex; + var nextPageIndex = pageIndex; + if (nextWordIndex >= currentWords.length) { + nextWordIndex = 0; + nextLineIndex += 1; + } + if (nextLineIndex >= currentLines.length) { + nextLineIndex = 0; + nextPageIndex += 1; + } + if (nextPageIndex >= parseResults.length) { + return [-1, -1, -1]; + } + return [nextPageIndex, nextLineIndex, nextWordIndex]; + }(); + var _ref3 = _slicedToArray(_ref2, 3); + pageIndex = _ref3[0]; + lineIndex = _ref3[1]; + wordIndex = _ref3[2]; + return { + value: value, + done: false + }; + }; + return { + next: next + }; +} +function iterateThroughParseResults(parseResults, fn) { + var iterator = wordIteratorFromParseResults(parseResults); + while (true) { + var _iterator$next = iterator.next(), + done = _iterator$next.done, + value = _iterator$next.value; + if (done) break; + var shouldContinue = fn(value); + if (!shouldContinue) break; + } +} +var getMatchedBlockInfo = function getMatchedBlockInfo(matchedLineWords) { + var matchedLineWordsCopy = _toConsumableArray(matchedLineWords); + var _matchedLineWordsCopy = _slicedToArray(matchedLineWordsCopy, 1), + firstWord = _matchedLineWordsCopy[0]; + var _matchedLineWordsCopy2 = matchedLineWordsCopy.reverse(), + _matchedLineWordsCopy3 = _slicedToArray(_matchedLineWordsCopy2, 1), + lastWord = _matchedLineWordsCopy3[0]; + var left = firstWord.Left; + var width = lastWord.Left + lastWord.Width - left; + var top, height; + matchedLineWordsCopy.reverse().forEach(function (_ref4) { + var Height = _ref4.Height, + Top = _ref4.Top; + if (top === undefined || top > Top) top = Top; + if (height === undefined || height < Height) height = Height; + }); + return { + BlockRect: { + Left: left, + Top: top, + Width: width, + Height: height + }, + BlockCenterPoint: [Math.round(left + width / 2), Math.round(top + height / 2)] + }; +}; +function getOcrPositionedWordsFromParseResults(parseResults, searchText) { + var searchWords = searchText.toLowerCase().split(/\s+/).filter(function (word) { + return word !== ""; + }); -/** - * Gets the bitmask value for the "alt" modifier. - * - * @return {number} - */ + // Perform a deep copy of the data to ensure that the original + // data is used for each search operation + // const cachedDataDeepCopy = JSON.parse(JSON.stringify(cachedData)); + // const { TextOverlay } = cachedDataDeepCopy[0]; + // const { Lines } = TextOverlay; + + var TextOverlay = parseResults[0].TextOverlay; + var Lines = TextOverlay.Lines; + console.log('TextOverlay:>> ', TextOverlay); + console.log('Lines:>> ', Lines); + var searchResult = []; + if (searchWords.length !== 0) { + for (var i = 0; i < Lines.length; i++) { + var lineWords = Lines[i].Words; + var currentMatch = []; + for (var j = 0; j < lineWords.length; j++) { + var word = lineWords[j]; + var wordText = word.WordText.toLowerCase().replace(/[,\.\"]/g, ""); + var currentSearchWordIndex = currentMatch.length; + var currentSearchWord = searchWords[currentSearchWordIndex]; + if (currentSearchWord.indexOf("?") > -1 || currentSearchWord.indexOf("*") > -1) { + // Regular expression matching based on wildcard characters such as ? and * + + var searchPattern = currentSearchWord.replace(/\?/g, ".").replace(/\*/g, ".*?"); + var regexp = new RegExp("^".concat(searchPattern, "$")); + if (regexp.test(wordText)) { + currentMatch.push(word); + } else { + currentMatch = []; + } + } else { + // Matching based on text comparison method. + if (wordText === currentSearchWord) { + currentMatch.push(word); + } else { + currentMatch = []; + } + } -/** - * Gets the bitmask value for the "shift" modifier. - * - * @return {number} - */ -; + // When a set of information is matched, push it into searchResult, clear + // currentMatch, and prepare to start matching the next set of information. + if (currentMatch.length === searchWords.length) { + var _getMatchedBlockInfo = getMatchedBlockInfo(currentMatch), + BlockRect = _getMatchedBlockInfo.BlockRect, + BlockCenterPoint = _getMatchedBlockInfo.BlockCenterPoint; + + // Since searchText could be either text or a regular expression, concatenation + // should be based on the actual matched content rather than searchText + var matchedBlockText = currentMatch.map(function (_ref5) { + var WordText = _ref5.WordText; + return WordText; + }).join(" "); + searchResult.push({ + Block: _objectSpread({ + Text: matchedBlockText + }, BlockRect), + BlockCenterPoint: BlockCenterPoint, + Words: currentMatch + }); + currentMatch = []; + } + } + } + } + var SearchResult = { + MatchesFound: searchResult.length, + Matches: searchResult + }; + console.log('SearchResult:>> ', SearchResult); + var convertSearchResultToFound = function convertSearchResultToFound(searchResult) { + var found = []; + searchResult.Matches.forEach(function (match) { + var foundItem = []; + match.Words.forEach(function (word) { + foundItem.push({ + word: word, + position: { + pageIndex: word.pageIndex, + lineIndex: word.lineIndex, + wordIndex: word.wordIndex + } + }); + }); + found.push(foundItem); + }); + return found; + }; + var found = convertSearchResultToFound(SearchResult); + return found; +} +function searchTextInOCRResponse(data) { + var text = data.text, + index = data.index, + parsedResults = data.parsedResults, + exhaust = data.exhaust; + console.log('searchTextInOCRResponse data:>> ', data); + var isExactMatch = /^\[.*\]$/.test(text); + var realText = isExactMatch ? text.slice(1, -1) : text; + var words = realText.split(/\s+/g).map(function (s) { + return s.trim(); + }).filter(function (s) { + return s.length > 0; + }); + if (index < 0 || Math.round(index) !== index) { + throw new Error('index must be positive integer'); + } + var found = []; + + // iterateThroughParseResults(parsedResults, (wordWithPos: OcrPositionedWord) => { + // const matchType = (() => { + // if (isExactMatch) return WordMatchType.Full + // if (words.length === 1) return WordMatchType.AnyPart + // if (wordIndex === 0) return WordMatchType.Postfix + // if (wordIndex === words.length - 1) return WordMatchType.Prefix + // return WordMatchType.Full + // })() + + // if (!hasWordMatch(words[wordIndex], wordWithPos.word.WordText, matchType)) { + // found[matchIndex] = [] + // wordIndex = 0 + // return true + // } + + // found[matchIndex] = found[matchIndex] || [] + // found[matchIndex].push(wordWithPos) + // wordIndex += 1 + + // // Whether it's the last word + // if (wordIndex >= words.length) { + // matchIndex += 1 + // wordIndex = 0 + + // const shouldContinue = exhaust || matchIndex <= index + // return shouldContinue + // } + + // return true + // }) + + found = getOcrPositionedWordsFromParseResults(parsedResults, text); + console.log('found:>> ', found); + var all = found.filter(function (pWords) { + return pWords.length === words.length; + }).map(function (pWords) { + return { + words: pWords, + // Note: similarity is useless in current implementation + similarity: 1 + }; + }); + var hit = all[index] || null; + return { + hit: hit, + all: all, + exhaust: exhaust + }; +} +function isWordEqual(a, b) { + if (!a || !b) return false; + return a.trim().toLowerCase() === b.trim().toLowerCase(); +} +var WordMatchType = exports.WordMatchType = /*#__PURE__*/function (WordMatchType) { + WordMatchType[WordMatchType["Full"] = 0] = "Full"; + WordMatchType[WordMatchType["Prefix"] = 1] = "Prefix"; + WordMatchType[WordMatchType["Postfix"] = 2] = "Postfix"; + WordMatchType[WordMatchType["AnyPart"] = 3] = "AnyPart"; + return WordMatchType; +}({}); +function wildcardToRegExp(pattern) { + // Escape special characters in the pattern + var escapedPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + + // Replace wildcard characters with their regex equivalents + var regexPattern = escapedPattern.replace(/\\\*/g, '.*') // Replace \* with .* + .replace(/\\\?/g, '.'); // Replace \? with . + + // Create RegExp object with the pattern and global flag + return new RegExp('^' + regexPattern + '$'); +} + +// Example usage: +// console.log(matchWithWildcard('hello', 'he*')); // true +// console.log(matchWithWildcard('hello', 'h?llo')); // true +// console.log(matchWithWildcard('hello', 'he??o')); // true +// console.log(matchWithWildcard('hello', 'hi*')); // false +function matchWithWildcard(string, pattern) { + var regex = wildcardToRegExp(pattern); + return regex.test(string); +} +function hasWordMatch(pattern, target, matchType) { + if (!pattern || !target) return false; + var lowerPattern = pattern.trim().toLowerCase(); + var lowerTarget = target.trim().toLowerCase(); + switch (matchType) { + case WordMatchType.Full: + { + return lowerPattern === lowerTarget; + } + case WordMatchType.Prefix: + { + return lowerTarget.indexOf(lowerPattern) === 0; + } + case WordMatchType.Postfix: + { + var index = lowerTarget.indexOf(lowerPattern); + return index !== -1 && index === lowerTarget.length - lowerPattern.length; + } + case WordMatchType.AnyPart: + { + var wMatch = matchWithWildcard(lowerTarget, lowerPattern); + console.log('wMatch:>> ', wMatch); + return wMatch; + } + } +} +function isWordPositionEqual(a, b) { + return a.pageIndex === b.pageIndex && a.lineIndex === b.lineIndex && a.wordIndex === b.wordIndex; +} +function allWordsWithPosition(parseResults, excludePositions) { + var result = []; + var isAtKnownPosition = function isAtKnownPosition(wordWithPos) { + return excludePositions.reduce(function (prev, pos) { + if (prev) return true; + return isWordPositionEqual(pos, wordWithPos.position); + }, false); + }; -/** - * Simulates a keyboard with a particular key-to-character and key-to-action - * mapping. Use `US_ENGLISH` to get a pre-configured keyboard. - */ + // TODO: consider using getOcrPositionedWordsFromParseResults instead of iterateThroughParseResults + iterateThroughParseResults(parseResults, function (wordWithPos) { + if (!isAtKnownPosition(wordWithPos)) { + result.push(wordWithPos); + } + return true; + }); + return result; +} +function ocrMatchRect(match) { + var rectsByLine = match.words.reduce(function (prev, cur) { + var key = "".concat(cur.position.pageIndex, "_").concat(cur.position.lineIndex); + if (!prev[key]) { + prev[key] = { + x: cur.word.Left, + y: cur.word.Top, + width: cur.word.Width, + height: cur.word.Height + }; + } else { + prev[key] = _objectSpread(_objectSpread({}, prev[key]), {}, { + width: Math.max(prev[key].width, cur.word.Left + cur.word.Width - prev[key].x), + height: Math.max(prev[key].height, cur.word.Top + cur.word.Height - prev[key].y) + }); + } + return prev; + }, {}); + var widestRect = Object.keys(rectsByLine).reduce(function (prev, key) { + return prev.width < rectsByLine[key].width ? rectsByLine[key] : prev; + }, { + x: 0, + y: 0, + width: 0, + height: 0 + }); + return widestRect; +} +function ocrMatchCenter(match) { + var rect = ocrMatchRect(match); + return { + x: rect.x + rect.width / 2, + y: rect.y + rect.height / 2, + width: rect.width, + height: rect.height + }; +} +function scaleOcrParseResultWord(word, scale) { + return _objectSpread(_objectSpread({}, word), {}, { + Width: scale * word.Width, + Height: scale * word.Height, + Left: scale * word.Left, + Top: scale * word.Top + }); +} +// export function scaleOcrParseResultWord (word: OcrParseResultWord, scale: number): OcrParseResultWord { const scaledWord = { +// ...word, +// Width: scale * word.Width, +// Height: scale * word.Height, +// Left: scale * word.Left, +// Top: scale * word.Top +// }; -Keystroke.CTRL = CTRL; -Keystroke.META = META; -Keystroke.ALT = ALT; -Keystroke.SHIFT = SHIFT; +// // Adjust positions based on scaling factor +// scaledWord.Left /= scale; +// scaledWord.Top /= scale; -var Keyboard = exports.Keyboard = function () { - /** - * @param {Object.} charCodeKeyCodeMap - * @param {Object.} actionKeyCodeMap - */ - function Keyboard(charCodeKeyCodeMap, actionKeyCodeMap) { - (0, _classCallCheck3.default)(this, Keyboard); +// return scaledWord; +// } - this._charCodeKeyCodeMap = charCodeKeyCodeMap; - this._actionKeyCodeMap = actionKeyCodeMap; - } +function scaleOcrResponseCoordinates(res, scale) { + var data = (0, _ts_utils.safeUpdateIn)(['ParsedResults', '[]', 'TextOverlay', 'Lines', '[]', 'Words', '[]'], function (word) { + return scaleOcrParseResultWord(word, scale); + }, res); + return data; +} +function scaleOcrTextSearchMatch(match, scale) { + var data = (0, _ts_utils.safeUpdateIn)(['words', '[]', 'word'], function (word) { + return scaleOcrParseResultWord(word, scale); + }, match); + return data; +} - /** - * Determines the character code generated by pressing the given keystroke. - * - * @param {Keystroke} keystroke - * @return {?number} - */ +/***/ }), +/***/ 64013: +/***/ ((__unused_webpack_module, exports) => { - (0, _createClass3.default)(Keyboard, [{ - key: 'charCodeForKeystroke', - value: function charCodeForKeystroke(keystroke) { - var map = this._charCodeKeyCodeMap; - for (var charCode in map) { - if (Object.prototype.hasOwnProperty.call(map, charCode)) { - var keystrokeForCharCode = map[charCode]; - if (keystroke.keyCode === keystrokeForCharCode.keyCode && keystroke.modifiers === keystrokeForCharCode.modifiers) { - return parseInt(charCode, 10); - } - } - } - return null; - } +"use strict"; - /** - * Creates an event ready for dispatching onto the given target. - * - * @param {string} type One of "keydown", "keypress", "keyup", "textInput" or "input". - * @param {Keystroke} keystroke - * @param {HTMLElement} target - * @return {Event} - */ - }, { - key: 'createEventFromKeystroke', - value: function createEventFromKeystroke(type, keystroke, target) { - var document = target.ownerDocument; - var window = document.defaultView; - var Event = window.Event; - - var event = void 0; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.convertOcrLanguageToTesseractLanguage = convertOcrLanguageToTesseractLanguage; +exports.isValidOCRLanguage = isValidOCRLanguage; +exports.tesseractLanguages = exports.tesseractLanguageOptions = exports.ocrLanguages = exports.ocrLanguageOptions = void 0; +var ocr_languages = { + ara: { + "lang": "ara", + "name": "Arabic", + "short": "AR" + }, + chs: { + "lang": "chs", + "name": "ChineseSimplified", + "short": "简" + }, + cht: { + "lang": "cht", + "name": "ChineseTraditional", + "short": "繁" + }, + ce: { + "lang": "ce", + "name": "Czech", + "short": "CS" + }, + dan: { + "lang": "dan", + "name": "Danish", + "short": "DA" + }, + dut: { + "lang": "dut", + "name": "Dutch", + "short": "NL" + }, + eng: { + "lang": "eng", + "name": "English", + "short": "EN" + }, + fin: { + "lang": "fin", + "name": "Finnish", + "short": "FI" + }, + fre: { + "lang": "fre", + "name": "French", + "short": "FR" + }, + ger: { + "lang": "ger", + "name": "German", + "short": "DE" + }, + gre: { + "lang": "gre", + "name": "Greek", + "short": "EL" + }, + hun: { + "lang": "hun", + "name": "Hungarian", + "short": "HU" + }, + ita: { + "lang": "ita", + "name": "Italian", + "short": "IT" + }, + jpn: { + "lang": "jpn", + "name": "Japanese", + "short": "JP" + }, + kor: { + "lang": "kor", + "name": "Korean", + "short": "KO" + }, + nor: { + "lang": "nor", + "name": "Norwegian", + "short": "NN" + }, + pol: { + "lang": "pol", + "name": "Polish", + "short": "PL" + }, + por: { + "lang": "por", + "name": "Portuguese", + "short": "PT" + }, + rus: { + "lang": "rus", + "name": "Russian", + "short": "RU" + }, + spa: { + "lang": "spa", + "name": "Spanish", + "short": "ES" + }, + swe: { + "lang": "swe", + "name": "Swedish", + "short": "SV" + }, + tur: { + "lang": "tur", + "name": "Turkish", + "short": "TR" + } +}; - try { - event = new Event(type); - } catch (e) { - event = document.createEvent('UIEvents'); - } +// tesseract languages reflecting ocr_languages +var tesseract_languages = { + ara: { + "lang": "ara", + "name": "Arabic", + "short": "AR" + }, + chi_sim: { + "lang": "chi_sim", + "name": "ChineseSimplified", + "short": "简" + }, + chi_tra: { + "lang": "chi_tra", + "name": "ChineseTraditional", + "short": "繁" + }, + ces: { + "lang": "ces", + "name": "Czech", + "short": "CS" + }, + dan: { + "lang": "dan", + "name": "Danish", + "short": "DA" + }, + nld: { + "lang": "nld", + "name": "Dutch", + "short": "NL" + }, + eng: { + "lang": "eng", + "name": "English", + "short": "EN" + }, + fin: { + "lang": "fin", + "name": "Finnish", + "short": "FI" + }, + fra: { + "lang": "fra", + "name": "French", + "short": "FR" + }, + deu: { + "lang": "deu", + "name": "German", + "short": "DE" + }, + ell: { + "lang": "ell", + "name": "Greek", + "short": "EL" + }, + hun: { + "lang": "hun", + "name": "Hungarian", + "short": "HU" + }, + ita: { + "lang": "ita", + "name": "Italian", + "short": "IT" + }, + jpn: { + "lang": "jpn", + "name": "Japanese", + "short": "JP" + }, + kor: { + "lang": "kor", + "name": "Korean", + "short": "KO" + }, + nor: { + "lang": "nor", + "name": "Norwegian", + "short": "NN" + }, + pol: { + "lang": "pol", + "name": "Polish", + "short": "PL" + }, + por: { + "lang": "por", + "name": "Portuguese", + "short": "PT" + }, + rus: { + "lang": "rus", + "name": "Russian", + "short": "RU" + }, + spa: { + "lang": "spa", + "name": "Spanish", + "short": "ES" + }, + swe: { + "lang": "swe", + "name": "Swedish", + "short": "SV" + }, + tur: { + "lang": "tur", + "name": "Turkish", + "short": "TR" + } +}; +var ocrLanguages = exports.ocrLanguages = ocr_languages; +var ocrLanguageOptions = exports.ocrLanguageOptions = function () { + var list = Object.keys(ocrLanguages).map(function (key) { + return { + text: ocrLanguages[key].name, + value: ocrLanguages[key].lang + }; + }); + list.sort(function (a, b) { + if (a.text < b.text) return -1; + if (a.text > b.text) return 1; + return 0; + }); + return list; +}(); +var tesseractLanguages = exports.tesseractLanguages = tesseract_languages; +var tesseractLanguageOptions = exports.tesseractLanguageOptions = function () { + var list = Object.keys(tesseractLanguages).map(function (key) { + return { + text: tesseractLanguages[key].name, + value: tesseractLanguages[key].lang + }; + }); + list.sort(function (a, b) { + if (a.text < b.text) return -1; + if (a.text > b.text) return 1; + return 0; + }); + return list; +}(); - event.initEvent(type, true, true); +/** + * + * @param ocrLang + * @returns + * @throws Error if the language is not found + * @example + * convertOcrLanguageToTesseractLanguage('ger') // 'deu' + * convertOcrLanguageToTesseractLanguage('chs') // 'chi_sim' + * convertOcrLanguageToTesseractLanguage('cht') // 'chi_tra' + * convertOcrLanguageToTesseractLanguage('eng') // 'eng' + */ +function convertOcrLanguageToTesseractLanguage(ocrLang) { + // if there's an entry in tesseract_languages with the key, just return it + var tesseractLangObj = tesseract_languages[ocrLang]; + if (tesseractLangObj) { + return tesseractLangObj.lang; + } + var ocrLangObj = ocr_languages[ocrLang]; + if (!ocrLangObj) { + throw new Error("E502: JavaScript OCR encountered a problem"); + } else { + // find language by name + var languageName = ocrLangObj.name; + var found = Object.keys(tesseract_languages).filter(function (res) { + var _ref; + return ((_ref = tesseract_languages[res]) === null || _ref === void 0 || (_ref = _ref.name) === null || _ref === void 0 ? void 0 : _ref.toLowerCase()) === languageName.toLowerCase(); + }); + if (found.length > 0) { + var tesseractLang = tesseract_languages[found[0]].lang; + return tesseractLang; + } else { + throw new Error("Tesseract language not found for ".concat(ocrLang)); + } + } +} +function isValidOCRLanguage(lang, store) { + var ocrEngine = store.getState().config.ocrEngine; + var ocrLanguageOption = store.getState().config.ocrLanguageOption; + if (ocrEngine == 99) { + var found = ocrLanguageOption.filter(function (res) { + return res.value.toLowerCase() === lang.toLowerCase(); + }); + return typeof lang === 'string' && !!(found.length > 0); + } else if (ocrEngine == 98) { + var tesseractLangAr = tesseractLanguageOptions.map(function (item) { + return { + text: item.text, + value: item.value + }; + }); + var _found = tesseractLangAr.filter(function (res) { + return res.value.toLowerCase() === lang.toLowerCase(); + }); + return typeof lang === 'string' && !!(_found.length > 0); + } else { + return typeof lang === 'string' && !!ocr_languages[lang.toLowerCase()]; + } +} - switch (type) { - case 'textInput': - event.data = String.fromCharCode(this.charCodeForKeystroke(keystroke)); - break; +/***/ }), - case 'keydown': - case 'keypress': - case 'keyup': - event.shiftKey = keystroke.shiftKey; - event.altKey = keystroke.altKey; - event.metaKey = keystroke.metaKey; - event.ctrlKey = keystroke.ctrlKey; - event.keyCode = type === 'keypress' ? this.charCodeForKeystroke(keystroke) : keystroke.keyCode; - event.charCode = type === 'keypress' ? event.keyCode : 0; - event.which = event.keyCode; - break; - } +/***/ 67802: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - return event; - } +"use strict"; - /** - * Fires the correct sequence of events on the given target as if the given - * action was undertaken by a human. - * - * @param {string} action e.g. "alt+shift+left" or "backspace" - * @param {HTMLElement} target - */ - }, { - key: 'dispatchEventsForAction', - value: function dispatchEventsForAction(action, target) { - var keystroke = this.keystrokeForAction(action); - this.dispatchEventsForKeystroke(keystroke, target); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _tesseract = __webpack_require__(34995); +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +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), !0).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; } +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 _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 _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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +var TesseractWrapper = /*#__PURE__*/function () { + function TesseractWrapper() { + _classCallCheck(this, TesseractWrapper); + // logger + _defineProperty(this, "log", function (log, isNetwork) { + console.log('Tesseract Logger:', { + timestamp: +new Date(), + log: log + }); + console.log('Tesseract Logger:', "isNetwork: ".concat(isNetwork)); + }); + this.workers = {}; + } + _createClass(TesseractWrapper, [{ + key: "setLogger", + value: function setLogger(logger) { + this.log = logger; } - - /** - * Fires the correct sequence of events on the given target as if the given - * input had been typed by a human. - * - * @param {string} input - * @param {HTMLElement} target - */ - }, { - key: 'dispatchEventsForInput', - value: function dispatchEventsForInput(input, target) { - var currentModifierState = 0; - for (var i = 0, length = input.length; i < length; i++) { - var keystroke = this.keystrokeForCharCode(input.charCodeAt(i)); - if (!keystroke) continue; - - this.dispatchModifierStateTransition(target, currentModifierState, keystroke.modifiers); - this.dispatchEventsForKeystroke(keystroke, target, false); - currentModifierState = keystroke.modifiers; + key: "getWorker", + value: function () { + var _getWorker = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(language) { + var _this = this; + var tesseractWorkerConfig, languageFileName, url; + return _regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + tesseractWorkerConfig = { + workerBlobURL: false, + workerPath: './lib/tesseract/worker.min.js', + corePath: './lib/tesseract/core' + }; + console.log('language:>>', language); + languageFileName = "".concat(language, ".traineddata.gz"); + url = chrome.runtime.getURL("./lib/tesseract/lang/".concat(languageFileName)); + console.log('lang file url:>>', url); + // see if file existx + return _context2.abrupt("return", fetch(url).then(function (response) { + console.log("lang file ".concat(languageFileName, " exists:>>")); + return true; + })["catch"](function (error) { + console.log("lang file ".concat(languageFileName, " doesn't exist:>>")); + return false; + }).then( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(langFileExists) { + var initConfig, _initConfig; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(!_this.workers[language] && langFileExists)) { + _context.next = 7; + break; + } + // Use local language pack + initConfig = _objectSpread(_objectSpread({}, tesseractWorkerConfig), {}, { + langPath: './lib/tesseract/lang', + logger: function logger(log) { + _this.log(log, false); + } + }); + _context.next = 4; + return (0, _tesseract.createWorker)(language, 1, initConfig); + case 4: + _this.workers[language] = _context.sent; + _context.next = 12; + break; + case 7: + if (_this.workers[language]) { + _context.next = 12; + break; + } + // Use network for other languages + _initConfig = _objectSpread(_objectSpread({}, tesseractWorkerConfig), {}, { + logger: function logger(log) { + _this.log(log, true); + } + }); + _context.next = 11; + return (0, _tesseract.createWorker)(language, 1, _initConfig); + case 11: + _this.workers[language] = _context.sent; + case 12: + return _context.abrupt("return", _this.workers[language]); + case 13: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x2) { + return _ref.apply(this, arguments); + }; + }())); + case 6: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + function getWorker(_x) { + return _getWorker.apply(this, arguments); } - this.dispatchModifierStateTransition(target, currentModifierState, 0); + return getWorker; + }() + }, { + key: "transferToOCRSpaceFormat", + value: function transferToOCRSpaceFormat() { + var lines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var ParsedText = arguments.length > 1 ? arguments[1] : undefined; + var Lines = lines.map(function (_ref2) { + var LineText = _ref2.text, + _ref2$words = _ref2.words, + words = _ref2$words === void 0 ? [] : _ref2$words; + var MaxHeight, MinTop; + return { + LineText: LineText, + Words: words.map(function (_ref3) { + var WordText = _ref3.text, + _ref3$bbox = _ref3.bbox, + bbox = _ref3$bbox === void 0 ? {} : _ref3$bbox; + var x0 = bbox.x0, + y0 = bbox.y0, + x1 = bbox.x1, + y1 = bbox.y1; + var Width = x1 - x0; + var Height = y1 - y0; + if (MaxHeight === undefined || Height > MaxHeight) { + MaxHeight = Height; + } + if (MinTop === undefined || y0 < MinTop) { + MinTop = y0; + } + return { + WordText: WordText, + Left: x0, + Top: y0, + Height: Height, + Width: Width + }; + }), + MaxHeight: MaxHeight, + MinTop: MinTop + }; + }); + return [{ + TextOverlay: { + Lines: Lines, + HasOverlay: true, + Message: "Total lines: ".concat(lines.length) + }, + TextOrientation: "0", + FileParseExitCode: 1, + ParsedText: ParsedText, + ErrorMessage: "", + ErrorDetails: "" + }]; } + }, { + key: "start", + value: function () { + var _start = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(input, language) { + var startTime, worker, _ref4, data, resultData, processingTimeInMilliseconds; + return _regeneratorRuntime().wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + startTime = performance.now(); + _context3.prev = 1; + _context3.next = 4; + return this.getWorker(language); + case 4: + worker = _context3.sent; + _context3.next = 7; + return worker.reinitialize(language); + case 7: + _context3.next = 9; + return worker.recognize(input); + case 9: + _ref4 = _context3.sent; + data = _ref4.data; + console.log('Tesseract raw data:', data); + resultData = this.transferToOCRSpaceFormat(data.lines, data.text); // Calculate the processing time of Tesseract + processingTimeInMilliseconds = performance.now() - startTime; + return _context3.abrupt("return", { + resultData: resultData, + processingTimeInMilliseconds: processingTimeInMilliseconds + }); + case 17: + _context3.prev = 17; + _context3.t0 = _context3["catch"](1); + throw new Error(_context3.t0); + case 20: + case "end": + return _context3.stop(); + } + }, _callee3, this, [[1, 17]]); + })); + function start(_x3, _x4) { + return _start.apply(this, arguments); + } + return start; + }() + }], [{ + key: "getInstance", + value: function () { + var _getInstance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { + return _regeneratorRuntime().wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!this.instance) { + this.instance = new TesseractWrapper(); + } + return _context4.abrupt("return", this.instance); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function getInstance() { + return _getInstance.apply(this, arguments); + } + return getInstance; + }() + }]); + return TesseractWrapper; +}(); +var _default = exports["default"] = TesseractWrapper; - /** - * Fires the correct sequence of events on the given target as if the given - * keystroke was performed by a human. When simulating, for example, typing - * the letter "A" (assuming a U.S. English keyboard) then the sequence will - * look like this: - * - * keydown keyCode=16 (SHIFT) charCode=0 shiftKey=true - * keydown keyCode=65 (A) charCode=0 shiftKey=true - * keypress keyCode=65 (A) charCode=65 (A) shiftKey=true - * textInput data=A - * input - * keyup keyCode=65 (A) charCode=0 shiftKey=true - * keyup keyCode=16 (SHIFT) charCode=0 shiftKey=false - * - * If the keystroke would not cause a character to be input, such as when - * pressing alt+shift+left, the sequence looks like this: - * - * keydown keyCode=16 (SHIFT) charCode=0 altKey=false shiftKey=true - * keydown keyCode=18 (ALT) charCode=0 altKey=true shiftKey=true - * keydown keyCode=37 (LEFT) charCode=0 altKey=true shiftKey=true - * keyup keyCode=37 (LEFT) charCode=0 altKey=true shiftKey=true - * keyup keyCode=18 (ALT) charCode=0 altKey=false shiftKey=true - * keyup keyCode=16 (SHIFT) charCode=0 altKey=false shiftKey=false - * - * To disable handling of modifier keys, call with `transitionModifers` set - * to false. Doing so will omit the keydown and keyup events associated with - * shift, ctrl, alt, and meta keys surrounding the actual keystroke. - * - * @param {Keystroke} keystroke - * @param {HTMLElement} target - * @param {boolean=} transitionModifiers - * @param {number} events - */ +/***/ }), - }, { - key: 'dispatchEventsForKeystroke', - value: function dispatchEventsForKeystroke(keystroke, target) { - var transitionModifiers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; - var events = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : KeyEvents.ALL; +/***/ 35847: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - if (!keystroke) return; +"use strict"; - if (transitionModifiers) { - this.dispatchModifierStateTransition(target, 0, keystroke.modifiers, events); - } - var keydownEvent = void 0; - if (events & KeyEvents.DOWN) { - keydownEvent = this.createEventFromKeystroke('keydown', keystroke, target); - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.OCRExitCode = exports.FileParseExitCode = void 0; +Object.defineProperty(exports, "OCRLanguage", ({ + enumerable: true, + get: function get() { + return _languages.OCRLanguage; + } +})); +exports.OcrHighlightType = void 0; +var _languages = __webpack_require__(64013); +var OCRExitCode = exports.OCRExitCode = /*#__PURE__*/function (OCRExitCode) { + OCRExitCode[OCRExitCode["AllParsed"] = 1] = "AllParsed"; + OCRExitCode[OCRExitCode["PartiallyParsed"] = 2] = "PartiallyParsed"; + OCRExitCode[OCRExitCode["Failed"] = 3] = "Failed"; + OCRExitCode[OCRExitCode["Fatal"] = 4] = "Fatal"; + return OCRExitCode; +}({}); +var FileParseExitCode = exports.FileParseExitCode = /*#__PURE__*/function (FileParseExitCode) { + FileParseExitCode[FileParseExitCode["FileNotFound"] = 0] = "FileNotFound"; + FileParseExitCode[FileParseExitCode["Success"] = 1] = "Success"; + FileParseExitCode[FileParseExitCode["ParseError"] = -10] = "ParseError"; + FileParseExitCode[FileParseExitCode["Timeout"] = -20] = "Timeout"; + FileParseExitCode[FileParseExitCode["ValidationError"] = -30] = "ValidationError"; + FileParseExitCode[FileParseExitCode["UnknownError"] = -99] = "UnknownError"; + return FileParseExitCode; +}({}); +var OcrHighlightType = exports.OcrHighlightType = /*#__PURE__*/function (OcrHighlightType) { + OcrHighlightType[OcrHighlightType["Identified"] = 0] = "Identified"; + OcrHighlightType[OcrHighlightType["Matched"] = 1] = "Matched"; + OcrHighlightType[OcrHighlightType["TopMatched"] = 2] = "TopMatched"; + OcrHighlightType[OcrHighlightType["WildcardTopMatched"] = 3] = "WildcardTopMatched"; + OcrHighlightType[OcrHighlightType["WildcardMatched"] = 4] = "WildcardMatched"; + return OcrHighlightType; +}({}); - if (keydownEvent && target.dispatchEvent(keydownEvent) && this.targetCanReceiveTextInput(target)) { - var keypressEvent = void 0; - if (events & KeyEvents.PRESS) { - keypressEvent = this.createEventFromKeystroke('keypress', keystroke, target); - } - if (keypressEvent && keypressEvent.charCode && target.dispatchEvent(keypressEvent)) { - if (events & KeyEvents.INPUT) { - var textinputEvent = this.createEventFromKeystroke('textInput', keystroke, target); - target.dispatchEvent(textinputEvent); +/***/ }), - var inputEvent = this.createEventFromKeystroke('input', keystroke, target); - target.dispatchEvent(inputEvent); - } - } - } +/***/ 41279: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - if (events & KeyEvents.UP) { - var keyupEvent = this.createEventFromKeystroke('keyup', keystroke, target); - target.dispatchEvent(keyupEvent); - } +"use strict"; - if (transitionModifiers) { - this.dispatchModifierStateTransition(target, keystroke.modifiers, 0); - } - } - /** - * Transitions from one modifier state to another by dispatching key events. - * - * @param {EventTarget} target - * @param {number} fromModifierState - * @param {number} toModifierState - * @param {number} events - * @private - */ - - }, { - key: 'dispatchModifierStateTransition', - value: function dispatchModifierStateTransition(target, fromModifierState, toModifierState) { - var events = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : KeyEvents.ALL; - - var currentModifierState = fromModifierState; - var didHaveMeta = (fromModifierState & META) === META; - var willHaveMeta = (toModifierState & META) === META; - var didHaveCtrl = (fromModifierState & CTRL) === CTRL; - var willHaveCtrl = (toModifierState & CTRL) === CTRL; - var didHaveShift = (fromModifierState & SHIFT) === SHIFT; - var willHaveShift = (toModifierState & SHIFT) === SHIFT; - var didHaveAlt = (fromModifierState & ALT) === ALT; - var willHaveAlt = (toModifierState & ALT) === ALT; - - var includeKeyUp = events & KeyEvents.UP; - var includeKeyDown = events & KeyEvents.DOWN; - - if (includeKeyUp && didHaveMeta === true && willHaveMeta === false) { - // Release the meta key. - currentModifierState &= ~META; - target.dispatchEvent(this.createEventFromKeystroke('keyup', new Keystroke(currentModifierState, this._actionKeyCodeMap.META), target)); - } - - if (includeKeyUp && didHaveCtrl === true && willHaveCtrl === false) { - // Release the ctrl key. - currentModifierState &= ~CTRL; - target.dispatchEvent(this.createEventFromKeystroke('keyup', new Keystroke(currentModifierState, this._actionKeyCodeMap.CTRL), target)); - } - - if (includeKeyUp && didHaveShift === true && willHaveShift === false) { - // Release the shift key. - currentModifierState &= ~SHIFT; - target.dispatchEvent(this.createEventFromKeystroke('keyup', new Keystroke(currentModifierState, this._actionKeyCodeMap.SHIFT), target)); - } - - if (includeKeyUp && didHaveAlt === true && willHaveAlt === false) { - // Release the alt key. - currentModifierState &= ~ALT; - target.dispatchEvent(this.createEventFromKeystroke('keyup', new Keystroke(currentModifierState, this._actionKeyCodeMap.ALT), target)); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.polyfillTimeoutFunctions = polyfillTimeoutFunctions; +var _log = _interopRequireDefault(__webpack_require__(89130)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +var oldSetTimeout = window.setTimeout; +var oldClearTimeout = window.clearTimeout; +var oldSetInterval = window.setInterval; +var oldClearInterval = window.clearInterval; +function uid() { + return Math.floor(Math.random() * 1e8); +} +function polyfillTimeoutFunctions(csIpc) { + var timeoutRecords = {}; + function createSetTimeoutViaBackground(identity) { + var id = identity !== null && identity !== void 0 ? identity : uid(); + return function setTimeoutViaBackground(fn) { + var timeout = 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]; } + timeoutRecords[id] = true; + csIpc.ask('TIMEOUT', { + id: id, + timeout: timeout + }).then(function (identity) { + if (!timeoutRecords[identity]) { + return; + } + fn.apply(void 0, args); + })["catch"](function (e) { + _log["default"].error('Error in setTimeout', e.stack); + }); + return id; + }; + } + function clearTimeoutViaBackground(id) { + delete timeoutRecords[id]; + } - if (includeKeyDown && didHaveMeta === false && willHaveMeta === true) { - // Press the meta key. - currentModifierState |= META; - target.dispatchEvent(this.createEventFromKeystroke('keydown', new Keystroke(currentModifierState, this._actionKeyCodeMap.META), target)); + // Call both native setTimeout and setTimeoutViaBackground + // and take the first one resolved + function smartSetTimeout(fn) { + var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var done = false; + var wrappedFn = function wrappedFn() { + if (done) { + return null; } - - if (includeKeyDown && didHaveCtrl === false && willHaveCtrl === true) { - // Press the ctrl key. - currentModifierState |= CTRL; - target.dispatchEvent(this.createEventFromKeystroke('keydown', new Keystroke(currentModifierState, this._actionKeyCodeMap.CTRL), target)); + done = true; + return fn.apply(void 0, arguments); + }; + for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { + args[_key2 - 2] = arguments[_key2]; + } + var id = oldSetTimeout.apply(void 0, [wrappedFn, timeout].concat(args)); + createSetTimeoutViaBackground(id).apply(void 0, [wrappedFn, timeout].concat(args)); + return id; + } + var intervalRecords = {}; + function smartSetInterval(fn) { + var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + for (var _len3 = arguments.length, args = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { + args[_key3 - 2] = arguments[_key3]; + } + var id = uid(); + var wrappedFn = function wrappedFn() { + if (!intervalRecords[id]) { + return; } + smartSetTimeout(wrappedFn, timeout); + fn.apply(void 0, args); + }; + intervalRecords[id] = true; + smartSetTimeout(wrappedFn, timeout); + return id; + } + function clearIntervalViaBackground(id) { + delete intervalRecords[id]; + } + var runBoth = function runBoth(f1, f2) { + return function () { + f1.apply(void 0, arguments); + f2.apply(void 0, arguments); + }; + }; + window.setTimeout = smartSetTimeout; + window.clearTimeout = runBoth(clearTimeoutViaBackground, oldClearTimeout); + window.setInterval = smartSetInterval; + window.clearInterval = clearIntervalViaBackground; +} - if (includeKeyDown && didHaveShift === false && willHaveShift === true) { - // Press the shift key. - currentModifierState |= SHIFT; - target.dispatchEvent(this.createEventFromKeystroke('keydown', new Keystroke(currentModifierState, this._actionKeyCodeMap.SHIFT), target)); - } +/***/ }), - if (includeKeyDown && didHaveAlt === false && willHaveAlt === true) { - // Press the alt key. - currentModifierState |= ALT; - target.dispatchEvent(this.createEventFromKeystroke('keydown', new Keystroke(currentModifierState, this._actionKeyCodeMap.ALT), target)); - } +/***/ 67203: +/***/ ((__unused_webpack_module, exports) => { - if (currentModifierState !== toModifierState) { - throw new Error('internal error, expected modifier state: ' + toModifierState + (', got: ' + currentModifierState)); - } - } +"use strict"; - /** - * Returns the keystroke associated with the given action. - * - * @param {string} action - * @return {?Keystroke} - */ - }, { - key: 'keystrokeForAction', - value: function keystrokeForAction(action) { - var keyCode = null; - var modifiers = 0; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ViewportRectService = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +var ViewportRectService = exports.ViewportRectService = /*#__PURE__*/function () { + function ViewportRectService(params) { + _classCallCheck(this, ViewportRectService); + this.params = params; + } + _createClass(ViewportRectService, [{ + key: "getViewportRectInScreen", + value: function getViewportRectInScreen() { + var _this = this; + return this.params.devicePixelRatioService.getDevicePixelRatioInfo().then(function (info) { + var _this$params$window; + var win = (_this$params$window = _this.params.window) !== null && _this$params$window !== void 0 ? _this$params$window : window; + var innerScreenX = window.mozInnerScreenX; + var innerScreenY = window.mozInnerScreenY; + var innerWidth = window.innerWidth * info.zoom; + var innerHeight = window.innerHeight * info.zoom; + + // Firefox has mozInnerScreenX/mozInnerScreenY tell the exact screen coordinates of viewport + if (typeof innerScreenX !== 'undefined') { + return { + x: innerScreenX, + y: innerScreenY, + width: innerWidth, + height: innerHeight + }; + } - // Note: when it comes to a single character as '+', - // should not take it as a key combiniation (no action.split) - var parts = action.length === 1 ? [action] : action.split('+'); - var lastPart = parts.pop(); + // For Chrome, it's tricker to get the screen coordinates as there are no properties like InnerScreenX, + // so have to derive it from window.screenLeft and border/toolbar width/height, assuming download bar is already + // hidden when this method is called, and dev tool is not opened - parts.forEach(function (part) { - switch (part.toUpperCase()) { - case 'CTRL': - modifiers |= CTRL; - break; - case 'META': - modifiers |= META; - break; - case 'ALT': - modifiers |= ALT; - break; - case 'SHIFT': - modifiers |= SHIFT; - break; - default: - console.error('parts', parts); - throw new Error('in "' + action + '", invalid modifier: ' + part); - } + // window.innerHeight is shrinked when you zoom in on page + var toolbarHeight = window.outerHeight - window.innerHeight * info.zoom; + // Window on Windows has a border, about 8px in width + var windowBorder = window.navigator.platform.match(/Win(.)*/ig) ? 8 : 0; + return { + x: win.screenLeft + windowBorder, + y: win.screenTop + toolbarHeight - windowBorder, + width: innerWidth, + height: innerHeight + }; }); + } + }]); + return ViewportRectService; +}(); - if (lastPart.toUpperCase() in this._actionKeyCodeMap) { - keyCode = this._actionKeyCodeMap[lastPart.toUpperCase()]; - } else if (lastPart.length === 1) { - var lastPartKeystroke = this.keystrokeForCharCode(lastPart.charCodeAt(0)); - if (!lastPartKeystroke) return null; +/***/ }), - modifiers |= lastPartKeystroke.modifiers; - keyCode = lastPartKeystroke.keyCode; - } else { - throw new Error('in "' + action + '", invalid action: ' + lastPart); - } +/***/ 97846: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - return new Keystroke(modifiers, keyCode); - } +"use strict"; - /** - * Gets the keystroke used to generate the given character code. - * - * @param {number} charCode - * @return {?Keystroke} - */ +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.XModuleTypes = exports.XModule = void 0; +var _storage = _interopRequireDefault(__webpack_require__(88555)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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), !0).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; } +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 _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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +var XModuleTypes = exports.XModuleTypes = /*#__PURE__*/function (XModuleTypes) { + XModuleTypes["XFile"] = "xFile"; + XModuleTypes["XLocal"] = "xLocal"; + XModuleTypes["XUserIO"] = "xClick"; + XModuleTypes["XDesktop"] = "xDesktop"; + XModuleTypes["XScreenCapture"] = "xScreenCapture"; + return XModuleTypes; +}({}); +var XModule = exports.XModule = /*#__PURE__*/function () { + function XModule() { + _classCallCheck(this, XModule); + _defineProperty(this, "cachedConfig", {}); + this.initConfig(); + } + _createClass(XModule, [{ + key: "getVersion", + value: function getVersion() { + var _this = this; + return this.getAPI().reconnect()["catch"](function (e) { + throw new Error("".concat(_this.getName(), " is not installed yet")); + }).then(function (api) { + return api.getVersion().then(function (version) { + return { + version: version, + installed: true + }; + }); + })["catch"](function (e) { + return { + installed: false + }; + }); + } }, { - key: 'keystrokeForCharCode', - value: function keystrokeForCharCode(charCode) { - return this._charCodeKeyCodeMap[charCode] || null; + key: "setConfig", + value: function setConfig(config) { + var _this2 = this; + this.cachedConfig = _objectSpread(_objectSpread({}, this.cachedConfig), config); + return this.getConfig().then(function (oldConfig) { + var nextConfig = _objectSpread(_objectSpread({}, oldConfig), config); + return _storage["default"].set(_this2.getStoreKey(), nextConfig).then(function (success) { + if (success) { + _this2.cachedConfig = nextConfig; + } + return success; + }); + }); } - - /** - * @param {EventTarget} target - * @private - */ - }, { - key: 'targetCanReceiveTextInput', - value: function targetCanReceiveTextInput(target) { - if (!target) { - return false; - } - - return (0, _domElementIsNativelyEditable2.default)(target); + key: "getConfig", + value: function getConfig() { + var _this3 = this; + return _storage["default"].get(this.getStoreKey()).then(function (data) { + _this3.cachedConfig = data || {}; + return _this3.cachedConfig; + }); + } + }, { + key: "getCachedConfig", + value: function getCachedConfig() { + return this.cachedConfig; + } + }, { + key: "getStoreKey", + value: function getStoreKey() { + return this.getName().toLowerCase(); } }]); - return Keyboard; + return XModule; }(); -var US_ENGLISH_CHARCODE_KEYCODE_MAP = { - 32: new Keystroke(0, 32), // - 33: new Keystroke(SHIFT, 49), // ! - 34: new Keystroke(SHIFT, 222), // " - 35: new Keystroke(SHIFT, 51), // # - 36: new Keystroke(SHIFT, 52), // $ - 37: new Keystroke(SHIFT, 53), // % - 38: new Keystroke(SHIFT, 55), // & - 39: new Keystroke(0, 222), // ' - 40: new Keystroke(SHIFT, 57), // ( - 41: new Keystroke(SHIFT, 48), // ) - 42: new Keystroke(SHIFT, 56), // * - 43: new Keystroke(SHIFT, 187), // + - 44: new Keystroke(0, 188), // , - 45: new Keystroke(0, 189), // - - 46: new Keystroke(0, 190), // . - 47: new Keystroke(0, 191), // / - 48: new Keystroke(0, 48), // 0 - 49: new Keystroke(0, 49), // 1 - 50: new Keystroke(0, 50), // 2 - 51: new Keystroke(0, 51), // 3 - 52: new Keystroke(0, 52), // 4 - 53: new Keystroke(0, 53), // 5 - 54: new Keystroke(0, 54), // 6 - 55: new Keystroke(0, 55), // 7 - 56: new Keystroke(0, 56), // 8 - 57: new Keystroke(0, 57), // 9 - 58: new Keystroke(SHIFT, 186), // : - 59: new Keystroke(0, 186), // ; - 60: new Keystroke(SHIFT, 188), // < - 61: new Keystroke(0, 187), // = - 62: new Keystroke(SHIFT, 190), // > - 63: new Keystroke(SHIFT, 191), // ? - 64: new Keystroke(SHIFT, 50), // @ - 65: new Keystroke(SHIFT, 65), // A - 66: new Keystroke(SHIFT, 66), // B - 67: new Keystroke(SHIFT, 67), // C - 68: new Keystroke(SHIFT, 68), // D - 69: new Keystroke(SHIFT, 69), // E - 70: new Keystroke(SHIFT, 70), // F - 71: new Keystroke(SHIFT, 71), // G - 72: new Keystroke(SHIFT, 72), // H - 73: new Keystroke(SHIFT, 73), // I - 74: new Keystroke(SHIFT, 74), // J - 75: new Keystroke(SHIFT, 75), // K - 76: new Keystroke(SHIFT, 76), // L - 77: new Keystroke(SHIFT, 77), // M - 78: new Keystroke(SHIFT, 78), // N - 79: new Keystroke(SHIFT, 79), // O - 80: new Keystroke(SHIFT, 80), // P - 81: new Keystroke(SHIFT, 81), // Q - 82: new Keystroke(SHIFT, 82), // R - 83: new Keystroke(SHIFT, 83), // S - 84: new Keystroke(SHIFT, 84), // T - 85: new Keystroke(SHIFT, 85), // U - 86: new Keystroke(SHIFT, 86), // V - 87: new Keystroke(SHIFT, 87), // W - 88: new Keystroke(SHIFT, 88), // X - 89: new Keystroke(SHIFT, 89), // Y - 90: new Keystroke(SHIFT, 90), // Z - 91: new Keystroke(0, 219), // [ - 92: new Keystroke(0, 220), // \ - 93: new Keystroke(0, 221), // ] - 94: new Keystroke(SHIFT, 54), // ^ - 95: new Keystroke(SHIFT, 189), // _ - 96: new Keystroke(0, 192), // ` - 97: new Keystroke(0, 65), // a - 98: new Keystroke(0, 66), // b - 99: new Keystroke(0, 67), // c - 100: new Keystroke(0, 68), // d - 101: new Keystroke(0, 69), // e - 102: new Keystroke(0, 70), // f - 103: new Keystroke(0, 71), // g - 104: new Keystroke(0, 72), // h - 105: new Keystroke(0, 73), // i - 106: new Keystroke(0, 74), // j - 107: new Keystroke(0, 75), // k - 108: new Keystroke(0, 76), // l - 109: new Keystroke(0, 77), // m - 110: new Keystroke(0, 78), // n - 111: new Keystroke(0, 79), // o - 112: new Keystroke(0, 80), // p - 113: new Keystroke(0, 81), // q - 114: new Keystroke(0, 82), // r - 115: new Keystroke(0, 83), // s - 116: new Keystroke(0, 84), // t - 117: new Keystroke(0, 85), // u - 118: new Keystroke(0, 86), // v - 119: new Keystroke(0, 87), // w - 120: new Keystroke(0, 88), // x - 121: new Keystroke(0, 89), // y - 122: new Keystroke(0, 90), // z - 123: new Keystroke(SHIFT, 219), // { - 124: new Keystroke(SHIFT, 220), // | - 125: new Keystroke(SHIFT, 221), // } - 126: new Keystroke(SHIFT, 192) // ~ -}; - -var US_ENGLISH_ACTION_KEYCODE_MAP = { - BACKSPACE: 8, - TAB: 9, - ENTER: 13, - SHIFT: 16, - CTRL: 17, - ALT: 18, - PAUSE: 19, - CAPSLOCK: 20, - ESCAPE: 27, - PAGEUP: 33, - PAGEDOWN: 34, - END: 35, - HOME: 36, - LEFT: 37, - UP: 38, - RIGHT: 39, - DOWN: 40, - INSERT: 45, - DELETE: 46, - META: 91, - F1: 112, - F2: 113, - F3: 114, - F4: 115, - F5: 116, - F6: 117, - F7: 118, - F8: 119, - F9: 120, - F10: 121, - F11: 122, - F12: 123 -}; - -/** - * Gets a keyboard instance configured as a U.S. English keyboard would be. - * - * @return {Keyboard} - */ -Keyboard.US_ENGLISH = new Keyboard(US_ENGLISH_CHARCODE_KEYCODE_MAP, US_ENGLISH_ACTION_KEYCODE_MAP); - /***/ }), -/***/ 75789: +/***/ 63109: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = sendKeys; - -var _keysim = __webpack_require__(3575); - -var Keysim = _interopRequireWildcard(_keysim); - -var _utils = __webpack_require__(63370); - -var _log = __webpack_require__(77242); - -var _log2 = _interopRequireDefault(_log); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -var keyboard = Keysim.Keyboard.US_ENGLISH; - -var findParentByTag = function findParentByTag(el, tag) { - var p = el; - - // eslint-disable-next-line no-cond-assign - while (p = p.parentNode) { - if (p.tagName === tag.toUpperCase()) { - return p; +exports.getXFile = exports.XFile = void 0; +var _common = __webpack_require__(97846); +var _filesystem = __webpack_require__(89937); +var _ts_utils = __webpack_require__(1601); +var _path = _interopRequireDefault(__webpack_require__(26513)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +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."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +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; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +var XFile = exports.XFile = /*#__PURE__*/function (_XModule) { + _inherits(XFile, _XModule); + function XFile() { + _classCallCheck(this, XFile); + return _callSuper(this, XFile, arguments); + } + _createClass(XFile, [{ + key: "getName", + value: function getName() { + return _common.XModuleTypes.XFile; } - } - - return null; -}; - -var splitStringToChars = function splitStringToChars(str) { - var specialKeys = ['KEY_LEFT', 'KEY_UP', 'KEY_RIGHT', 'KEY_DOWN', 'KEY_PGUP', 'KEY_PAGE_UP', 'KEY_PGDN', 'KEY_PAGE_DOWN', 'KEY_BKSP', 'KEY_BACKSPACE', 'KEY_DEL', 'KEY_DELETE', 'KEY_ENTER', 'KEY_TAB']; - var reg = new RegExp('\\$\\{(' + specialKeys.join('|') + ')\\}'); - var parts = (0, _utils.splitKeep)(reg, str); - - return parts.reduce(function (prev, cur) { - if (reg.test(cur)) { - prev.push(cur); - } else { - prev = prev.concat(cur.split('')); + }, { + key: "getAPI", + value: function getAPI() { + return (0, _filesystem.getNativeFileSystemAPI)(); } - - return prev; - }, []); -}; - -var getKeyStrokeAction = function getKeyStrokeAction(str) { - var reg = /^\$\{([^}]+)\}$/; - var match = void 0; - - // eslint-disable-next-line no-cond-assign - if (match = str.match(reg)) { - switch (match[1]) { - case 'KEY_LEFT': - return 'LEFT'; - - case 'KEY_UP': - return 'UP'; - - case 'KEY_RIGHT': - return 'RIGHT'; - - case 'KEY_DOWN': - return 'DOWN'; - - case 'KEY_PGUP': - case 'KEY_PAGE_UP': - return 'PAGEUP'; - - case 'KEY_PGDN': - case 'KEY_PAGE_DOWN': - return 'PAGEDOWN'; - - case 'KEY_BKSP': - case 'KEY_BACKSPACE': - return 'BACKSPACE'; - - case 'KEY_DEL': - case 'KEY_DELETE': - return 'DELETE'; - - case 'KEY_ENTER': - return 'ENTER'; - - case 'KEY_TAB': - return 'TAB'; + }, { + key: "getLangs", + value: function getLangs(osType) { + return this.getConfig().then(function (config) { + var _getXFile$getCachedCo = getXFile().getCachedConfig(), + rootDir = _getXFile$getCachedCo.rootDir; + var fsAPI = (0, _filesystem.getNativeFileSystemAPI)(); + return fsAPI.getSpecialFolderPath({ + folder: _filesystem.SpecialFolder.UserProfile + }).then(function (profilePath) { + var uivision = osType == "mac" ? '/Library/uivision-xmodules/2.2.2/xmodules/' : _path["default"].join(profilePath, "\\AppData\\Roaming\\UI.Vision\\XModules\\ocr"); + return fsAPI.ensureDir({ + path: uivision + }).then(function (Opath) { + var path = uivision; + var outputpath = rootDir; + var filepath = '', + Arguments = ''; + var ocrOutputJson = ''; + if (osType == "mac") { + filepath = path + '/ocr3'; + Arguments = " --in get-installed-lng --out " + outputpath + "/logs/ocrlang.json"; + ocrOutputJson = outputpath + "/logs/ocrlang.json"; + } else { + filepath = path + '\\ocrexe\\ocrcl1.exe'; + Arguments = "get-installed-lng " + outputpath + "\\logs\\ocrlang.json"; + ocrOutputJson = outputpath + "\\logs\\ocrlang.json"; + } + var params = { + fileName: filepath, + arguments: Arguments, + waitForExit: true + }; + return fsAPI.runProcess(params).then(function (res) { + if (res != undefined && res.exitCode != null && res.exitCode >= 0) { + var _params = { + path: ocrOutputJson, + waitForExit: true + }; + return fsAPI.readAllBytes(_params); + } else { + return; + } + }).then(function (json) { + if (json) { + if (json.errorCode == 0) { + console.log(json.content); + return json.content; + } else { + return false; + } + } + })["catch"](function () { + return console.log({ + result: false + }); + }); + }); + })["catch"](function (e) { + // Ignore host not found error, `initConfig` is supposed to be called on start + // But we can't guarantee that native fs module is already installed + if (!/Specified native messaging host not found/.test(e)) { + throw e; + } + }); + }); } - } - - return str; -}; - -var isEditable = function isEditable(el) { - if (el.getAttribute('readonly') !== null) return false; - var tag = el.tagName.toUpperCase(); - var type = (el.type || '').toLowerCase(); - var editableTypes = ['text', 'search', 'tel', 'url', 'email', 'password', 'number']; - - if (tag === 'TEXTAREA') return true; - if (tag === 'INPUT' && editableTypes.indexOf(type) !== -1) return true; - - return false; -}; - -var maybeEditText = function maybeEditText(target, c) { - if (!isEditable(target)) return; - if (c.length === 1) { - if (!isNil(target.selectionStart)) { - var lastStart = target.selectionStart; - target.value = target.value.substring(0, target.selectionStart) + c + target.value.substring(target.selectionEnd); - - setSelection(target, lastStart + 1); - } else { - target.value = target.value + c; + }, { + key: "initConfig", + value: function initConfig() { + var _this = this; + return this.getConfig().then(function (config) { + if (!config.rootDir) { + var fsAPI = (0, _filesystem.getNativeFileSystemAPI)(); + return fsAPI.getSpecialFolderPath({ + folder: _filesystem.SpecialFolder.UserDesktop + }).then(function (profilePath) { + var kantuDir = _path["default"].join(profilePath, 'uivision'); + return fsAPI.ensureDir({ + path: kantuDir + }).then(function (done) { + _this.setConfig({ + rootDir: done ? kantuDir : profilePath + }); + }); + })["catch"](function (e) { + // Ignore host not found error, `initConfig` is supposed to be called on start + // But we can't guarantee that native fs module is already installed + if (!/Specified native messaging host not found/.test(e)) { + throw e; + } + }); + } + }); } - } else { - switch (c) { - case 'ENTER': - target.value = target.value + '\n'; - setSelection(target, target.value.length); - break; - case 'TAB': - target.value = target.value + '\t'; - setSelection(target, target.value.length); - break; - case 'LEFT': - setSelection(target, target.selectionStart - 1); - break; - case 'RIGHT': - setSelection(target, target.selectionEnd + 1); - break; - case 'BACKSPACE': - { - var pos = target.selectionStart; - target.value = target.value.substring(0, target.selectionStart - 1) + target.value.substring(target.selectionEnd); - setSelection(target, pos - 1); - break; + }, { + key: "sanityCheck", + value: function sanityCheck(simple) { + var _this2 = this; + return Promise.all([this.getConfig(), this.getAPI().getVersion().then(function () { + return _this2.getAPI(); + }, function () { + return _this2.getAPI().reconnect(); + })["catch"](function (e) { + throw new Error('xFile is not installed yet'); + })]).then(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + config = _ref2[0], + api = _ref2[1]; + if (simple) { + return true; } - case 'DELETE': - { - var _pos = target.selectionEnd; - target.value = target.value.substring(0, target.selectionStart) + target.value.substring(target.selectionEnd + 1); - setSelection(target, _pos); - break; + if (!config.rootDir) { + throw new Error('rootDir is not set'); } + var checkDirectoryExists = function checkDirectoryExists() { + return api.directoryExists({ + path: config.rootDir + }).then(function (existed) { + if (!existed) throw new Error("Directory '".concat(config.rootDir, "' doesn't exist")); + return true; + }); + }; + var checkDirectoryWritable = function checkDirectoryWritable() { + var testDir = _path["default"].join(config.rootDir, '__kantu__' + Math.round(Math.random() * 100)); + return api.createDirectory({ + path: testDir + }).then(function (created) { + if (!created) throw new Error(); + return api.removeDirectory({ + path: testDir + }); + }).then(function (deleted) { + if (!deleted) throw new Error(); + return true; + })["catch"](function (e) { + throw new Error("Directory '".concat(config.rootDir, "' is not writable")); + }); + }; + return checkDirectoryExists().then(checkDirectoryWritable); + }); } - } -}; - -var maybeSubmitForm = function maybeSubmitForm(target, key) { - if (key !== 'ENTER') return; - if (!isEditable(target)) return; - - var form = findParentByTag(target, 'FORM'); - if (!form) return; - - form.submit(); -}; - -var isNil = function isNil(val) { - return val === null || val === undefined; -}; - -var setSelection = function setSelection($el, start, end) { - // Note: Inputs like number and email, doesn't support selectionEnd - // for safety, make sure those values are not null or undefined (infers that it's available) - if (!isNil($el.selectionStart)) { - $el.selectionStart = start; - } - - if (!isNil($el.selectionEnd)) { - $el.selectionEnd = end !== undefined ? end : start; - } -}; - -var replaceActionKey = function () { - var mapping = { - 0: null, // the NULL character - 8: 'BACKSPACE', - 9: 'TAB', - 10: 'ENTER', // \n new line - 11: null, // \v vertical tab - 12: null, // \f form feed - 13: null // \r carriage return - }; - - return function (c) { - // Note: it means it's already key stroke action - if (c.length > 1) return c; - return mapping[c.charCodeAt(0)] || c; - }; -}(); - -function sendKeys(target, str, noSpecialKeys) { - var rawChars = noSpecialKeys ? str.split('') : splitStringToChars(str); - var chars = rawChars.map(replaceActionKey).filter(function (x) { - return x && x.length; - }); - - target.focus(); - if (target.value) { - setSelection(target, target.value.length); - } - - chars.forEach(function (c) { - var action = getKeyStrokeAction(c); - - maybeEditText(target, action); - // Note: This line will take care of KEYDOWN KEYPRESS KEYUP and TEXTINPUT - keyboard.dispatchEventsForAction(action, target); - - if (!noSpecialKeys) { - maybeSubmitForm(target, action); + }, { + key: "checkUpdate", + value: function checkUpdate() { + return Promise.reject(new Error('checkUpdate is not implemented yet')); } - }); -} + }, { + key: "checkUpdateLink", + value: function checkUpdateLink(modVersion, extVersion) { + return "https://goto.ui.vision/x/idehelp?help=xfileaccess_updatecheck&xversion=".concat(modVersion, "&kantuversion=").concat(extVersion); + } + }, { + key: "downloadLink", + value: function downloadLink() { + return 'https://goto.ui.vision/x/idehelp?help=xfileaccess_download'; + } + }, { + key: "infoLink", + value: function infoLink() { + return 'https://goto.ui.vision/x/idehelp?help=xfileaccess'; + } + }]); + return XFile; +}(_common.XModule); +var getXFile = exports.getXFile = (0, _ts_utils.singletonGetter)(function () { + return new XFile(); +}); /***/ }), -/***/ 20326: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 12660: +/***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -3676,20508 +7034,26038 @@ function sendKeys(target, str, noSpecialKeys) { Object.defineProperty(exports, "__esModule", ({ value: true })); - -var _extends2 = __webpack_require__(88239); - -var _extends3 = _interopRequireDefault(_extends2); - -var _keys = __webpack_require__(88902); - -var _keys2 = _interopRequireDefault(_keys); - -var _defineProperty2 = __webpack_require__(88106); - -var _defineProperty3 = _interopRequireDefault(_defineProperty2); - -var _web_extension = __webpack_require__(61171); - -var _web_extension2 = _interopRequireDefault(_web_extension); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var local = _web_extension2.default.storage.local; - -exports["default"] = { - get: function get(key) { - return local.get(key).then(function (obj) { - return obj[key]; - }); - }, - - set: function set(key, value) { - return local.set((0, _defineProperty3.default)({}, key, value)).then(function () { - return true; - }); - }, - - remove: function remove(key) { - return local.remove(key).then(function () { - return true; - }); - }, - - clear: function clear() { - return local.clear().then(function () { - return true; - }); - }, - - addListener: function addListener(fn) { - _web_extension2.default.storage.onChanged.addListener(function (changes, areaName) { - var list = (0, _keys2.default)(changes).map(function (key) { - return (0, _extends3.default)({}, changes[key], { key: key }); - }); - fn(list); - }); - } -}; - -/***/ }), - -/***/ 67585: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); - -var _ext_storage = __webpack_require__(20326); - -var _ext_storage2 = _interopRequireDefault(_ext_storage); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports["default"] = _ext_storage2.default; - -/***/ }), - -/***/ 63370: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.bind = exports.bindOnce = exports.mockAPIWith = exports.dpiFromFileName = exports.getPageDpi = exports.sanitizeFileName = exports.validateStandardName = exports.ensureExtName = exports.loadImage = exports.loadCsv = exports.and = exports.uniqueName = exports.withFileExtension = exports.randomName = exports.retry = exports.withTimeout = exports.insertScript = exports.toRegExp = exports.parseQuery = exports.composePromiseFn = exports.nameFactory = exports.splitKeep = exports.formatDate = exports.objMap = exports.cn = exports.splitIntoTwo = exports.flatten = exports.uid = exports.pick = exports.getIn = exports.setIn = exports.updateIn = exports.on = exports.map = exports.compose = exports.reduceRight = exports.partial = exports.range = exports.until = exports.delay = undefined; - -var _typeof2 = __webpack_require__(72444); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _keys = __webpack_require__(88902); - -var _keys2 = _interopRequireDefault(_keys); - -var _defineProperty2 = __webpack_require__(88106); - -var _defineProperty3 = _interopRequireDefault(_defineProperty2); - -var _extends3 = __webpack_require__(88239); - -var _extends4 = _interopRequireDefault(_extends3); - -var _toConsumableArray2 = __webpack_require__(85315); - -var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2); - -var _promise = __webpack_require__(46593); - -var _promise2 = _interopRequireDefault(_promise); - -exports.dataURItoArrayBuffer = dataURItoArrayBuffer; -exports.dataURItoBlob = dataURItoBlob; -exports.blobToDataURL = blobToDataURL; -exports.blobToText = blobToText; -exports.arrayBufferToString = arrayBufferToString; -exports.stringToArrayBuffer = stringToArrayBuffer; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// delay the call of a function and return a promise -var delay = exports.delay = function delay(fn, timeout) { - return new _promise2.default(function (resolve, reject) { - setTimeout(function () { - try { - resolve(fn()); - } catch (e) { - reject(e); - } - }, timeout); - }); +exports.pointAtPos = exports.getAnchorRects = exports.genGetAnchorRects = exports.fitSquarePoint = exports.diagonalPos = exports.diagonalPoint = exports.calcRectAndAnchor = exports.Box = exports.BOX_ANCHOR_POS = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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), !0).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; } +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 _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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +var BOX_ANCHOR_POS = exports.BOX_ANCHOR_POS = { + TOP_LEFT: 1, + TOP_RIGHT: 2, + BOTTOM_RIGHT: 3, + BOTTOM_LEFT: 4 }; - -// Poll on whatever you want to check, and will time out after a specific duration -// `check` should return `{ pass: Boolean, result: Any }` -// `name` is for a meaningful error message -var until = exports.until = function until(name, check) { - var interval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1000; - var expire = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 10000; - var errorMsg = arguments[4]; - - var start = new Date(); - var go = function go() { - if (expire && new Date() - start >= expire) { - var msg = errorMsg || 'until: ' + name + ' expired!'; - throw new Error(msg); - } - - var _check = check(), - pass = _check.pass, - result = _check.result; - - if (pass) return _promise2.default.resolve(result); - return delay(go, interval); +var fitSquarePoint = exports.fitSquarePoint = function fitSquarePoint(movingPoint, fixedPoint) { + var mp = movingPoint; + var fp = fixedPoint; + var xlen = Math.abs(mp.x - fp.x); + var ylen = Math.abs(mp.y - fp.y); + var len = Math.min(xlen, ylen); + return { + x: fp.x + Math.sign(mp.x - fp.x) * len, + y: fp.y + Math.sign(mp.y - fp.y) * len }; - - return new _promise2.default(function (resolve, reject) { - try { - resolve(go()); - } catch (e) { - reject(e); - } - }); -}; - -var range = exports.range = function range(start, end) { - var step = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; - - var ret = []; - - for (var i = start; i < end; i += step) { - ret.push(i); - } - - return ret; }; - -// create a curry version of the passed in function -var partial = exports.partial = function partial(fn) { - var len = fn.length; - var _arbitary = void 0; - - _arbitary = function arbitary(curArgs, leftArgCnt) { - return function () { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - if (args.length >= leftArgCnt) { - return fn.apply(null, curArgs.concat(args)); - } - - return _arbitary(curArgs.concat(args), leftArgCnt - args.length); +var calcRectAndAnchor = exports.calcRectAndAnchor = function calcRectAndAnchor(movingPoint, fixedPoint) { + var mp = movingPoint; + var fp = fixedPoint; + var pos = null; + var tlp = null; + if (mp.x <= fp.x && mp.y <= fp.y) { + pos = BOX_ANCHOR_POS.TOP_LEFT; + tlp = mp; + } else if (mp.x > fp.x && mp.y > fp.y) { + pos = BOX_ANCHOR_POS.BOTTOM_RIGHT; + tlp = fp; + } else if (mp.x > fp.x) { + pos = BOX_ANCHOR_POS.TOP_RIGHT; + tlp = { + x: fp.x, + y: mp.y + }; + } else if (mp.y > fp.y) { + pos = BOX_ANCHOR_POS.BOTTOM_LEFT; + tlp = { + x: mp.x, + y: fp.y }; + } + return { + rect: { + x: tlp.x, + y: tlp.y, + width: Math.abs(mp.x - fp.x), + height: Math.abs(mp.y - fp.y) + }, + anchorPos: pos }; - - return _arbitary([], len); }; - -var reduceRight = exports.reduceRight = function reduceRight(fn, initial, list) { - var ret = initial; - - for (var i = list.length - 1; i >= 0; i--) { - ret = fn(list[i], ret); +var pointAtPos = exports.pointAtPos = function pointAtPos(rect, pos) { + switch (pos) { + case BOX_ANCHOR_POS.TOP_LEFT: + return { + x: rect.x, + y: rect.y + }; + case BOX_ANCHOR_POS.TOP_RIGHT: + return { + x: rect.x + rect.width, + y: rect.y + }; + case BOX_ANCHOR_POS.BOTTOM_RIGHT: + return { + x: rect.x + rect.width, + y: rect.y + rect.height + }; + case BOX_ANCHOR_POS.BOTTOM_LEFT: + return { + x: rect.x, + y: rect.y + rect.height + }; } - - return ret; }; - -// compose functions into one -var compose = exports.compose = function compose() { - for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; +var diagonalPos = exports.diagonalPos = function diagonalPos(pos) { + switch (pos) { + case BOX_ANCHOR_POS.TOP_LEFT: + return BOX_ANCHOR_POS.BOTTOM_RIGHT; + case BOX_ANCHOR_POS.TOP_RIGHT: + return BOX_ANCHOR_POS.BOTTOM_LEFT; + case BOX_ANCHOR_POS.BOTTOM_RIGHT: + return BOX_ANCHOR_POS.TOP_LEFT; + case BOX_ANCHOR_POS.BOTTOM_LEFT: + return BOX_ANCHOR_POS.TOP_RIGHT; } - - return reduceRight(function (cur, prev) { - return function (x) { - return cur(prev(x)); +}; +var diagonalPoint = exports.diagonalPoint = function diagonalPoint(rect, anchorPos) { + return pointAtPos(rect, diagonalPos(anchorPos)); +}; +var genGetAnchorRects = exports.genGetAnchorRects = function genGetAnchorRects(ANCHOR_POS, pointAtPos) { + return function (_ref) { + var rect = _ref.rect, + _ref$size = _ref.size, + size = _ref$size === void 0 ? 5 : _ref$size; + var values = function values(obj) { + return Object.keys(obj).map(function (key) { + return obj[key]; + }); }; - }, function (x) { - return x; - }, args); + var createRect = function createRect(point, size) { + return { + x: point.x - size, + y: point.y - size, + width: size * 2, + height: size * 2 + }; + }; + return values(ANCHOR_POS).map(function (pos) { + return { + anchorPos: pos, + rect: createRect(pointAtPos(rect, pos), size) + }; + }); + }; }; +var getAnchorRects = exports.getAnchorRects = genGetAnchorRects(BOX_ANCHOR_POS, pointAtPos); +var Box = exports.Box = /*#__PURE__*/function () { + function Box(options) { + _classCallCheck(this, Box); + _defineProperty(this, "state", { + type: 'box', + data: null, + style: {}, + rect: { + x: 0, + y: 0, + width: 0, + height: 0 + } + }); + _defineProperty(this, "local", {}); + var opts = Object.assign({ + firstSilence: true, + transform: function transform(x) { + return x; + }, + onStateChange: function onStateChange() {} + }, options); + this.transform = opts.transform; + this.onStateChange = opts.onStateChange; + this.normalizeRect = opts.normalizeRect || function (x) { + return x; + }; + this.__setState({ + id: opts.id, + data: opts.data, + type: this.getType(), + style: this.getDefaultStyle(), + category: this.getCategory(), + rect: { + x: opts.x, + y: opts.y, + width: opts.width || 0, + height: opts.height || 0 + } + }, { + silent: opts.firstSilence + }); + } + _createClass(Box, [{ + key: "getType", + value: function getType() { + return 'box'; + } + }, { + key: "getCategory", + value: function getCategory() { + return Box.category; + } + }, { + key: "getDefaultAnchorPos", + value: function getDefaultAnchorPos() { + return BOX_ANCHOR_POS.BOTTOM_RIGHT; + } + }, { + key: "getDefaultStyle", + value: function getDefaultStyle() { + return {}; + } + }, { + key: "getId", + value: function getId() { + return this.state.id; + } + }, { + key: "getState", + value: function getState() { + return this.transform(this.state); + } + }, { + key: "processIncomingStyle", + value: function processIncomingStyle(style) { + return style; + } + }, { + key: "setStyle", + value: function setStyle(obj) { + this.__setState({ + style: _objectSpread(_objectSpread({}, this.state.style), this.processIncomingStyle(obj)) + }); + } + }, { + key: "setData", + value: function setData(data) { + this.__setState({ + data: data + }); + } + }, { + key: "moveAnchorStart", + value: function moveAnchorStart(_ref2) { + var anchorPos = _ref2.anchorPos; + this.__setLocal({ + oldPoint: pointAtPos(this.state.rect, anchorPos), + oldAnchorPos: anchorPos, + anchorPos: anchorPos + }); + } + }, { + key: "moveAnchor", + value: function moveAnchor(_ref3) { + var x = _ref3.x, + y = _ref3.y; + var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + fit = _ref4.fit; + var old = this.state.rect; + var pos = this.local.anchorPos; + var fixed = diagonalPoint(old, pos); + var moving = !fit ? { + x: x, + y: y + } : fitSquarePoint({ + x: x, + y: y + }, fixed); + var res = calcRectAndAnchor(moving, fixed); + this.__setLocal({ + anchorPos: res.anchorPos + }); + this.__setState({ + rect: this.normalizeRect(res.rect, 'moveAnchor') + }); + } + }, { + key: "moveAnchorEnd", + value: function moveAnchorEnd() { + this.__setLocal({ + oldPoint: null, + oldAnchorPos: null, + anchorPos: null + }); + } + }, { + key: "moveBoxStart", + value: function moveBoxStart() { + this.__setLocal({ + oldRect: _objectSpread({}, this.state.rect) + }); + } + }, { + key: "moveBox", + value: function moveBox(_ref5) { + var dx = _ref5.dx, + dy = _ref5.dy; + var old = this.local.oldRect; + var upd = _objectSpread(_objectSpread({}, old), {}, { + x: old.x + dx, + y: old.y + dy + }); + this.__setState({ + rect: this.normalizeRect(upd, 'moveBox') + }); + } + }, { + key: "moveBoxEnd", + value: function moveBoxEnd() { + this.__setLocal({ + oldRect: null + }); + } + }, { + key: "__setState", + value: function __setState(obj) { + var _this = this; + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var last = this.getState(); + this.state = _objectSpread(_objectSpread({}, this.state), obj); + if (opts.silent) return; + var fn = function fn() { + return _this.onStateChange(_this.getState(), last); + }; + var invoke = opts.nextTick ? function (fn) { + return setTimeout(fn, 0); + } : function (fn) { + return fn(); + }; + invoke(fn); + } + }, { + key: "__setLocal", + value: function __setLocal(obj) { + this.local = _objectSpread(_objectSpread({}, this.local), obj); + } + }]); + return Box; +}(); +// Note: possible settings +_defineProperty(Box, "settings", []); +_defineProperty(Box, "category", 'rect'); +_defineProperty(Box, "defaultAnchorPos", BOX_ANCHOR_POS.BOTTOM_RIGHT); -var map = exports.map = partial(function (fn, list) { - var result = []; - - for (var i = 0, len = list.length; i < len; i++) { - result.push(fn(list[i])); - } - - return result; -}); - -var on = exports.on = partial(function (key, fn, dict) { - if (Array.isArray(dict)) { - return [].concat((0, _toConsumableArray3.default)(dict.slice(0, key)), [fn(dict[key])], (0, _toConsumableArray3.default)(dict.slice(key + 1))); - } - - return (0, _extends4.default)({}, dict, (0, _defineProperty3.default)({}, key, fn(dict[key]))); -}); - -// immutably update any part in an object -var updateIn = exports.updateIn = partial(function (keys, fn, obj) { - var updater = compose.apply(null, keys.map(function (key) { - return key === '[]' ? map : on(key); - })); - return updater(fn)(obj); -}); - -// immutably set any part in an object -// a restricted version of updateIn -var setIn = exports.setIn = partial(function (keys, value, obj) { - var updater = compose.apply(null, keys.map(function (key) { - return key === '[]' ? map : on(key); - })); - return updater(function () { - return value; - })(obj); -}); +/***/ }), -// return part of the object with a few keys deep inside -var getIn = exports.getIn = partial(function (keys, obj) { - return keys.reduce(function (prev, key) { - if (!prev) return prev; - return prev[key]; - }, obj); -}); +/***/ 21208: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -// return the passed in object with only certains keys -var pick = exports.pick = function pick(keys, obj) { - return keys.reduce(function (prev, key) { - if (obj[key] !== undefined) { - prev[key] = obj[key]; - } - return prev; - }, {}); -}; +"use strict"; -var uid = exports.uid = function uid() { - return '' + new Date() * 1 + '.' + Math.floor(Math.random() * 10000000).toString(16); -}; -var flatten = exports.flatten = function flatten(list) { - return [].concat.apply([], list); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.encryptIfNeeded = exports.encrypt = exports.decryptIfNeeded = exports.decrypt = exports.aesEncrypt = exports.aesDecrypt = void 0; +var _pbkdf = _interopRequireDefault(__webpack_require__(78396)); +var _aesJs = _interopRequireDefault(__webpack_require__(33836)); +var _web_extension = _interopRequireDefault(__webpack_require__(41953)); +var _storage = _interopRequireDefault(__webpack_require__(88555)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +var RAW_PREFIX = '@_KANTU_@'; +var DEPRECATED_CIPHER_PREFIX = '__KANTU_ENCRYPTED__'; +var CIPHER_PREFIX = '__RPA_ENCRYPTED__'; +var RAW_PREFIX_REG = new RegExp('^' + RAW_PREFIX); +var CIPHER_PREFIX_REG = new RegExp("^(".concat(CIPHER_PREFIX, "|").concat(DEPRECATED_CIPHER_PREFIX, ")")); +var getEncryptConfig = function getEncryptConfig() { + return _storage["default"].get('config').then(function (config) { + return { + shouldEncrypt: config.shouldEncryptPassword === 'master_password', + masterPassword: config.masterPassword + }; + }); }; - -var splitIntoTwo = exports.splitIntoTwo = function splitIntoTwo(pattern, str) { - var index = str.indexOf(pattern); - if (index === -1) return [str]; - - return [str.substr(0, index), str.substr(index + 1)]; +var aesEncrypt = exports.aesEncrypt = function aesEncrypt(text, password) { + var key = _pbkdf["default"].pbkdf2Sync(password, 'salt', 1, 256 / 8, 'sha512'); + var engine = new _aesJs["default"].ModeOfOperation.ctr(key); + return _aesJs["default"].utils.hex.fromBytes(engine.encrypt(_aesJs["default"].utils.utf8.toBytes(text))); }; - -var cn = exports.cn = function cn() { - for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - args[_key3] = arguments[_key3]; +var aesDecrypt = exports.aesDecrypt = function aesDecrypt(text, password) { + var key = _pbkdf["default"].pbkdf2Sync(password, 'salt', 1, 256 / 8, 'sha512'); + var engine = new _aesJs["default"].ModeOfOperation.ctr(key); + return _aesJs["default"].utils.utf8.fromBytes(engine.decrypt(_aesJs["default"].utils.hex.toBytes(text))); +}; +var encrypt = exports.encrypt = function encrypt(text) { + return getEncryptConfig().then(function (_ref) { + var shouldEncrypt = _ref.shouldEncrypt, + masterPassword = _ref.masterPassword; + if (!shouldEncrypt) return text; + return "".concat(CIPHER_PREFIX).concat(aesEncrypt(RAW_PREFIX + text, masterPassword)); + }); +}; +var decrypt = exports.decrypt = function decrypt(text) { + return getEncryptConfig().then(function (_ref2) { + var shouldEncrypt = _ref2.shouldEncrypt, + masterPassword = _ref2.masterPassword; + if (!shouldEncrypt) return text; + var raw = aesDecrypt(text.replace(CIPHER_PREFIX_REG, ''), masterPassword); + if (raw.indexOf(RAW_PREFIX) !== 0) throw new Error('Wrong master password'); + return raw.replace(RAW_PREFIX_REG, ''); + })["catch"](function (e) { + throw new Error('password string invalid'); + }); +}; +var encryptIfNeeded = exports.encryptIfNeeded = function encryptIfNeeded(text, dom) { + if (dom && dom.tagName.toUpperCase() === 'INPUT' && dom.type === 'password') { + return encrypt(text); } - - return args.reduce(function (prev, cur) { - if (typeof cur === 'string') { - prev.push(cur); - } else { - (0, _keys2.default)(cur).forEach(function (key) { - if (cur[key]) { - prev.push(key); - } - }); - } - - return prev; - }, []).join(' '); + return Promise.resolve(text); }; - -var objMap = exports.objMap = function objMap(fn, obj) { - return (0, _keys2.default)(obj).reduce(function (prev, key, i) { - prev[key] = fn(obj[key], key, i); - return prev; - }, {}); +var decryptIfNeeded = exports.decryptIfNeeded = function decryptIfNeeded(text, dom) { + if (!CIPHER_PREFIX_REG.test(text)) { + return Promise.resolve(text); + } + if (!dom || ['INPUT', 'TEXTAREA'].indexOf(dom.tagName.toUpperCase()) !== -1) { + return decrypt(text); + } + return Promise.resolve(text); }; -var formatDate = exports.formatDate = function formatDate(d) { - var pad = function pad(n) { - return n >= 10 ? '' + n : '0' + n; - }; - return [d.getFullYear(), d.getMonth() + 1, d.getDate()].map(pad).join('-'); -}; +/***/ }), -var splitKeep = exports.splitKeep = function splitKeep(pattern, str) { - var result = []; - var startIndex = 0; - var reg = void 0, - match = void 0, - lastMatchIndex = void 0; +/***/ 42143: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - if (pattern instanceof RegExp) { - reg = new RegExp(pattern, pattern.flags.indexOf('g') !== -1 ? pattern.flags : pattern.flags + 'g'); - } else if (typeof pattern === 'string') { - reg = new RegExp(pattern, 'g'); - } +"use strict"; - // eslint-disable-next-line no-cond-assign - while (match = reg.exec(str)) { - if (lastMatchIndex === match.index) { - break; - } - if (match.index > startIndex) { - result.push(str.substring(startIndex, match.index)); - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.globMatch = globMatch; +var _kdGlobToRegexp = _interopRequireDefault(__webpack_require__(44191)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function globMatch(pattern, text, opts) { + var reg = (0, _kdGlobToRegexp["default"])(pattern, opts || {}); + var res = reg.test(text); + return res; +} - result.push(match[0]); - startIndex = match.index + match[0].length; - lastMatchIndex = match.index; - } +/***/ }), - if (startIndex < str.length) { - result.push(str.substr(startIndex)); - } +/***/ 51152: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - return result; -}; +"use strict"; -var nameFactory = exports.nameFactory = function nameFactory() { - var all = {}; - return function (str) { - if (!all[str]) { - all[str] = true; - return str; - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _log = _interopRequireDefault(__webpack_require__(89130)); +var _dom_utils = __webpack_require__(92950); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +/* + * Basic tool function + */ - var n = 2; - while (all[str + '-' + n]) { - n++; +var extend = function extend() { + var args = Array.from(arguments); + var len = args.length; + if (len <= 0) return {}; + if (len === 1) return args[0]; + var head = args[0]; + var rest = args.slice(1); + return rest.reduce(function (prev, cur) { + for (var i = 0, keys = Object.keys(cur), len = keys.length; i < len; i++) { + prev[keys[i]] = cur[keys[i]]; } - - all[str + '-' + n] = true; - return str + '-' + n; - }; + return prev; + }, head); }; - -var composePromiseFn = exports.composePromiseFn = function composePromiseFn() { - for (var _len4 = arguments.length, list = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - list[_key4] = arguments[_key4]; +var isArray = Array.isArray; +var id = function id(x) { + return x; +}; +var trim = function trim(str) { + return str.replace(/^\s*|\s*$/g, ''); +}; +var flatten = function flatten(list) { + return [].concat.apply([], list); +}; +var sum = function sum() { + var list = Array.from(arguments); + return list.reduce(function (prev, cur) { + return prev + cur; + }, 0); +}; +var last = function last(list) { + return list[list.length - 1]; +}; +var or = function or(list) { + return (list || []).reduce(function (prev, cur) { + return prev || cur; + }, false); +}; +var and = function and(list) { + return (list || []).reduce(function (prev, cur) { + return prev && cur; + }, true); +}; +var zipWith = function zipWith(fn) { + if (arguments.length < 3) return null; + var list = Array.from(arguments).slice(1); + var len = list.reduce(function (min, cur) { + return cur.length < min ? cur.length : min; + }, Infinity); + var ret = []; + for (var i = 0; i < len; i++) { + ret.push(fn.apply(null, list.map(function (item) { + return item[i]; + }))); } - - return reduceRight(function (cur, prev) { - return function (x) { - return prev(x).then(cur); - }; - }, function (x) { - return _promise2.default.resolve(x); - }, list); + return ret; }; - -var parseQuery = exports.parseQuery = function parseQuery(query) { - return query.slice(1).split('&').reduce(function (prev, cur) { - var index = cur.indexOf('='); - var key = cur.substring(0, index); - var val = cur.substring(index + 1); - - prev[key] = decodeURIComponent(val); - return prev; - }, {}); +var intersect = function intersect() { + var list = Array.from(arguments); + var len = Math.max.apply(null, list.map(function (item) { + return item.length; + })); + var result = []; + for (var i = 0; i < len; i++) { + var val = list[0][i]; + var no = list.filter(function (item) { + return item[i] !== val; + }); + if (no && no.length) break; + result.push(val); + } + return result; }; - -var toRegExp = exports.toRegExp = function toRegExp(str) { - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$needEncode = _ref.needEncode, - needEncode = _ref$needEncode === undefined ? false : _ref$needEncode, - _ref$flag = _ref.flag, - flag = _ref$flag === undefined ? '' : _ref$flag; - - return new RegExp(needEncode ? str.replace(/[[\](){}^$.*+?|]/g, '\\$&') : str, flag); +var deepEqual = function deepEqual(a, b) { + if (isArray(a) && isArray(b)) { + return a.length === b.length && and(zipWith(deepEqual, a, b)); + } + if (_typeof(a) === 'object' && _typeof(b) === 'object') { + // TODO + return false; + } + return a === b; }; -var insertScript = exports.insertScript = function insertScript(file) { - var s = document.constructor.prototype.createElement.call(document, 'script'); - - s.setAttribute('type', 'text/javascript'); - s.setAttribute('src', file); +/* + * Dom helper function + */ - document.documentElement.appendChild(s); - s.parentNode.removeChild(s); +var pixel = function pixel(num) { + if ((num + '').indexOf('px') !== -1) return num; + return (num || 0) + 'px'; }; - -var withTimeout = exports.withTimeout = function withTimeout(timeout, fn) { - return new _promise2.default(function (resolve, reject) { - var cancel = function cancel() { - return clearTimeout(timer); - }; - var timer = setTimeout(function () { - reject(new Error('timeout')); - }, timeout); - - _promise2.default.resolve(fn(cancel)).then(function (data) { - cancel(); - resolve(data); - }, function (e) { - cancel(); - reject(e); - }); - }); +var getStyle = function getStyle(dom, styleName) { + if (!dom) throw new Error('getStyle: dom does not exist'); + return getComputedStyle(dom)[styleName]; +}; +var setStyle = function setStyle(dom, style) { + if (!dom) throw new Error('setStyle: dom does not exist'); + for (var i = 0, keys = Object.keys(style), len = keys.length; i < len; i++) { + dom.style[keys[i]] = style[keys[i]]; + } + return dom; +}; +var cssSum = function cssSum(dom, list) { + var isInline = getStyle(dom, 'display') === 'inline'; + return list.reduce(function (prev, cur) { + var val = isInline && ['width', 'height'].indexOf(cur) !== -1 ? dom.getClientRects()[0][cur] : getStyle(dom, cur); + return prev + parseInt(val || '0', 10); + }, 0); +}; +var offset = function offset(dom, noPx) { + if (!dom) return { + left: 0, + top: 0 + }; + var rect = dom.getBoundingClientRect(); + var fn = noPx ? id : pixel; + return { + left: fn(rect.left + window.scrollX), + top: fn(rect.top + window.scrollY) + }; +}; +var rect = function rect(dom, noPx) { + var pos = offset(dom, noPx); + var isInline = getStyle(dom, 'display') === 'inline'; + var w = isInline ? dom.getClientRects()[0]['width'] : getStyle(dom, 'width'); + var h = isInline ? dom.getClientRects()[0]['height'] : getStyle(dom, 'height'); + var fn = noPx ? id : pixel; + return extend({ + width: fn(w), + height: fn(h) + }, pos); }; -var retry = exports.retry = function retry(fn, options) { - return function () { - for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { - args[_key5] = arguments[_key5]; +// Reference: http://ryanve.com/lab/dimensions/ +var clientWidth = function clientWidth(document) { + return document.documentElement.clientWidth; +}; +var clientHeight = function clientHeight(document) { + return document.documentElement.clientHeight; +}; +var removeChildren = function removeChildren(dom, predicate) { + var pred = predicate || function () { + return true; + }; + var children = dom.childNodes; + for (var i = children.length - 1; i >= 0; i--) { + if (pred(children[i])) { + dom.removeChild(children[i]); } - - var _timeout$retryInterva = (0, _extends4.default)({ - timeout: 5000, - retryInterval: 1000, - onFirstFail: function onFirstFail() {}, - onFinal: function onFinal() {}, - shouldRetry: function shouldRetry() { - return false; - } - }, options), - timeout = _timeout$retryInterva.timeout, - onFirstFail = _timeout$retryInterva.onFirstFail, - onFinal = _timeout$retryInterva.onFinal, - shouldRetry = _timeout$retryInterva.shouldRetry, - retryInterval = _timeout$retryInterva.retryInterval; - - var retryCount = 0; - var lastError = null; - var timerToClear = null; - var done = false; - - var wrappedOnFinal = function wrappedOnFinal() { - done = true; - - if (timerToClear) { - clearTimeout(timerToClear); - } - - return onFinal.apply(undefined, arguments); - }; - - var intervalMan = function () { - var lastInterval = null; - var intervalFactory = function () { - switch (typeof retryInterval === 'undefined' ? 'undefined' : (0, _typeof3.default)(retryInterval)) { - case 'function': - return retryInterval; - - case 'number': - return function () { - return retryInterval; - }; - - default: - throw new Error('retryInterval must be either a number or a function'); - } - }(); - - return { - getLastInterval: function getLastInterval() { - return lastInterval; - }, - getInterval: function getInterval() { - var interval = intervalFactory(retryCount, lastInterval); - lastInterval = interval; - return interval; - } - }; - }(); - - var onError = function onError(e, reject) { - if (!shouldRetry(e, retryCount)) { - wrappedOnFinal(e); - - if (reject) return reject(e);else throw e; - } - lastError = e; - - return new _promise2.default(function (resolve, reject) { - if (retryCount++ === 0) { - onFirstFail(e); - timerToClear = setTimeout(function () { - wrappedOnFinal(lastError); - reject(lastError); - }, timeout); - } - - if (done) return; - - delay(run, intervalMan.getInterval()).then(resolve, function (e) { - return onError(e, reject); - }); - }); - }; - - var run = function run() { - return new _promise2.default(function (resolve) { - resolve(fn.apply(undefined, args.concat([{ - retryCount: retryCount, - retryInterval: intervalMan.getLastInterval() - }]))); - }).catch(onError); - }; - - return run().then(function (result) { - wrappedOnFinal(null, result); - return result; - }); - }; -}; - -// refer to https://stackoverflow.com/questions/12168909/blob-from-dataurl -function dataURItoArrayBuffer(dataURI) { - // convert base64 to raw binary data held in a string - // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this - var byteString = atob(/^data:/.test(dataURI) ? dataURI.split(',')[1] : dataURI); - - // write the bytes of the string to an ArrayBuffer - var ab = new ArrayBuffer(byteString.length); - - // create a view into the buffer - var ia = new Uint8Array(ab); - - // set the bytes of the buffer to the correct values - for (var i = 0; i < byteString.length; i++) { - ia[i] = byteString.charCodeAt(i); - } - - return ab; -} - -function dataURItoBlob(dataURI) { - var ab = dataURItoArrayBuffer(dataURI); - // separate out the mime component - var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; - // write the ArrayBuffer to a blob, and you're done - var blob = new Blob([ab], { type: mimeString }); - return blob; -} - -function blobToDataURL(blob) { - var withBase64Prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - - return new _promise2.default(function (resolve, reject) { - var reader = new FileReader(); - reader.onerror = reject; - reader.onload = function (e) { - var str = reader.result; - if (withBase64Prefix) return resolve(str); - - var b64 = 'base64,'; - var i = str.indexOf(b64); - var ret = str.substr(i + b64.length); - - resolve(ret); - }; - reader.readAsDataURL(blob); - }); -} - -function blobToText(blob) { - return new _promise2.default(function (resolve, reject) { - var reader = new FileReader(); - reader.onerror = reject; - reader.onload = function (e) { - var str = reader.result; - resolve(str); - }; - reader.readAsText(blob); - }); -} - -function arrayBufferToString(buf) { - var decoder = new TextDecoder('utf-8'); - return decoder.decode(new Uint8Array(buf)); - // return String.fromCharCode.apply(null, new Uint16Array(buf)) -} - -function stringToArrayBuffer(str) { - var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char - var bufView = new Uint16Array(buf); - - for (var i = 0, strLen = str.length; i < strLen; i++) { - bufView[i] = str.charCodeAt(i); } - return buf; -} - -var randomName = exports.randomName = function randomName() { - var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 6; - - if (length <= 0 || length > 100) throw new Error('randomName, length must be between 1 and 100'); - - var randomChar = function randomChar() { - var n = Math.floor(62 * Math.random()); - var code = void 0; - - if (n <= 9) { - code = 48 + n; - } else if (n <= 35) { - code = 65 + n - 10; - } else { - code = 97 + n - 36; - } - - return String.fromCharCode(code); - }; - - return range(0, length).map(randomChar).join('').toLowerCase(); }; - -var withFileExtension = exports.withFileExtension = function withFileExtension(origName, fn) { - var reg = /\.\w+$/; - var m = origName.match(reg); - - var extName = m ? m[0] : ''; - var baseName = m ? origName.replace(reg, '') : origName; - var result = fn(baseName, function (name) { - return name + extName; - }); - - if (!result) { - throw new Error('withFileExtension: should not return null/undefined'); - } - - if (typeof result.then === 'function') { - return result.then(function (name) { - return name + extName; - }); - } - - return result + extName; +var inDom = function inDom($outer, $el) { + if (!$el) return false; + if ($outer === $el) return true; + return inDom($outer, $el.parentNode); }; - -var uniqueName = exports.uniqueName = function uniqueName(name, options) { - var opts = (0, _extends4.default)({ - generate: function generate(old) { - var step = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; - - var reg = /_\((\d+)\)$/; - var m = old.match(reg); - - if (!m) return old + '_(' + step + ')'; - return old.replace(reg, function (_, n) { - return '_(' + (parseInt(n, 10) + step) + ')'; - }); - }, - check: function check() { - return _promise2.default.resolve(true); +var inDomList = function inDomList(list, $el) { + return or(list.map(function ($outer) { + return inDom($outer, $el); + })); +}; +var parentWithTag = function parentWithTag(tag, $el) { + var lowerTag = tag.toLowerCase(); + var $dom = $el; + while ($dom) { + if ($dom.tagName.toLowerCase() === lowerTag) { + return $dom; } - }, options || {}); - var generate = opts.generate, - check = opts.check; - - - return withFileExtension(name, function (baseName, getFullName) { - var go = function go(fileName, step) { - return check(getFullName(fileName)).then(function (pass) { - if (pass) return fileName; - return go(generate(fileName, step), step); - }); - }; - - return go(baseName, 1); - }); + $dom = $dom.parentNode; + } + return null; }; - -var and = exports.and = function and() { - for (var _len6 = arguments.length, list = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { - list[_key6] = arguments[_key6]; +var parentWithClass = function parentWithClass(className, $el) { + var $dom = $el; + while ($dom) { + // Note: In Firefox, HTML Document object doesn't have `classList` property + if ($dom.classList !== undefined && $dom.classList.contains(className)) { + return $dom; + } + $dom = $dom.parentNode; } - - return list.reduce(function (prev, cur) { - return prev && cur; - }, true); + return null; }; - -var loadCsv = exports.loadCsv = function loadCsv(url) { - return fetch(url).then(function (res) { - if (!res.ok) throw new Error('failed to load csv - ' + url); - return res.text(); +var selector = function selector(dom) { + if (dom.nodeType !== 1) return ''; + if (dom.tagName === 'BODY') return 'body'; + if (dom.id) return '#' + dom.id; + var classes = (dom.getAttribute('class') || '').split(/\s+/g).filter(function (item) { + return item && item.length; }); -}; - -var loadImage = exports.loadImage = function loadImage(url) { - return fetch(url).then(function (res) { - if (!res.ok) throw new Error('failed to load image - ' + url); - return res.blob(); + var children = Array.from(dom.parentNode.childNodes).filter(function ($el) { + return $el.nodeType === 1; }); -}; - -var ensureExtName = exports.ensureExtName = function ensureExtName(ext, name) { - var extName = ext.indexOf('.') === 0 ? ext : '.' + ext; - if (name.lastIndexOf(extName) + extName.length === name.length) return name; - return name + extName; -}; - -var validateStandardName = exports.validateStandardName = function validateStandardName(name, isFileName) { - if (!isFileName && !/^_|[a-zA-Z]/.test(name)) { - throw new Error('must start with a letter or the underscore character.'); - } - - if (isFileName && !/^_|[a-zA-Z0-9]/.test(name)) { - throw new Error('must start with alpha-numeric or the underscore character.'); + var sameTag = children.filter(function ($el) { + return $el.tagName === dom.tagName; + }); + var sameClass = children.filter(function ($el) { + var cs = ($el.getAttribute('class') || '').split(/\s+/g); + return and(classes.map(function (c) { + return cs.indexOf(c) !== -1; + })); + }); + var extra = ''; + if (sameTag.length === 1) { + extra = ''; + } else if (classes.length && sameClass.length === 1) { + extra = '.' + classes.join('.'); + } else { + extra = ':nth-child(' + (1 + children.findIndex(function (item) { + return item === dom; + })) + ')'; } + var me = dom.tagName.toLowerCase() + extra; - if (!/^[a-zA-Z0-9_]+$/.test(name)) { - throw new Error('can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )'); - } + // Note: browser will add an extra 'tbody' when tr directly in table, which will cause an wrong selector, + // so the hack is to remove all tbody here + var ret = selector(dom.parentNode) + ' > ' + me; + return ret; + // return ret.replace(/\s*>\s*tbody\s*>?/g, ' ') }; - -var sanitizeFileName = exports.sanitizeFileName = function sanitizeFileName(fileName) { - return withFileExtension(fileName, function (baseName) { - return baseName.replace(/[\\/:*?<>|]/g, '_'); - }); +var getTagIndex = function getTagIndex(dom) { + return Array.from(dom.parentNode.childNodes).filter(function (item) { + return item.nodeType === dom.nodeType && item.tagName === dom.tagName; + }).reduce(function (prev, node, i) { + if (prev !== null) return prev; + return node === dom ? i + 1 : prev; + }, null); }; - -var getPageDpi = exports.getPageDpi = function getPageDpi() { - var DEFAULT_DPI = 96; - var matchDpi = function matchDpi(dpi) { - return window.matchMedia('(max-resolution: ' + dpi + 'dpi)').matches === true; +var relativeXPath = function relativeXPath(dom) { + if (!dom) return null; + if (dom.nodeType === 3) return '@text'; + var index = getTagIndex(dom); + var count = Array.from(dom.parentNode.childNodes).filter(function (item) { + return item.nodeType === dom.nodeType && item.tagName === dom.tagName; + }).length; + var tag = dom.tagName.toLowerCase(); + return index > 1 ? tag + '[' + index + ']' : tag; +}; +var xpath = function xpath(dom, cur, list) { + var helper = function helper(dom, cur, list) { + if (!dom) return null; + if (!cur) { + if (dom.nodeType === 3) { + return helper(dom.parentNode); + } else { + return helper(dom, dom, []); + } + } + if (!cur.parentNode) { + return ['html'].concat(list); + } + if (cur.tagName === 'BODY') { + return ['html', 'body'].concat(list); + } + if (cur.id) { + return ["*[@id=\"".concat(cur.id, "\"]")].concat(list); + } + return helper(dom, cur.parentNode, [relativeXPath(cur)].concat(list)); }; - - // We iteratively scan all possible media query matches. - // We can't use binary search, because there are "many" correct answer in - // problem space and we need the very first match. - // To speed up computation we divide problem space into buckets. - // We test each bucket's first element and if we found a match, - // we make a full scan for previous bucket with including first match. - // Still, we could use "divide-and-conquer" for such problems. - // Due to common DPI values, it's not worth to implement such algorithm. - - var bucketSize = 24; // common divisor for 72, 96, 120, 144 etc. - - for (var i = bucketSize; i < 3000; i += bucketSize) { - if (matchDpi(i)) { - var start = i - bucketSize; - var end = i; - - for (var k = start; k <= end; ++k) { - if (matchDpi(k)) { - return k; - } + var parts = helper(dom, cur, list); + var prefix = parts[0] === 'html' ? '/' : '//'; + var ret = prefix + parts.join('/'); + return ret; +}; +var xpathPosition = function xpathPosition(dom) { + var path = ''; + var current = dom; + try { + while (current !== null) { + var currentPath = void 0; + if (current.parentNode != null) { + currentPath = '/' + relativeXPath(current); + } else if (current.tagName === 'BODY') { + currentPath = 'html/body'; + } else { + currentPath = '/' + current.nodeName.toLowerCase(); + } + path = currentPath + path; + var locator = '/' + path; + if (dom === (0, _dom_utils.getElementByXPath)(locator)) { + return locator; } + current = current.parentNode; + } + } catch (e) {} + return null; +}; +var attributeValue = function attributeValue(value) { + if (value.indexOf("'") < 0) { + return "'" + value + "'"; + } else if (value.indexOf('"') < 0) { + return '"' + value + '"'; + } else { + var result = 'concat('; + var part = ''; + var didReachEndOfValue = false; + while (!didReachEndOfValue) { + var apos = value.indexOf("'"); + var quot = value.indexOf('"'); + if (apos < 0) { + result += "'" + value + "'"; + didReachEndOfValue = true; + break; + } else if (quot < 0) { + result += '"' + value + '"'; + didReachEndOfValue = true; + break; + } else if (quot < apos) { + part = value.substring(0, apos); + result += "'" + part + "'"; + value = value.substring(part.length); + } else { + part = value.substring(0, quot); + result += '"' + part + '"'; + value = value.substring(part.length); + } + result += ','; } + result += ')'; + return result; } - - return DEFAULT_DPI; // default fallback }; - -var dpiFromFileName = exports.dpiFromFileName = function dpiFromFileName(fileName) { - var reg = /_dpi_(\d+)/i; - var m = fileName.match(reg); - return m ? parseInt(m[1], 10) : 0; +var xpathAttr = function xpathAttr(dom) { + function attributesXPath(name, attNames, attributes) { + var locator = '//' + name + '['; + for (var i = 0; i < attNames.length; i++) { + if (i > 0) { + locator += ' and '; + } + var attName = attNames[i]; + locator += '@' + attName + '=' + attributeValue(attributes[attName]); + } + locator += ']'; + return locator; + } + try { + var PREFERRED_ATTRIBUTES = ['id', 'name', 'value', 'type', 'action', 'onclick']; + var i = 0; + if (dom.attributes) { + var atts = dom.attributes; + var attsMap = {}; + for (i = 0; i < atts.length; i++) { + var att = atts[i]; + attsMap[att.name] = att.value; + } + var names = []; + // try preferred attributes + for (i = 0; i < PREFERRED_ATTRIBUTES.length; i++) { + var name = PREFERRED_ATTRIBUTES[i]; + if (attsMap[name] != null) { + names.push(name); + var locator = attributesXPath(dom.nodeName.toLowerCase(), names, attsMap); + if (dom === (0, _dom_utils.getElementByXPath)(locator)) { + return locator; + } + } + } + } + } catch (e) {} + return null; +}; +var atXPath = function atXPath(xpath, document) { + var lower = function lower(str) { + return str && str.toLowerCase(); + }; + var reg = /^([a-zA-Z0-9]+)(\[(\d+)\])?$/; + return xpath.reduce(function (prev, cur) { + if (!prev) return prev; + if (!prev.childNodes || !prev.childNodes.length) return null; + var match = cur.match(reg); + var tag = match[1]; + var index = match[3] ? parseInt(match[3], 10) : 1; + var list = Array.from(prev.childNodes).filter(function (item) { + return item.nodeType === 1 && lower(item.tagName) === lower(tag); + }); + return list[index - 1]; + }, document); +}; +var domText = function domText($dom) { + var it = $dom.innerText && $dom.innerText.trim(); + var tc = $dom.textContent; + var pos = tc.toUpperCase().indexOf(it.toUpperCase()); + return tc.substr(pos, it.length); +}; +var getFirstWorkingLocator = function getFirstWorkingLocator(locators, $el) { + var _loop = function _loop(i) { + var $match = function () { + try { + return (0, _dom_utils.getElementByLocator)(locators[i]); + } catch (e) { + return null; + } + }(); + if ($el === $match) { + return { + v: locators[i] + }; + } + }, + _ret; + for (var i = 0, len = locators.length; i < len; i++) { + _ret = _loop(i); + if (_ret) return _ret.v; + } + return null; }; -var mockAPIWith = exports.mockAPIWith = function mockAPIWith(factory, mock) { - var promiseFunctionKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - - var real = mock; - var exported = objMap(function (val, key) { - if (typeof val === 'function') { - if (promiseFunctionKeys.indexOf(key) !== -1) { - return function () { - for (var _len7 = arguments.length, args = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { - args[_key7] = arguments[_key7]; +// Note: get the locator of a DOM +var getLocator = function getLocator($dom, withAllOptions) { + var id = $dom.getAttribute('id'); + var name = $dom.getAttribute('name'); + var isLink = $dom.tagName.toLowerCase() === 'a'; + var text = function () { + try { + return domText($dom); + } catch (e) { + return null; + } + }(); + var classes = Array.from($dom.classList); + var candidates = []; + + // link + if (isLink && text && text.length) { + var links = [].slice.call(document.getElementsByTagName('a')); + var matches = links.filter(function ($el) { + return domText($el) === text; + }); + var index = matches.findIndex(function ($el) { + return $el === $dom; + }); + if (index !== -1) { + candidates.push(index === 0 ? "linkText=".concat(text) : "linkText=".concat(text, "@POS=").concat(index + 1)); + } + } + + // id + if (id && id.length) { + candidates.push("id=".concat(id)); + } + + // name + if (name && name.length) { + candidates.push("name=".concat(name)); + } + + // xpath + candidates.push('xpath=' + xpath($dom)); + var attrXPath = xpathAttr($dom); + if (attrXPath) { + candidates.push('xpath=' + attrXPath); + } + var positionXPath = xpathPosition($dom); + if (positionXPath) { + candidates.push('xpath=' + positionXPath); + } + + // css + // Try with simple css selector first. If not unqiue, use full css selector + /** + * Below is the old logic with a shorter css selector + * + let sel = null + if (classes.length > 0) { + sel = $dom.tagName.toLowerCase() + classes.map(c => '.' + c).join('') + if ($dom !== document.querySelectorAll(sel)[0]) { + sel = null + } + } + if (!sel) { + sel = selector($dom) + } + */ + candidates.push("css=".concat(selector($dom))); + + // Get the first one working + var chosen = getFirstWorkingLocator(candidates, $dom); + if (withAllOptions) { + return { + target: chosen, + targetOptions: candidates + }; + } + return chosen; +}; +var checkIframe = function checkIframe(iframeWin) { + var key = new Date() * 1 + '' + Math.random(); + try { + iframeWin[key] = 'asd'; + return iframeWin[key] === 'asd'; + } catch (e) { + return false; + } +}; + +// Note: get the locator for frame +var getFrameLocator = function getFrameLocator(frameWin, win) { + if (checkIframe(frameWin)) { + var frameDom = frameWin.frameElement; + var locator = getLocator(frameDom); + if (/^id=/.test(locator) || /^name=/.test(locator)) { + return locator; + } + } + for (var i = 0, len = win.frames.length; i < len; i++) { + if (win.frames[i] === frameWin) { + return "index=".concat(i); + } + } + throw new Error('Frame locator not found'); +}; + +/* + * Mask related + */ + +var maskFactory = function maskFactory() { + var cache = []; + var prefix = '__mask__' + new Date() * 1 + Math.round(Math.random() * 1000) + '__'; + var uid = 1; + var defaultStyle = { + position: 'absolute', + zIndex: '999', + display: 'none', + boxSizing: 'border-box', + backgroundColor: 'red', + opacity: 0.5, + pointerEvents: 'none' + }; + var genMask = function genMask(style, dom) { + var mask = document.createElement('div'); + if (dom) { + style = extend({}, defaultStyle, style || {}, rect(dom)); + } else { + style = extend({}, defaultStyle, style || {}); + } + setStyle(mask, style); + mask.id = prefix + uid++; + cache.push(mask); + return mask; + }; + var clear = function clear() { + for (var i = 0, len = cache.length; i < len; i++) { + var mask = cache[i]; + if (mask && mask.parentNode) { + mask.parentNode.removeChild(mask); + } + } + }; + return { + gen: genMask, + clear: clear + }; +}; +var showMaskOver = function showMaskOver(mask, el) { + var pos = offset(el); + var w = cssSum(el, ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth']); + var h = cssSum(el, ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', ' borderBottomWidth']); + setStyle(mask, extend(pos, { + width: pixel(w), + height: pixel(h), + display: 'block' + })); +}; +var isVisible = function isVisible(el) { + if (el === window.document) return true; + if (!el) return true; + var style = window.getComputedStyle(el); + if (style.display === 'none' || style.opacity === '0' || style.visibility === 'hidden') return false; + return isVisible(el.parentNode); +}; +var _default = exports["default"] = { + offset: offset, + setStyle: setStyle, + selector: selector, + xpath: xpath, + atXPath: atXPath, + domText: domText, + getLocator: getLocator, + getFrameLocator: getFrameLocator, + maskFactory: maskFactory, + showMaskOver: showMaskOver, + inDom: inDom, + isVisible: isVisible, + parentWithTag: parentWithTag, + parentWithClass: parentWithClass +}; + +/***/ }), + +/***/ 50366: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.postMessage = exports.onMessage = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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), !0).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; } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +var TYPE = 'SELENIUM_IDE_CS_MSG'; +var postMessage = exports.postMessage = function postMessage(targetWin, myWin, payload) { + var target = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '*'; + var timeout = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 60000; + return new Promise(function (resolve, reject) { + if (!targetWin || !targetWin.postMessage) { + throw new Error('E350: csPostMessage: targetWin is not a window'); + } + if (!myWin || !myWin.addEventListener || !myWin.removeEventListener) { + throw new Error('E351: csPostMessage: myWin is not a window', myWin); + } + var secret = Math.random(); + var type = TYPE; + + // Note: create a listener with a corresponding secret every time + var onMsg = function onMsg(e) { + if (e.data && e.data.type === TYPE && !e.data.isRequest && e.data.secret === secret) { + myWin.removeEventListener('message', onMsg); + var _e$data = e.data, + _payload = _e$data.payload, + error = _e$data.error; + if (error) return reject(new Error(error)); + if (_payload !== undefined) return resolve(_payload); + reject(new Error('E352: csPostMessage: No payload nor error found')); + } + }; + myWin.addEventListener('message', onMsg); + + // Note: + // * `type` to make sure we check our own msg only + // * `secret` is for 1 to 1 relationship between a msg and a listener + // * `payload` is the real data you want to send + // * `isRequest` is to mark that it's not an answer to some previous request + + targetWin.postMessage({ + type: type, + secret: secret, + payload: payload, + isRequest: true + }, target); + setTimeout(function () { + reject(new Error("E353: csPostMessage: timeout ".concat(timeout, " ms"))); //Why 5000? + }, timeout); + }); +}; +var onMessage = exports.onMessage = function onMessage(win, fn) { + if (!win || !win.addEventListener || !win.removeEventListener) { + throw new Error('csOnMessage: not a window', win); + } + var onMsg = function onMsg(e) { + // Note: only respond to msg with `isRequest` as true + if (e && e.data && e.data.type === TYPE && e.data.isRequest && e.data.secret) { + var tpl = { + type: TYPE, + secret: e.data.secret + }; + + // Note: wrapped with a new Promise to catch any exception during the execution of fn + new Promise(function (resolve, reject) { + var ret; + try { + ret = fn(e.data.payload, { + source: e.source + }); + } catch (err) { + reject(err); + } + + // Note: only resolve if returned value is not undefined. With this, we can have multiple + // listeners added to onMessage, and each one takes care of what it really cares + if (ret !== undefined) { + resolve(ret); + } + }).then(function (res) { + e.source.postMessage(_objectSpread(_objectSpread({}, tpl), {}, { + payload: res + }), '*'); + }, function (err) { + e.source.postMessage(_objectSpread(_objectSpread({}, tpl), {}, { + error: err.message + }), '*'); + }); + } + }; + win.addEventListener('message', onMsg); + return function () { + return win.removeEventListener('message', onMsg); + }; +}; + +/***/ }), + +/***/ 59711: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.spInit = exports.openBgWithCs = exports.csInit = exports.bgInit = exports.SIDEPANEL_TAB_ID = exports.SIDEPANEL_PORT_NAME = void 0; +var _ipc_promise = _interopRequireDefault(__webpack_require__(18020)); +var _ipc_cache = __webpack_require__(75866); +var _web_extension = _interopRequireDefault(__webpack_require__(41953)); +var _log = _interopRequireDefault(__webpack_require__(89130)); +var _utils = __webpack_require__(46580); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +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 _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +var TIMEOUT = -1; +// this is a constant number to identify sidePanel +var SIDEPANEL_TAB_ID = exports.SIDEPANEL_TAB_ID = 999999999; +// sidepanel port name +var SIDEPANEL_PORT_NAME = exports.SIDEPANEL_PORT_NAME = 'uiv_sidepanel'; +// this is a constant string to identify sidePanel +var SIDEPANEL_CUID = 'uiv-sidepanel'; + +// Note: `cuid` is a kind of unique id so that you can create multiple +// ipc promise instances between the same two end points +var openBgWithCs = exports.openBgWithCs = function openBgWithCs(cuid) { + var wrap = function wrap(str) { + return str + '_' + cuid; + }; + + // factory function to generate ipc promise instance for background + // `tabId` is needed to identify which tab to send messages to + var ipcBg = function ipcBg(tabId) { + var bgListeners = []; + + // `sender` contains tab info. Background may need this to store the corresponding + // relationship between tabId and ipc instance + var addSender = function addSender(obj, sender) { + var _sender$tab; + if (!obj || _typeof(obj) !== 'object') return obj; + // limiting the size of 'sender' reduces memory leak + obj.sender = { + tab: { + id: (_sender$tab = sender.tab) === null || _sender$tab === void 0 ? void 0 : _sender$tab.id + }, + url: sender.url + }; + return obj; + }; + + // `sender` contains tab info. Background may need this to store the corresponding + // relationship between tabId and ipc instance + var addSenderToArgsOnAskBg = function addSenderToArgsOnAskBg(obj, sender) { + var _sender$tab2; + if (!obj || _typeof(obj) !== 'object') return obj; + + // two things required for sender object + // sender.tab.id + // sender.url + // OR + // isSidePanel, isFileSchema, isHttpSchema + + // limiting the size of 'sender' reduces memory leak + obj.sender = { + tab: { + id: (_sender$tab2 = sender.tab) === null || _sender$tab2 === void 0 ? void 0 : _sender$tab2.id // sender can be sidepanel + }, + url: sender.url + }; + return obj; + }; + _web_extension["default"].runtime.onMessage.addListener(function (req, sender, sendResponse) { + if (req.type === wrap('CS_ANSWER_BG') || req.type === wrap('CS_ASK_BG')) { + sendResponse(true); + } + bgListeners.forEach(function (listener) { + return listener(req, sender); + }); + return true; + }); + return (0, _ipc_promise["default"])({ + timeout: TIMEOUT, + ask: function ask(uid, cmd, args) { + // Note: We need to send request to the same tab where the response is from + // check if the response is from sidePanel + if (tabId === SIDEPANEL_TAB_ID) { + // send request to sidePanel + return _web_extension["default"].runtime.sendMessage({ + type: wrap('BG_ASK_CS'), + uid: uid, + cmd: cmd, + args: args + }); + } else { + return _web_extension["default"].tabs.sendMessage(tabId, { + type: wrap('BG_ASK_CS'), + uid: uid, + cmd: cmd, + args: args + }); + } + }, + onAnswer: function onAnswer(fn) { + bgListeners.push(function (req, sender) { + if (req.type !== wrap('CS_ANSWER_BG')) return; + fn(req.uid, req.err, addSender(req.data, sender)); + }); + }, + onAsk: function onAsk(fn) { + bgListeners.push(function (req, sender) { + if (req.type !== wrap('CS_ASK_BG')) return; + if (req.cmd == 'PANEL_LOG') { + // this is handled upstream, so that it cannot create memory leak + return; + } else { + var reqArgs = addSenderToArgsOnAskBg(req.args, sender); + fn(req.uid, req.cmd, reqArgs); + } + }); + }, + answer: function answer(uid, err, data) { + // check if the request is from sidePanel + if (tabId === SIDEPANEL_TAB_ID) { + // send response to sidePanel + return _web_extension["default"].runtime.sendMessage({ + type: wrap('BG_ANSWER_CS'), + uid: uid, + err: err, + data: data + }); + } else { + return _web_extension["default"].tabs.sendMessage(tabId, { + type: wrap('BG_ANSWER_CS'), + uid: uid, + err: err, + data: data + }); + } + }, + destroy: function destroy() { + bgListeners = []; + } + }); + }; + + // factory function to generate ipc promise for content scripts + // this will run in content script or app running in a separate window (having a tabId) + var ipcCs = function ipcCs(checkReady) { + var csListeners = []; + _web_extension["default"].runtime.onMessage.addListener(function (req, sender, sendResponse) { + if (req.type === wrap('BG_ANSWER_CS') || req.type === wrap('BG_ASK_CS')) { + sendResponse(true); + } + csListeners.forEach(function (listener) { + return listener(req, sender); + }); + return true; + }); + return (0, _ipc_promise["default"])({ + timeout: TIMEOUT, + checkReady: checkReady, + ask: function ask(uid, cmd, args) { + // log('cs ask', uid, cmd, args) + return _web_extension["default"].runtime.sendMessage({ + type: wrap('CS_ASK_BG'), + uid: uid, + cmd: cmd, + args: args + }); + }, + onAnswer: function onAnswer(fn) { + csListeners.push(function (req, sender) { + if (req.type !== wrap('BG_ANSWER_CS')) return; + fn(req.uid, req.err, req.data); + }); + }, + onAsk: function onAsk(fn) { + csListeners.push(function (req, sender) { + if (req.type !== wrap('BG_ASK_CS')) return; + fn(req.uid, req.cmd, req.args); + }); + }, + answer: function answer(uid, err, data) { + return _web_extension["default"].runtime.sendMessage({ + type: wrap('CS_ANSWER_BG'), + uid: uid, + err: err, + data: data + }); + }, + destroy: function destroy() { + csListeners = []; + } + }); + }; + + // factory function to generate ipc promise for sidePanel + var ipcSp = function ipcSp(checkReady) { + var csListeners = []; + // this will run in sidePanel. A sidePanel doesn't have a tabId, so we use a random number instead + _web_extension["default"].runtime.onMessage.addListener(function (req, sender, sendResponse) { + if (req.type === wrap('BG_ANSWER_CS') || req.type === wrap('BG_ASK_CS')) { + sendResponse(true); + } + csListeners.forEach(function (listener) { + return listener(req, sender); + }); + return true; + }); + return (0, _ipc_promise["default"])({ + timeout: TIMEOUT, + checkReady: checkReady, + ask: function ask(uid, cmd, args) { + // log('CS_ASK_BG', uid, cmd, args) + return _web_extension["default"].runtime.sendMessage({ + type: wrap('CS_ASK_BG'), + uid: uid, + cmd: cmd, + args: args + }); + }, + onAnswer: function onAnswer(fn) { + csListeners.push(function (req, sender) { + if (req.type !== wrap('BG_ANSWER_CS')) return; + fn(req.uid, req.err, req.data); + }); + }, + onAsk: function onAsk(fn) { + csListeners.push(function (req, sender) { + if (req.type !== wrap('BG_ASK_CS')) return; + fn(req.uid, req.cmd, req.args); + }); + }, + answer: function answer(uid, err, data) { + return _web_extension["default"].runtime.sendMessage({ + type: wrap('CS_ANSWER_BG'), + uid: uid, + err: err, + data: data + }); + }, + destroy: function destroy() { + csListeners = []; + } + }); + }; + return { + ipcCs: ipcCs, + ipcSp: ipcSp, + ipcBg: ipcBg + }; +}; + +// Helper function to init ipc promise instance for content scripts +// The idea here is to send CONNECT message to background when initializing +var csInit = exports.csInit = function csInit() { + var noRecover = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var cuid = '' + Math.floor(Math.random() * 10000); + if (noRecover) { + _web_extension["default"].runtime.sendMessage({ + type: 'CONNECT', + cuid: cuid + }); + return openBgWithCs(cuid).ipcCs(); + } + + // log('sending Connect...') + + // Note: Ext.runtime.getURL is available in content script, but not injected js + // We use it here to detect whether it is loaded by content script or injected + // Calling runtime.sendMessage in injected js will cause an uncatchable exception + if (!_web_extension["default"].runtime.getURL) return; + + // try this process in case we're in none-src frame + try { + // let connected = false + // const checkReady = () => { + // if (connected) return Promise.resolve(true) + // return Promise.reject(new Error('cs not connected with bg yet')) + // } + var reconnect = function reconnect() { + return (0, _utils.withTimeout)(500, function () { + return _web_extension["default"].runtime.sendMessage({ + type: 'RECONNECT' + }).then(function (cuid) { + // log('got existing cuid', cuid) + if (cuid) return openBgWithCs(cuid).ipcCs(); + throw new Error('failed to reconnect'); + }); + }); + }; + var connectBg = function connectBg() { + return (0, _utils.withTimeout)(1000, function () { + return _web_extension["default"].runtime.sendMessage({ + type: 'CONNECT', + cuid: cuid + }).then(function (done) { + if (done) return openBgWithCs(cuid).ipcCs(); + throw new Error('not done'); + }); + }); + }; + var tryConnect = (0, _utils.retry)(connectBg, { + shouldRetry: function shouldRetry() { + return true; + }, + retryInterval: 1000, + // 1000 from testing purpose. default value: 0, + timeout: 5000 + }); + + // Note: Strategy here + // 1. Try to recover connection with background (get the existing cuid) + // 2. If cuid not found, try to create new connection (cuid) with background + // 3. Both of these two steps above are async, but this api itself is synchronous, + // so we have to create a mock API and return it first + var enhancedConnect = function enhancedConnect() { + return reconnect()["catch"](function () { + return tryConnect(); + })["catch"](function (e) { + _log["default"].error('Failed to create cs ipc'); + throw e; + }); + }; + return (0, _utils.mockAPIWith)(enhancedConnect, { + ask: function ask() { + return Promise.reject(new Error('mock ask')); + }, + onAsk: function onAsk() {/* log('mock onAsk', ...args ) */}, + destroy: function destroy() {}, + secret: cuid + }, ['ask']); + } catch (e) { + _log["default"].error(e.stack); + } +}; + +// Helper function to init ipc promise instance for sidePanel +// The idea here is to send CONNECT message to background when initializing +var spInit = exports.spInit = function spInit() { + var cuid = SIDEPANEL_CUID; + try { + // log('sending Connect...') + var connectBg = function connectBg() { + return (0, _utils.withTimeout)(1000, function () { + return _web_extension["default"].runtime.sendMessage({ + type: 'CONNECT', + cuid: cuid + }).then(function (done) { + if (done) return openBgWithCs(cuid).ipcSp(); + throw new Error('sp connect not done'); + }); + }); + }; + var tryConnect = (0, _utils.retry)(connectBg, { + shouldRetry: function shouldRetry() { + return true; + }, + retryInterval: 1000, + // 1000 from testing purpose. default value: 0, + timeout: 5000 + }); + + // Note: Strategy here + // 1. Try to recover connection with background (get the existing cuid) + // 2. If cuid not found, try to create new connection (cuid) with background + // 3. Both of these two steps above are async, but this api itself is synchronous, + // so we have to create a mock API and return it first + var enhancedConnect = function enhancedConnect() { + return tryConnect()["catch"](function (e) { + _log["default"].error('Failed to create cs ipc - spInit'); + throw e; + }); + }; + return (0, _utils.mockAPIWith)(enhancedConnect, { + ask: function ask() { + return Promise.reject(new Error('mock ask')); + }, + onAsk: function onAsk() {/* log('mock onAsk', ...args) */}, + destroy: function destroy() {}, + secret: cuid + }, ['ask']); + } catch (e) { + _log["default"].error(e.stack); + } +}; + +// Helper function to init ipc promise instance for background +// it accepts a `fn` function to handle CONNECT message from content scripts +var bgInit = exports.bgInit = function bgInit(fn, getLogServiceForBg) { + _web_extension["default"].runtime.onMessage.addListener(function (req, sender, sendResponse) { + // this is handled here to prevent memory leak from 'PANEL_LOG' + if (req.cmd == 'PANEL_LOG') { + return getLogServiceForBg().log(req.args.log); + } + switch (req.type) { + case 'CONNECT': + { + if (req.cuid) { + if (req.cuid === SIDEPANEL_CUID) { + fn(SIDEPANEL_TAB_ID, SIDEPANEL_CUID, openBgWithCs(SIDEPANEL_CUID).ipcBg(SIDEPANEL_TAB_ID)); + sendResponse(true); + } else { + fn(sender.tab.id, req.cuid, openBgWithCs(req.cuid).ipcBg(sender.tab.id)); + sendResponse(true); + } + } + break; + } + case 'RECONNECT': + { + (0, _ipc_cache.getIpcCache)().getCuid(sender.tab.id).then( /*#__PURE__*/function () { + var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(cuid) { + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!cuid) { + _context.next = 3; + break; + } + _context.next = 3; + return (0, _ipc_cache.getIpcCache)().enable(sender.tab.id); + case 3: + sendResponse(cuid || null); + case 4: + case "end": + return _context.stop(); + } + }, _callee); + })); + return function (_x) { + return _ref.apply(this, arguments); + }; + }()); + break; + } + case 'BringIDEToFront': + { + var delay = req.delay || 0; + setTimeout(function () { + _web_extension["default"].windows.update(req.windowId, { + focused: true + }); + }, delay); + break; + } + } + return true; + }); +}; + +/***/ }), + +/***/ 96571: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _ipc_bg_cs = __webpack_require__(59711); +var throwNotTop = function throwNotTop() { + throw new Error('You are not a top window, not allowed to initialize/use csIpc'); +}; + +// browser.runtime.id in firefox extension isn't necessarily found in window.location.href +// window.location.href eg. "moz-extension://add2840d-0b3e-41f0-8da1-55d780cc5dd8/sidepanel.html" +var isSidepanelInFirefox = typeof window !== 'undefined' && window.location.href.match(/moz-extension:\/\/[a-z0-9-]+\/sidepanel.html/); +var isSidepanel = false; +if (typeof window !== 'undefined' && (window.location.href.startsWith("chrome-extension://".concat(chrome.runtime.id, "/sidepanel.html")) || isSidepanelInFirefox)) { + isSidepanel = true; +} + +// Note: csIpc is only available to top window +var ipc = typeof window !== 'undefined' && window.top === window ? isSidepanel ? (0, _ipc_bg_cs.spInit)() : (0, _ipc_bg_cs.csInit)() : { + ask: throwNotTop, + send: throwNotTop, + onAsk: throwNotTop, + destroy: throwNotTop +}; + +// Note: one ipc singleton per content script +var _default = exports["default"] = ipc; + +/***/ }), + +/***/ 18020: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + + +var _config = _interopRequireDefault(__webpack_require__(8747)); +var _utils = __webpack_require__(46580); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +var TO_BE_REMOVED = false; +var log = function log(msg) { + if (console && console.log) console.log(msg); +}; +var transformError = function transformError(err) { + console.error(err); + if (err instanceof Error) { + return { + isError: true, + name: err.name, + message: err.message, + stack: err.stack + }; + } + return err; +}; + +// Note: The whole idea of ipc promise is about transforming the callback style +// ipc communication API to a Promise style +// +// eg. Orignial: `chrome.runtime.sendMessage({}, () => {})` +// ipcPromise: `ipc.ask({}).then(() => {})` +// +// The benifit is +// 1. You can chain this promise with others +// 2. Create kind of connected channels between two ipc ends +// +// This is a generic interface to define a ipc promise utility +// All you need to declare is 4 functions +// +// e.g. +// ``` +// ipcPromise({ +// ask: function (uid, cmd, args) { ... }, +// answer: function (uid, err, data) { ... }, +// onAsk: function (fn) { ... }, +// onAnswer: function (fn) { ... }, +// }) +// ``` +function ipcPromise(options) { + var ask = options.ask; + var answer = options.answer; + var timeout = options.timeout; + var onAnswer = options.onAnswer; + var onAsk = options.onAsk; + var userDestroy = options.destroy; + var checkReady = options.checkReady || function () { + return Promise.resolve(true); + }; + var nid = 0; + var askCache = {}; + var unhandledAsk = []; + var markUnhandled = function markUnhandled(uid, cmd, args) { + unhandledAsk.push({ + uid: uid, + cmd: cmd, + args: args + }); + }; + var handler = markUnhandled; + var getNextNid = function getNextNid() { + nid = (nid + 1) % 100000; + return nid; + }; + var runHandlers = function runHandlers(handlers, cmd, args, resolve, reject) { + for (var i = 0, len = handlers.length; i < len; i++) { + var res = void 0; + try { + res = handlers[i](cmd, args); + } catch (e) { + return reject(e); + } + if (res !== undefined) { + return resolve(res); + } + } + // Note: DO NOT resolve anything if all handlers return undefined + }; + + // both for ask and unhandledAsk + timeout = timeout || -1; + onAnswer(function (uid, err, data) { + if (uid && askCache[uid] === TO_BE_REMOVED) { + delete askCache[uid]; + return; + } + if (!uid || !askCache[uid]) { + // log('ipcPromise: response uid invalid: ' + uid); + return; + } + var resolve = askCache[uid][0]; + var reject = askCache[uid][1]; + delete askCache[uid]; + if (err) { + reject(transformError(err)); + } else { + resolve(data); + } + }); + onAsk(function (uid, cmd, args) { + if (timeout > 0) { + setTimeout(function () { + var found = unhandledAsk && unhandledAsk.find(function (item) { + return item.uid === uid; + }); + if (!found) return; + answer(uid, new Error('ipcPromise: answer timeout ' + timeout + ' for cmd "' + cmd + '", args "' + args + '"')); + }, timeout); + } + if (handler === markUnhandled) { + markUnhandled(uid, cmd, args); + return; + } + return new Promise(function (resolve, reject) { + runHandlers(handler, cmd, args, resolve, reject); + }).then(function (data) { + // note: handler doesn't handle the cmd => return undefined, should wait for timeout + if (data === undefined) return markUnhandled(uid, cmd, args); + answer(uid, null, data); + }, function (err) { + answer(uid, transformError(err), null); + }); + }); + var wrapAsk = function wrapAsk(cmd, args, timeoutToOverride) { + var uid = 'ipcp_' + new Date() * 1 + '_' + getNextNid(); + var finalTimeout = timeoutToOverride || timeout; + var timer; + if (args && args.payload && args.payload.args && args.payload.args.command && args.payload.args.command.cmd) { + var _cmd = args.payload.args.command.cmd; + if (_cmd === 'executeScript') { + var minimumTimeout = _config["default"].executeScript.minimumTimeout; // 5000 + finalTimeout = finalTimeout < minimumTimeout ? minimumTimeout : finalTimeout; + } + } + + // Note: make it possible to disable timeout + if (finalTimeout > 0) { + timer = setTimeout(function () { + var reject; + if (askCache && askCache[uid]) { + reject = askCache[uid][1]; + askCache[uid] = TO_BE_REMOVED; + console.error('ipcPromise: onAsk timeout ' + finalTimeout + ' for cmd "' + cmd + '", args ' + stringify(args)); + var errMsg = "Error #102: Lost contact to website"; + reject(new Error(errMsg)); + } + }, finalTimeout); + } + return new Promise(function (resolve, reject) { + askCache[uid] = [resolve, reject]; + Promise.resolve(ask(uid, cmd, args || []))["catch"](function (e) { + reject(e); + }); + }).then(function (data) { + if (timer) { + clearTimeout(timer); + } + return data; + }, function (e) { + if (timer) { + clearTimeout(timer); + } + throw e; + }); + }; + var wrapOnAsk = function wrapOnAsk(fn) { + if (Array.isArray(handler)) { + handler.push(fn); + } else { + handler = [fn]; + } + var ps = unhandledAsk.map(function (task) { + return new Promise(function (resolve, reject) { + runHandlers(handler, task.cmd, task.args, resolve, reject); + }).then(function (data) { + // note: handler doens't handle the cmd => return undefined, should wait for timeout + if (data === undefined) return; + answer(task.uid, null, data); + return task.uid; + }, function (err) { + answer(task.uid, err, null); + return task.uid; + }); + }); + Promise.all(ps).then(function (uids) { + var _iterator = _createForOfIteratorHelper(uids), + _step; + try { + var _loop = function _loop() { + var uid = _step.value; + if (uid === undefined) return 1; // continue + var index = unhandledAsk.findIndex(function (item) { + return item.uid === uid; + }); + unhandledAsk.splice(index, 1); + }; + for (_iterator.s(); !(_step = _iterator.n()).done;) { + if (_loop()) continue; + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + }); + }; + var destroy = function destroy(noReject) { + userDestroy && userDestroy(); + ask = null; + answer = null; + onAnswer = null; + onAsk = null; + unhandledAsk = null; + if (!noReject) { + Object.keys(askCache).forEach(function (uid) { + var tuple = askCache[uid]; + var reject = tuple[1]; + reject && reject(new Error('IPC Promise has been Destroyed.')); + delete askCache[uid]; + }); + } + }; + var waitForReady = function waitForReady(checkReady, fn) { + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + var makeSureReady = (0, _utils.retry)(checkReady, { + shouldRetry: function shouldRetry() { + return true; + }, + retryInterval: 100, + timeout: 5000 + }); + return makeSureReady().then(function () { + return fn.apply(void 0, args); + }); + }; + }; + return { + ask: waitForReady(checkReady, wrapAsk), + onAsk: wrapOnAsk, + destroy: destroy + }; +} +ipcPromise.serialize = function (obj) { + return { + ask: function ask(cmd, args, timeout) { + return obj.ask(cmd, JSON.stringify(args), timeout); + }, + onAsk: function onAsk(fn) { + return obj.onAsk(function (cmd, args) { + return fn(cmd, JSON.parse(args)); + }); + }, + destroy: obj.destroy + }; +}; +function stringify(v) { + return v === undefined ? 'undefined' : JSON.stringify(v); +} +module.exports = ipcPromise; + +/***/ }), + +/***/ 62807: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.Keystroke = exports.Keyboard = exports.KeyEvents = void 0; +var _domElementIsNativelyEditable = _interopRequireDefault(__webpack_require__(69423)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +var CTRL = 1 << 0; +var META = 1 << 1; +var ALT = 1 << 2; +var SHIFT = 1 << 3; + +// Key Events +var KeyEvents = exports.KeyEvents = { + DOWN: 1 << 0, + PRESS: 1 << 1, + UP: 1 << 2, + INPUT: 1 << 3 +}; +KeyEvents.ALL = KeyEvents.DOWN | KeyEvents.PRESS | KeyEvents.UP | KeyEvents.INPUT; + +/** + * Represents a keystroke, or a single key code with a set of active modifiers. + * + * @class Keystroke + */ +var Keystroke = exports.Keystroke = /*#__PURE__*/_createClass( +/** + * @param {number} modifiers A bitmask formed by CTRL, META, ALT, and SHIFT. + * @param {number} keyCode + */ +function Keystroke(modifiers, keyCode) { + _classCallCheck(this, Keystroke); + this.modifiers = modifiers; + this.ctrlKey = !!(modifiers & CTRL); + this.metaKey = !!(modifiers & META); + this.altKey = !!(modifiers & ALT); + this.shiftKey = !!(modifiers & SHIFT); + this.keyCode = keyCode; +} + +/** + * Gets the bitmask value for the "control" modifier. + * + * @type {number} + */); +/** + * Simulates a keyboard with a particular key-to-character and key-to-action + * mapping. Use `US_ENGLISH` to get a pre-configured keyboard. + */ +_defineProperty(Keystroke, "CTRL", CTRL); +/** + * Gets the bitmask value for the "meta" modifier. + * + * @return {number} + */ +_defineProperty(Keystroke, "META", META); +/** + * Gets the bitmask value for the "alt" modifier. + * + * @return {number} + */ +_defineProperty(Keystroke, "ALT", ALT); +/** + * Gets the bitmask value for the "shift" modifier. + * + * @return {number} + */ +_defineProperty(Keystroke, "SHIFT", SHIFT); +var Keyboard = exports.Keyboard = /*#__PURE__*/function () { + /** + * @param {Object.} charCodeKeyCodeMap + * @param {Object.} actionKeyCodeMap + */ + function Keyboard(charCodeKeyCodeMap, actionKeyCodeMap) { + _classCallCheck(this, Keyboard); + this._charCodeKeyCodeMap = charCodeKeyCodeMap; + this._actionKeyCodeMap = actionKeyCodeMap; + } + + /** + * Determines the character code generated by pressing the given keystroke. + * + * @param {Keystroke} keystroke + * @return {?number} + */ + _createClass(Keyboard, [{ + key: "charCodeForKeystroke", + value: function charCodeForKeystroke(keystroke) { + var map = this._charCodeKeyCodeMap; + for (var charCode in map) { + if (Object.prototype.hasOwnProperty.call(map, charCode)) { + var keystrokeForCharCode = map[charCode]; + if (keystroke.keyCode === keystrokeForCharCode.keyCode && keystroke.modifiers === keystrokeForCharCode.modifiers) { + return parseInt(charCode, 10); + } + } + } + return null; + } + + /** + * Creates an event ready for dispatching onto the given target. + * + * @param {string} type One of "keydown", "keypress", "keyup", "textInput" or "input". + * @param {Keystroke} keystroke + * @param {HTMLElement} target + * @return {Event} + */ + }, { + key: "createEventFromKeystroke", + value: function createEventFromKeystroke(type, keystroke, target) { + var document = target.ownerDocument; + var window = document.defaultView; + var Event = window.Event; + var event; + try { + event = new Event(type); + } catch (e) { + event = document.createEvent('UIEvents'); + } + event.initEvent(type, true, true); + switch (type) { + case 'textInput': + event.data = String.fromCharCode(this.charCodeForKeystroke(keystroke)); + break; + case 'keydown': + case 'keypress': + case 'keyup': + event.shiftKey = keystroke.shiftKey; + event.altKey = keystroke.altKey; + event.metaKey = keystroke.metaKey; + event.ctrlKey = keystroke.ctrlKey; + event.keyCode = type === 'keypress' ? this.charCodeForKeystroke(keystroke) : keystroke.keyCode; + event.charCode = type === 'keypress' ? event.keyCode : 0; + event.which = event.keyCode; + break; + } + return event; + } + + /** + * Fires the correct sequence of events on the given target as if the given + * action was undertaken by a human. + * + * @param {string} action e.g. "alt+shift+left" or "backspace" + * @param {HTMLElement} target + */ + }, { + key: "dispatchEventsForAction", + value: function dispatchEventsForAction(action, target) { + var keystroke = this.keystrokeForAction(action); + this.dispatchEventsForKeystroke(keystroke, target); + } + + /** + * Fires the correct sequence of events on the given target as if the given + * input had been typed by a human. + * + * @param {string} input + * @param {HTMLElement} target + */ + }, { + key: "dispatchEventsForInput", + value: function dispatchEventsForInput(input, target) { + var currentModifierState = 0; + for (var i = 0, length = input.length; i < length; i++) { + var keystroke = this.keystrokeForCharCode(input.charCodeAt(i)); + if (!keystroke) continue; + this.dispatchModifierStateTransition(target, currentModifierState, keystroke.modifiers); + this.dispatchEventsForKeystroke(keystroke, target, false); + currentModifierState = keystroke.modifiers; + } + this.dispatchModifierStateTransition(target, currentModifierState, 0); + } + + /** + * Fires the correct sequence of events on the given target as if the given + * keystroke was performed by a human. When simulating, for example, typing + * the letter "A" (assuming a U.S. English keyboard) then the sequence will + * look like this: + * + * keydown keyCode=16 (SHIFT) charCode=0 shiftKey=true + * keydown keyCode=65 (A) charCode=0 shiftKey=true + * keypress keyCode=65 (A) charCode=65 (A) shiftKey=true + * textInput data=A + * input + * keyup keyCode=65 (A) charCode=0 shiftKey=true + * keyup keyCode=16 (SHIFT) charCode=0 shiftKey=false + * + * If the keystroke would not cause a character to be input, such as when + * pressing alt+shift+left, the sequence looks like this: + * + * keydown keyCode=16 (SHIFT) charCode=0 altKey=false shiftKey=true + * keydown keyCode=18 (ALT) charCode=0 altKey=true shiftKey=true + * keydown keyCode=37 (LEFT) charCode=0 altKey=true shiftKey=true + * keyup keyCode=37 (LEFT) charCode=0 altKey=true shiftKey=true + * keyup keyCode=18 (ALT) charCode=0 altKey=false shiftKey=true + * keyup keyCode=16 (SHIFT) charCode=0 altKey=false shiftKey=false + * + * To disable handling of modifier keys, call with `transitionModifers` set + * to false. Doing so will omit the keydown and keyup events associated with + * shift, ctrl, alt, and meta keys surrounding the actual keystroke. + * + * @param {Keystroke} keystroke + * @param {HTMLElement} target + * @param {boolean=} transitionModifiers + * @param {number} events + */ + }, { + key: "dispatchEventsForKeystroke", + value: function dispatchEventsForKeystroke(keystroke, target) { + var transitionModifiers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + var events = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : KeyEvents.ALL; + if (!keystroke) return; + if (transitionModifiers) { + this.dispatchModifierStateTransition(target, 0, keystroke.modifiers, events); + } + var keydownEvent; + if (events & KeyEvents.DOWN) { + keydownEvent = this.createEventFromKeystroke('keydown', keystroke, target); + } + if (keydownEvent && target.dispatchEvent(keydownEvent) && this.targetCanReceiveTextInput(target)) { + var keypressEvent; + if (events & KeyEvents.PRESS) { + keypressEvent = this.createEventFromKeystroke('keypress', keystroke, target); + } + if (keypressEvent && keypressEvent.charCode && target.dispatchEvent(keypressEvent)) { + if (events & KeyEvents.INPUT) { + var textinputEvent = this.createEventFromKeystroke('textInput', keystroke, target); + target.dispatchEvent(textinputEvent); + var inputEvent = this.createEventFromKeystroke('input', keystroke, target); + target.dispatchEvent(inputEvent); + } + } + } + if (events & KeyEvents.UP) { + var keyupEvent = this.createEventFromKeystroke('keyup', keystroke, target); + target.dispatchEvent(keyupEvent); + } + if (transitionModifiers) { + this.dispatchModifierStateTransition(target, keystroke.modifiers, 0); + } + } + + /** + * Transitions from one modifier state to another by dispatching key events. + * + * @param {EventTarget} target + * @param {number} fromModifierState + * @param {number} toModifierState + * @param {number} events + * @private + */ + }, { + key: "dispatchModifierStateTransition", + value: function dispatchModifierStateTransition(target, fromModifierState, toModifierState) { + var events = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : KeyEvents.ALL; + var currentModifierState = fromModifierState; + var didHaveMeta = (fromModifierState & META) === META; + var willHaveMeta = (toModifierState & META) === META; + var didHaveCtrl = (fromModifierState & CTRL) === CTRL; + var willHaveCtrl = (toModifierState & CTRL) === CTRL; + var didHaveShift = (fromModifierState & SHIFT) === SHIFT; + var willHaveShift = (toModifierState & SHIFT) === SHIFT; + var didHaveAlt = (fromModifierState & ALT) === ALT; + var willHaveAlt = (toModifierState & ALT) === ALT; + var includeKeyUp = events & KeyEvents.UP; + var includeKeyDown = events & KeyEvents.DOWN; + if (includeKeyUp && didHaveMeta === true && willHaveMeta === false) { + // Release the meta key. + currentModifierState &= ~META; + target.dispatchEvent(this.createEventFromKeystroke('keyup', new Keystroke(currentModifierState, this._actionKeyCodeMap.META), target)); + } + if (includeKeyUp && didHaveCtrl === true && willHaveCtrl === false) { + // Release the ctrl key. + currentModifierState &= ~CTRL; + target.dispatchEvent(this.createEventFromKeystroke('keyup', new Keystroke(currentModifierState, this._actionKeyCodeMap.CTRL), target)); + } + if (includeKeyUp && didHaveShift === true && willHaveShift === false) { + // Release the shift key. + currentModifierState &= ~SHIFT; + target.dispatchEvent(this.createEventFromKeystroke('keyup', new Keystroke(currentModifierState, this._actionKeyCodeMap.SHIFT), target)); + } + if (includeKeyUp && didHaveAlt === true && willHaveAlt === false) { + // Release the alt key. + currentModifierState &= ~ALT; + target.dispatchEvent(this.createEventFromKeystroke('keyup', new Keystroke(currentModifierState, this._actionKeyCodeMap.ALT), target)); + } + if (includeKeyDown && didHaveMeta === false && willHaveMeta === true) { + // Press the meta key. + currentModifierState |= META; + target.dispatchEvent(this.createEventFromKeystroke('keydown', new Keystroke(currentModifierState, this._actionKeyCodeMap.META), target)); + } + if (includeKeyDown && didHaveCtrl === false && willHaveCtrl === true) { + // Press the ctrl key. + currentModifierState |= CTRL; + target.dispatchEvent(this.createEventFromKeystroke('keydown', new Keystroke(currentModifierState, this._actionKeyCodeMap.CTRL), target)); + } + if (includeKeyDown && didHaveShift === false && willHaveShift === true) { + // Press the shift key. + currentModifierState |= SHIFT; + target.dispatchEvent(this.createEventFromKeystroke('keydown', new Keystroke(currentModifierState, this._actionKeyCodeMap.SHIFT), target)); + } + if (includeKeyDown && didHaveAlt === false && willHaveAlt === true) { + // Press the alt key. + currentModifierState |= ALT; + target.dispatchEvent(this.createEventFromKeystroke('keydown', new Keystroke(currentModifierState, this._actionKeyCodeMap.ALT), target)); + } + if (currentModifierState !== toModifierState) { + throw new Error("internal error, expected modifier state: ".concat(toModifierState) + ", got: ".concat(currentModifierState)); + } + } + + /** + * Returns the keystroke associated with the given action. + * + * @param {string} action + * @return {?Keystroke} + */ + }, { + key: "keystrokeForAction", + value: function keystrokeForAction(action) { + var keyCode = null; + var modifiers = 0; + + // Note: when it comes to a single character as '+', + // should not take it as a key combiniation (no action.split) + var parts = action.length === 1 ? [action] : action.split('+'); + var lastPart = parts.pop(); + parts.forEach(function (part) { + switch (part.toUpperCase()) { + case 'CTRL': + modifiers |= CTRL; + break; + case 'META': + modifiers |= META; + break; + case 'ALT': + modifiers |= ALT; + break; + case 'SHIFT': + modifiers |= SHIFT; + break; + default: + console.error('parts', parts); + throw new Error("in \"".concat(action, "\", invalid modifier: ").concat(part)); + } + }); + if (lastPart.toUpperCase() in this._actionKeyCodeMap) { + keyCode = this._actionKeyCodeMap[lastPart.toUpperCase()]; + } else if (lastPart.length === 1) { + var lastPartKeystroke = this.keystrokeForCharCode(lastPart.charCodeAt(0)); + if (!lastPartKeystroke) return null; + modifiers |= lastPartKeystroke.modifiers; + keyCode = lastPartKeystroke.keyCode; + } else { + throw new Error("in \"".concat(action, "\", invalid action: ").concat(lastPart)); + } + return new Keystroke(modifiers, keyCode); + } + + /** + * Gets the keystroke used to generate the given character code. + * + * @param {number} charCode + * @return {?Keystroke} + */ + }, { + key: "keystrokeForCharCode", + value: function keystrokeForCharCode(charCode) { + return this._charCodeKeyCodeMap[charCode] || null; + } + + /** + * @param {EventTarget} target + * @private + */ + }, { + key: "targetCanReceiveTextInput", + value: function targetCanReceiveTextInput(target) { + if (!target) { + return false; + } + return (0, _domElementIsNativelyEditable["default"])(target); + } + }]); + return Keyboard; +}(); +var US_ENGLISH_CHARCODE_KEYCODE_MAP = { + 32: new Keystroke(0, 32), + // + 33: new Keystroke(SHIFT, 49), + // ! + 34: new Keystroke(SHIFT, 222), + // " + 35: new Keystroke(SHIFT, 51), + // # + 36: new Keystroke(SHIFT, 52), + // $ + 37: new Keystroke(SHIFT, 53), + // % + 38: new Keystroke(SHIFT, 55), + // & + 39: new Keystroke(0, 222), + // ' + 40: new Keystroke(SHIFT, 57), + // ( + 41: new Keystroke(SHIFT, 48), + // ) + 42: new Keystroke(SHIFT, 56), + // * + 43: new Keystroke(SHIFT, 187), + // + + 44: new Keystroke(0, 188), + // , + 45: new Keystroke(0, 189), + // - + 46: new Keystroke(0, 190), + // . + 47: new Keystroke(0, 191), + // / + 48: new Keystroke(0, 48), + // 0 + 49: new Keystroke(0, 49), + // 1 + 50: new Keystroke(0, 50), + // 2 + 51: new Keystroke(0, 51), + // 3 + 52: new Keystroke(0, 52), + // 4 + 53: new Keystroke(0, 53), + // 5 + 54: new Keystroke(0, 54), + // 6 + 55: new Keystroke(0, 55), + // 7 + 56: new Keystroke(0, 56), + // 8 + 57: new Keystroke(0, 57), + // 9 + 58: new Keystroke(SHIFT, 186), + // : + 59: new Keystroke(0, 186), + // ; + 60: new Keystroke(SHIFT, 188), + // < + 61: new Keystroke(0, 187), + // = + 62: new Keystroke(SHIFT, 190), + // > + 63: new Keystroke(SHIFT, 191), + // ? + 64: new Keystroke(SHIFT, 50), + // @ + 65: new Keystroke(SHIFT, 65), + // A + 66: new Keystroke(SHIFT, 66), + // B + 67: new Keystroke(SHIFT, 67), + // C + 68: new Keystroke(SHIFT, 68), + // D + 69: new Keystroke(SHIFT, 69), + // E + 70: new Keystroke(SHIFT, 70), + // F + 71: new Keystroke(SHIFT, 71), + // G + 72: new Keystroke(SHIFT, 72), + // H + 73: new Keystroke(SHIFT, 73), + // I + 74: new Keystroke(SHIFT, 74), + // J + 75: new Keystroke(SHIFT, 75), + // K + 76: new Keystroke(SHIFT, 76), + // L + 77: new Keystroke(SHIFT, 77), + // M + 78: new Keystroke(SHIFT, 78), + // N + 79: new Keystroke(SHIFT, 79), + // O + 80: new Keystroke(SHIFT, 80), + // P + 81: new Keystroke(SHIFT, 81), + // Q + 82: new Keystroke(SHIFT, 82), + // R + 83: new Keystroke(SHIFT, 83), + // S + 84: new Keystroke(SHIFT, 84), + // T + 85: new Keystroke(SHIFT, 85), + // U + 86: new Keystroke(SHIFT, 86), + // V + 87: new Keystroke(SHIFT, 87), + // W + 88: new Keystroke(SHIFT, 88), + // X + 89: new Keystroke(SHIFT, 89), + // Y + 90: new Keystroke(SHIFT, 90), + // Z + 91: new Keystroke(0, 219), + // [ + 92: new Keystroke(0, 220), + // \ + 93: new Keystroke(0, 221), + // ] + 94: new Keystroke(SHIFT, 54), + // ^ + 95: new Keystroke(SHIFT, 189), + // _ + 96: new Keystroke(0, 192), + // ` + 97: new Keystroke(0, 65), + // a + 98: new Keystroke(0, 66), + // b + 99: new Keystroke(0, 67), + // c + 100: new Keystroke(0, 68), + // d + 101: new Keystroke(0, 69), + // e + 102: new Keystroke(0, 70), + // f + 103: new Keystroke(0, 71), + // g + 104: new Keystroke(0, 72), + // h + 105: new Keystroke(0, 73), + // i + 106: new Keystroke(0, 74), + // j + 107: new Keystroke(0, 75), + // k + 108: new Keystroke(0, 76), + // l + 109: new Keystroke(0, 77), + // m + 110: new Keystroke(0, 78), + // n + 111: new Keystroke(0, 79), + // o + 112: new Keystroke(0, 80), + // p + 113: new Keystroke(0, 81), + // q + 114: new Keystroke(0, 82), + // r + 115: new Keystroke(0, 83), + // s + 116: new Keystroke(0, 84), + // t + 117: new Keystroke(0, 85), + // u + 118: new Keystroke(0, 86), + // v + 119: new Keystroke(0, 87), + // w + 120: new Keystroke(0, 88), + // x + 121: new Keystroke(0, 89), + // y + 122: new Keystroke(0, 90), + // z + 123: new Keystroke(SHIFT, 219), + // { + 124: new Keystroke(SHIFT, 220), + // | + 125: new Keystroke(SHIFT, 221), + // } + 126: new Keystroke(SHIFT, 192) // ~ +}; +var US_ENGLISH_ACTION_KEYCODE_MAP = { + BACKSPACE: 8, + TAB: 9, + ENTER: 13, + SHIFT: 16, + CTRL: 17, + ALT: 18, + PAUSE: 19, + CAPSLOCK: 20, + ESCAPE: 27, + PAGEUP: 33, + PAGEDOWN: 34, + END: 35, + HOME: 36, + LEFT: 37, + UP: 38, + RIGHT: 39, + DOWN: 40, + INSERT: 45, + DELETE: 46, + META: 91, + F1: 112, + F2: 113, + F3: 114, + F4: 115, + F5: 116, + F6: 117, + F7: 118, + F8: 119, + F9: 120, + F10: 121, + F11: 122, + F12: 123 +}; + +/** + * Gets a keyboard instance configured as a U.S. English keyboard would be. + * + * @return {Keyboard} + */ +Keyboard.US_ENGLISH = new Keyboard(US_ENGLISH_CHARCODE_KEYCODE_MAP, US_ENGLISH_ACTION_KEYCODE_MAP); + +/***/ }), + +/***/ 26513: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +Object.defineProperty(exports, "posix", ({ + enumerable: true, + get: function get() { + return _path.posix; + } +})); +Object.defineProperty(exports, "win32", ({ + enumerable: true, + get: function get() { + return _path.win32; + } +})); +var _path = __webpack_require__(43627); +var isWindows = /windows/i.test(self.navigator.userAgent); +var path = isWindows ? _path.win32 : _path.posix; +var _default = exports["default"] = path; + +/***/ }), + +/***/ 60414: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = sendKeys; +var Keysim = _interopRequireWildcard(__webpack_require__(62807)); +var _utils = __webpack_require__(46580); +var _log = _interopRequireDefault(__webpack_require__(89130)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +var keyboard = Keysim.Keyboard.US_ENGLISH; +var findParentByTag = function findParentByTag(el, tag) { + var p = el; + + // eslint-disable-next-line no-cond-assign + while (p = p.parentNode) { + if (p.tagName === tag.toUpperCase()) { + return p; + } + } + return null; +}; +var splitStringToChars = function splitStringToChars(str) { + var specialKeys = ['KEY_LEFT', 'KEY_UP', 'KEY_RIGHT', 'KEY_DOWN', 'KEY_PGUP', 'KEY_PAGE_UP', 'KEY_PGDN', 'KEY_PAGE_DOWN', 'KEY_BKSP', 'KEY_BACKSPACE', 'KEY_DEL', 'KEY_DELETE', 'KEY_ENTER', 'KEY_TAB']; + var reg = new RegExp("\\$\\{(".concat(specialKeys.join('|'), ")\\}")); + var parts = (0, _utils.splitKeep)(reg, str); + return parts.reduce(function (prev, cur) { + if (reg.test(cur)) { + prev.push(cur); + } else { + prev = prev.concat(cur.split('')); + } + return prev; + }, []); +}; +var getKeyStrokeAction = function getKeyStrokeAction(str) { + var reg = /^\$\{([^}]+)\}$/; + var match; + + // eslint-disable-next-line no-cond-assign + if (match = str.match(reg)) { + switch (match[1]) { + case 'KEY_LEFT': + return 'LEFT'; + case 'KEY_UP': + return 'UP'; + case 'KEY_RIGHT': + return 'RIGHT'; + case 'KEY_DOWN': + return 'DOWN'; + case 'KEY_PGUP': + case 'KEY_PAGE_UP': + return 'PAGEUP'; + case 'KEY_PGDN': + case 'KEY_PAGE_DOWN': + return 'PAGEDOWN'; + case 'KEY_BKSP': + case 'KEY_BACKSPACE': + return 'BACKSPACE'; + case 'KEY_DEL': + case 'KEY_DELETE': + return 'DELETE'; + case 'KEY_ENTER': + return 'ENTER'; + case 'KEY_TAB': + return 'TAB'; + } + } + return str; +}; +var isEditable = function isEditable(el) { + if (el.getAttribute('readonly') !== null) return false; + var tag = el.tagName.toUpperCase(); + var type = (el.type || '').toLowerCase(); + var editableTypes = ['text', 'search', 'tel', 'url', 'email', 'password', 'number']; + if (tag === 'TEXTAREA') return true; + if (tag === 'INPUT' && editableTypes.indexOf(type) !== -1) return true; + return false; +}; +var maybeEditText = function maybeEditText(target, c) { + if (!isEditable(target)) return; + if (c.length === 1) { + if (!isNil(target.selectionStart)) { + var lastStart = target.selectionStart; + target.value = target.value.substring(0, target.selectionStart) + c + target.value.substring(target.selectionEnd); + setSelection(target, lastStart + 1); + } else { + target.value = target.value + c; + } + } else { + switch (c) { + case 'ENTER': + target.value = target.value + '\n'; + setSelection(target, target.value.length); + break; + case 'TAB': + target.value = target.value + '\t'; + setSelection(target, target.value.length); + break; + case 'LEFT': + setSelection(target, target.selectionStart - 1); + break; + case 'RIGHT': + setSelection(target, target.selectionEnd + 1); + break; + case 'BACKSPACE': + { + var pos = target.selectionStart; + target.value = target.value.substring(0, target.selectionStart - 1) + target.value.substring(target.selectionEnd); + setSelection(target, pos - 1); + break; + } + case 'DELETE': + { + var _pos = target.selectionEnd; + target.value = target.value.substring(0, target.selectionStart) + target.value.substring(target.selectionEnd + 1); + setSelection(target, _pos); + break; + } + } + } +}; +var maybeSubmitForm = function maybeSubmitForm(target, key) { + if (key !== 'ENTER') return; + if (!isEditable(target)) return; + var form = findParentByTag(target, 'FORM'); + if (!form) return; + form.submit(); +}; +var isNil = function isNil(val) { + return val === null || val === undefined; +}; +var setSelection = function setSelection($el, start, end) { + // Note: Inputs like number and email, doesn't support selectionEnd + // for safety, make sure those values are not null or undefined (infers that it's available) + if (!isNil($el.selectionStart)) { + $el.selectionStart = start; + } + if (!isNil($el.selectionEnd)) { + $el.selectionEnd = end !== undefined ? end : start; + } +}; +var replaceActionKey = function () { + var mapping = { + 0: null, + // the NULL character + 8: 'BACKSPACE', + 9: 'TAB', + 10: 'ENTER', + // \n new line + 11: null, + // \v vertical tab + 12: null, + // \f form feed + 13: null // \r carriage return + }; + return function (c) { + // Note: it means it's already key stroke action + if (c.length > 1) return c; + return mapping[c.charCodeAt(0)] || c; + }; +}(); +function sendKeys(target, str, noSpecialKeys) { + var rawChars = noSpecialKeys ? str.split('') : splitStringToChars(str); + var chars = rawChars.map(replaceActionKey).filter(function (x) { + return x && x.length; + }); + target.focus(); + if (target.value) { + setSelection(target, target.value.length); + } + chars.forEach(function (c) { + var action = getKeyStrokeAction(c); + maybeEditText(target, action); + // Note: This line will take care of KEYDOWN KEYPRESS KEYUP and TEXTINPUT + keyboard.dispatchEventsForAction(action, target); + if (!noSpecialKeys) { + maybeSubmitForm(target, action); + } + }); +} + +/***/ }), + +/***/ 41334: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _web_extension = _interopRequireDefault(__webpack_require__(41953)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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), !0).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; } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +var local = _web_extension["default"].storage.local; +var _default = exports["default"] = { + get: function get(key) { + return local.get(key).then(function (obj) { + return obj[key]; + }); + }, + set: function set(key, value) { + return local.set(_defineProperty({}, key, value)).then(function () { + return true; + }); + }, + remove: function remove(key) { + return local.remove(key).then(function () { + return true; + }); + }, + clear: function clear() { + return local.clear().then(function () { + return true; + }); + }, + addListener: function addListener(fn) { + _web_extension["default"].storage.onChanged.addListener(function (changes, areaName) { + var list = Object.keys(changes).map(function (key) { + return _objectSpread(_objectSpread({}, changes[key]), {}, { + key: key + }); + }); + fn(list); + }); + } +}; + +/***/ }), + +/***/ 88555: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _ext_storage = _interopRequireDefault(__webpack_require__(41334)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +var _default = exports["default"] = _ext_storage["default"]; + +/***/ }), + +/***/ 46580: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.and = void 0; +exports.arrayBufferToString = arrayBufferToString; +exports.bindOnce = exports.bind = void 0; +exports.blobToDataURL = blobToDataURL; +exports.blobToText = blobToText; +exports.composePromiseFn = exports.compose = exports.cn = exports.cloneSerializableLocalStorage = void 0; +exports.dataURItoArrayBuffer = dataURItoArrayBuffer; +exports.dataURItoBlob = dataURItoBlob; +exports.splitKeep = exports.splitIntoTwo = exports.setIn = exports.sanitizeFileName = exports.retry = exports.reduceRight = exports.range = exports.randomName = exports.pick = exports.partial = exports.parseQuery = exports.on = exports.objMap = exports.nameFactory = exports.mockAPIWith = exports.map = exports.loadImage = exports.loadCsv = exports.isSidePanelWindowAsync = exports.isSidePanelWindow = exports.insertScript = exports.getPageDpi = exports.getIn = exports.formatDate = exports.flatten = exports.ensureExtName = exports.dpiFromFileName = exports.delayMs = exports.delay = void 0; +exports.stringToArrayBuffer = stringToArrayBuffer; +exports.withTimeout = exports.withFileExtension = exports.waitForRenderComplete = exports.validateStandardName = exports.updateIn = exports.until = exports.uniqueName = exports.uid = exports.toRegExp = exports.subjectiveBindOnce = void 0; +var _lodash = _interopRequireDefault(__webpack_require__(20181)); +var _web_extension = _interopRequireDefault(__webpack_require__(41953)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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), !0).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; } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +// delay the call of a function and return a promise +var delay = exports.delay = function delay(fn, timeout) { + return new Promise(function (resolve, reject) { + setTimeout(function () { + try { + resolve(fn()); + } catch (e) { + reject(e); + } + }, timeout); + }); +}; + +// Poll on whatever you want to check, and will time out after a specific duration +// `check` should return `{ pass: Boolean, result: Any }` +// `name` is for a meaningful error message +var until = exports.until = function until(name, check) { + var interval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1000; + var expire = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 10000; + var errorMsg = arguments.length > 4 ? arguments[4] : undefined; + var start = new Date(); + var go = function go() { + if (expire && new Date() - start >= expire) { + var msg = errorMsg || "until: ".concat(name, " expired!"); + throw new Error(msg); + } + var _check = check(), + pass = _check.pass, + result = _check.result; + if (pass) return Promise.resolve(result); + return delay(go, interval); + }; + return new Promise(function (resolve, reject) { + try { + resolve(go()); + } catch (e) { + reject(e); + } + }); +}; +var range = exports.range = function range(start, end) { + var step = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var ret = []; + for (var i = start; i < end; i += step) { + ret.push(i); + } + return ret; +}; + +// create a curry version of the passed in function +var partial = exports.partial = function partial(fn) { + var len = fn.length; + var _arbitary; + _arbitary = function arbitary(curArgs, leftArgCnt) { + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (args.length >= leftArgCnt) { + return fn.apply(null, curArgs.concat(args)); + } + return _arbitary(curArgs.concat(args), leftArgCnt - args.length); + }; + }; + return _arbitary([], len); +}; +var reduceRight = exports.reduceRight = function reduceRight(fn, initial, list) { + var ret = initial; + for (var i = list.length - 1; i >= 0; i--) { + ret = fn(list[i], ret); + } + return ret; +}; + +// compose functions into one +var compose = exports.compose = function compose() { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + return reduceRight(function (cur, prev) { + return function (x) { + return cur(prev(x)); + }; + }, function (x) { + return x; + }, args); +}; +var map = exports.map = partial(function (fn, list) { + var result = []; + for (var i = 0, len = list.length; i < len; i++) { + result.push(fn(list[i])); + } + return result; +}); +var on = exports.on = partial(function (key, fn, dict) { + if (Array.isArray(dict)) { + return [].concat(_toConsumableArray(dict.slice(0, key)), [fn(dict[key])], _toConsumableArray(dict.slice(key + 1))); + } + return Object.assign({}, dict, _defineProperty({}, key, fn(dict[key]))); +}); + +// immutably update any part in an object +var updateIn = exports.updateIn = partial(function (keys, fn, obj) { + var updater = compose.apply(null, keys.map(function (key) { + return key === '[]' ? map : on(key); + })); + return updater(fn)(obj); +}); + +// immutably set any part in an object +// a restricted version of updateIn +var setIn = exports.setIn = partial(function (keys, value, obj) { + var updater = compose.apply(null, keys.map(function (key) { + return key === '[]' ? map : on(key); + })); + return updater(function () { + return value; + })(obj); +}); + +// return part of the object with a few keys deep inside +var getIn = exports.getIn = partial(function (keys, obj) { + return keys.reduce(function (prev, key) { + if (!prev) return prev; + return prev[key]; + }, obj); +}); + +// return the passed in object with only certains keys +var pick = exports.pick = function pick(keys, obj) { + return keys.reduce(function (prev, key) { + if (obj[key] !== undefined) { + prev[key] = obj[key]; + } + return prev; + }, {}); +}; +var uid = exports.uid = function uid() { + return '' + new Date() * 1 + '.' + Math.floor(Math.random() * 10000000).toString(16); +}; +var flatten = exports.flatten = function flatten(list) { + return [].concat.apply([], list); +}; +var splitIntoTwo = exports.splitIntoTwo = function splitIntoTwo(pattern, str) { + var index = str.indexOf(pattern); + if (index === -1) return [str]; + return [str.substr(0, index), str.substr(index + 1)]; +}; +var cn = exports.cn = function cn() { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + return args.reduce(function (prev, cur) { + if (typeof cur === 'string') { + prev.push(cur); + } else { + Object.keys(cur).forEach(function (key) { + if (cur[key]) { + prev.push(key); + } + }); + } + return prev; + }, []).join(' '); +}; +var objMap = exports.objMap = function objMap(fn, obj) { + return Object.keys(obj).reduce(function (prev, key, i) { + prev[key] = fn(obj[key], key, i); + return prev; + }, {}); +}; +var formatDate = exports.formatDate = function formatDate(d) { + var pad = function pad(n) { + return n >= 10 ? '' + n : '0' + n; + }; + return [d.getFullYear(), d.getMonth() + 1, d.getDate()].map(pad).join('-'); +}; +var splitKeep = exports.splitKeep = function splitKeep(pattern, str) { + var result = []; + var startIndex = 0; + var reg, match, lastMatchIndex; + if (pattern instanceof RegExp) { + reg = new RegExp(pattern, pattern.flags.indexOf('g') !== -1 ? pattern.flags : pattern.flags + 'g'); + } else if (typeof pattern === 'string') { + reg = new RegExp(pattern, 'g'); + } + + // eslint-disable-next-line no-cond-assign + while (match = reg.exec(str)) { + if (lastMatchIndex === match.index) { + break; + } + if (match.index > startIndex) { + result.push(str.substring(startIndex, match.index)); + } + result.push(match[0]); + startIndex = match.index + match[0].length; + lastMatchIndex = match.index; + } + if (startIndex < str.length) { + result.push(str.substr(startIndex)); + } + return result; +}; +var nameFactory = exports.nameFactory = function nameFactory() { + var all = {}; + return function (str) { + if (!all[str]) { + all[str] = true; + return str; + } + var n = 2; + while (all[str + '-' + n]) { + n++; + } + all[str + '-' + n] = true; + return str + '-' + n; + }; +}; +var composePromiseFn = exports.composePromiseFn = function composePromiseFn() { + for (var _len4 = arguments.length, list = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + list[_key4] = arguments[_key4]; + } + return reduceRight(function (cur, prev) { + return function (x) { + return prev(x).then(cur); + }; + }, function (x) { + return Promise.resolve(x); + }, list); +}; +var parseQuery = exports.parseQuery = function parseQuery(query) { + return query.slice(1).split('&').reduce(function (prev, cur) { + var index = cur.indexOf('='); + var key = cur.substring(0, index); + var val = cur.substring(index + 1); + prev[key] = decodeURIComponent(val); + return prev; + }, {}); +}; +var toRegExp = exports.toRegExp = function toRegExp(str) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$needEncode = _ref.needEncode, + needEncode = _ref$needEncode === void 0 ? false : _ref$needEncode, + _ref$flag = _ref.flag, + flag = _ref$flag === void 0 ? '' : _ref$flag; + return new RegExp(needEncode ? str.replace(/[[\](){}^$.*+?|]/g, '\\$&') : str, flag); +}; +var insertScript = exports.insertScript = function insertScript(file) { + var s = document.constructor.prototype.createElement.call(document, 'script'); + s.setAttribute('type', 'text/javascript'); + s.setAttribute('src', file); + document.documentElement.appendChild(s); + s.parentNode.removeChild(s); +}; +var withTimeout = exports.withTimeout = function withTimeout(timeout, fn) { + return new Promise(function (resolve, reject) { + var cancel = function cancel() { + return clearTimeout(timer); + }; + var timer = setTimeout(function () { + reject(new Error('timeout')); + }, timeout); + Promise.resolve(fn(cancel)).then(function (data) { + cancel(); + resolve(data); + }, function (e) { + cancel(); + reject(e); + }); + }); +}; +var retry = exports.retry = function retry(fn, options) { + return function () { + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + var _timeout$retryInterva = _objectSpread({ + timeout: 5000, + retryInterval: 1000, + onFirstFail: function onFirstFail() {}, + onFinal: function onFinal() {}, + shouldRetry: function shouldRetry() { + return false; + } + }, options), + timeout = _timeout$retryInterva.timeout, + onFirstFail = _timeout$retryInterva.onFirstFail, + onFinal = _timeout$retryInterva.onFinal, + shouldRetry = _timeout$retryInterva.shouldRetry, + retryInterval = _timeout$retryInterva.retryInterval; + var retryCount = 0; + var lastError = null; + var timerToClear = null; + var done = false; + var wrappedOnFinal = function wrappedOnFinal() { + done = true; + if (timerToClear) { + clearTimeout(timerToClear); + } + return onFinal.apply(void 0, arguments); + }; + var intervalMan = function () { + var lastInterval = null; + var intervalFactory = function () { + switch (_typeof(retryInterval)) { + case 'function': + return retryInterval; + case 'number': + return function () { + return retryInterval; + }; + default: + throw new Error('retryInterval must be either a number or a function'); + } + }(); + return { + getLastInterval: function getLastInterval() { + return lastInterval; + }, + getInterval: function getInterval() { + var interval = intervalFactory(retryCount, lastInterval); + lastInterval = interval; + return interval; + } + }; + }(); + var onError = function onError(e, reject) { + if (!shouldRetry(e, retryCount)) { + wrappedOnFinal(e); + if (reject) return reject(e);else throw e; + } + lastError = e; + return new Promise(function (resolve, reject) { + if (retryCount++ === 0) { + onFirstFail(e); + timerToClear = setTimeout(function () { + wrappedOnFinal(lastError); + reject(lastError); + }, timeout); + } + if (done) return; + delay(run, intervalMan.getInterval()).then(resolve, function (e) { + return onError(e, reject); + }); + }); + }; + var run = function run() { + return new Promise(function (resolve) { + resolve(fn.apply(void 0, args.concat([{ + retryCount: retryCount, + retryInterval: intervalMan.getLastInterval() + }]))); + })["catch"](onError); + }; + return run().then(function (result) { + wrappedOnFinal(null, result); + return result; + }); + }; +}; + +// refer to https://stackoverflow.com/questions/12168909/blob-from-dataurl +function dataURItoArrayBuffer(dataURI) { + // convert base64 to raw binary data held in a string + // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this + var byteString = atob(/^data:/.test(dataURI) ? dataURI.split(',')[1] : dataURI); + + // write the bytes of the string to an ArrayBuffer + var ab = new ArrayBuffer(byteString.length); + + // create a view into the buffer + var ia = new Uint8Array(ab); + + // set the bytes of the buffer to the correct values + for (var i = 0; i < byteString.length; i++) { + ia[i] = byteString.charCodeAt(i); + } + return ab; +} +function dataURItoBlob(dataURI) { + var ab = dataURItoArrayBuffer(dataURI); + // separate out the mime component + var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; + // write the ArrayBuffer to a blob, and you're done + var blob = new Blob([ab], { + type: mimeString + }); + return blob; +} +function blobToDataURL(blob) { + var withBase64Prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.onerror = reject; + reader.onload = function (e) { + var str = reader.result; + if (withBase64Prefix) return resolve(str); + var b64 = 'base64,'; + var i = str.indexOf(b64); + var ret = str.substr(i + b64.length); + resolve(ret); + }; + reader.readAsDataURL(blob); + }); +} +function blobToText(blob) { + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.onerror = reject; + reader.onload = function (e) { + var str = reader.result; + resolve(str); + }; + reader.readAsText(blob); + }); +} +function arrayBufferToString(buf) { + var decoder = new TextDecoder('utf-8'); + return decoder.decode(new Uint8Array(buf)); + // return String.fromCharCode.apply(null, new Uint16Array(buf)) +} +function stringToArrayBuffer(str) { + var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char + var bufView = new Uint16Array(buf); + for (var i = 0, strLen = str.length; i < strLen; i++) { + bufView[i] = str.charCodeAt(i); + } + return buf; +} +var randomName = exports.randomName = function randomName() { + var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 6; + if (length <= 0 || length > 100) throw new Error('randomName, length must be between 1 and 100'); + var randomChar = function randomChar() { + var n = Math.floor(62 * Math.random()); + var code; + if (n <= 9) { + code = 48 + n; + } else if (n <= 35) { + code = 65 + n - 10; + } else { + code = 97 + n - 36; + } + return String.fromCharCode(code); + }; + return range(0, length).map(randomChar).join('').toLowerCase(); +}; +var withFileExtension = exports.withFileExtension = function withFileExtension(origName, fn) { + var reg = /\.\w+$/; + var m = origName.match(reg); + var extName = m ? m[0] : ''; + var baseName = m ? origName.replace(reg, '') : origName; + var result = fn(baseName, function (name) { + return name + extName; + }); + if (!result) { + throw new Error('withFileExtension: should not return null/undefined'); + } + if (typeof result.then === 'function') { + return result.then(function (name) { + return name + extName; + }); + } + return result + extName; +}; +var uniqueName = exports.uniqueName = function uniqueName(name, options) { + var opts = _objectSpread({ + generate: function generate(old) { + var step = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + var reg = /_\((\d+)\)$/; + var m = old.match(reg); + if (!m) return "".concat(old, "_(").concat(step, ")"); + return old.replace(reg, function (_, n) { + return "_(".concat(parseInt(n, 10) + step, ")"); + }); + }, + check: function check() { + return Promise.resolve(true); + } + }, options || {}); + var generate = opts.generate, + check = opts.check; + return withFileExtension(name, function (baseName, getFullName) { + var go = function go(fileName, step) { + return check(getFullName(fileName)).then(function (pass) { + if (pass) return fileName; + return go(generate(fileName, step), step); + }); + }; + return go(baseName, 1); + }); +}; +var and = exports.and = function and() { + for (var _len6 = arguments.length, list = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + list[_key6] = arguments[_key6]; + } + return list.reduce(function (prev, cur) { + return prev && cur; + }, true); +}; +var loadCsv = exports.loadCsv = function loadCsv(url) { + return fetch(url).then(function (res) { + if (!res.ok) throw new Error("failed to load csv - ".concat(url)); + return res.text(); + }); +}; +var loadImage = exports.loadImage = function loadImage(url) { + return fetch(url).then(function (res) { + if (!res.ok) throw new Error("failed to load image - ".concat(url)); + return res.blob(); + }); +}; +var ensureExtName = exports.ensureExtName = function ensureExtName(ext, name) { + var extName = ext.indexOf('.') === 0 ? ext : '.' + ext; + if (name.lastIndexOf(extName) + extName.length === name.length) return name; + return name + extName; +}; +var validateStandardName = exports.validateStandardName = function validateStandardName(name, isFileName) { + if (!isFileName && !/^_|[a-zA-Z]/.test(name)) { + throw new Error("must start with a letter or the underscore character."); + } + if (isFileName && !/^_|[a-zA-Z0-9]/.test(name)) { + throw new Error("must start with alpha-numeric or the underscore character."); + } + if (!/^[a-zA-Z0-9_]+$/.test(name)) { + throw new Error("can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )"); + } +}; +var sanitizeFileName = exports.sanitizeFileName = function sanitizeFileName(fileName) { + return withFileExtension(fileName, function (baseName) { + return baseName.trim().replace(/[\\/:*?"<>|]/g, '_'); + }); +}; +var getPageDpi = exports.getPageDpi = function getPageDpi() { + var DEFAULT_DPI = 96; + var matchDpi = function matchDpi(dpi) { + return window.matchMedia("(max-resolution: ".concat(dpi, "dpi)")).matches === true; + }; + + // We iteratively scan all possible media query matches. + // We can't use binary search, because there are "many" correct answer in + // problem space and we need the very first match. + // To speed up computation we divide problem space into buckets. + // We test each bucket's first element and if we found a match, + // we make a full scan for previous bucket with including first match. + // Still, we could use "divide-and-conquer" for such problems. + // Due to common DPI values, it's not worth to implement such algorithm. + + var bucketSize = 24; // common divisor for 72, 96, 120, 144 etc. + + for (var i = bucketSize; i < 3000; i += bucketSize) { + if (matchDpi(i)) { + var start = i - bucketSize; + var end = i; + for (var k = start; k <= end; ++k) { + if (matchDpi(k)) { + return k; + } + } + } + } + return DEFAULT_DPI; // default fallback +}; +var dpiFromFileName = exports.dpiFromFileName = function dpiFromFileName(fileName) { + var reg = /_dpi_(\d+)/i; + var m = fileName.match(reg); + return m ? parseInt(m[1], 10) : 0; +}; +var mockAPIWith = exports.mockAPIWith = function mockAPIWith(factory, mock) { + var promiseFunctionKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + var real = mock; + var exported = objMap(function (val, key) { + if (typeof val === 'function') { + if (promiseFunctionKeys.indexOf(key) !== -1) { + return function () { + for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { + args[_key7] = arguments[_key7]; + } + return p.then(function () { + var _real; + return (_real = real)[key].apply(_real, args); + }); + }; + } else { + return function () { + var _real3; + for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { + args[_key8] = arguments[_key8]; + } + p.then(function () { + var _real2; + return (_real2 = real)[key].apply(_real2, args); + }); + return (_real3 = real)[key].apply(_real3, args); + }; + } + } else { + return val; + } + }, mock); + var p = Promise.resolve(factory()).then(function (api) { + real = api; + }); + return exported; +}; +var bindOnce = exports.bindOnce = function bindOnce(target, eventName, fn) { + for (var _len9 = arguments.length, rest = new Array(_len9 > 3 ? _len9 - 3 : 0), _key9 = 3; _key9 < _len9; _key9++) { + rest[_key9 - 3] = arguments[_key9]; + } + var wrapped = function wrapped() { + try { + target.removeEventListener.apply(target, [eventName, wrapped].concat(rest)); + } catch (e) {} + return fn.apply(void 0, arguments); + }; + target.addEventListener.apply(target, [eventName, wrapped].concat(rest)); +}; +var subjectiveBindOnce = exports.subjectiveBindOnce = function subjectiveBindOnce(target, eventName, fn) { + for (var _len10 = arguments.length, rest = new Array(_len10 > 3 ? _len10 - 3 : 0), _key10 = 3; _key10 < _len10; _key10++) { + rest[_key10 - 3] = arguments[_key10]; + } + var wrapped = function wrapped() { + try { + var _ref2; + if ((_ref2 = arguments.length <= 0 ? undefined : arguments[0]) !== null && _ref2 !== void 0 && (_ref2 = _ref2.detail) !== null && _ref2 !== void 0 && _ref2.json) { + // don't remove the event listener, because, + // it's probably coming from embedded Ui.Vision macros. https://ui.vision/demo/runweb + } else { + target.removeEventListener.apply(target, [eventName, wrapped].concat(rest)); + } + } catch (e) {} + return fn.apply(void 0, arguments); + }; + target.addEventListener.apply(target, [eventName, wrapped].concat(rest)); +}; +var bind = exports.bind = function bind(target, eventName, fn) { + for (var _len11 = arguments.length, rest = new Array(_len11 > 3 ? _len11 - 3 : 0), _key11 = 3; _key11 < _len11; _key11++) { + rest[_key11 - 3] = arguments[_key11]; + } + target.addEventListener.apply(target, [eventName, fn].concat(rest)); +}; +var isSidePanelWindowAsync = exports.isSidePanelWindowAsync = function isSidePanelWindowAsync(win) { + if (!win) return Promise.resolve(false); + return new Promise(function (resolve) { + var isSidePanel_ = win.location.href.startsWith("chrome-extension://".concat(_web_extension["default"].runtime.id, "/sidepanel.html")) || win.location.href.match(/moz-extension:\/\/[a-z0-9-]+\/sidepanel.html/); + console.log('isSidePanelWindowAsync:>>', isSidePanel_); + resolve(isSidePanel_); + }); +}; + +// export const isSidePanelWindow = () => window && window?.location?.href?.includes('sidepanel.html') +var isSidePanelWindow = exports.isSidePanelWindow = function isSidePanelWindow() { + if (typeof window !== 'undefined') { + return window.location.href.includes('sidepanel.html'); + } else { + // running inside service worker + return false; + } +}; +var waitForRenderComplete = exports.waitForRenderComplete = function waitForRenderComplete() { + var parentSelector = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var debounceInterval = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200; + var debounceResolve = (0, _lodash["default"])(function (resolve) { + resolve(); + }, debounceInterval); + return new Promise(function (resolve, reject) { + var parentElement = parentSelector && document.querySelector(parentSelector) || document.body; + if (!parentElement) { + console.error('waitForRenderComplete: parentElement not found with selector:', parentSelector); + reject(new Error('Rendering element not found.')); + } + var observer = new MutationObserver(function (mutations) { + mutations.forEach(function (mutation) { + if (mutation.addedNodes.length > 0) { + // console.log('waitForRenderComplete...'); + debounceResolve(resolve); + } + }); + }); + observer.observe(parentElement, { + childList: true + }); + debounceResolve(resolve); + }); +}; +var delayMs = exports.delayMs = function delayMs(ms) { + return new Promise(function (resolve) { + setTimeout(function () { + resolve(); + }, ms); + }); +}; +var cloneSerializableLocalStorage = exports.cloneSerializableLocalStorage = function cloneSerializableLocalStorage(localStorage) { + var clonedData = {}; + for (var i = 0; i < localStorage.length; i++) { + var key = localStorage.key(i); + try { + // Attempt to stringify and store in cloned object + clonedData[key] = localStorage.getItem(key); + } catch (error) { + // Skip non-serializable values + console.warn("Skipping non-serializable item from localStorage: ".concat(key)); + } + } + return clonedData; +}; + +/***/ }), + +/***/ 41953: +/***/ ((module) => { + +"use strict"; + + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +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."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +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; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +/* global chrome browser */ + +// Note: it's an adapter for both chrome and web extension API +// chrome and web extension API have almost the same API signatures +// except that chrome accepts callback while web extension returns promises +// +// The whole idea here is to make sure all callback style API of chrome +// also return promises +// +// Important: You need to specify whatever API you need to use in `UsedAPI` below + +(function () { + var isDevelopment = "production" !== 'production'; + var adaptChrome = function adaptChrome(obj, chrome) { + var adapt = function adapt(src, ret, obj, fn) { + return Object.keys(obj).reduce(function (prev, key) { + var keyParts = key.split('.'); + var _keyParts$reduce = keyParts.reduce(function (tuple, subkey) { + var tar = tuple[0]; + var src = tuple[1]; + tar[subkey] = tar[subkey] || {}; + return [tar[subkey], src && src[subkey]]; + }, [prev, src]), + _keyParts$reduce2 = _slicedToArray(_keyParts$reduce, 2), + target = _keyParts$reduce2[0], + source = _keyParts$reduce2[1]; + obj[key].forEach(function (method) { + fn(method, source, target, isDevelopment); + }); + return prev; + }, ret); + }; + var promisify = function promisify(method, source, target, isDevelopment) { + if (!source) return; + // array of error messages that should not be shown + var ignoredErrors = [/The message port closed before a res?ponse was received/, /Extension context invalidated/, /Could not establish connection. Receiving end does not exist/]; + target[method] = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return new Promise(function (resolve, reject) { + var callback = function callback(result) { + if (chrome.runtime.lastError) { + if (ignoredErrors.some(function (error) { + return error.test(chrome.runtime.lastError.message); + })) { + // don't show the error + // console.error(`#31 never-show ${chrome.runtime.lastError.message}, ${method}, ${JSON.stringify(args)}`) + } else { + if (isDevelopment) { + // #31 show in development only + console.error("".concat(chrome.runtime.lastError.message, ", ").concat(method, ", ").concat(JSON.stringify(args))); + } + return reject(chrome.runtime.lastError); + } + } + resolve(result); + }; + source[method].apply(source, args.concat(callback)); + }); + }; + }; + var copy = function copy(method, source, target) { + if (!source) return; + target[method] = source[method]; + }; + return [[obj.toPromisify, promisify], [obj.toCopy, copy]].reduce(function (prev, tuple) { + return adapt(chrome, prev, tuple[0], tuple[1]); + }, {}); + }; + var UsedAPI = { + toPromisify: { + tabs: ['create', 'sendMessage', 'get', 'update', 'query', 'captureVisibleTab', 'remove', 'getZoom'], + windows: ['update', 'getLastFocused', 'getCurrent', 'getAll', 'remove', 'create', 'get'], + runtime: ['sendMessage', 'setUninstallURL'], + cookies: ['get', 'getAll', 'set', 'remove'], + notifications: ['create', 'clear'], + action: ['getBadgeText', 'setIcon'], + bookmarks: ['create', 'getTree'], + "debugger": ['attach', 'detach', 'sendCommand', 'getTargets'], + downloads: ['search', 'setUiOptions'], + extension: ['isAllowedFileSchemeAccess'], + contextMenus: ['create', 'update', 'remove', 'removeAll'], + 'storage.local': ['get', 'set'], + scripting: ['executeScript'], + permissions: ['request', 'contains'] + }, + toCopy: { + tabs: ['onActivated', 'onUpdated', 'onRemoved'], + windows: ['onFocusChanged'], + runtime: ['onMessage', 'onInstalled', 'getManifest', 'getURL', 'onStartup', 'getPlatformInfo', 'onConnect', 'id'], + storage: ['onChanged'], + action: ['setBadgeText', 'setBadgeBackgroundColor', 'onClicked'], + contextMenus: ['onClicked'], + extension: ['getURL'], + "debugger": ['onEvent', 'onDetach'], + downloads: ['onCreated', 'onChanged', 'onDeterminingFilename'], + webRequest: ['onAuthRequired'], + sidePanel: ['setOptions', 'open'], + sidebarAction: ['open', 'close', 'toggle'] + } + }; + var Ext = typeof chrome !== 'undefined' ? adaptChrome(UsedAPI, chrome) : browser; + Object.assign(Ext, { + isFirefox: function isFirefox() { + return /Firefox/.test(self.navigator.userAgent); + } + }); + if (true) { + module.exports = Ext; + } else {} +})(); + +/***/ }), + +/***/ 31897: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.run = exports.getFrameByLocator = exports.getElementByLocatorWithTargetOptions = void 0; +var _domElementIsNativelyEditable = _interopRequireDefault(__webpack_require__(69423)); +var _kdGlobToRegexp = _interopRequireDefault(__webpack_require__(44191)); +var _glob = __webpack_require__(42143); +var _utils = __webpack_require__(46580); +var _dom_utils = __webpack_require__(92950); +var _ts_utils = __webpack_require__(1601); +var _cs_postmessage = __webpack_require__(50366); +var _web_extension = _interopRequireDefault(__webpack_require__(41953)); +var _log = _interopRequireDefault(__webpack_require__(89130)); +var _drag_mock = _interopRequireDefault(__webpack_require__(63747)); +var _send_keys = _interopRequireDefault(__webpack_require__(60414)); +var _encrypt = __webpack_require__(21208); +var _constant = __webpack_require__(95902); +var _eval = __webpack_require__(20652); +var _config = _interopRequireDefault(__webpack_require__(8747)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +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."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +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; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +var HIGHLIGHT_TIMEOUT = 500; + +// reference: https://github.com/timoxley/offset +var viewportOffset = function viewportOffset(el) { + var box = el.getBoundingClientRect(); + + // Note: simply use bouddingClientRect since elementFromPoint uses + // the same top/left relative to the current viewport/window instead of whole document + return { + top: box.top, + left: box.left + }; +}; +var getIframeViewportOffset = function getIframeViewportOffset() { + if (window === window.top) { + return Promise.resolve({ + x: 0, + y: 0 + }); + } + return (0, _cs_postmessage.postMessage)(window.parent, window, { + action: 'SOURCE_VIEWPORT_OFFSET', + data: {} + }); +}; +var focusIfEditable = function focusIfEditable($el) { + if ((0, _domElementIsNativelyEditable["default"])($el) && typeof $el.focus === 'function') { + $el.focus(); + } +}; + +// We now save targetOptions in command, if main target can't be found (extra?.retryInfo.final === true), +// it should try all targetOptions just for once +var getElementByLocatorWithTargetOptions = exports.getElementByLocatorWithTargetOptions = function getElementByLocatorWithTargetOptions(locator, shouldWaitForVisible, command, csIpc) { + var _ref = command || {}, + extra = _ref.extra, + targetOptions = _ref.targetOptions; + if (extra && extra.retryInfo && extra.retryInfo["final"] && targetOptions && targetOptions.length) { + for (var i = 0, len = targetOptions.length; i < len; i++) { + var target = targetOptions[i]; + try { + var el = (0, _dom_utils.getElementByLocator)(target, shouldWaitForVisible); + csIpc.ask('CS_ADD_LOG', { + warning: "Element found with secondary locator \"".concat(target, "\". To use it by default, update the target field to use it as primary locator.") + }); + return el; + } catch (e) { + if (i === len - 1) { + throw e; + } + } + } + } + return (0, _dom_utils.getElementByLocator)(locator, shouldWaitForVisible); +}; +var getFrameByLocator = exports.getFrameByLocator = function getFrameByLocator(str, helpers) { + var i = str.indexOf('='); + + // Note: try to parse format of 'index=0' and 'relative=top/parent' + if (i !== -1) { + var method = str.substr(0, i); + var value = str.substr(i + 1); + switch (method) { + case 'index': + { + var index = parseInt(value, 10); + var frames = window.frames; + var frame = frames[index]; + if (!frame) { + throw new Error("Frame index out of range (index ".concat(value, " in ").concat(frames.length, " frames")); + } + return { + frame: frame + }; + } + case 'relative': + { + if (value === 'top') { + return { + frame: window.top + }; + } + if (value === 'parent') { + return { + frame: window.parent + }; + } + throw new Error('Unsupported relative type, ' + value); + } + } + } + + // Note: consider it as name, if no '=' found and it has no xpath pattern + if (i === -1 && !/^\/.*/.test(str)) { + str = 'name=' + str; + } + var frameDom = (0, _dom_utils.getElementByLocator)(str); + if (!frameDom || !frameDom.contentWindow) { + throw new Error("The element found based on ".concat(str, " is NOT a frame/iframe")); + } + + // Note: for those iframe/frame that don't have src, they won't load content_script.js + // so we have to inject the script by ourselves + if (!frameDom.getAttribute('src')) { + var file = _web_extension["default"].runtime.getURL('content_script.js'); + var doc = frameDom.contentDocument; + var s = doc.constructor.prototype.createElement.call(doc, 'script'); + s.setAttribute('type', 'text/javascript'); + s.setAttribute('src', file); + doc.documentElement.appendChild(s); + s.parentNode.removeChild(s); + helpers.hackAlertConfirmPrompt(doc); + } + + // Note: can't return the contentWindow directly, because Promise 'resolve' will + // try to test its '.then' method, which will cause a cross origin violation + // so, we wrap it in an object + return { + frame: frameDom.contentWindow + }; +}; +var run = exports.run = function run(command, csIpc, helpers) { + var cmd = command.cmd, + target = command.target, + value = command.value, + extra = command.extra; + var wrap = function wrap(fn, genOptions) { + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + var options = genOptions.apply(void 0, args); + return new Promise(function (resolve, reject) { + try { + resolve(fn.apply(void 0, args)); + } catch (e) { + reject(new Error(options.errorMsg(e.message))); + } + }); + }; + }; + var wrapWithPromiseAndErrorMessageTransform = (0, _ts_utils.partial)(function (getLocator, fn) { + return wrap(fn, function () { + var locator = getLocator.apply(void 0, arguments); + return { + errorMsg: function errorMsg(msg) { + if (/element is found but not visible yet/.test(msg)) { + return "element is found but not visible yet for '".concat(locator, "' (use !WaitForVisible = false to disable waiting for visible)"); + } + return "timeout reached when looking for element '".concat(locator, "'"); + } + }; + }); + }); + var wrapWithLogForEfp = (0, _ts_utils.partial)(function (getLocator, fn) { + return function () { + var el = fn.apply(void 0, arguments); + var locator = getLocator.apply(void 0, arguments); + if ((0, _dom_utils.isElementFromPoint)(locator)) { + var elXpath = 'unkown'; + try { + elXpath = helpers.xpath(el); + } catch (e) {} + var msg = "".concat(locator, " => xpath \"").concat(elXpath, "\""); + csIpc.ask('CS_ADD_LOG', { + info: msg + }); + } + return el; + }; + }); + var wrapWithSearchForInput = function wrapWithSearchForInput(fn) { + return function () { + var el = fn.apply(void 0, arguments); + if (!el || el.tagName === 'INPUT') { + return el; + } + var label = (0, _dom_utils.getAncestor)(el, function (node) { + return node.tagName === 'LABEL'; + }); + if (!label) { + return el; + } + var input = label.querySelector('input'); + return input || el; + }; + }; + var getElementByLocatorWithLogForEfp = wrapWithLogForEfp(getElementByLocatorWithTargetOptions, function (locator) { + return locator; + }); + var __getFrameByLocator = wrap(getFrameByLocator, function (locator) { + return { + errorMsg: function errorMsg(msg) { + return "timeout reached when looking for frame '".concat(locator, "'"); + } + }; + }); + var __getElementByLocator = (0, _ts_utils.compose)(wrapWithPromiseAndErrorMessageTransform(function (locator) { + return locator; + }), wrapWithLogForEfp(function (locator) { + return locator; + }))(getElementByLocatorWithTargetOptions); + var __getInputElementByLocator = (0, _ts_utils.compose)(wrapWithPromiseAndErrorMessageTransform(function (locator) { + return locator; + }), wrapWithLogForEfp(function (locator) { + return locator; + }), wrapWithSearchForInput)(getElementByLocatorWithTargetOptions); + var __expectNoElementByLocator = function __expectNoElementByLocator(locator, shouldWaitForVisible) { + return __getElementByLocator(locator, shouldWaitForVisible).then(function () { + if (shouldWaitForVisible) { + throw new Error("timeout reached when waiting for element '".concat(locator, "' to be not present")); + } else { + throw new Error("timeout reached when waiting for element '".concat(locator, "' to be not visible")); + } + }, function () { + return true; + }); + }; + switch (cmd) { + case 'openBrowser': + case 'open': + if (window.noCommandsYet) { + return true; + } + return (0, _utils.until)('document.body', function () { + return { + pass: !!document.body, + result: document.body + }; + }).then(function (body) { + setTimeout(function () { + csIpc.ask('CS_LOAD_URL', { + url: command.target, + cmd: command.cmd + }).then(function () { + return true; + }); + }); + return true; + }); + case 'refresh': + setTimeout(function () { + return window.location.reload(); + }, 0); + return true; + case 'mouseOver': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + try { + if (extra.playScrollElementsIntoView) el.scrollIntoView({ + block: 'center' + }); + if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); + } catch (e) { + _log["default"].error('error in scroll and highlight', e.message); + } + el.dispatchEvent(new MouseEvent('mouseover', { + bubbles: true + })); + return true; + }); + } + + // Note: 'locate' command is only for internal use + case 'locate': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + try { + if (extra.playScrollElementsIntoView) el.scrollIntoView({ + block: 'center' + }); + if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); + } catch (e) { + _log["default"].error('error in scroll and highlight', e.message); + } + var vpOffset = viewportOffset(el); + return getIframeViewportOffset().then(function (windowOffset) { + return { + rect: { + x: vpOffset.left + windowOffset.x, + y: vpOffset.top + windowOffset.y, + width: el.offsetWidth, + height: el.offsetHeight + } + }; + }); + }); + } + case 'dragAndDropToObject': + { + return Promise.all([__getElementByLocator(target, false, command, csIpc), __getElementByLocator(value)]).then(function (_ref2) { + var _ref3 = _slicedToArray(_ref2, 2), + $src = _ref3[0], + $tgt = _ref3[1]; + return _drag_mock["default"].triggerDragEvent($src, $tgt).then(function () { + return true; + }); + }); + } + case 'waitForElementVisible': + case 'waitForVisible': + { + return __getElementByLocator(target, true, command, csIpc).then(function () { + return true; + }); + } + case 'waitForElementNotVisible': + { + return __expectNoElementByLocator(target, true).then(function () { + return true; + }); + } + case 'waitForElementPresent': + { + return __getElementByLocator(target, false, command, csIpc).then(function () { + return true; + }); + } + case 'waitForElementNotPresent': + { + return __expectNoElementByLocator(target, false).then(function () { + return true; + }); + } + case 'clickAt': + { + var isEfp = (0, _dom_utils.isElementFromPoint)(target); + var pTarget = function () { + if (!isEfp) return Promise.resolve(target); + return getIframeViewportOffset().then(function (iframeOffset) { + (0, _log["default"])('iframeOffset', iframeOffset); + var _viewportCoordinateBy = (0, _dom_utils.viewportCoordinateByElementFromPoint)(target), + _viewportCoordinateBy2 = _slicedToArray(_viewportCoordinateBy, 2), + x = _viewportCoordinateBy2[0], + y = _viewportCoordinateBy2[1]; + return "#elementfrompoint (".concat(x - iframeOffset.x, ", ").concat(y - iframeOffset.y, ")"); + }); + }(); + return pTarget.then(function (target) { + return __getElementByLocator(target, extra.waitForVisible, command, csIpc).then(function (el) { + if (!/^\d+\s*,\s*\d+$/.test(value) && !(0, _dom_utils.isElementFromPoint)(target)) { + throw new Error("invalid offset for clickAt: ".concat(value)); + } + var scrollAndHighlight = function scrollAndHighlight() { + try { + if (extra.playScrollElementsIntoView) el.scrollIntoView({ + block: 'center' + }); + if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); + } catch (e) { + _log["default"].error('error in scroll and highlight'); + } + }; + var _ref4 = function () { + if (isEfp) { + return (0, _dom_utils.viewportCoordinateByElementFromPoint)(target); + } else { + var _value$split$map = value.split(',').map(function (str) { + return parseInt(str.trim(), 10); + }), + _value$split$map2 = _slicedToArray(_value$split$map, 2), + x = _value$split$map2[0], + y = _value$split$map2[1]; + var _viewportOffset = viewportOffset(el), + top = _viewportOffset.top, + left = _viewportOffset.left; + return [left + x, top + y]; + } + }(), + _ref5 = _slicedToArray(_ref4, 2), + origClientX = _ref5[0], + origClientY = _ref5[1]; + var lastScrollX = window.scrollX; + var lastScrollY = window.scrollY; + if (!isEfp) scrollAndHighlight(); + var clientX = origClientX + (lastScrollX - window.scrollX); + var clientY = origClientY + (lastScrollY - window.scrollY); + (0, _log["default"])('clickAt clientX/clientY', clientX, clientY); + ['mousedown', 'mouseup', 'click'].forEach(function (eventType) { + el.dispatchEvent(new MouseEvent(eventType, { + view: window, + bubbles: true, + cancelable: true, + clientX: clientX, + clientY: clientY + })); + }); + + // Note: delay scroll and highlight for efp, + // otherwise that scroll could mess up the whole coodirnate calculation + if (isEfp) scrollAndHighlight(); + focusIfEditable(el); + return true; + }); + }); + } + case 'saveItem': + case 'click': + case 'clickAndWait': + { + return __getElementByLocator(target, extra.waitForVisible, command, csIpc).then(function (el) { + try { + if (extra.playScrollElementsIntoView) el.scrollIntoView({ + block: 'center' + }); + if (command.cmd === 'saveItem') { + var img = el; + var url = img.src; + var filename = url.substring(url.lastIndexOf('/') + 1); + var a = document.createElement('a'); + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + } + if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); + } catch (e) { + _log["default"].error('error in scroll and highlight'); + } + ; + ['mousedown', 'mouseup', 'click'].forEach(function (eventType) { + if (eventType === 'click' && typeof el.click === 'function') { + return el.click(); + } + el.dispatchEvent(new MouseEvent(eventType, { + view: window, + bubbles: true, + cancelable: true + })); + }); + + // csIpc.ask('CS_ON_DOWNLOAD', { + // fileName: "", + // wait: (value || '').trim() === 'true', + // timeout: extra.timeoutDownload * 1000, + // timeoutForStart: extra.timeoutDownloadStart * 1000 + // }) + + focusIfEditable(el); + return true; + }); + } + case 'check': + case 'uncheck': + { + return __getInputElementByLocator(target, extra.waitForVisible, command, csIpc).then(function (el) { + el.checked = cmd === 'check'; + el.dispatchEvent(new Event('change', { + target: el, + bubbles: true + })); + return true; + }); + } + case 'addSelection': + case 'removeSelection': + case 'select': + case 'selectAndWait': + { + return __getElementByLocator(target, extra.waitForVisible, command, csIpc).then(function (el) { + var options = [].slice.call(el.getElementsByTagName('option')); + var i = value.indexOf('='); + var optionType = value.substring(0, i); + var optionValue = value.substring(i + 1); + var option = function () { + switch (optionType) { + case 'label': + return options.find(function (op) { + return (0, _glob.globMatch)(optionValue, (0, _dom_utils.domText)(op).trim()); + }); + case 'index': + return options.find(function (_, index) { + return index === parseInt(optionValue); + }); + case 'id': + return options.find(function (op, index) { + return op.id === optionValue; + }); + case 'value': + return options.find(function (op) { + return op.value === optionValue; + }); + default: + throw new Error("Option type \"".concat(optionType, "\" not supported")); + } + }(); + if (!option) { + throw new Error("cannot find option with '".concat(value, "'")); + } + if (extra.playScrollElementsIntoView) el.scrollIntoView({ + block: 'center' + }); + if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); + switch (cmd) { + case 'addSelection': + option.selected = true; + break; + case 'removeSelection': + option.selected = false; + break; + default: + el.value = option.value; + break; + } + el.dispatchEvent(new Event('change', { + target: el, + bubbles: true + })); + return true; + }); + } + case 'type': + { + return __getElementByLocator(target, extra.waitForVisible, command, csIpc).then(function (el) { + var tag = el.tagName.toLowerCase(); + if (tag !== 'input' && tag !== 'textarea') { + throw new Error('run command: element found is neither input nor textarea'); + } + if (extra.playScrollElementsIntoView) el.scrollIntoView({ + block: 'center' + }); + if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); + + // Note: need the help of chrome.debugger to set file path to file input + if (el.type && el.type.toLowerCase() === 'file') { + if (_web_extension["default"].isFirefox()) { + throw new Error('Setting file path fo file inputs is not supported by Firefox extension api yet'); + } + return csIpc.ask('CS_SET_FILE_INPUT_FILES', { + files: value.split(';'), + selector: (0, _dom_utils.cssSelector)(el) + }); + } + focusIfEditable(el); + return (0, _encrypt.decryptIfNeeded)(value, el).then(function (realValue) { + el.value = ''; + if (realValue.length <= _config["default"].commandRunner.sendKeysMaxCharCount) { + (0, _send_keys["default"])(el, realValue, true); + } + el.value = realValue; + el.dispatchEvent(new Event('change', { + target: el, + bubbles: true + })); + return true; + }); + })["catch"](function (e) { + if (/This input element accepts a filename/i.test(e.message)) { + throw new Error('Sorry, upload can not be automated Chrome (API limitation).'); + } + throw e; + }); + } + case 'editContent': + { + return __getElementByLocator(target, extra.waitForVisible, command, csIpc).then(function (el) { + if (el.contentEditable !== 'true') { + throw new Error("Target is not contenteditable"); + } + if (extra.playScrollElementsIntoView) el.scrollIntoView({ + block: 'center' + }); + if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); + el.focus(); + el.innerHTML = value; + el.blur(); + return true; + }); + } + case 'selectFrame': + { + return __getFrameByLocator(target, helpers).then(function (frameWindow) { + if (!frameWindow) { + throw new Error('Invalid frame/iframe'); + } + return frameWindow; + }); + } + case 'verifyText': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + var text = (0, _dom_utils.domText)(el); + if (!(0, _glob.globMatch)(value, text)) { + return { + log: { + error: "text not matched, \n\texpected: \"".concat(value, "\", \n\tactual: \"").concat(text, "\"") + } + }; + } + return true; + }); + } + case 'verifyTitle': + { + if (!(0, _glob.globMatch)(target, document.title)) { + return { + log: { + error: "title not matched, \n\texpected: \"".concat(target, "\", \n\tactual: \"").concat(document.title, "\"") + } + }; + } + return true; + } + case 'verifyElementPresent': + { + var _ref6 = extra || {}, + timeoutElement = _ref6.timeoutElement, + retryInfo = _ref6.retryInfo; + return __getElementByLocator(target, false, command, csIpc).then(function () { + return true; + }, function (e) { + var shotsLeft = timeoutElement * 1000 / retryInfo.retryInterval - retryInfo.retryCount; + var isLastChance = shotsLeft <= 1; + if (isLastChance) { + return { + log: { + error: "'".concat(target, "' element not present") + } + }; + } + throw e; + }); + } + case 'verifyElementNotPresent': + { + var _ref7 = extra || {}, + _timeoutElement = _ref7.timeoutElement, + _retryInfo = _ref7.retryInfo; + return __expectNoElementByLocator(target).then(function () { + return true; + }, function (e) { + var shotsLeft = _timeoutElement * 1000 / _retryInfo.retryInterval - _retryInfo.retryCount; + var isLastChance = shotsLeft <= 1; + if (isLastChance) { + return { + log: { + error: "'".concat(target, "' element is still present") + } + }; + } + throw e; + }); + } + case 'verifyEditable': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + var editable = (0, _dom_utils.isEditable)(el); + if (!editable) { + return { + log: { + error: "'".concat(target, "' is not editable") + } + }; + } + return true; + }); + } + case 'verifyNotEditable': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + var editable = (0, _dom_utils.isEditable)(el); + if (editable) { + return { + log: { + error: "'".concat(target, "' is editable") + } + }; + } + return true; + }); + } + case 'verifyChecked': + { + return __getInputElementByLocator(target, false, command, csIpc).then(function (el) { + var checked = !!el.checked; + if (!checked) { + return { + log: { + error: "'".concat(target, "' is not checked") + } + }; + } + return true; + }); + } + case 'verifyNotChecked': + { + return __getInputElementByLocator(target, false, command, csIpc).then(function (el) { + var checked = !!el.checked; + if (checked) { + return { + log: { + error: "'".concat(target, "' is checked") + } + }; + } + return true; + }); + } + case 'verifyAttribute': + { + var index = target.lastIndexOf('@'); + if (index === -1) { + throw new Error("invalid target for verifyAttribute - ".concat(target)); + } + var locator = target.substr(0, index); + var attrName = target.substr(index + 1); + return __getElementByLocator(locator, false, command, csIpc).then(function (el) { + var attr = el.getAttribute(attrName); + if (!(0, _glob.globMatch)(value, attr)) { + return { + log: { + error: "attribute not matched, \n\texpected: \"".concat(value, "\", \n\tactual: \"").concat(attr, "\"") + } + }; + } + return true; + }); + } + case 'verifyError': + { + if (extra.lastCommandOk) { + return { + log: { + error: target + } + }; + } + return true; + } + case 'assertText': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + var text = (0, _dom_utils.domText)(el); + if (!(0, _glob.globMatch)(value, text)) { + throw new Error("text not matched, \n\texpected: \"".concat(value, "\", \n\tactual: \"").concat(text, "\"")); + } + return true; + }); + } + case 'assertTitle': + { + if (!(0, _glob.globMatch)(target, document.title)) { + throw new Error("title not matched, \n\texpected: \"".concat(target, "\", \n\tactual: \"").concat(document.title, "\"")); + } + return true; + } + case 'assertElementPresent': + { + return __getElementByLocator(target, false, command, csIpc).then(function () { + return true; + }); + } + case 'assertElementNotPresent': + { + return __expectNoElementByLocator(target); + } + case 'assertChecked': + { + return __getInputElementByLocator(target, false, command, csIpc).then(function (el) { + var checked = !!el.checked; + if (!checked) { + throw new Error("'".concat(target, "' is not checked")); + } + return true; + }); + } + case 'assertNotChecked': + { + return __getInputElementByLocator(target, false, command, csIpc).then(function (el) { + var checked = !!el.checked; + if (checked) { + throw new Error("'".concat(target, "' is checked")); + } + return true; + }); + } + case 'assertEditable': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + var editable = (0, _dom_utils.isEditable)(el); + if (!editable) { + throw new Error("'".concat(target, "' is not editable")); + } + return true; + }); + } + case 'assertNotEditable': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + var editable = (0, _dom_utils.isEditable)(el); + if (editable) { + throw new Error("'".concat(target, "' is editable")); + } + return true; + }); + } + case 'assertAttribute': + { + var _index = target.lastIndexOf('@'); + if (_index === -1) { + throw new Error("invalid target for assertAttribute - ".concat(target)); + } + var _locator = target.substr(0, _index); + var _attrName = target.substr(_index + 1); + return __getElementByLocator(_locator, false, command, csIpc).then(function (el) { + var attr = el.getAttribute(_attrName); + if (!(0, _glob.globMatch)(value, attr)) { + throw new Error("attribute not matched, \n\texpected: \"".concat(value, "\", \n\tactual: \"").concat(attr, "\"")); + } + return true; + }); + } + case 'assertError': + { + if (extra.lastCommandOk) { + throw new Error(target); + } + return true; + } + case 'assertAlert': + { + var msg = document.body.getAttribute('data-alert'); + if (!msg) { + throw new Error('no alert found!'); + } + if (!(0, _glob.globMatch)(target, msg)) { + throw new Error("unmatched alert msg, \n\texpected: \"".concat(target, "\", \n\tactual: \"").concat(msg, "\"")); + } + document.body.setAttribute('data-alert', ''); + return true; + } + case 'assertConfirmation': + { + var _msg = document.body.getAttribute('data-confirm'); + if (!_msg) { + throw new Error('no confirm found!'); + } + if (!(0, _glob.globMatch)(target, _msg)) { + throw new Error("unmatched confirm msg, \n\texpected: \"".concat(target, "\", \n\tactual: \"").concat(_msg, "\"")); + } + document.body.setAttribute('data-confirm', ''); + return true; + } + case 'assertPrompt': + { + var _msg2 = document.body.getAttribute('data-prompt'); + if (!_msg2) { + throw new Error('no prompt found!'); + } + if (!(0, _glob.globMatch)(target, _msg2)) { + throw new Error("unmatched prompt msg, \n\texpected: \"".concat(target, "\", \n\tactual: \"").concat(_msg2, "\"")); + } + document.body.setAttribute('data-prompt', ''); + return true; + } + case 'answerOnNextPrompt': + { + document.body.setAttribute('data-prompt-answer', target); + return true; + } + case 'waitForPageToLoad': + return true; + case 'storeXpathCount': + { + var i = target.indexOf('='); + var method = target.substr(0, i); + var xpathStr = target.substr(i + 1); + var lowerMethod = method && method.toLowerCase(); + if (lowerMethod !== 'xpath') { + throw new Error("storeXpathCount: target should start with \"xpath=\""); + } + return { + vars: _defineProperty({}, value, (0, _dom_utils.getElementsByXPath)(xpathStr).length) + }; + } + case 'storeTitle': + { + return { + vars: _defineProperty({}, value, document.title) + }; + } + case 'storeText': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + return { + vars: _defineProperty({}, value, (0, _dom_utils.domText)(el)) + }; + }); + } + case 'storeAttribute': + { + var _index2 = target.lastIndexOf('@'); + if (_index2 === -1) { + throw new Error("invalid target for storeAttribute - ".concat(target)); + } + var _locator2 = target.substr(0, _index2); + var _attrName2 = target.substr(_index2 + 1); + return __getElementByLocator(_locator2, false, command, csIpc).then(function (el) { + var attr = el.getAttribute(_attrName2); + if (!attr) { + throw new Error("missing attribute '".concat(_attrName2, "'")); + } + return { + vars: _defineProperty({}, value, attr) + }; + }); + } + case 'storeEval': + { + return (0, _eval.untilInjected)().then(function (api) { + return api.eval(target).then(function (result) { + return { + vars: _defineProperty({}, value, result) + }; + })["catch"](function (e) { + throw new Error("Error in runEval code: ".concat(e.message)); + }); + }); + } + case 'storeValue': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + var text = el.value || ''; + return { + vars: _defineProperty({}, value, text) + }; + }); + } + case 'storeChecked': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + var checked = !!el.checked; + return { + vars: _defineProperty({}, value, checked) + }; + }); + } + case 'verifyValue': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + var text = el.value; + if (!(0, _glob.globMatch)(value, text)) { + return { + log: { + error: "value not matched, \n\texpected: \"".concat(value, "\", \n\tactual: \"").concat(text, "\"") + } + }; + } + return true; + }); + } + case 'assertValue': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + var text = el.value; + if (!(0, _glob.globMatch)(value, text)) { + throw new Error("value not matched, \n\texpected: \"".concat(value, "\", \n\tactual: \"").concat(text, "\"")); } - - return p.then(function () { - var _real; - - return (_real = real)[key].apply(_real, args); + return true; + }); + } + case 'executeScript': + case 'executeAsyncScript': + { + var minimumTimeout = _config["default"].executeScript.minimumTimeout; // 5000 + var userDefinedTimeout = extra.timeoutElement ? extra.timeoutElement * 1000 : 0; + var maxTimeout = userDefinedTimeout > minimumTimeout ? userDefinedTimeout : minimumTimeout; + return (0, _eval.untilInjected)(maxTimeout).then(function (api) { + var code = "Promise.resolve((function () { ".concat(target, " })());"); + return api.eval(code).then(function (result) { + if (value && value.length) { + return { + vars: _defineProperty({}, value, result) + }; + } + return true; + })["catch"](function (e) { + throw new Error("Error in ".concat(cmd, " code: ").concat(e.message)); }); + }); + } + case 'sendKeys': + { + return __getElementByLocator(target, false, command, csIpc).then(function (el) { + focusIfEditable(el); + (0, _send_keys["default"])(el, value); + return true; + }); + } + case 'sourceSearch': + case 'sourceExtract': + { + if (!target) { + throw new Error('Must provide text / regular expression to search for'); + } + if (!value) { + throw new Error('Must specify a variable to save the result'); + } + var getMatchAndCaptureIndex = function getMatchAndCaptureIndex(str) { + var nonZeroIndex = function nonZeroIndex(n) { + var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + if (n === undefined) return 0; + return Math.max(0, parseInt(n, 10) + offset); + }; + var m = /@\s*(\d+)(?:\s*,\s*(\d+))?\s*$/.exec(str); + if (!m) { + return { + rest: str, + matchIndex: 0, + captureIndex: 0 + }; + } + return { + rest: str.substring(0, m.index), + matchIndex: nonZeroIndex(m[1], -1), + captureIndex: nonZeroIndex(m[2]) + }; }; - } else { - return function () { - var _real3; - for (var _len8 = arguments.length, args = Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { - args[_key8] = arguments[_key8]; + // Note: get matchIndex captureIndex first, no matter it's for regexp or simple text + var _getMatchAndCaptureIn = getMatchAndCaptureIndex(target), + rest = _getMatchAndCaptureIn.rest, + matchIndex = _getMatchAndCaptureIn.matchIndex, + captureIndex = _getMatchAndCaptureIn.captureIndex; + if (cmd === 'sourceSearch' && rest !== target) { + throw new Error('The @ parameter is only supported in sourceExtract'); + } + var regexp = function () { + if (!/^regex(=|:)/i.test(rest)) { + return null; } - - p.then(function () { - var _real2; - - return (_real2 = real)[key].apply(_real2, args); + var raw = rest.replace(/^regex(=|:)/i, ''); + var reg = /^\/(.*)\/([gimsuy]+)?$/; + if (!reg.test(raw)) { + return (0, _utils.toRegExp)(raw.replace(/^\/|\/g?$/g, ''), { + needEncode: false, + flag: 'g' + }); + } + var match = raw.match(reg); + if (!match || !match.length) { + return null; + } + var _match = _slicedToArray(match, 3), + _ = _match[0], + regexpText = _match[1], + flags = _match[2]; + var flagText = _ts_utils.uniqueStrings.apply(void 0, ['g'].concat(_toConsumableArray(flags.split('')))).join(''); + return (0, _utils.toRegExp)(regexpText, { + needEncode: false, + flag: flagText }); - return (_real3 = real)[key].apply(_real3, args); - }; - } - } else { - return val; - } - }, mock); - - var p = _promise2.default.resolve(factory()).then(function (api) { - real = api; - }); - - return exported; -}; - -var bindOnce = exports.bindOnce = function bindOnce(target, eventName, fn) { - for (var _len9 = arguments.length, rest = Array(_len9 > 3 ? _len9 - 3 : 0), _key9 = 3; _key9 < _len9; _key9++) { - rest[_key9 - 3] = arguments[_key9]; - } - - var wrapped = function wrapped() { - try { - target.removeEventListener.apply(target, [eventName, wrapped].concat(rest)); - } catch (e) {} - - return fn.apply(undefined, arguments); - }; - - target.addEventListener.apply(target, [eventName, wrapped].concat(rest)); -}; - -var bind = exports.bind = function bind(target, eventName, fn) { - for (var _len10 = arguments.length, rest = Array(_len10 > 3 ? _len10 - 3 : 0), _key10 = 3; _key10 < _len10; _key10++) { - rest[_key10 - 3] = arguments[_key10]; - } - - target.addEventListener.apply(target, [eventName, fn].concat(rest)); -}; - -/***/ }), - -/***/ 61171: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -var _extends2 = __webpack_require__(88239); - -var _extends3 = _interopRequireDefault(_extends2); - -var _stringify = __webpack_require__(63239); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _promise = __webpack_require__(46593); - -var _promise2 = _interopRequireDefault(_promise); - -var _slicedToArray2 = __webpack_require__(12424); - -var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); - -var _keys = __webpack_require__(88902); - -var _keys2 = _interopRequireDefault(_keys); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/* global chrome browser */ - -// Note: it's an adapter for both chrome and web extension API -// chrome and web extension API have almost the same API signatures -// except that chrome accepts callback while web extension returns promises -// -// The whole idea here is to make sure all callback style API of chrome -// also return promises -// -// Important: You need to specify whatever API you need to use in `UsedAPI` below - -(function () { - var adaptChrome = function adaptChrome(obj, chrome) { - var adapt = function adapt(src, ret, obj, fn) { - return (0, _keys2.default)(obj).reduce(function (prev, key) { - var keyParts = key.split('.'); - - var _keyParts$reduce = keyParts.reduce(function (tuple, subkey) { - var tar = tuple[0]; - var src = tuple[1]; - - tar[subkey] = tar[subkey] || {}; - return [tar[subkey], src && src[subkey]]; - }, [prev, src]), - _keyParts$reduce2 = (0, _slicedToArray3.default)(_keyParts$reduce, 2), - target = _keyParts$reduce2[0], - source = _keyParts$reduce2[1]; - - obj[key].forEach(function (method) { - fn(method, source, target); - }); + }(); + var regexpForText = function () { + if (regexp) return null; + var raw = rest.replace(/^text(=|:)/i, ''); + if (cmd === 'sourceExtract' && !/\*/.test(raw)) { + throw new Error('Missing * or REGEX in sourceExtract. Extracting a plain text doesn\'t make much sense'); + } - return prev; - }, ret); - }; + // flag 's': Allows . to match newline characters. (Added in ES2018, not yet supported in Firefox). + // reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Advanced_searching_with_flags_2 + var flags = RegExp.prototype.hasOwnProperty('dotAll') ? 'gs' : 'g'; + return (0, _kdGlobToRegexp["default"])(raw, { + flags: flags, + capture: true, + nonGreedy: true + }); + }(); + var matches = function () { + var html = document.documentElement.outerHTML; + var reg = regexp || regexpForText; + var result = []; + var m; - var promisify = function promisify(method, source, target) { - if (!source) return; - var reg = /The message port closed before a res?ponse was received/; + // eslint-disable-next-line no-cond-assign + while (m = reg.exec(html)) { + result.push(m); - target[method] = function () { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + // Note: save some energy, if it's already enough to get what users want + if (cmd === 'sourceExtract' && result.length >= matchIndex + 1) { + break; + } + } + return result; + }(); + (0, _log["default"])('matches', matches, regexp, regexpForText); + if (cmd === 'sourceSearch') { + return { + vars: _defineProperty({}, value, matches.length) + }; } - - return new _promise2.default(function (resolve, reject) { - var callback = function callback(result) { - // Note: The message port closed before a reponse was received. - // Ignore this message - if (chrome.runtime.lastError && !reg.test(chrome.runtime.lastError.message)) { - console.error(chrome.runtime.lastError.message + ', ' + method + ', ' + (0, _stringify2.default)(args)); - return reject(chrome.runtime.lastError); + if (cmd === 'sourceExtract') { + var guard = function guard(str) { + return str !== undefined ? str : '#nomatchfound'; + }; + return { + vars: _defineProperty({}, value, guard((matches[matchIndex] || [])[captureIndex])) + }; + } + throw new Error('Impossible to reach here'); + } + case 'visionLimitSearchArea': + case 'storeImage': + { + var _run = function _run(locator, fileName) { + return __getElementByLocator(locator).then(function (el) { + if (!fileName || !fileName.length) { + throw new Error("storeImage: 'value' is required as image name"); } - resolve(result); + var clientRect = el.getBoundingClientRect(); + var pSourceOffset = function () { + if (window.top === window) { + return Promise.resolve({ + x: 0, + y: 0 + }); + } + + // Note: it's too complicated to take screenshot of element deep in iframe stack + // if you have to scroll each level of iframe to get the full image of it. + el.scrollIntoView(); + return (0, _cs_postmessage.postMessage)(window.parent, window, { + action: 'SOURCE_PAGE_OFFSET', + data: {} + }); + }(); + return pSourceOffset.then(function (sourceOffset) { + var rect = { + x: sourceOffset.x + clientRect.x + (0, _dom_utils.scrollLeft)(document), + y: sourceOffset.y + clientRect.y + (0, _dom_utils.scrollTop)(document), + width: clientRect.width, + height: clientRect.height + }; + return csIpc.ask('CS_STORE_SCREENSHOT_IN_SELECTION', { + rect: rect, + fileName: (0, _utils.ensureExtName)('.png', fileName), + devicePixelRatio: window.devicePixelRatio + }).then(function () { + return { + vars: { + '!storedImageRect': rect + } + }; + }); + }); + }); + }; + var _locator3, fileName; + if (cmd === 'storeImage') { + _locator3 = target; + fileName = value; + } else if (cmd === 'visionLimitSearchArea') { + _locator3 = target.trim().replace(/^element:/i, '').trim(); + fileName = _constant.LAST_SCREENSHOT_FILE_NAME; + } + return _run(_locator3, fileName); + } + case 'onDownload': + { + return csIpc.ask('CS_ON_DOWNLOAD', { + fileName: target, + wait: (value || '').trim() === 'true', + timeout: extra.timeoutDownload * 1000, + timeoutForStart: extra.timeoutDownloadStart * 1000 + }); + } + case 'deleteAllCookies': + { + return csIpc.ask('CS_DELETE_ALL_COOKIES', { + url: window.location.origin + }).then(function () { + return true; + }); + } + case 'if': + case 'while': + case 'gotoIf': + { + return (0, _eval.untilInjected)().then(function (api) { + return api.eval(target); + }).then(function (result) { + return { + condition: result }; - - source[method].apply(source, args.concat(callback)); }); - }; - }; - - var copy = function copy(method, source, target) { - if (!source) return; - target[method] = source[method]; - }; - - return [[obj.toPromisify, promisify], [obj.toCopy, copy]].reduce(function (prev, tuple) { - return adapt(chrome, prev, tuple[0], tuple[1]); - }, {}); - }; - - var UsedAPI = { - toPromisify: { - tabs: ['create', 'sendMessage', 'get', 'update', 'query', 'captureVisibleTab', 'remove', 'getZoom'], - windows: ['update', 'getLastFocused', 'getCurrent', 'getAll', 'remove', 'create', 'get'], - runtime: ['sendMessage', 'setUninstallURL'], - cookies: ['get', 'getAll', 'set', 'remove'], - notifications: ['create', 'clear'], - action: ['getBadgeText', 'setIcon'], - bookmarks: ['create', 'getTree'], - debugger: ['attach', 'detach', 'sendCommand', 'getTargets'], - downloads: ['search'], - extension: ['isAllowedFileSchemeAccess'], - contextMenus: ['create', 'update', 'remove', 'removeAll'], - 'storage.local': ['get', 'set'] - }, - toCopy: { - tabs: ['onActivated', 'onUpdated', 'onRemoved'], - windows: ['onFocusChanged'], - runtime: ['onMessage', 'onInstalled', 'getManifest', 'getURL'], - storage: ['onChanged'], - action: ['setBadgeText', 'setBadgeBackgroundColor', 'onClicked'], - contextMenus: ['onClicked'], - extension: ['getURL'], - debugger: ['onEvent', 'onDetach'], - downloads: ['onCreated', 'onChanged', 'onDeterminingFilename', 'setShelfEnabled'], - webRequest: ['onAuthRequired'] - } - }; - - var Ext = typeof chrome !== 'undefined' ? adaptChrome(UsedAPI, chrome) : browser; - - (0, _extends3.default)(Ext, { - isFirefox: function isFirefox() { - return (/Firefox/.test(self.navigator.userAgent) - ); - } - }); - - if (true) { - module.exports = Ext; - } else {} -})(); + } + default: + throw new Error("Command ".concat(cmd, " not supported yet")); + } +}; /***/ }), -/***/ 77750: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 65296: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.run = exports.getFrameByLocator = exports.getElementByLocatorWithTargetOptions = undefined; - -var _toConsumableArray2 = __webpack_require__(85315); - -var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2); - -var _defineProperty2 = __webpack_require__(88106); - -var _defineProperty3 = _interopRequireDefault(_defineProperty2); - -var _slicedToArray2 = __webpack_require__(12424); - -var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); - -var _promise = __webpack_require__(46593); - -var _promise2 = _interopRequireDefault(_promise); - -var _domElementIsNativelyEditable = __webpack_require__(34673); - -var _domElementIsNativelyEditable2 = _interopRequireDefault(_domElementIsNativelyEditable); - -var _kdGlobToRegexp = __webpack_require__(33733); - -var _kdGlobToRegexp2 = _interopRequireDefault(_kdGlobToRegexp); - -var _glob = __webpack_require__(64341); - -var _utils = __webpack_require__(63370); - -var _dom_utils = __webpack_require__(24874); - -var _ts_utils = __webpack_require__(55452); - -var _cs_postmessage = __webpack_require__(5116); - -var _web_extension = __webpack_require__(61171); - -var _web_extension2 = _interopRequireDefault(_web_extension); - -var _log = __webpack_require__(77242); - -var _log2 = _interopRequireDefault(_log); - -var _drag_mock = __webpack_require__(44380); - -var _drag_mock2 = _interopRequireDefault(_drag_mock); - -var _send_keys = __webpack_require__(75789); - -var _send_keys2 = _interopRequireDefault(_send_keys); - -var _encrypt = __webpack_require__(77930); - -var _constant = __webpack_require__(43232); - -var _eval = __webpack_require__(39505); - -var _config = __webpack_require__(62275); +function removeFromArray(array, item) { + var index = array.indexOf(item); + if (index >= 0) { + array.splice(index, 1); + } +} +var DataTransfer = function DataTransfer() { + this.dataByFormat = {}; + this.dropEffect = 'none'; + this.effectAllowed = 'all'; + this.files = []; + this.types = []; +}; +DataTransfer.prototype.clearData = function (dataFormat) { + if (dataFormat) { + delete this.dataByFormat[dataFormat]; + removeFromArray(this.types, dataFormat); + } else { + this.dataByFormat = {}; + this.types = []; + } +}; +DataTransfer.prototype.getData = function (dataFormat) { + return this.dataByFormat[dataFormat]; +}; +DataTransfer.prototype.setData = function (dataFormat, data) { + this.dataByFormat[dataFormat] = data; + if (this.types.indexOf(dataFormat) < 0) { + this.types.push(dataFormat); + } + return true; +}; +DataTransfer.prototype.setDragImage = function () { + // don't do anything (the stub just makes sure there is no error thrown if someone tries to call the method) +}; +module.exports = function () { + // Note: in Firefox, window.DataTransfer exists, but it can't be used as constructor + // In Firefox, `new window.DataTransfer()` throws errors like 'TypeError: Illegal constructor' + if (window.DataTransfer) { + try { + var tmp = new window.DataTransfer(); + return window.DataTransfer; + } catch (e) {} + } + return DataTransfer; +}(); -var _config2 = _interopRequireDefault(_config); +/***/ }), -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/***/ 12374: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var HIGHLIGHT_TIMEOUT = 500; +"use strict"; -// reference: https://github.com/timoxley/offset -var viewportOffset = function viewportOffset(el) { - var box = el.getBoundingClientRect(); - // Note: simply use bouddingClientRect since elementFromPoint uses - // the same top/left relative to the current viewport/window instead of whole document +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +var eventFactory = __webpack_require__(49873), + DataTransfer = __webpack_require__(65296); +function _noop() {} +function parseParams(targetElement, eventProperties, configCallback) { + if (typeof eventProperties === 'function') { + configCallback = eventProperties; + eventProperties = null; + } + if (!targetElement || _typeof(targetElement) !== 'object') { + throw new Error('Expected first parameter to be a targetElement. Instead got: ' + targetElement); + } return { - top: box.top, - left: box.left + targetElement: targetElement, + eventProperties: eventProperties || {}, + configCallback: configCallback || _noop }; +} +function customizeEvent(event, configCallback, isPrimaryEvent) { + if (configCallback) { + // call configCallback only for the primary event if the callback takes less than two arguments + if (configCallback.length < 2) { + if (isPrimaryEvent) { + configCallback(event); + } + } + // call configCallback for each event if the callback takes two arguments + else { + configCallback(event, event.type); + } + } +} +function createAndDispatchEvents(targetElement, eventNames, primaryEventName, dataTransfer, eventProperties, configCallback) { + eventNames.forEach(function (eventName) { + var event = eventFactory.createEvent(eventName, eventProperties, dataTransfer); + var isPrimaryEvent = eventName === primaryEventName; + customizeEvent(event, configCallback, isPrimaryEvent); + targetElement.dispatchEvent(event); + }); +} +var DragDropAction = function DragDropAction() { + this.lastDragSource = null; + this.lastDataTransfer = null; + this.pendingActionsQueue = []; }; - -var getIframeViewportOffset = function getIframeViewportOffset() { - if (window === window.top) { - return _promise2.default.resolve({ x: 0, y: 0 }); +DragDropAction.prototype._queue = function (fn) { + this.pendingActionsQueue.push(fn); + if (this.pendingActionsQueue.length === 1) { + this._queueExecuteNext(); } - - return (0, _cs_postmessage.postMessage)(window.parent, window, { - action: 'SOURCE_VIEWPORT_OFFSET', - data: {} +}; +DragDropAction.prototype._queueExecuteNext = function () { + if (this.pendingActionsQueue.length === 0) { + return; + } + var self = this; + var firstPendingAction = this.pendingActionsQueue[0]; + var doneCallback = function doneCallback() { + self.pendingActionsQueue.shift(); + self._queueExecuteNext(); + }; + if (firstPendingAction.length === 0) { + firstPendingAction.call(this); + doneCallback(); + } else { + firstPendingAction.call(this, doneCallback); + } +}; +DragDropAction.prototype.dragStart = function (targetElement, eventProperties, configCallback) { + var params = parseParams(targetElement, eventProperties, configCallback), + events = ['mousedown', 'dragstart', 'drag'], + dataTransfer = new DataTransfer(); + this._queue(function () { + createAndDispatchEvents(params.targetElement, events, 'drag', dataTransfer, params.eventProperties, params.configCallback); + this.lastDragSource = targetElement; + this.lastDataTransfer = dataTransfer; + }); + return this; +}; +DragDropAction.prototype.dragEnter = function (overElement, eventProperties, configCallback) { + var params = parseParams(overElement, eventProperties, configCallback), + events = ['mousemove', 'mouseover', 'dragenter']; + this._queue(function () { + createAndDispatchEvents(params.targetElement, events, 'dragenter', this.lastDataTransfer, params.eventProperties, params.configCallback); + }); + return this; +}; +DragDropAction.prototype.dragOver = function (overElement, eventProperties, configCallback) { + var params = parseParams(overElement, eventProperties, configCallback), + events = ['mousemove', 'mouseover', 'dragover']; + this._queue(function () { + createAndDispatchEvents(params.targetElement, events, 'drag', this.lastDataTransfer, params.eventProperties, params.configCallback); + }); + return this; +}; +DragDropAction.prototype.dragLeave = function (overElement, eventProperties, configCallback) { + var params = parseParams(overElement, eventProperties, configCallback), + events = ['mousemove', 'mouseover', 'dragleave']; + this._queue(function () { + createAndDispatchEvents(params.targetElement, events, 'dragleave', this.lastDataTransfer, params.eventProperties, params.configCallback); }); + return this; }; - -var focusIfEditable = function focusIfEditable($el) { - if ((0, _domElementIsNativelyEditable2.default)($el) && typeof $el.focus === 'function') { - $el.focus(); - } -}; - -// We now save targetOptions in command, if main target can't be found (extra?.retryInfo.final === true), -// it should try all targetOptions just for once -var getElementByLocatorWithTargetOptions = exports.getElementByLocatorWithTargetOptions = function getElementByLocatorWithTargetOptions(locator, shouldWaitForVisible, command, csIpc) { - var _ref = command || {}, - extra = _ref.extra, - targetOptions = _ref.targetOptions; - - if (extra && extra.retryInfo && extra.retryInfo.final && targetOptions && targetOptions.length) { - for (var i = 0, len = targetOptions.length; i < len; i++) { - var target = targetOptions[i]; - - try { - var el = (0, _dom_utils.getElementByLocator)(target, shouldWaitForVisible); - - csIpc.ask('CS_ADD_LOG', { - warning: 'Element found with secondary locator "' + target + '". To use it by default, update the target field to use it as primary locator.' - }); - - return el; - } catch (e) { - if (i === len - 1) { - throw e; - } - } +DragDropAction.prototype.drop = function (targetElement, eventProperties, configCallback) { + var params = parseParams(targetElement, eventProperties, configCallback); + var eventsOnDropTarget = ['mousemove', 'mouseup', 'drop']; + var eventsOnDragSource = ['dragend']; + this._queue(function () { + createAndDispatchEvents(params.targetElement, eventsOnDropTarget, 'drop', this.lastDataTransfer, params.eventProperties, params.configCallback); + if (this.lastDragSource) { + // trigger dragend event on last drag source element + createAndDispatchEvents(this.lastDragSource, eventsOnDragSource, 'drop', this.lastDataTransfer, params.eventProperties, params.configCallback); } - } - - return (0, _dom_utils.getElementByLocator)(locator, shouldWaitForVisible); + }); + return this; }; +DragDropAction.prototype.then = function (callback) { + this._queue(function () { + callback.call(this); + }); // make sure _queue() is given a callback with no arguments -var getFrameByLocator = exports.getFrameByLocator = function getFrameByLocator(str, helpers) { - var i = str.indexOf('='); - - // Note: try to parse format of 'index=0' and 'relative=top/parent' - if (i !== -1) { - var method = str.substr(0, i); - var value = str.substr(i + 1); + return this; +}; +DragDropAction.prototype.delay = function (waitingTimeMs) { + this._queue(function (done) { + window.setTimeout(done, waitingTimeMs); + }); + return this; +}; +module.exports = DragDropAction; - switch (method) { - case 'index': - { - var index = parseInt(value, 10); - var frames = window.frames; - var frame = frames[index]; +/***/ }), - if (!frame) { - throw new Error('Frame index out of range (index ' + value + ' in ' + frames.length + ' frames'); - } +/***/ 49873: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - return { frame: frame }; - } +"use strict"; - case 'relative': - { - if (value === 'top') { - return { frame: window.top }; - } - if (value === 'parent') { - return { frame: window.parent }; - } +var DataTransfer = __webpack_require__(65296); +var dataTransferEvents = ['drag', 'dragstart', 'dragenter', 'dragover', 'dragend', 'drop', 'dragleave']; +function mergeInto(destObj, srcObj) { + for (var key in srcObj) { + if (!srcObj.hasOwnProperty(key)) { + continue; + } // ignore inherited properties - throw new Error('Unsupported relative type, ' + value); - } - } + destObj[key] = srcObj[key]; } + return destObj; +} +function isFirefox() { + return /Firefox/.test(window.navigator.userAgent); +} +function createModernEvent(eventName, eventType, eventProperties) { + // if (eventType === 'DragEvent') { eventType = 'CustomEvent'; } // Firefox fix (since FF does not allow us to override dataTransfer) - // Note: consider it as name, if no '=' found and it has no xpath pattern - if (i === -1 && !/^\/.*/.test(str)) { - str = 'name=' + str; + var constructor = window[eventType]; + var options = { + view: window, + bubbles: true, + cancelable: true + }; + mergeInto(options, eventProperties); + var event = new constructor(eventName, options); + mergeInto(event, eventProperties); + return event; +} +function createLegacyEvent(eventName, eventType, eventProperties) { + var event; + switch (eventType) { + case 'MouseEvent': + event = document.createEvent('MouseEvent'); + event.initEvent(eventName, true, true); + break; + default: + event = document.createEvent('CustomEvent'); + event.initCustomEvent(eventName, true, true, 0); } - var frameDom = (0, _dom_utils.getElementByLocator)(str); - - if (!frameDom || !frameDom.contentWindow) { - throw new Error('The element found based on ' + str + ' is NOT a frame/iframe'); + // copy eventProperties into event + if (eventProperties) { + mergeInto(event, eventProperties); } - - // Note: for those iframe/frame that don't have src, they won't load content_script.js - // so we have to inject the script by ourselves - if (!frameDom.getAttribute('src')) { - var file = _web_extension2.default.runtime.getURL('content_script.js'); - var doc = frameDom.contentDocument; - var s = doc.constructor.prototype.createElement.call(doc, 'script'); - - s.setAttribute('type', 'text/javascript'); - s.setAttribute('src', file); - - doc.documentElement.appendChild(s); - s.parentNode.removeChild(s); - - helpers.hackAlertConfirmPrompt(doc); + return event; +} +function _createEvent(eventName, eventType, eventProperties) { + if (isFirefox()) { + return createLegacyEvent(eventName, eventType, eventProperties); + } + try { + return createModernEvent(eventName, eventType, eventProperties); + } catch (error) { + return createLegacyEvent(eventName, eventType, eventProperties); + } +} +var EventFactory = { + createEvent: function createEvent(eventName, eventProperties, dataTransfer) { + var eventType = 'CustomEvent'; + if (eventName.match(/^mouse/)) { + eventType = 'MouseEvent'; + } else if (eventName.match(/^(drag|drop)/)) { + eventType = 'DragEvent'; + } + if (dataTransferEvents.indexOf(eventName) > -1) { + eventProperties.dataTransfer = dataTransfer || new DataTransfer(); + } + var event = _createEvent(eventName, eventType, eventProperties); + return event; } - - // Note: can't return the contentWindow directly, because Promise 'resolve' will - // try to test its '.then' method, which will cause a cross origin violation - // so, we wrap it in an object - return { frame: frameDom.contentWindow }; }; +module.exports = EventFactory; -var run = exports.run = function run(command, csIpc, helpers) { - var cmd = command.cmd, - target = command.target, - value = command.value, - extra = command.extra; - - var wrap = function wrap(fn, genOptions) { - return function () { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - var options = genOptions.apply(undefined, args); - - return new _promise2.default(function (resolve, reject) { - try { - resolve(fn.apply(undefined, args)); - } catch (e) { - reject(new Error(options.errorMsg(e.message))); - } - }); - }; - }; - var wrapWithPromiseAndErrorMessageTransform = (0, _ts_utils.partial)(function (getLocator, fn) { - return wrap(fn, function () { - var locator = getLocator.apply(undefined, arguments); +/***/ }), - return { - errorMsg: function errorMsg(msg) { - if (/element is found but not visible yet/.test(msg)) { - return 'element is found but not visible yet for \'' + locator + '\' (use !WaitForVisible = false to disable waiting for visible)'; - } +/***/ 63747: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - return 'timeout reached when looking for element \'' + locator + '\''; - } - }; - }); - }); - var wrapWithLogForEfp = (0, _ts_utils.partial)(function (getLocator, fn) { - return function () { - var el = fn.apply(undefined, arguments); - var locator = getLocator.apply(undefined, arguments); +"use strict"; - if ((0, _dom_utils.isElementFromPoint)(locator)) { - var elXpath = 'unkown'; - try { - elXpath = helpers.xpath(el); - } catch (e) {} +var _eval = __webpack_require__(20652); +var DragDropAction = __webpack_require__(12374); +function call(instance, methodName, args) { + return instance[methodName].apply(instance, args); +} +function triggerDragEvent(element, target) { + console.log('drag event start!! >>>>>>'); + var getXpathOfElement = function getXpathOfElement(element) { + if (element == null) { + return 'null'; + } + if (element.parentElement == null) { + return '/' + element.tagName; + } + var siblingElement = element.parentElement.children; + var tagCount = 0; + var totalTagCount = 0; + var isFound = false; + for (var i = 0; i < siblingElement.length; i++) { + if (siblingElement[i].tagName == element.tagName && !isFound) { + tagCount++; + totalTagCount++; + } else if (siblingElement[i].tagName == element.tagName) { + totalTagCount++; + } + if (siblingElement[i] == element) { + isFound = true; + } + } + if (totalTagCount > 1) { + return getXpathOfElement(element.parentElement) + "/" + element.tagName + "[" + tagCount + "]"; + } + return getXpathOfElement(element.parentElement) + "/" + element.tagName; + }; + var script = " \ + function simulateDragDrop(sourceNode, destinationNode){\ + function createCustomEvent(type) { \ + var event = new CustomEvent('CustomEvent'); \ + event.initCustomEvent(type, true, true, null); \ + event.dataTransfer = { \ + data: { \ + }, \ + setData: function(type, val) { \ + this.data[type] = val; \ + }, \ + getData: function(type) { \ + return this.data[type]; \ + } \ + }; \ + return event; \ + } \ + function dispatchEvent(node, type, event) { \ + if (node.dispatchEvent) { \ + return node.dispatchEvent(event); \ + } \ + if (node.fireEvent) { \ + return node.fireEvent('on' + type, event); \ + } \ + } \ + var event = createCustomEvent('dragstart'); \ + dispatchEvent(sourceNode, 'dragstart', event); \ + \ + var dropEvent = createCustomEvent('drop'); \ + dropEvent.dataTransfer = event.dataTransfer; \ + dispatchEvent(destinationNode, 'drop', dropEvent); \ + \ + var dragEndEvent = createCustomEvent('dragend'); \ + dragEndEvent.dataTransfer = event.dataTransfer; \ + dispatchEvent(sourceNode, 'dragend', dragEndEvent); \ + } \ + simulateDragDrop(document.evaluate('" + getXpathOfElement(element) + "', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, document.evaluate('" + getXpathOfElement(target) + "', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue);\ + "; + return (0, _eval.evalViaInject)(script); +} +var dragMock = { + dragStart: function dragStart(targetElement, eventProperties, configCallback) { + return call(new DragDropAction(), 'dragStart', arguments); + }, + dragEnter: function dragEnter(targetElement, eventProperties, configCallback) { + return call(new DragDropAction(), 'dragEnter', arguments); + }, + dragOver: function dragOver(targetElement, eventProperties, configCallback) { + return call(new DragDropAction(), 'dragOver', arguments); + }, + dragLeave: function dragLeave(targetElement, eventProperties, configCallback) { + return call(new DragDropAction(), 'dragLeave', arguments); + }, + drop: function drop(targetElement, eventProperties, configCallback) { + return call(new DragDropAction(), 'drop', arguments); + }, + delay: function delay(targetElement, eventProperties, configCallback) { + return call(new DragDropAction(), 'delay', arguments); + }, + triggerDragEvent: triggerDragEvent, + // Just for unit testing: + DataTransfer: __webpack_require__(65296), + DragDropAction: __webpack_require__(12374), + eventFactory: __webpack_require__(49873) +}; +module.exports = dragMock; - var msg = locator + ' => xpath "' + elXpath + '"'; +/***/ }), - csIpc.ask('CS_ADD_LOG', { info: msg }); - } +/***/ 35645: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - return el; - }; - }); - var wrapWithSearchForInput = function wrapWithSearchForInput(fn) { - return function () { - var el = fn.apply(undefined, arguments); +"use strict"; - if (!el || el.tagName === 'INPUT') { - return el; - } - var label = (0, _dom_utils.getAncestor)(el, function (node) { - return node.tagName === 'LABEL'; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.selectAreaPromise = exports.selectArea = exports.createRect = exports.createEl = exports.commonStyle = void 0; +var _dom_utils = __webpack_require__(92950); +var _box = __webpack_require__(12660); +var _web_extension = _interopRequireDefault(__webpack_require__(41953)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +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), !0).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; } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +var commonStyle = exports.commonStyle = { + boxSizing: 'border-box', + fontFamily: 'Arial' +}; +var createEl = exports.createEl = function createEl(_ref) { + var _ref$tag = _ref.tag, + tag = _ref$tag === void 0 ? 'div' : _ref$tag, + _ref$attrs = _ref.attrs, + attrs = _ref$attrs === void 0 ? {} : _ref$attrs, + _ref$style = _ref.style, + style = _ref$style === void 0 ? {} : _ref$style, + text = _ref.text; + var $el = document.createElement(tag); + Object.keys(attrs).forEach(function (key) { + $el.setAttribute(key, attrs[key]); + }); + if (text && text.length) { + $el.innerText = text; + } + (0, _dom_utils.setStyle)($el, style); + return $el; +}; +var createRect = exports.createRect = function createRect(opts) { + var containerStyle = _objectSpread(_objectSpread({}, commonStyle), {}, { + position: 'absolute', + zIndex: 100000, + top: (0, _dom_utils.pixel)(opts.top), + left: (0, _dom_utils.pixel)(opts.left), + width: (0, _dom_utils.pixel)(opts.width), + height: (0, _dom_utils.pixel)(opts.height) + }, opts.containerStyle || {}); + var rectStyle = _objectSpread(_objectSpread({}, commonStyle), {}, { + width: '100%', + height: '100%', + border: "".concat(opts.rectBorderWidth, "px solid rgb(239, 93, 143)"), + cursor: 'move', + background: 'transparent' + }, opts.rectStyle || {}); + var circleStyle = _objectSpread(_objectSpread({}, commonStyle), {}, { + width: '8px', + height: '8px', + border: "".concat(opts.rectBorderWidth, "px solid rgb(239, 93, 143)"), + cursor: 'pointer', + background: 'red', + position: 'absolute', + 'border-radius': '50%', + top: '50%', + left: '50%', + transform: 'translate(-50%, -50%)' + }, opts.rectStyle || {}); + var $container = createEl({ + style: containerStyle + }); + var $rectangle = createEl({ + style: rectStyle + }); + var $circlePointer = createEl({ + style: circleStyle + }); + $container.appendChild($rectangle); + $container.appendChild($circlePointer); + document.documentElement.appendChild($container); + return { + $container: $container, + $rectangle: $rectangle, + destroy: function destroy() { + $container.remove(); + }, + hide: function hide() { + (0, _dom_utils.setStyle)($container, { + display: 'none' }); + }, + show: function show() { + (0, _dom_utils.setStyle)($container, { + display: 'block' + }); + } + }; +}; +var createOverlay = function createOverlay(extraStyles) { + var $overlay = createEl({ + style: _objectSpread({ + position: 'fixed', + zIndex: 9000, + top: 0, + bottom: 0, + left: 0, + right: 0, + background: 'transparent', + cursor: 'crosshair' + }, extraStyles) + }); + document.documentElement.appendChild($overlay); + return { + $overlay: $overlay, + destroy: function destroy() { + return $overlay.remove(); + } + }; +}; +var selectArea = exports.selectArea = function selectArea(_ref2) { + var done = _ref2.done, + _ref2$onDestroy = _ref2.onDestroy, + onDestroy = _ref2$onDestroy === void 0 ? function () {} : _ref2$onDestroy, + _ref2$allowCursor = _ref2.allowCursor, + allowCursor = _ref2$allowCursor === void 0 ? function (e) { + return true; + } : _ref2$allowCursor, + _ref2$overlayStyles = _ref2.overlayStyles, + overlayStyles = _ref2$overlayStyles === void 0 ? {} : _ref2$overlayStyles, + _ref2$clickToDestroy = _ref2.clickToDestroy, + clickToDestroy = _ref2$clickToDestroy === void 0 ? true : _ref2$clickToDestroy, + _ref2$preventGlobalCl = _ref2.preventGlobalClick, + preventGlobalClick = _ref2$preventGlobalCl === void 0 ? true : _ref2$preventGlobalCl; + var go = function go(done) { + var state = { + box: null, + activated: false, + startPos: null, + rect: null + }; + var resetBodyStyle = function () { + var userSelectKey = _web_extension["default"].isFirefox() ? '-moz-user-select' : 'user-select'; + var style = window.getComputedStyle(document.body); + var oldCursor = style.cursor; + var oldUserSelect = style[userSelectKey]; + (0, _dom_utils.setStyle)(document.body, _defineProperty({ + cursor: 'crosshair' + }, userSelectKey, 'none')); + return function () { + return (0, _dom_utils.setStyle)(document.body, _defineProperty({ + cursor: oldCursor + }, userSelectKey, oldUserSelect)); + }; + }(); + var overlayApi = createOverlay(overlayStyles); + var unbindDrag = (0, _dom_utils.bindDrag)({ + preventGlobalClick: preventGlobalClick, + $el: overlayApi.$overlay, + onDragStart: function onDragStart(e) { + e.preventDefault(); + if (!allowCursor(e)) return; + state.activated = true; + state.startPos = { + x: e.pageX, + y: e.pageY + }; + }, + onDragEnd: function onDragEnd(e) { + e.preventDefault(); + state.activated = false; + if (state.box) { + state.box.moveAnchorEnd(); + var boundingRect = rectObj.$container.getBoundingClientRect(); + API.hide(); - if (!label) { - return el; + // Note: API.hide() takes some time to have effect + setTimeout(function () { + state.box = null; + return Promise.resolve(done(state.rect, boundingRect))["catch"](function (e) {}).then(function () { + return API.destroy(); + }); + }, 100); + } + }, + onDrag: function onDrag(e, _ref3) { + var dx = _ref3.dx, + dy = _ref3.dy; + e.preventDefault(); + if (!allowCursor(e)) return; + if (!state.activated) return; + if (!state.box) { + var rect = { + x: state.startPos.x, + y: state.startPos.y, + width: dx, + height: dy + }; + state.rect = rect; + state.box = new _box.Box(_objectSpread(_objectSpread({}, rect), {}, { + onStateChange: function onStateChange(_ref4) { + var rect = _ref4.rect; + state.rect = rect; + API.show(); + API.updatePos(rect); + } + })); + state.box.moveAnchorStart({ + anchorPos: _box.BOX_ANCHOR_POS.BOTTOM_RIGHT + }); + } + state.box.moveAnchor({ + x: e.pageX, + y: e.pageY + }); } - - var input = label.querySelector('input'); - - return input || el; + }); + var rectObj = createRect({ + top: -999, + left: -999, + width: 0, + height: 0, + rectStyle: { + border: '1px solid #ff0000', + background: 'rgba(255, 0, 0, 0.1)' + } + }); + var API = { + updatePos: function updatePos(rect) { + (0, _dom_utils.setStyle)(rectObj.$container, { + top: (0, _dom_utils.pixel)(rect.y), + left: (0, _dom_utils.pixel)(rect.x), + width: (0, _dom_utils.pixel)(rect.width), + height: (0, _dom_utils.pixel)(rect.height) + }); + }, + destroy: function destroy() { + resetBodyStyle(); + unbindDrag(); + overlayApi.destroy(); + rectObj.destroy(); + setTimeout(function () { + document.removeEventListener('click', onClick, true); + document.removeEventListener('keydown', onKeyDown, true); + }, 0); + onDestroy(); + }, + hide: function hide() { + rectObj.hide(); + }, + show: function show() { + rectObj.show(); + } + }; + var onClick = function onClick(e) { + // If drag starts, we should ignore click event + if (state.box) return; + e.preventDefault(); + e.stopPropagation(); + API.destroy(); + }; + var onKeyDown = function onKeyDown(e) { + return e.keyCode === 27 && API.destroy(); }; + document.addEventListener('keydown', onKeyDown, true); + if (clickToDestroy) { + document.addEventListener('click', onClick, true); + } + API.hide(); + return API; }; - var getElementByLocatorWithLogForEfp = wrapWithLogForEfp(getElementByLocatorWithTargetOptions, function (locator) { - return locator; - }); - var __getFrameByLocator = wrap(getFrameByLocator, function (locator) { - return { - errorMsg: function errorMsg(msg) { - return 'timeout reached when looking for frame \'' + locator + '\''; - } + return go(done); +}; +var selectAreaPromise = exports.selectAreaPromise = function selectAreaPromise(opts) { + return new Promise(function (resolve, reject) { + var wrappedDone = function wrappedDone() { + resolve(opts.done.apply(opts, arguments)); + }; + var wrappedOnDestroy = function wrappedOnDestroy() { + try { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (opts.onDestroy) opts.onDestroy(args); + } catch (e) {} + resolve(); }; + selectArea(_objectSpread(_objectSpread({}, opts), {}, { + done: wrappedDone, + onDestroy: wrappedOnDestroy + })); }); - var __getElementByLocator = (0, _ts_utils.compose)(wrapWithPromiseAndErrorMessageTransform(function (locator) { - return locator; - }), wrapWithLogForEfp(function (locator) { - return locator; - }))(getElementByLocatorWithTargetOptions); - - var __getInputElementByLocator = (0, _ts_utils.compose)(wrapWithPromiseAndErrorMessageTransform(function (locator) { - return locator; - }), wrapWithLogForEfp(function (locator) { - return locator; - }), wrapWithSearchForInput)(getElementByLocatorWithTargetOptions); +}; - var __expectNoElementByLocator = function __expectNoElementByLocator(locator, shouldWaitForVisible) { - return __getElementByLocator(locator, shouldWaitForVisible).then(function () { - if (shouldWaitForVisible) { - throw new Error('timeout reached when waiting for element \'' + locator + '\' to be not present'); - } else { - throw new Error('timeout reached when waiting for element \'' + locator + '\' to be not visible'); - } - }, function () { - return true; - }); - }; +/***/ }), - switch (cmd) { - case 'open': - if (window.noCommandsYet) { - return true; - } +/***/ 67526: +/***/ ((__unused_webpack_module, exports) => { - return (0, _utils.until)('document.body', function () { - return { - pass: !!document.body, - result: document.body - }; - }).then(function (body) { - setTimeout(function () { - csIpc.ask('CS_LOAD_URL', { url: command.target }).then(function () { - return true; - }); - }); - return true; - }); +"use strict"; - case 'refresh': - setTimeout(function () { - return window.location.reload(); - }, 0); - return true; - case 'mouseOver': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - try { - if (extra.playScrollElementsIntoView) el.scrollIntoView({ block: 'center' }); - if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); - } catch (e) { - _log2.default.error('error in scroll and highlight', e.message); - } +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray - el.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); - return true; - }); - } +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - // Note: 'locate' command is only for internal use - case 'locate': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - try { - if (extra.playScrollElementsIntoView) el.scrollIntoView({ block: 'center' }); - if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); - } catch (e) { - _log2.default.error('error in scroll and highlight', e.message); - } +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} - var vpOffset = viewportOffset(el); +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 - return getIframeViewportOffset().then(function (windowOffset) { - return { - rect: { - x: vpOffset.left + windowOffset.x, - y: vpOffset.top + windowOffset.y, - width: el.offsetWidth, - height: el.offsetHeight - } - }; - }); - }); - } +function getLens (b64) { + var len = b64.length - case 'dragAndDropToObject': - { - return _promise2.default.all([__getElementByLocator(target, false, command, csIpc), __getElementByLocator(value)]).then(function (_ref2) { - var _ref3 = (0, _slicedToArray3.default)(_ref2, 2), - $src = _ref3[0], - $tgt = _ref3[1]; + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } - return _drag_mock2.default.triggerDragEvent($src, $tgt).then(function () { - return true; - }); - }); - } + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len - case 'waitForElementVisible': - case 'waitForVisible': - { - return __getElementByLocator(target, true, command, csIpc).then(function () { - return true; - }); - } + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) - case 'waitForElementNotVisible': - { - return __expectNoElementByLocator(target, true).then(function () { - return true; - }); - } + return [validLen, placeHoldersLen] +} - case 'waitForElementPresent': - { - return __getElementByLocator(target, false, command, csIpc).then(function () { - return true; - }); - } +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} - case 'waitForElementNotPresent': - { - return __expectNoElementByLocator(target, false).then(function () { - return true; - }); - } +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} - case 'clickAt': - { - var isEfp = (0, _dom_utils.isElementFromPoint)(target); - var pTarget = function () { - if (!isEfp) return _promise2.default.resolve(target); - return getIframeViewportOffset().then(function (iframeOffset) { - (0, _log2.default)('iframeOffset', iframeOffset); +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] - var _viewportCoordinateBy = (0, _dom_utils.viewportCoordinateByElementFromPoint)(target), - _viewportCoordinateBy2 = (0, _slicedToArray3.default)(_viewportCoordinateBy, 2), - x = _viewportCoordinateBy2[0], - y = _viewportCoordinateBy2[1]; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - return '#elementfrompoint (' + (x - iframeOffset.x) + ', ' + (y - iframeOffset.y) + ')'; - }); - }(); + var curByte = 0 - return pTarget.then(function (target) { - return __getElementByLocator(target, extra.waitForVisible, command, csIpc).then(function (el) { - if (!/^\d+\s*,\s*\d+$/.test(value) && !(0, _dom_utils.isElementFromPoint)(target)) { - throw new Error('invalid offset for clickAt: ' + value); - } + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen - var scrollAndHighlight = function scrollAndHighlight() { - try { - if (extra.playScrollElementsIntoView) el.scrollIntoView({ block: 'center' }); - if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); - } catch (e) { - _log2.default.error('error in scroll and highlight'); - } - }; + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } - var _ref4 = function () { - if (isEfp) { - return (0, _dom_utils.viewportCoordinateByElementFromPoint)(target); - } else { - var _value$split$map = value.split(',').map(function (str) { - return parseInt(str.trim(), 10); - }), - _value$split$map2 = (0, _slicedToArray3.default)(_value$split$map, 2), - x = _value$split$map2[0], - y = _value$split$map2[1]; + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } - var _viewportOffset = viewportOffset(el), - top = _viewportOffset.top, - left = _viewportOffset.left; + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } - return [left + x, top + y]; - } - }(), - _ref5 = (0, _slicedToArray3.default)(_ref4, 2), - origClientX = _ref5[0], - origClientY = _ref5[1]; + return arr +} - var lastScrollX = window.scrollX; - var lastScrollY = window.scrollY; +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} - if (!isEfp) scrollAndHighlight(); +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} - var clientX = origClientX + (lastScrollX - window.scrollX); - var clientY = origClientY + (lastScrollY - window.scrollY); +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 - (0, _log2.default)('clickAt clientX/clientY', clientX, clientY);['mousedown', 'mouseup', 'click'].forEach(function (eventType) { - el.dispatchEvent(new MouseEvent(eventType, { - view: window, - bubbles: true, - cancelable: true, - clientX: clientX, - clientY: clientY - })); - }); + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } - // Note: delay scroll and highlight for efp, - // otherwise that scroll could mess up the whole coodirnate calculation - if (isEfp) scrollAndHighlight(); + return parts.join('') +} - focusIfEditable(el); - return true; - }); - }); - } - case 'click': - case 'clickAndWait': - { - return __getElementByLocator(target, extra.waitForVisible, command, csIpc).then(function (el) { - try { - if (extra.playScrollElementsIntoView) el.scrollIntoView({ block: 'center' }); - if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); - } catch (e) { - _log2.default.error('error in scroll and highlight'); - } +/***/ }), - ;['mousedown', 'mouseup', 'click'].forEach(function (eventType) { - if (eventType === 'click' && typeof el.click === 'function') { - return el.click(); - } +/***/ 48287: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - el.dispatchEvent(new MouseEvent(eventType, { - view: window, - bubbles: true, - cancelable: true - })); - }); +"use strict"; +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ - focusIfEditable(el); - return true; - }); - } - case 'check': - case 'uncheck': - { - return __getInputElementByLocator(target, extra.waitForVisible, command, csIpc).then(function (el) { - el.checked = cmd === 'check'; - el.dispatchEvent(new Event('change', { - target: el, - bubbles: true - })); - return true; - }); - } - case 'addSelection': - case 'removeSelection': - case 'select': - case 'selectAndWait': - { - return __getElementByLocator(target, extra.waitForVisible, command, csIpc).then(function (el) { - var options = [].slice.call(el.getElementsByTagName('option')); - var i = value.indexOf('='); - var optionType = value.substring(0, i); - var optionValue = value.substring(i + 1); +const base64 = __webpack_require__(67526) +const ieee754 = __webpack_require__(251) +const customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null - var option = function () { - switch (optionType) { - case 'label': - return options.find(function (op) { - return (0, _glob.globMatch)(optionValue, (0, _dom_utils.domText)(op).trim()); - }); +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 - case 'index': - return options.find(function (_, index) { - return index === parseInt(optionValue); - }); +const K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH - case 'id': - return options.find(function (op, index) { - return op.id === optionValue; - }); +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - case 'value': - return options.find(function (op) { - return op.value === optionValue; - }); +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} - default: - throw new Error('Option type "' + optionType + '" not supported'); - } - }(); +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + const arr = new Uint8Array(1) + const proto = { foo: function () { return 42 } } + Object.setPrototypeOf(proto, Uint8Array.prototype) + Object.setPrototypeOf(arr, proto) + return arr.foo() === 42 + } catch (e) { + return false + } +} - if (!option) { - throw new Error('cannot find option with \'' + value + '\''); - } +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) - if (extra.playScrollElementsIntoView) el.scrollIntoView({ block: 'center' }); - if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) - switch (cmd) { - case 'addSelection': - option.selected = true; - break; +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + const buf = new Uint8Array(length) + Object.setPrototypeOf(buf, Buffer.prototype) + return buf +} - case 'removeSelection': - option.selected = false; - break; +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ - default: - el.value = option.value; - break; - } +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} - el.dispatchEvent(new Event('change', { - target: el, - bubbles: true - })); - return true; - }); - } +Buffer.poolSize = 8192 // not used by this implementation - case 'type': - { - return __getElementByLocator(target, extra.waitForVisible, command, csIpc).then(function (el) { - var tag = el.tagName.toLowerCase(); +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } - if (tag !== 'input' && tag !== 'textarea') { - throw new Error('run command: element found is neither input nor textarea'); - } + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } - if (extra.playScrollElementsIntoView) el.scrollIntoView({ block: 'center' }); - if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } - // Note: need the help of chrome.debugger to set file path to file input - if (el.type && el.type.toLowerCase() === 'file') { - if (_web_extension2.default.isFirefox()) { - throw new Error('Setting file path fo file inputs is not supported by Firefox extension api yet'); - } + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } - return csIpc.ask('CS_SET_FILE_INPUT_FILES', { - files: value.split(';'), - selector: (0, _dom_utils.cssSelector)(el) - }); - } + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } - focusIfEditable(el); + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } - return (0, _encrypt.decryptIfNeeded)(value, el).then(function (realValue) { - el.value = ''; + const valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } - if (realValue.length <= _config2.default.commandRunner.sendKeysMaxCharCount) { - (0, _send_keys2.default)(el, realValue, true); - } + const b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} - el.value = realValue; - el.dispatchEvent(new Event('change', { - target: el, - bubbles: true - })); - return true; - }); - }).catch(function (e) { - if (/This input element accepts a filename/i.test(e.message)) { - throw new Error('Sorry, upload can not be automated Chrome (API limitation).'); - } +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} - throw e; - }); - } +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) +Object.setPrototypeOf(Buffer, Uint8Array) - case 'editContent': - { - return __getElementByLocator(target, extra.waitForVisible, command, csIpc).then(function (el) { - if (el.contentEditable !== 'true') { - throw new Error('Target is not contenteditable'); - } +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} - if (extra.playScrollElementsIntoView) el.scrollIntoView({ block: 'center' }); - if (extra.playHighlightElements) helpers.highlightDom(el, HIGHLIGHT_TIMEOUT); +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} - el.focus(); - el.innerHTML = value; - el.blur(); +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} - return true; - }); - } +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} - case 'selectFrame': - { - return __getFrameByLocator(target, helpers).then(function (frameWindow) { - if (!frameWindow) { - throw new Error('Invalid frame/iframe'); - } +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} - return frameWindow; - }); - } +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } - case 'verifyText': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - var text = (0, _dom_utils.domText)(el); + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } - if (!(0, _glob.globMatch)(value, text)) { - return { - log: { - error: 'text not matched, \n\texpected: "' + value + '", \n\tactual: "' + text + '"' - } - }; - } + const length = byteLength(string, encoding) | 0 + let buf = createBuffer(length) - return true; - }); - } + const actual = buf.write(string, encoding) - case 'verifyTitle': - { - if (!(0, _glob.globMatch)(target, document.title)) { - return { - log: { - error: 'title not matched, \n\texpected: "' + target + '", \n\tactual: "' + document.title + '"' - } - }; - } + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } - return true; - } + return buf +} - case 'verifyElementPresent': - { - var _ref6 = extra || {}, - timeoutElement = _ref6.timeoutElement, - retryInfo = _ref6.retryInfo; +function fromArrayLike (array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0 + const buf = createBuffer(length) + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} - return __getElementByLocator(target, false, command, csIpc).then(function () { - return true; - }, function (e) { - var shotsLeft = timeoutElement * 1000 / retryInfo.retryInterval - retryInfo.retryCount; - var isLastChance = shotsLeft <= 1; +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView) + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} - if (isLastChance) { - return { - log: { - error: '\'' + target + '\' element not present' - } - }; - } +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } - throw e; - }); - } + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } - case 'verifyElementNotPresent': - { - var _ref7 = extra || {}, - _timeoutElement = _ref7.timeoutElement, - _retryInfo = _ref7.retryInfo; + let buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } - return __expectNoElementByLocator(target).then(function () { - return true; - }, function (e) { - var shotsLeft = _timeoutElement * 1000 / _retryInfo.retryInterval - _retryInfo.retryCount; - var isLastChance = shotsLeft <= 1; + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype) - if (isLastChance) { - return { - log: { - error: '\'' + target + '\' element is still present' - } - }; - } + return buf +} - throw e; - }); - } +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + const len = checked(obj.length) | 0 + const buf = createBuffer(len) - case 'verifyEditable': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - var editable = (0, _dom_utils.isEditable)(el); + if (buf.length === 0) { + return buf + } - if (!editable) { - return { - log: { - error: '\'' + target + '\' is not editable' - } - }; - } + obj.copy(buf, 0, 0, len) + return buf + } - return true; - }); - } + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } - case 'verifyNotEditable': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - var editable = (0, _dom_utils.isEditable)(el); + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} - if (editable) { - return { - log: { - error: '\'' + target + '\' is editable' - } - }; - } +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} - return true; - }); - } +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} - case 'verifyChecked': - { - return __getInputElementByLocator(target, false, command, csIpc).then(function (el) { - var checked = !!el.checked; +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} - if (!checked) { - return { - log: { - error: '\'' + target + '\' is not checked' - } - }; - } +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } - return true; - }); - } - case 'verifyNotChecked': - { - return __getInputElementByLocator(target, false, command, csIpc).then(function (el) { - var checked = !!el.checked; + if (a === b) return 0 - if (checked) { - return { - log: { - error: '\'' + target + '\' is checked' - } - }; - } + let x = a.length + let y = b.length - return true; - }); - } + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } - case 'verifyAttribute': - { - var index = target.lastIndexOf('@'); + if (x < y) return -1 + if (y < x) return 1 + return 0 +} - if (index === -1) { - throw new Error('invalid target for verifyAttribute - ' + target); - } +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} - var locator = target.substr(0, index); - var attrName = target.substr(index + 1); +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } - return __getElementByLocator(locator, false, command, csIpc).then(function (el) { - var attr = el.getAttribute(attrName); + if (list.length === 0) { + return Buffer.alloc(0) + } - if (!(0, _glob.globMatch)(value, attr)) { - return { - log: { - error: 'attribute not matched, \n\texpected: "' + value + '", \n\tactual: "' + attr + '"' - } - }; - } + let i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } - return true; - }); + const buffer = Buffer.allocUnsafe(length) + let pos = 0 + for (i = 0; i < list.length; ++i) { + let buf = list[i] + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + buf.copy(buffer, pos) + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ) } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos) + } + pos += buf.length + } + return buffer +} - case 'verifyError': - { - if (extra.lastCommandOk) { - return { - log: { - error: target - } - }; - } +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } - return true; - } + const len = string.length + const mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 - case 'assertText': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - var text = (0, _dom_utils.domText)(el); + // Use a for loop to avoid recursion + let loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength - if (!(0, _glob.globMatch)(value, text)) { - throw new Error('text not matched, \n\texpected: "' + value + '", \n\tactual: "' + text + '"'); - } +function slowToString (encoding, start, end) { + let loweredCase = false - return true; - }); - } + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - case 'assertTitle': - { - if (!(0, _glob.globMatch)(target, document.title)) { - throw new Error('title not matched, \n\texpected: "' + target + '", \n\tactual: "' + document.title + '"'); - } + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } - return true; - } + if (end === undefined || end > this.length) { + end = this.length + } - case 'assertElementPresent': - { - return __getElementByLocator(target, false, command, csIpc).then(function () { - return true; - }); - } + if (end <= 0) { + return '' + } - case 'assertElementNotPresent': - { - return __expectNoElementByLocator(target); - } + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 - case 'assertChecked': - { - return __getInputElementByLocator(target, false, command, csIpc).then(function (el) { - var checked = !!el.checked; + if (end <= start) { + return '' + } - if (!checked) { - throw new Error('\'' + target + '\' is not checked'); - } + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) - return true; - }); - } + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - case 'assertNotChecked': - { - return __getInputElementByLocator(target, false, command, csIpc).then(function (el) { - var checked = !!el.checked; + case 'ascii': + return asciiSlice(this, start, end) - if (checked) { - throw new Error('\'' + target + '\' is checked'); - } + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) - return true; - }); - } + case 'base64': + return base64Slice(this, start, end) - case 'assertEditable': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - var editable = (0, _dom_utils.isEditable)(el); + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) - if (!editable) { - throw new Error('\'' + target + '\' is not editable'); - } + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} - return true; - }); - } +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true - case 'assertNotEditable': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - var editable = (0, _dom_utils.isEditable)(el); +function swap (b, n, m) { + const i = b[n] + b[n] = b[m] + b[m] = i +} - if (editable) { - throw new Error('\'' + target + '\' is editable'); - } +Buffer.prototype.swap16 = function swap16 () { + const len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} - return true; - }); - } +Buffer.prototype.swap32 = function swap32 () { + const len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} - case 'assertAttribute': - { - var _index = target.lastIndexOf('@'); +Buffer.prototype.swap64 = function swap64 () { + const len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} - if (_index === -1) { - throw new Error('invalid target for assertAttribute - ' + target); - } +Buffer.prototype.toString = function toString () { + const length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} - var _locator = target.substr(0, _index); - var _attrName = target.substr(_index + 1); +Buffer.prototype.toLocaleString = Buffer.prototype.toString - return __getElementByLocator(_locator, false, command, csIpc).then(function (el) { - var attr = el.getAttribute(_attrName); +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} - if (!(0, _glob.globMatch)(value, attr)) { - throw new Error('attribute not matched, \n\texpected: "' + value + '", \n\tactual: "' + attr + '"'); - } +Buffer.prototype.inspect = function inspect () { + let str = '' + const max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect +} - return true; - }); - } +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } - case 'assertError': - { - if (extra.lastCommandOk) { - throw new Error(target); - } + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } - return true; - } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } - case 'assertAlert': - { - var msg = document.body.getAttribute('data-alert'); + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } - if (!msg) { - throw new Error('no alert found!'); - } + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 - if (!(0, _glob.globMatch)(target, msg)) { - throw new Error('unmatched alert msg, \n\texpected: "' + target + '", \n\tactual: "' + msg + '"'); - } + if (this === target) return 0 - document.body.setAttribute('data-alert', ''); - return true; - } + let x = thisEnd - thisStart + let y = end - start + const len = Math.min(x, y) - case 'assertConfirmation': - { - var _msg = document.body.getAttribute('data-confirm'); + const thisCopy = this.slice(thisStart, thisEnd) + const targetCopy = target.slice(start, end) - if (!_msg) { - throw new Error('no confirm found!'); - } + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } - if (!(0, _glob.globMatch)(target, _msg)) { - throw new Error('unmatched confirm msg, \n\texpected: "' + target + '", \n\tactual: "' + _msg + '"'); - } + if (x < y) return -1 + if (y < x) return 1 + return 0 +} - document.body.setAttribute('data-confirm', ''); - return true; - } +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 - case 'assertPrompt': - { - var _msg2 = document.body.getAttribute('data-prompt'); + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } - if (!_msg2) { - throw new Error('no prompt found!'); - } + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } - if (!(0, _glob.globMatch)(target, _msg2)) { - throw new Error('unmatched prompt msg, \n\texpected: "' + target + '", \n\tactual: "' + _msg2 + '"'); - } + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } - document.body.setAttribute('data-prompt', ''); - return true; + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } - case 'answerOnNextPrompt': - { - document.body.setAttribute('data-prompt-answer', target); - return true; - } + throw new TypeError('val must be string, number or Buffer') +} - case 'waitForPageToLoad': - return true; +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + let indexSize = 1 + let arrLength = arr.length + let valLength = val.length - case 'storeXpathCount': - { - var i = target.indexOf('='); - var method = target.substr(0, i); - var xpathStr = target.substr(i + 1); - var lowerMethod = method && method.toLowerCase(); + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } - if (lowerMethod !== 'xpath') { - throw new Error('storeXpathCount: target should start with "xpath="'); - } + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } - return { - vars: (0, _defineProperty3.default)({}, value, (0, _dom_utils.getElementsByXPath)(xpathStr).length) - }; + let i + if (dir) { + let foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 } - - case 'storeTitle': - { - return { - vars: (0, _defineProperty3.default)({}, value, document.title) - }; + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + let found = true + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } } + if (found) return i + } + } - case 'storeText': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - return { - vars: (0, _defineProperty3.default)({}, value, (0, _dom_utils.domText)(el)) - }; - }); - } + return -1 +} - case 'storeAttribute': - { - var _index2 = target.lastIndexOf('@'); +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} - if (_index2 === -1) { - throw new Error('invalid target for storeAttribute - ' + target); - } +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} - var _locator2 = target.substr(0, _index2); - var _attrName2 = target.substr(_index2 + 1); +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} - return __getElementByLocator(_locator2, false, command, csIpc).then(function (el) { - var attr = el.getAttribute(_attrName2); +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + const remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } - if (!attr) { - throw new Error('missing attribute \'' + _attrName2 + '\''); - } + const strLen = string.length - return { - vars: (0, _defineProperty3.default)({}, value, attr) - }; - }); - } + if (length > strLen / 2) { + length = strLen / 2 + } + let i + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} - case 'storeEval': - { - return (0, _eval.untilInjected)().then(function (api) { - return api.eval(target).then(function (result) { - return { - vars: (0, _defineProperty3.default)({}, value, result) - }; - }).catch(function (e) { - throw new Error('Error in runEval code: ' + e.message); - }); - }); - } +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} - case 'storeValue': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - var text = el.value || ''; +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} - return { - vars: (0, _defineProperty3.default)({}, value, text) - }; - }); - } +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} - case 'storeChecked': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - var checked = !!el.checked; +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} - return { - vars: (0, _defineProperty3.default)({}, value, checked) - }; - }); - } +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } - case 'verifyValue': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - var text = el.value; + const remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining - if (!(0, _glob.globMatch)(value, text)) { - return { - log: { - error: 'value not matched, \n\texpected: "' + value + '", \n\tactual: "' + text + '"' - } - }; - } + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } - return true; - }); - } + if (!encoding) encoding = 'utf8' - case 'assertValue': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - var text = el.value; + let loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) - if (!(0, _glob.globMatch)(value, text)) { - throw new Error('value not matched, \n\texpected: "' + value + '", \n\tactual: "' + text + '"'); - } + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) - return true; - }); - } + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) - case 'executeScript': - case 'executeAsyncScript': - { - return (0, _eval.untilInjected)().then(function (api) { - var code = 'Promise.resolve((function () { ' + target + ' })());'; + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) - return api.eval(code).then(function (result) { - if (value && value.length) { - return { - vars: (0, _defineProperty3.default)({}, value, result) - }; - } + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) - return true; - }).catch(function (e) { - throw new Error('Error in ' + cmd + ' code: ' + e.message); - }); - }); - } + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} - case 'sendKeys': - { - return __getElementByLocator(target, false, command, csIpc).then(function (el) { - focusIfEditable(el); - (0, _send_keys2.default)(el, value); - return true; - }); - } +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} - case 'sourceSearch': - case 'sourceExtract': - { - if (!target) { - throw new Error('Must provide text / regular expression to search for'); - } +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} - if (!value) { - throw new Error('Must specify a variable to save the result'); - } +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + const res = [] - var getMatchAndCaptureIndex = function getMatchAndCaptureIndex(str) { - var nonZeroIndex = function nonZeroIndex(n) { - var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + let i = start + while (i < end) { + const firstByte = buf[i] + let codePoint = null + let bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1 - if (n === undefined) return 0; - return Math.max(0, parseInt(n, 10) + offset); - }; - var m = /@\s*(\d+)(?:\s*,\s*(\d+))?\s*$/.exec(str); + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint - if (!m) { - return { - rest: str, - matchIndex: 0, - captureIndex: 0 - }; + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } - return { - rest: str.substring(0, m.index), - matchIndex: nonZeroIndex(m[1], -1), - captureIndex: nonZeroIndex(m[2]) - }; - }; + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } - // Note: get matchIndex captureIndex first, no matter it's for regexp or simple text + res.push(codePoint) + i += bytesPerSequence + } - var _getMatchAndCaptureIn = getMatchAndCaptureIndex(target), - rest = _getMatchAndCaptureIn.rest, - matchIndex = _getMatchAndCaptureIn.matchIndex, - captureIndex = _getMatchAndCaptureIn.captureIndex; + return decodeCodePointsArray(res) +} - if (cmd === 'sourceSearch' && rest !== target) { - throw new Error('The @ parameter is only supported in sourceExtract'); - } +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +const MAX_ARGUMENTS_LENGTH = 0x1000 - var regexp = function () { - if (!/^regex(=|:)/i.test(rest)) { - return null; - } +function decodeCodePointsArray (codePoints) { + const len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } - var raw = rest.replace(/^regex(=|:)/i, ''); - var reg = /^\/(.*)\/([gimsuy]+)?$/; + // Decode in chunks to avoid "call stack size exceeded". + let res = '' + let i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} - if (!reg.test(raw)) { - return (0, _utils.toRegExp)(raw.replace(/^\/|\/g?$/g, ''), { needEncode: false, flag: 'g' }); - } +function asciiSlice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) - var match = raw.match(reg); + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} - if (!match || !match.length) { - return null; - } +function latin1Slice (buf, start, end) { + let ret = '' + end = Math.min(buf.length, end) - var _match = (0, _slicedToArray3.default)(match, 3), - _ = _match[0], - regexpText = _match[1], - flags = _match[2]; + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} - var flagText = _ts_utils.uniqueStrings.apply(undefined, ['g'].concat((0, _toConsumableArray3.default)(flags.split('')))).join(''); +function hexSlice (buf, start, end) { + const len = buf.length - return (0, _utils.toRegExp)(regexpText, { needEncode: false, flag: flagText }); - }(); - var regexpForText = function () { - if (regexp) return null; - var raw = rest.replace(/^text(=|:)/i, ''); + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len - if (cmd === 'sourceExtract' && !/\*/.test(raw)) { - throw new Error('Missing * or REGEX in sourceExtract. Extracting a plain text doesn\'t make much sense'); - } + let out = '' + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]] + } + return out +} - // flag 's': Allows . to match newline characters. (Added in ES2018, not yet supported in Firefox). - // reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Advanced_searching_with_flags_2 - var flags = RegExp.prototype.hasOwnProperty('dotAll') ? 'gs' : 'g'; - return (0, _kdGlobToRegexp2.default)(raw, { flags: flags, capture: true, nonGreedy: true }); - }(); - var matches = function () { - var html = document.documentElement.outerHTML; - var reg = regexp || regexpForText; - var result = []; - var m = void 0; +function utf16leSlice (buf, start, end) { + const bytes = buf.slice(start, end) + let res = '' + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} - // eslint-disable-next-line no-cond-assign - while (m = reg.exec(html)) { - result.push(m); +Buffer.prototype.slice = function slice (start, end) { + const len = this.length + start = ~~start + end = end === undefined ? len : ~~end - // Note: save some energy, if it's already enough to get what users want - if (cmd === 'sourceExtract' && result.length >= matchIndex + 1) { - break; - } - } + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } - return result; - }(); + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } - (0, _log2.default)('matches', matches, regexp, regexpForText); + if (end < start) end = start - if (cmd === 'sourceSearch') { - return { - vars: (0, _defineProperty3.default)({}, value, matches.length) - }; - } + const newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype) - if (cmd === 'sourceExtract') { - var guard = function guard(str) { - return str !== undefined ? str : '#nomatchfound'; - }; + return newBuf +} - return { - vars: (0, _defineProperty3.default)({}, value, guard((matches[matchIndex] || [])[captureIndex])) - }; - } +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} - throw new Error('Impossible to reach here'); - } +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - case 'visionLimitSearchArea': - case 'storeImage': - { - var _run = function _run(locator, fileName) { - return __getElementByLocator(locator).then(function (el) { - if (!fileName || !fileName.length) { - throw new Error('storeImage: \'value\' is required as image name'); - } + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } - var clientRect = el.getBoundingClientRect(); - var pSourceOffset = function () { - if (window.top === window) { - return _promise2.default.resolve({ x: 0, y: 0 }); - } + return val +} - // Note: it's too complicated to take screenshot of element deep in iframe stack - // if you have to scroll each level of iframe to get the full image of it. - el.scrollIntoView(); +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } - return (0, _cs_postmessage.postMessage)(window.parent, window, { - action: 'SOURCE_PAGE_OFFSET', - data: {} - }); - }(); + let val = this[offset + --byteLength] + let mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } - return pSourceOffset.then(function (sourceOffset) { - var rect = { - x: sourceOffset.x + clientRect.x + (0, _dom_utils.scrollLeft)(document), - y: sourceOffset.y + clientRect.y + (0, _dom_utils.scrollTop)(document), - width: clientRect.width, - height: clientRect.height - }; + return val +} - return csIpc.ask('CS_STORE_SCREENSHOT_IN_SELECTION', { - rect: rect, - fileName: (0, _utils.ensureExtName)('.png', fileName), - devicePixelRatio: window.devicePixelRatio - }).then(function () { - return { - vars: { - '!storedImageRect': rect - } - }; - }); - }); - }); - }; +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} - var _locator3 = void 0, - fileName = void 0; +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} - if (cmd === 'storeImage') { - _locator3 = target; - fileName = value; - } else if (cmd === 'visionLimitSearchArea') { - _locator3 = target.trim().replace(/^element:/i, '').trim(); - fileName = _constant.LAST_SCREENSHOT_FILE_NAME; - } +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} - return _run(_locator3, fileName); - } +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) - case 'onDownload': - { - return csIpc.ask('CS_ON_DOWNLOAD', { - fileName: target, - wait: (value || '').trim() === 'true', - timeout: extra.timeoutDownload * 1000, - timeoutForStart: extra.timeoutDownloadStart * 1000 - }); - } + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} - case 'deleteAllCookies': - { - return csIpc.ask('CS_DELETE_ALL_COOKIES', { - url: window.location.origin - }).then(function () { - return true; - }); - } +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) - case 'if': - case 'while': - case 'gotoIf': - { - return (0, _eval.untilInjected)().then(function (api) { - return api.eval(target); - }).then(function (result) { - return { condition: result }; - }); - } + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} - default: - throw new Error('Command ' + cmd + ' not supported yet'); +Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) } -}; -/***/ }), + const lo = first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24 -/***/ 30751: -/***/ ((module) => { + const hi = this[++offset] + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + last * 2 ** 24 -"use strict"; + return BigInt(lo) + (BigInt(hi) << BigInt(32)) +}) +Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } -function removeFromArray(array, item) { - var index = array.indexOf(item); + const hi = first * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] - if (index >= 0) { - array.splice(index, 1); - } -} + const lo = this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last -var DataTransfer = function DataTransfer() { - this.dataByFormat = {}; + return (BigInt(hi) << BigInt(32)) + BigInt(lo) +}) - this.dropEffect = 'none'; - this.effectAllowed = 'all'; - this.files = []; - this.types = []; -}; +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) -DataTransfer.prototype.clearData = function (dataFormat) { - if (dataFormat) { - delete this.dataByFormat[dataFormat]; - removeFromArray(this.types, dataFormat); - } else { - this.dataByFormat = {}; - this.types = []; + let val = this[offset] + let mul = 1 + let i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul } -}; + mul *= 0x80 -DataTransfer.prototype.getData = function (dataFormat) { - return this.dataByFormat[dataFormat]; -}; + if (val >= mul) val -= Math.pow(2, 8 * byteLength) -DataTransfer.prototype.setData = function (dataFormat, data) { - this.dataByFormat[dataFormat] = data; + return val +} - if (this.types.indexOf(dataFormat) < 0) { - this.types.push(dataFormat); +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + let i = byteLength + let mul = 1 + let val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul } + mul *= 0x80 - return true; -}; - -DataTransfer.prototype.setDragImage = function () { - // don't do anything (the stub just makes sure there is no error thrown if someone tries to call the method) -}; + if (val >= mul) val -= Math.pow(2, 8 * byteLength) -module.exports = function () { - // Note: in Firefox, window.DataTransfer exists, but it can't be used as constructor - // In Firefox, `new window.DataTransfer()` throws errors like 'TypeError: Illegal constructor' - if (window.DataTransfer) { - try { - var tmp = new window.DataTransfer(); - return window.DataTransfer; - } catch (e) {} - } + return val +} - return DataTransfer; -}(); +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} -/***/ }), +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} -/***/ 47875: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + const val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} -"use strict"; +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} -var _typeof2 = __webpack_require__(72444); +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) -var _typeof3 = _interopRequireDefault(_typeof2); + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) + } -var eventFactory = __webpack_require__(26538), - DataTransfer = __webpack_require__(30751); + const val = this[offset + 4] + + this[offset + 5] * 2 ** 8 + + this[offset + 6] * 2 ** 16 + + (last << 24) // Overflow -function _noop() {} + return (BigInt(val) << BigInt(32)) + + BigInt(first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24) +}) -function parseParams(targetElement, eventProperties, configCallback) { - if (typeof eventProperties === 'function') { - configCallback = eventProperties; - eventProperties = null; +Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) { + offset = offset >>> 0 + validateNumber(offset, 'offset') + const first = this[offset] + const last = this[offset + 7] + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8) } - if (!targetElement || (typeof targetElement === 'undefined' ? 'undefined' : (0, _typeof3.default)(targetElement)) !== 'object') { - throw new Error('Expected first parameter to be a targetElement. Instead got: ' + targetElement); - } + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset] - return { - targetElement: targetElement, - eventProperties: eventProperties || {}, - configCallback: configCallback || _noop - }; -} + return (BigInt(val) << BigInt(32)) + + BigInt(this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last) +}) -function customizeEvent(event, configCallback, isPrimaryEvent) { - if (configCallback) { - // call configCallback only for the primary event if the callback takes less than two arguments - if (configCallback.length < 2) { - if (isPrimaryEvent) { - configCallback(event); - } - } - // call configCallback for each event if the callback takes two arguments - else { - configCallback(event, event.type); - } - } +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) } -function createAndDispatchEvents(targetElement, eventNames, primaryEventName, dataTransfer, eventProperties, configCallback) { - eventNames.forEach(function (eventName) { - var event = eventFactory.createEvent(eventName, eventProperties, dataTransfer); - var isPrimaryEvent = eventName === primaryEventName; - - customizeEvent(event, configCallback, isPrimaryEvent); +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} - targetElement.dispatchEvent(event); - }); +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) } -var DragDropAction = function DragDropAction() { - this.lastDragSource = null; - this.lastDataTransfer = null; - this.pendingActionsQueue = []; -}; +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} -DragDropAction.prototype._queue = function (fn) { - this.pendingActionsQueue.push(fn); +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} - if (this.pendingActionsQueue.length === 1) { - this._queueExecuteNext(); +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) } -}; -DragDropAction.prototype._queueExecuteNext = function () { - if (this.pendingActionsQueue.length === 0) { - return; + let mul = 1 + let i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF } - var self = this; - var firstPendingAction = this.pendingActionsQueue[0]; - - var doneCallback = function doneCallback() { - self.pendingActionsQueue.shift(); - self._queueExecuteNext(); - }; + return offset + byteLength +} - if (firstPendingAction.length === 0) { - firstPendingAction.call(this); - doneCallback(); - } else { - firstPendingAction.call(this, doneCallback); +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) } -}; -DragDropAction.prototype.dragStart = function (targetElement, eventProperties, configCallback) { - var params = parseParams(targetElement, eventProperties, configCallback), - events = ['mousedown', 'dragstart', 'drag'], - dataTransfer = new DataTransfer(); + let i = byteLength - 1 + let mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } - this._queue(function () { - createAndDispatchEvents(params.targetElement, events, 'drag', dataTransfer, params.eventProperties, params.configCallback); + return offset + byteLength +} - this.lastDragSource = targetElement; - this.lastDataTransfer = dataTransfer; - }); +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} - return this; -}; +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} -DragDropAction.prototype.dragEnter = function (overElement, eventProperties, configCallback) { - var params = parseParams(overElement, eventProperties, configCallback), - events = ['mousemove', 'mouseover', 'dragenter']; +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} - this._queue(function () { - createAndDispatchEvents(params.targetElement, events, 'dragenter', this.lastDataTransfer, params.eventProperties, params.configCallback); - }); +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} - return this; -}; +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} -DragDropAction.prototype.dragOver = function (overElement, eventProperties, configCallback) { - var params = parseParams(overElement, eventProperties, configCallback), - events = ['mousemove', 'mouseover', 'dragover']; +function wrtBigUInt64LE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) - this._queue(function () { - createAndDispatchEvents(params.targetElement, events, 'drag', this.lastDataTransfer, params.eventProperties, params.configCallback); - }); + let lo = Number(value & BigInt(0xffffffff)) + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + lo = lo >> 8 + buf[offset++] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + hi = hi >> 8 + buf[offset++] = hi + return offset +} - return this; -}; +function wrtBigUInt64BE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7) -DragDropAction.prototype.dragLeave = function (overElement, eventProperties, configCallback) { - var params = parseParams(overElement, eventProperties, configCallback), - events = ['mousemove', 'mouseover', 'dragleave']; + let lo = Number(value & BigInt(0xffffffff)) + buf[offset + 7] = lo + lo = lo >> 8 + buf[offset + 6] = lo + lo = lo >> 8 + buf[offset + 5] = lo + lo = lo >> 8 + buf[offset + 4] = lo + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) + buf[offset + 3] = hi + hi = hi >> 8 + buf[offset + 2] = hi + hi = hi >> 8 + buf[offset + 1] = hi + hi = hi >> 8 + buf[offset] = hi + return offset + 8 +} - this._queue(function () { - createAndDispatchEvents(params.targetElement, events, 'dragleave', this.lastDataTransfer, params.eventProperties, params.configCallback); - }); +Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) - return this; -}; +Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}) -DragDropAction.prototype.drop = function (targetElement, eventProperties, configCallback) { - var params = parseParams(targetElement, eventProperties, configCallback); - var eventsOnDropTarget = ['mousemove', 'mouseup', 'drop']; - var eventsOnDragSource = ['dragend']; +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) - this._queue(function () { - createAndDispatchEvents(params.targetElement, eventsOnDropTarget, 'drop', this.lastDataTransfer, params.eventProperties, params.configCallback); + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } - if (this.lastDragSource) { - // trigger dragend event on last drag source element - createAndDispatchEvents(this.lastDragSource, eventsOnDragSource, 'drop', this.lastDataTransfer, params.eventProperties, params.configCallback); + let i = 0 + let mul = 1 + let sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 } - }); + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } - return this; -}; + return offset + byteLength +} -DragDropAction.prototype.then = function (callback) { - this._queue(function () { - callback.call(this); - }); // make sure _queue() is given a callback with no arguments +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1) - return this; -}; + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } -DragDropAction.prototype.delay = function (waitingTimeMs) { - this._queue(function (done) { - window.setTimeout(done, waitingTimeMs); - }); + let i = byteLength - 1 + let mul = 1 + let sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } - return this; -}; + return offset + byteLength +} -module.exports = DragDropAction; +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} -/***/ }), +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} -/***/ 26538: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} -"use strict"; +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} -var DataTransfer = __webpack_require__(30751); +Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) -var dataTransferEvents = ['drag', 'dragstart', 'dragenter', 'dragover', 'dragend', 'drop', 'dragleave']; +Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}) -function mergeInto(destObj, srcObj) { - for (var key in srcObj) { - if (!srcObj.hasOwnProperty(key)) { - continue; - } // ignore inherited properties +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} - destObj[key] = srcObj[key]; +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } - - return destObj; + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 } -function isFirefox() { - return (/Firefox/.test(window.navigator.userAgent) - ); +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) } -function createModernEvent(eventName, eventType, eventProperties) { - // if (eventType === 'DragEvent') { eventType = 'CustomEvent'; } // Firefox fix (since FF does not allow us to override dataTransfer) - - var constructor = window[eventType]; - var options = { view: window, bubbles: true, cancelable: true }; - - mergeInto(options, eventProperties); +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} - var event = new constructor(eventName, options); +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} - mergeInto(event, eventProperties); +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} - return event; +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) } -function createLegacyEvent(eventName, eventType, eventProperties) { - var event; +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 - switch (eventType) { - case 'MouseEvent': - event = document.createEvent('MouseEvent'); - event.initEvent(eventName, true, true); - break; + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') - default: - event = document.createEvent('CustomEvent'); - event.initCustomEvent(eventName, true, true, 0); + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start } - // copy eventProperties into event - if (eventProperties) { - mergeInto(event, eventProperties); + const len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) } - return event; + return len } -function _createEvent(eventName, eventType, eventProperties) { - if (isFirefox()) { - return createLegacyEvent(eventName, eventType, eventProperties); +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + const code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } else if (typeof val === 'boolean') { + val = Number(val) } - try { - return createModernEvent(eventName, eventType, eventProperties); - } catch (error) { - return createLegacyEvent(eventName, eventType, eventProperties); + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') } -} - -var EventFactory = { - createEvent: function createEvent(eventName, eventProperties, dataTransfer) { - var eventType = 'CustomEvent'; - if (eventName.match(/^mouse/)) { - eventType = 'MouseEvent'; - } else if (eventName.match(/^(drag|drop)/)) { - eventType = 'DragEvent'; - } + if (end <= start) { + return this + } - if (dataTransferEvents.indexOf(eventName) > -1) { - eventProperties.dataTransfer = dataTransfer || new DataTransfer(); - } + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 - var event = _createEvent(eventName, eventType, eventProperties); + if (!val) val = 0 - return event; + let i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + const bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + const len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } } -}; -module.exports = EventFactory; + return this +} -/***/ }), +// CUSTOM ERRORS +// ============= -/***/ 44380: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +// Simplified versions from Node, changed for Buffer-only usage +const errors = {} +function E (sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor () { + super() -"use strict"; + Object.defineProperty(this, 'message', { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }) + // Add the error code to the name to include it in the stack trace. + this.name = `${this.name} [${sym}]` + // Access the stack to generate the error message including the error code + // from the name. + this.stack // eslint-disable-line no-unused-expressions + // Reset the name to the actual name. + delete this.name + } -var _eval = __webpack_require__(39505); + get code () { + return sym + } -var DragDropAction = __webpack_require__(47875); + set code (value) { + Object.defineProperty(this, 'code', { + configurable: true, + enumerable: true, + value, + writable: true + }) + } -function call(instance, methodName, args) { - return instance[methodName].apply(instance, args); + toString () { + return `${this.name} [${sym}]: ${this.message}` + } + } } -function triggerDragEvent(element, target) { - var getXpathOfElement = function getXpathOfElement(element) { - if (element == null) { - return 'null'; - } - if (element.parentElement == null) { - return '/' + element.tagName; - } +E('ERR_BUFFER_OUT_OF_BOUNDS', + function (name) { + if (name) { + return `${name} is outside of buffer bounds` + } - var siblingElement = element.parentElement.children; - var tagCount = 0; - var totalTagCount = 0; - var isFound = false; + return 'Attempt to access memory outside buffer bounds' + }, RangeError) +E('ERR_INVALID_ARG_TYPE', + function (name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}` + }, TypeError) +E('ERR_OUT_OF_RANGE', + function (str, range, input) { + let msg = `The value of "${str}" is out of range.` + let received = input + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)) + } else if (typeof input === 'bigint') { + received = String(input) + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received) + } + received += 'n' + } + msg += ` It must be ${range}. Received ${received}` + return msg + }, RangeError) - for (var i = 0; i < siblingElement.length; i++) { - if (siblingElement[i].tagName == element.tagName && !isFound) { - tagCount++; - totalTagCount++; - } else if (siblingElement[i].tagName == element.tagName) { - totalTagCount++; - } - if (siblingElement[i] == element) { - isFound = true; - } - } +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}` +} - if (totalTagCount > 1) { - return getXpathOfElement(element.parentElement) + "/" + element.tagName + "[" + tagCount + "]"; - } +// CHECK FUNCTIONS +// =============== - return getXpathOfElement(element.parentElement) + "/" + element.tagName; - }; - var script = " \ - function simulateDragDrop(sourceNode, destinationNode){\ - function createCustomEvent(type) { \ - var event = new CustomEvent('CustomEvent'); \ - event.initCustomEvent(type, true, true, null); \ - event.dataTransfer = { \ - data: { \ - }, \ - setData: function(type, val) { \ - this.data[type] = val; \ - }, \ - getData: function(type) { \ - return this.data[type]; \ - } \ - }; \ - return event; \ - } \ - function dispatchEvent(node, type, event) { \ - if (node.dispatchEvent) { \ - return node.dispatchEvent(event); \ - } \ - if (node.fireEvent) { \ - return node.fireEvent('on' + type, event); \ - } \ - } \ - var event = createCustomEvent('dragstart'); \ - dispatchEvent(sourceNode, 'dragstart', event); \ - \ - var dropEvent = createCustomEvent('drop'); \ - dropEvent.dataTransfer = event.dataTransfer; \ - dispatchEvent(destinationNode, 'drop', dropEvent); \ - \ - var dragEndEvent = createCustomEvent('dragend'); \ - dragEndEvent.dataTransfer = event.dataTransfer; \ - dispatchEvent(sourceNode, 'dragend', dragEndEvent); \ - } \ - simulateDragDrop(document.evaluate('" + getXpathOfElement(element) + "', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, document.evaluate('" + getXpathOfElement(target) + "', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue);\ - "; +function checkBounds (buf, offset, byteLength) { + validateNumber(offset, 'offset') + if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { + boundsError(offset, buf.length - (byteLength + 1)) + } +} - return (0, _eval.evalViaInject)(script); +function checkIntBI (value, min, max, buf, offset, byteLength) { + if (value > max || value < min) { + const n = typeof min === 'bigint' ? 'n' : '' + let range + if (byteLength > 3) { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}` + } else { + range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + + `${(byteLength + 1) * 8 - 1}${n}` + } + } else { + range = `>= ${min}${n} and <= ${max}${n}` + } + throw new errors.ERR_OUT_OF_RANGE('value', range, value) + } + checkBounds(buf, offset, byteLength) } -var dragMock = { - dragStart: function dragStart(targetElement, eventProperties, configCallback) { - return call(new DragDropAction(), 'dragStart', arguments); - }, - dragEnter: function dragEnter(targetElement, eventProperties, configCallback) { - return call(new DragDropAction(), 'dragEnter', arguments); - }, - dragOver: function dragOver(targetElement, eventProperties, configCallback) { - return call(new DragDropAction(), 'dragOver', arguments); - }, - dragLeave: function dragLeave(targetElement, eventProperties, configCallback) { - return call(new DragDropAction(), 'dragLeave', arguments); - }, - drop: function drop(targetElement, eventProperties, configCallback) { - return call(new DragDropAction(), 'drop', arguments); - }, - delay: function delay(targetElement, eventProperties, configCallback) { - return call(new DragDropAction(), 'delay', arguments); - }, +function validateNumber (value, name) { + if (typeof value !== 'number') { + throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value) + } +} - triggerDragEvent: triggerDragEvent, +function boundsError (value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type) + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value) + } - // Just for unit testing: - DataTransfer: __webpack_require__(30751), - DragDropAction: __webpack_require__(47875), - eventFactory: __webpack_require__(26538) -}; + if (length < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS() + } -module.exports = dragMock; + throw new errors.ERR_OUT_OF_RANGE(type || 'offset', + `>= ${type ? 1 : 0} and <= ${length}`, + value) +} -/***/ }), +// HELPER FUNCTIONS +// ================ -/***/ 19455: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g -"use strict"; +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} +function utf8ToBytes (string, units) { + units = units || Infinity + let codePoint + const length = string.length + let leadSurrogate = null + const bytes = [] -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.selectAreaPromise = exports.selectArea = exports.createRect = exports.createEl = exports.commonStyle = undefined; + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) -var _promise = __webpack_require__(46593); + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } -var _promise2 = _interopRequireDefault(_promise); + // valid lead + leadSurrogate = codePoint -var _defineProperty2 = __webpack_require__(88106); + continue + } -var _defineProperty3 = _interopRequireDefault(_defineProperty2); + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } -var _extends2 = __webpack_require__(88239); + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } -var _extends3 = _interopRequireDefault(_extends2); + leadSurrogate = null -var _keys = __webpack_require__(88902); + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } -var _keys2 = _interopRequireDefault(_keys); + return bytes +} -var _dom_utils = __webpack_require__(24874); +function asciiToBytes (str) { + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} -var _box = __webpack_require__(10431); +function utf16leToBytes (str, units) { + let c, hi, lo + const byteArray = [] + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break -var _web_extension = __webpack_require__(61171); + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } -var _web_extension2 = _interopRequireDefault(_web_extension); + return byteArray +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} -var commonStyle = exports.commonStyle = { - boxSizing: 'border-box', - fontFamily: 'Arial' -}; +function blitBuffer (src, dst, offset, length) { + let i + for (i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} -var createEl = exports.createEl = function createEl(_ref) { - var _ref$tag = _ref.tag, - tag = _ref$tag === undefined ? 'div' : _ref$tag, - _ref$attrs = _ref.attrs, - attrs = _ref$attrs === undefined ? {} : _ref$attrs, - _ref$style = _ref.style, - style = _ref$style === undefined ? {} : _ref$style, - text = _ref.text; +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} - var $el = document.createElement(tag); +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +const hexSliceLookupTable = (function () { + const alphabet = '0123456789abcdef' + const table = new Array(256) + for (let i = 0; i < 16; ++i) { + const i16 = i * 16 + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j] + } + } + return table +})() - (0, _keys2.default)(attrs).forEach(function (key) { - $el.setAttribute(key, attrs[key]); - }); +// Return not function with Error if BigInt not supported +function defineBigIntMethod (fn) { + return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn +} - if (text && text.length) { - $el.innerText = text; - } +function BufferBigIntNotDefined () { + throw new Error('BigInt not supported') +} - (0, _dom_utils.setStyle)($el, style); - return $el; -}; -var createRect = exports.createRect = function createRect(opts) { - var containerStyle = (0, _extends3.default)({}, commonStyle, { - position: 'absolute', - zIndex: 100000, - top: (0, _dom_utils.pixel)(opts.top), - left: (0, _dom_utils.pixel)(opts.left), - width: (0, _dom_utils.pixel)(opts.width), - height: (0, _dom_utils.pixel)(opts.height) - }, opts.containerStyle || {}); - var rectStyle = (0, _extends3.default)({}, commonStyle, { - width: '100%', - height: '100%', - border: opts.rectBorderWidth + 'px solid rgb(239, 93, 143)', - cursor: 'move', - background: 'transparent' - }, opts.rectStyle || {}); +/***/ }), - var $container = createEl({ style: containerStyle }); - var $rectangle = createEl({ style: rectStyle }); +/***/ 38075: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - $container.appendChild($rectangle); - document.documentElement.appendChild($container); +"use strict"; - return { - $container: $container, - $rectangle: $rectangle, - destroy: function destroy() { - $container.remove(); - }, - hide: function hide() { - (0, _dom_utils.setStyle)($container, { display: 'none' }); - }, - show: function show() { - (0, _dom_utils.setStyle)($container, { display: 'block' }); - } - }; -}; -var createOverlay = function createOverlay(extraStyles) { - var $overlay = createEl({ - style: (0, _extends3.default)({ - position: 'fixed', - zIndex: 9000, - top: 0, - bottom: 0, - left: 0, - right: 0, - background: 'transparent', - cursor: 'crosshair' - }, extraStyles) - }); +var GetIntrinsic = __webpack_require__(70453); - document.documentElement.appendChild($overlay); +var callBind = __webpack_require__(10487); - return { - $overlay: $overlay, - destroy: function destroy() { - return $overlay.remove(); - } - }; +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; }; -var selectArea = exports.selectArea = function selectArea(_ref2) { - var done = _ref2.done, - _ref2$onDestroy = _ref2.onDestroy, - onDestroy = _ref2$onDestroy === undefined ? function () {} : _ref2$onDestroy, - _ref2$allowCursor = _ref2.allowCursor, - allowCursor = _ref2$allowCursor === undefined ? function (e) { - return true; - } : _ref2$allowCursor, - _ref2$overlayStyles = _ref2.overlayStyles, - overlayStyles = _ref2$overlayStyles === undefined ? {} : _ref2$overlayStyles, - _ref2$clickToDestroy = _ref2.clickToDestroy, - clickToDestroy = _ref2$clickToDestroy === undefined ? true : _ref2$clickToDestroy, - _ref2$preventGlobalCl = _ref2.preventGlobalClick, - preventGlobalClick = _ref2$preventGlobalCl === undefined ? true : _ref2$preventGlobalCl; - var go = function go(done) { - var state = { - box: null, - activated: false, - startPos: null, - rect: null - }; - var resetBodyStyle = function () { - var userSelectKey = _web_extension2.default.isFirefox() ? '-moz-user-select' : 'user-select'; - var style = window.getComputedStyle(document.body); - var oldCursor = style.cursor; - var oldUserSelect = style[userSelectKey]; +/***/ }), - (0, _dom_utils.setStyle)(document.body, (0, _defineProperty3.default)({ - cursor: 'crosshair' - }, userSelectKey, 'none')); - return function () { - return (0, _dom_utils.setStyle)(document.body, (0, _defineProperty3.default)({ cursor: oldCursor }, userSelectKey, oldUserSelect)); - }; - }(); +/***/ 10487: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - var overlayApi = createOverlay(overlayStyles); - var unbindDrag = (0, _dom_utils.bindDrag)({ - preventGlobalClick: preventGlobalClick, - $el: overlayApi.$overlay, - onDragStart: function onDragStart(e) { - e.preventDefault(); - if (!allowCursor(e)) return; +"use strict"; - state.activated = true; - state.startPos = { - x: e.pageX, - y: e.pageY - }; - }, - onDragEnd: function onDragEnd(e) { - e.preventDefault(); - state.activated = false; +var bind = __webpack_require__(66743); +var GetIntrinsic = __webpack_require__(70453); +var setFunctionLength = __webpack_require__(96897); - if (state.box) { - state.box.moveAnchorEnd(); +var $TypeError = __webpack_require__(69675); +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); - var boundingRect = rectObj.$container.getBoundingClientRect(); - API.hide(); +var $defineProperty = __webpack_require__(30655); +var $max = GetIntrinsic('%Math.max%'); - // Note: API.hide() takes some time to have effect - setTimeout(function () { - state.box = null; +module.exports = function callBind(originalFunction) { + if (typeof originalFunction !== 'function') { + throw new $TypeError('a function is required'); + } + var func = $reflectApply(bind, $call, arguments); + return setFunctionLength( + func, + 1 + $max(0, originalFunction.length - (arguments.length - 1)), + true + ); +}; - return _promise2.default.resolve(done(state.rect, boundingRect)).catch(function (e) {}).then(function () { - return API.destroy(); - }); - }, 100); - } - }, - onDrag: function onDrag(e, _ref3) { - var dx = _ref3.dx, - dy = _ref3.dy; +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; - e.preventDefault(); +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} - if (!allowCursor(e)) return; - if (!state.activated) return; - if (!state.box) { - var rect = { - x: state.startPos.x, - y: state.startPos.y, - width: dx, - height: dy - }; - state.rect = rect; - state.box = new _box.Box((0, _extends3.default)({}, rect, { - onStateChange: function onStateChange(_ref4) { - var rect = _ref4.rect; +/***/ }), - state.rect = rect; - API.show(); - API.updatePos(rect); - } - })); +/***/ 5971: +/***/ ((module) => { - state.box.moveAnchorStart({ - anchorPos: _box.BOX_ANCHOR_POS.BOTTOM_RIGHT - }); - } - state.box.moveAnchor({ - x: e.pageX, - y: e.pageY - }); - } - }); +/** + * Expose `Emitter`. + */ - var rectObj = createRect({ - top: -999, - left: -999, - width: 0, - height: 0, - rectStyle: { - border: '1px solid #ff0000', - background: 'rgba(255, 0, 0, 0.1)' - } - }); - var API = { - updatePos: function updatePos(rect) { - (0, _dom_utils.setStyle)(rectObj.$container, { - top: (0, _dom_utils.pixel)(rect.y), - left: (0, _dom_utils.pixel)(rect.x), - width: (0, _dom_utils.pixel)(rect.width), - height: (0, _dom_utils.pixel)(rect.height) - }); - }, - destroy: function destroy() { - resetBodyStyle(); - unbindDrag(); - overlayApi.destroy(); - rectObj.destroy(); +if (true) { + module.exports = Emitter; +} - setTimeout(function () { - document.removeEventListener('click', onClick, true); - document.removeEventListener('keydown', onKeyDown, true); - }, 0); +/** + * Initialize a new `Emitter`. + * + * @api public + */ - onDestroy(); - }, - hide: function hide() { - rectObj.hide(); - }, - show: function show() { - rectObj.show(); - } - }; +function Emitter(obj) { + if (obj) return mixin(obj); +}; - var onClick = function onClick(e) { - // If drag starts, we should ignore click event - if (state.box) return; +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ - e.preventDefault(); - e.stopPropagation(); - API.destroy(); - }; - var onKeyDown = function onKeyDown(e) { - return e.keyCode === 27 && API.destroy(); - }; +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} - document.addEventListener('keydown', onKeyDown, true); +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ - if (clickToDestroy) { - document.addEventListener('click', onClick, true); - } +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; - API.hide(); - return API; - }; +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ - return go(done); +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; }; -var selectAreaPromise = exports.selectAreaPromise = function selectAreaPromise(opts) { - return new _promise2.default(function (resolve, reject) { - var wrappedDone = function wrappedDone() { - resolve(opts.done.apply(opts, arguments)); - }; - var wrappedOnDestroy = function wrappedOnDestroy() { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ - try { - if (opts.onDestroy) opts.onDestroy(args); - } catch (e) {} +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; - resolve(); - }; + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + + // Remove event specific arrays for event types that no + // one is subscribed for to avoid memory leak. + if (callbacks.length === 0) { + delete this._callbacks['$' + event]; + } - selectArea((0, _extends3.default)({}, opts, { - done: wrappedDone, - onDestroy: wrappedOnDestroy - })); - }); + return this; }; -/***/ }), - -/***/ 24043: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ -module.exports = { "default": __webpack_require__(47185), __esModule: true }; +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; -/***/ }), + var args = new Array(arguments.length - 1) + , callbacks = this._callbacks['$' + event]; -/***/ 26378: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } -module.exports = { "default": __webpack_require__(3597), __esModule: true }; + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } -/***/ }), + return this; +}; -/***/ 40863: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ -module.exports = { "default": __webpack_require__(21035), __esModule: true }; +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; -/***/ }), +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ -/***/ 63239: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; -module.exports = { "default": __webpack_require__(92742), __esModule: true }; /***/ }), -/***/ 39730: +/***/ 20320: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -module.exports = { "default": __webpack_require__(97272), __esModule: true }; +var MD5 = __webpack_require__(88276) -/***/ }), - -/***/ 52945: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +module.exports = function (buffer) { + return new MD5().update(buffer).digest() +} -module.exports = { "default": __webpack_require__(56981), __esModule: true }; /***/ }), -/***/ 32242: +/***/ 30041: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -module.exports = { "default": __webpack_require__(33391), __esModule: true }; +"use strict"; -/***/ }), -/***/ 88902: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +var $defineProperty = __webpack_require__(30655); + +var $SyntaxError = __webpack_require__(58068); +var $TypeError = __webpack_require__(69675); + +var gopd = __webpack_require__(75795); + +/** @type {import('.')} */ +module.exports = function defineDataProperty( + obj, + property, + value +) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new $TypeError('`obj` must be an object or a function`'); + } + if (typeof property !== 'string' && typeof property !== 'symbol') { + throw new $TypeError('`property` must be a string or a symbol`'); + } + if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { + throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); + } + if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { + throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); + } + if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { + throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); + } + if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { + throw new $TypeError('`loose`, if provided, must be a boolean'); + } + + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + + /* @type {false | TypedPropertyDescriptor} */ + var desc = !!gopd && gopd(obj, property); + + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value: value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { + // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable + obj[property] = value; // eslint-disable-line no-param-reassign + } else { + throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); + } +}; -module.exports = { "default": __webpack_require__(98613), __esModule: true }; /***/ }), -/***/ 46593: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 69423: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { -module.exports = { "default": __webpack_require__(80112), __esModule: true }; +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* export default binding */ __WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony default export */ function __WEBPACK_DEFAULT_EXPORT__(element) { + if ( + element.ownerDocument.designMode && + element.ownerDocument.designMode.toLowerCase() === 'on' + ) { + return true + } -/***/ }), + switch (element.tagName.toLowerCase()) { + case 'input': + return isEditableInput(element) + case 'textarea': + return true + } -/***/ 93516: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (isContentEditable(element)) { + return true + } -module.exports = { "default": __webpack_require__(80025), __esModule: true }; + return false +} -/***/ }), +function isContentEditable (element) { + if ( + element.contentEditable && + element.contentEditable.toLowerCase() === 'true' + ) { + return true + } + if ( + element.contentEditable && + element.contentEditable.toLowerCase() === 'inherit' && + element.parentNode + ) { + return isContentEditable(element.parentNode) + } + return false +} -/***/ 64275: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function isEditableInput (input) { + switch (input.type) { + case 'text': + return true + case 'email': + return true + case 'password': + return true + case 'search': + return true + case 'tel': + return true + case 'url': + return true + default: + return false + } +} -module.exports = { "default": __webpack_require__(52392), __esModule: true }; /***/ }), -/***/ 36803: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 30655: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -exports.__esModule = true; - -var _promise = __webpack_require__(46593); +var GetIntrinsic = __webpack_require__(70453); -var _promise2 = _interopRequireDefault(_promise); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports["default"] = function (fn) { - return function () { - var gen = fn.apply(this, arguments); - return new _promise2.default(function (resolve, reject) { - function step(key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } +/** @type {import('.')} */ +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true) || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} - if (info.done) { - resolve(value); - } else { - return _promise2.default.resolve(value).then(function (value) { - step("next", value); - }, function (err) { - step("throw", err); - }); - } - } +module.exports = $defineProperty; - return step("next"); - }); - }; -}; /***/ }), -/***/ 99663: -/***/ ((__unused_webpack_module, exports) => { +/***/ 41237: +/***/ ((module) => { "use strict"; -exports.__esModule = true; +/** @type {import('./eval')} */ +module.exports = EvalError; -exports["default"] = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -}; /***/ }), -/***/ 22600: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 69383: +/***/ ((module) => { "use strict"; -exports.__esModule = true; - -var _defineProperty = __webpack_require__(32242); - -var _defineProperty2 = _interopRequireDefault(_defineProperty); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports["default"] = 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; - (0, _defineProperty2.default)(target, descriptor.key, descriptor); - } - } +/** @type {import('.')} */ +module.exports = Error; - return function (Constructor, protoProps, staticProps) { - if (protoProps) defineProperties(Constructor.prototype, protoProps); - if (staticProps) defineProperties(Constructor, staticProps); - return Constructor; - }; -}(); /***/ }), -/***/ 88106: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 79290: +/***/ ((module) => { "use strict"; -exports.__esModule = true; - -var _defineProperty = __webpack_require__(32242); - -var _defineProperty2 = _interopRequireDefault(_defineProperty); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports["default"] = function (obj, key, value) { - if (key in obj) { - (0, _defineProperty2.default)(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } +/** @type {import('./range')} */ +module.exports = RangeError; - return obj; -}; /***/ }), -/***/ 88239: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 79538: +/***/ ((module) => { "use strict"; -exports.__esModule = true; +/** @type {import('./ref')} */ +module.exports = ReferenceError; -var _assign = __webpack_require__(52945); -var _assign2 = _interopRequireDefault(_assign); +/***/ }), -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/***/ 58068: +/***/ ((module) => { -exports["default"] = _assign2.default || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; +"use strict"; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; -}; +/** @type {import('./syntax')} */ +module.exports = SyntaxError; + /***/ }), -/***/ 12424: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 69675: +/***/ ((module) => { "use strict"; -exports.__esModule = true; - -var _isIterable2 = __webpack_require__(40863); - -var _isIterable3 = _interopRequireDefault(_isIterable2); - -var _getIterator2 = __webpack_require__(26378); +/** @type {import('./type')} */ +module.exports = TypeError; -var _getIterator3 = _interopRequireDefault(_getIterator2); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/***/ }), -exports["default"] = function () { - function sliceIterator(arr, i) { - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; +/***/ 35345: +/***/ ((module) => { - try { - for (var _i = (0, _getIterator3.default)(arr), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); +"use strict"; - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"]) _i["return"](); - } finally { - if (_d) throw _e; - } - } - return _arr; - } +/** @type {import('./uri')} */ +module.exports = URIError; - return function (arr, i) { - if (Array.isArray(arr)) { - return arr; - } else if ((0, _isIterable3.default)(Object(arr))) { - return sliceIterator(arr, i); - } else { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); - } - }; -}(); /***/ }), -/***/ 85315: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 37007: +/***/ ((module) => { "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. -exports.__esModule = true; - -var _from = __webpack_require__(24043); - -var _from2 = _interopRequireDefault(_from); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports["default"] = function (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 (0, _from2.default)(arr); +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); } -}; -/***/ }), +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} -/***/ 72444: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} -"use strict"; +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; -exports.__esModule = true; +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; -var _iterator = __webpack_require__(64275); +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; -var _iterator2 = _interopRequireDefault(_iterator); +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; -var _symbol = __webpack_require__(93516); +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} -var _symbol2 = _interopRequireDefault(_symbol); +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); -var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; +EventEmitter.init = function() { -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } -exports["default"] = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { - return typeof obj === "undefined" ? "undefined" : _typeof(obj); -} : function (obj) { - return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); + this._maxListeners = this._maxListeners || undefined; }; -/***/ }), +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; -/***/ 52548: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} -/** - * Copyright (c) 2014-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; -// This method of obtaining a reference to the global object needs to be -// kept identical to the way it is obtained in runtime.js -var g = (function() { return this })() || Function("return this")(); +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); -// Use `getOwnPropertyNames` because not all browsers support calling -// `hasOwnProperty` on the global `self` object in a worker. See #183. -var hadRuntime = g.regeneratorRuntime && - Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0; + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; -// Save the old regeneratorRuntime in case it needs to be restored later. -var oldRuntime = hadRuntime && g.regeneratorRuntime; + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } -// Force reevalutation of runtime.js. -g.regeneratorRuntime = undefined; + var handler = events[type]; -module.exports = __webpack_require__(58544); + if (handler === undefined) + return false; -if (hadRuntime) { - // Restore the original runtime. - g.regeneratorRuntime = oldRuntime; -} else { - // Remove the global property added by runtime.js. - try { - delete g.regeneratorRuntime; - } catch(e) { - g.regeneratorRuntime = undefined; + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); } -} - -/***/ }), - -/***/ 58544: -/***/ ((module) => { + return true; +}; -/** - * Copyright (c) 2014-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; -!(function(global) { - "use strict"; + checkListener(listener); - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); - var inModule = "object" === "object"; - var runtime = global.regeneratorRuntime; - if (runtime) { - if (inModule) { - // If regeneratorRuntime is defined globally and we're in a module, - // make the exports object identical to regeneratorRuntime. - module.exports = runtime; + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; } - // Don't bother evaluating the rest of this file if the runtime was - // already defined globally. - return; + existing = events[type]; } - // Define the runtime globally (as expected by generated code) as either - // module.exports (if we're in a module) or a new, empty object. - runtime = global.regeneratorRuntime = inModule ? module.exports : {}; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - runtime.wrap = wrap; + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); } } - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; + return target; +} - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} +EventEmitter.prototype.on = EventEmitter.prototype.addListener; - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && - NativeIteratorPrototype !== Op && - hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} - var Gp = GeneratorFunctionPrototype.prototype = - Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = - GeneratorFunction.displayName = "GeneratorFunction"; +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - prototype[method] = function(arg) { - return this._invoke(method, arg); - }; - }); - } +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; - runtime.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; - runtime.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - genFun.prototype = Object.create(Gp); - return genFun; - }; + checkListener(listener); - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - runtime.awrap = function(arg) { - return { __await: arg }; - }; + events = this._events; + if (events === undefined) + return this; - function AsyncIterator(generator) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && - typeof value === "object" && - hasOwn.call(value, "__await")) { - return Promise.resolve(value.__await).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); } + } else if (typeof list !== 'function') { + position = -1; - return Promise.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. If the Promise is rejected, however, the - // result for this iteration will be rejected with the same - // reason. Note that rejections of yielded Promises are not - // thrown back into the generator function, as is the case - // when an awaited Promise is rejected. This difference in - // behavior between yield and await is important, because it - // allows the consumer to decide what to do with the yielded - // rejection (swallow it and continue, manually .throw it back - // into the generator, abandon iteration, whatever). With - // await, by contrast, there is no opportunity to examine the - // rejection reason outside the generator function, so the - // only option is to throw it from the await expression, and - // let the generator function handle the exception. - result.value = unwrapped; - resolve(result); - }, reject); - } - } + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } - var previousPromise; + if (position < 0) + return this; - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new Promise(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } + if (list.length === 1) + events[type] = list[0]; - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } - defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - runtime.AsyncIterator = AsyncIterator; + return this; + }; - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - runtime.async = function(innerFn, outerFn, self, tryLocsList) { - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList) - ); +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - return runtime.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; + events = this._events; + if (events === undefined) + return this; - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; } - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; } - context.method = method; - context.arg = arg; + listeners = events[type]; - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); } + } - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } + return this; + }; - state = GenStateExecuting; +function _listeners(target, type, unwrap) { + var events = target._events; - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; + if (events === undefined) + return []; - if (record.arg === ContinueSentinel) { - continue; - } + var evlistener = events[type]; + if (evlistener === undefined) + return []; - return { - value: record.arg, - done: context.done - }; + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; - if (context.method === "throw") { - if (delegate.iterator.return) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined; - maybeInvokeDelegate(delegate, context); +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; - context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method"); - } +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; - return ContinueSentinel; + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; } + } - var record = tryCatch(method, delegate.iterator, context.arg); + return 0; +} - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; - var info = record.arg; +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} - if (! info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined; + function resolver() { + if (typeof emitter.removeListener === 'function') { + emitter.removeListener('error', errorListener); } + resolve([].slice.call(arguments)); + }; - } else { - // Re-yield the result returned by the delegate method. - return info; + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== 'error') { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); } + }); +} - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; +function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); } +} - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === 'function') { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === 'function') { + // EventTarget does not have `error` event semantics like Node + // EventEmitters, we do not listen for `error` events here. + emitter.addEventListener(name, function wrapListener(arg) { + // IE does not have builtin `{ once: true }` support so we + // have to do it manually. + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } +} - Gp[toStringTagSymbol] = "Generator"; - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - Gp[iteratorSymbol] = function() { - return this; - }; +/***/ }), - Gp.toString = function() { - return "[object Generator]"; - }; +/***/ 78463: +/***/ ((module) => { - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; +module.exports = stringify +stringify.default = stringify +stringify.stable = deterministicStringify +stringify.stableStringify = deterministicStringify - if (1 in locs) { - entry.catchLoc = locs[1]; - } +var LIMIT_REPLACE_NODE = '[...]' +var CIRCULAR_REPLACE_NODE = '[Circular]' - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } +var arr = [] +var replacerStack = [] - this.tryEntries.push(entry); +function defaultOptions () { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER } +} - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; +// Regular stringify +function stringify (obj, replacer, spacer, options) { + if (typeof options === 'undefined') { + options = defaultOptions() } - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); + decirc(obj, '', 0, [], undefined, 0, options) + var res + try { + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer) + } else { + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) + } + } catch (_) { + return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') + } finally { + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } } + return res +} - runtime.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); +function setReplace (replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k, replace]) } - keys.reverse(); + } else { + parent[k] = replace + arr.push([parent, k, val]) + } +} - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } +function decirc (val, k, edgeIndex, stack, parent, depth, options) { + depth += 1 + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) + return } + } - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; + if ( + typeof options.depthLimit !== 'undefined' && + depth > options.depthLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } + if ( + typeof options.edgesLimit !== 'undefined' && + edgeIndex + 1 > options.edgesLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } - if (typeof iterable.next === "function") { - return iterable; + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, i, stack, val, depth, options) } - - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined; - next.done = true; - - return next; - }; - - return next.next = next; + } else { + var keys = Object.keys(val) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + decirc(val[key], key, i, stack, val, depth, options) } } + stack.pop() + } +} - // Return an iterator with no values. - return { next: doneResult }; +// Stable-stringify +function compareFunction (a, b) { + if (a < b) { + return -1 + } + if (a > b) { + return 1 } - runtime.values = values; + return 0 +} - function doneResult() { - return { value: undefined, done: true }; +function deterministicStringify (obj, replacer, spacer, options) { + if (typeof options === 'undefined') { + options = defaultOptions() } - Context.prototype = { - constructor: Context, + var tmp = deterministicDecirc(obj, '', 0, [], undefined, 0, options) || obj + var res + try { + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer) + } else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) + } + } catch (_) { + return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') + } finally { + // Ensure that we restore the object as it was. + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } + } + return res +} - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined; - this.done = false; - this.delegate = null; +function deterministicDecirc (val, k, edgeIndex, stack, parent, depth, options) { + depth += 1 + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent) + return + } + } + try { + if (typeof val.toJSON === 'function') { + return + } + } catch (_) { + return + } - this.method = "next"; - this.arg = undefined; + if ( + typeof options.depthLimit !== 'undefined' && + depth > options.depthLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } - this.tryEntries.forEach(resetTryEntry); + if ( + typeof options.edgesLimit !== 'undefined' && + edgeIndex + 1 > options.edgesLimit + ) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent) + return + } - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined; - } - } + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, i, stack, val, depth, options) } - }, - - stop: function() { - this.done = true; + } else { + // Create a temporary object in the required way + var tmp = {} + var keys = Object.keys(val).sort(compareFunction) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + deterministicDecirc(val[key], key, i, stack, val, depth, options) + tmp[key] = val[key] + } + if (typeof parent !== 'undefined') { + arr.push([parent, k, val]) + parent[k] = tmp + } else { + return tmp + } + } + stack.pop() + } +} - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; +// wraps replacer function to handle values we couldn't replace +// and mark them as replaced value +function replaceGetterValues (replacer) { + replacer = + typeof replacer !== 'undefined' + ? replacer + : function (k, v) { + return v } + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i] + if (part[1] === key && part[0] === val) { + val = part[2] + replacerStack.splice(i, 1) + break + } + } + } + return replacer.call(this, key, val) + } +} - return this.rval; - }, - dispatchException: function(exception) { - if (this.done) { - throw exception; - } +/***/ }), - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; +/***/ 89353: +/***/ ((module) => { - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined; - } +"use strict"; - return !! caught; - } - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; +/* eslint no-invalid-this: 1 */ - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); +var concatty = function concatty(a, b) { + var arr = []; - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } + 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]; + } - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } + return arr; +}; - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } +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; +}; - } else { - throw new Error("try statement without catch or finally"); - } +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; +}; - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } +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); - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } + 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 record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; + }; - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } - return this.complete(record); - }, + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } + return bound; +}; - return ContinueSentinel; - }, - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, +/***/ }), - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } +/***/ 66743: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, +"use strict"; - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined; - } +var implementation = __webpack_require__(89353); - return ContinueSentinel; - } - }; -})( - // In sloppy mode, unbound `this` refers to the global object, fallback to - // Function constructor if we're in global strict mode. That is sadly a form - // of indirect eval which violates Content Security Policy. - (function() { return this })() || Function("return this")() -); +module.exports = Function.prototype.bind || implementation; /***/ }), -/***/ 94942: +/***/ 70453: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -module.exports = __webpack_require__(52548); +"use strict"; + + +var undefined; + +var $Error = __webpack_require__(69383); +var $EvalError = __webpack_require__(41237); +var $RangeError = __webpack_require__(79290); +var $ReferenceError = __webpack_require__(79538); +var $SyntaxError = __webpack_require__(58068); +var $TypeError = __webpack_require__(69675); +var $URIError = __webpack_require__(35345); + +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 = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +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 = __webpack_require__(64039)(); +var hasProto = __webpack_require__(80024)(); + +var getProto = Object.getPrototypeOf || ( + hasProto + ? function (x) { return x.__proto__; } // eslint-disable-line no-proto + : null +); + +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, + '%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, + '%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 +}; + +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 = __webpack_require__(66743); +var hasOwn = __webpack_require__(9957); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.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; +}; /***/ }), -/***/ 79742: -/***/ ((__unused_webpack_module, exports) => { +/***/ 75795: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray +var GetIntrinsic = __webpack_require__(70453); -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } } -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 +module.exports = $gOPD; + + +/***/ }), + +/***/ 30592: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; -function getLens (b64) { - var len = b64.length - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } +var $defineProperty = __webpack_require__(30655); - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len +var hasPropertyDescriptors = function hasPropertyDescriptors() { + return !!$defineProperty; +}; - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) +hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!$defineProperty) { + return null; + } + try { + return $defineProperty([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; - return [validLen, placeHoldersLen] -} +module.exports = hasPropertyDescriptors; -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} +/***/ }), -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] +/***/ 80024: +/***/ ((module) => { - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) +"use strict"; - var curByte = 0 - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen +var test = { + __proto__: null, + foo: {} +}; - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } +var $Object = Object; - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } +/** @type {import('.')} */ +module.exports = function hasProto() { + // @ts-expect-error: TS errors on an inherited property for some reason + return { __proto__: test }.foo === test.foo + && !(test instanceof $Object); +}; - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - return arr -} +/***/ }), -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} +/***/ 64039: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} +"use strict"; -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = __webpack_require__(41333); - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } +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 parts.join('') -} + return hasSymbolSham(); +}; /***/ }), -/***/ 48764: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 41333: +/***/ ((module) => { "use strict"; -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ +/* 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; } -const base64 = __webpack_require__(79742) -const ieee754 = __webpack_require__(80645) -const customInspectSymbol = - (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation - ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation - : null + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } -const K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH + // 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 `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} + var symVal = 42; + obj[sym] = symVal; + for (sym 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; } -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - const arr = new Uint8Array(1) - const proto = { foo: function () { return 42 } } - Object.setPrototypeOf(proto, Uint8Array.prototype) - Object.setPrototypeOf(arr, proto) - return arr.foo() === 42 - } catch (e) { - return false - } -} + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - const buf = new Uint8Array(length) - Object.setPrototypeOf(buf, Buffer.prototype) - return buf -} + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ + return true; +}; -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) + +/***/ }), + +/***/ 4729: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; + +var Buffer = (__webpack_require__(17417).Buffer) +var Transform = (__webpack_require__(61603).Transform) +var inherits = __webpack_require__(56698) + +function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') } - return from(arg, encodingOrOffset, length) } -Buffer.poolSize = 8192 // not used by this implementation +function HashBase (blockSize) { + Transform.call(this) -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } + this._block = Buffer.allocUnsafe(blockSize) + this._blockSize = blockSize + this._blockOffset = 0 + this._length = [0, 0, 0, 0] - if (ArrayBuffer.isView(value)) { - return fromArrayView(value) - } + this._finalized = false +} - if (value == null) { - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) +inherits(HashBase, Transform) + +HashBase.prototype._transform = function (chunk, encoding, callback) { + var error = null + try { + this.update(chunk, encoding) + } catch (err) { + error = err } - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } + callback(error) +} - if (typeof SharedArrayBuffer !== 'undefined' && - (isInstance(value, SharedArrayBuffer) || - (value && isInstance(value.buffer, SharedArrayBuffer)))) { - return fromArrayBuffer(value, encodingOrOffset, length) +HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err } - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } + callback(error) +} - const valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } +HashBase.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) - const b = fromObject(value) - if (b) return b + // consume data + var block = this._block + var offset = 0 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length) + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry } - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) + return this } -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) +HashBase.prototype._update = function () { + throw new Error('_update is not implemented') } -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) -Object.setPrototypeOf(Buffer, Uint8Array) +HashBase.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} + var digest = this._digest() + if (encoding !== undefined) digest = digest.toString(encoding) -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpreted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} + // reset state + this._block.fill(0) + this._blockOffset = 0 + for (var i = 0; i < 4; ++i) this._length[i] = 0 -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) + return digest } -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) +HashBase.prototype._digest = function () { + throw new Error('_digest is not implemented') } -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} +module.exports = HashBase -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } +/***/ }), - const length = byteLength(string, encoding) | 0 - let buf = createBuffer(length) +/***/ 92260: +/***/ ((module) => { - const actual = buf.write(string, encoding) +"use strict"; - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - return buf -} +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } -function fromArrayLike (array) { - const length = array.length < 0 ? 0 : checked(array.length) | 0 - const buf = createBuffer(length) - for (let i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} +var codes = {}; -function fromArrayView (arrayView) { - if (isInstance(arrayView, Uint8Array)) { - const copy = new Uint8Array(arrayView) - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; } - return fromArrayLike(arrayView) -} -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); - let buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } - // Return an augmented `Uint8Array` instance - Object.setPrototypeOf(buf, Buffer.prototype) + return NodeError; + }(Base); - return buf -} + 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 fromObject (obj) { - if (Buffer.isBuffer(obj)) { - const len = checked(obj.length) | 0 - const buf = createBuffer(len) - if (buf.length === 0) { - return buf - } +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); - obj.copy(buf, 0, 0, len) - return buf + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) + +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; } - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) + 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; } -} -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; } - return length | 0 } -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 +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' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; } - return Buffer.alloc(+length) -} -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} + var msg; -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); } - if (a === b) return 0 + msg += ". Received type ".concat(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; - let x = a.length - let y = b.length - for (let i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } +/***/ }), - if (x < y) return -1 - if (y < x) return 1 - return 0 -} +/***/ 92818: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); +// 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. -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } +/**/ - if (list.length === 0) { - return Buffer.alloc(0) - } +var objectKeys = Object.keys || function (obj) { + var keys = []; - let i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } + for (var key in obj) { + keys.push(key); } - const buffer = Buffer.allocUnsafe(length) - let pos = 0 - for (i = 0; i < list.length; ++i) { - let buf = list[i] - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) - buf.copy(buffer, pos) - } else { - Uint8Array.prototype.set.call( - buffer, - buf, - pos - ) - } - } else if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } else { - buf.copy(buffer, pos) - } - pos += buf.length + return keys; +}; +/**/ + + +module.exports = Duplex; + +var Readable = __webpack_require__(6736); + +var Writable = __webpack_require__(62192); + +__webpack_require__(56698)(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]; } - return buffer } -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; - const len = string.length - const mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; - // Use a for loop to avoid recursion - let loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); } } } -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - let loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 +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(); } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' +}); +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 - if (end === undefined || end > this.length) { - end = this.length - } +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. - if (end <= 0) { - return '' - } + process.nextTick(onEndNT, this); +} - // Force coercion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 +function onEndNT(self) { + self.end(); +} - if (end <= start) { - return '' - } +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; + } - if (!encoding) encoding = 'utf8' + 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 - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); - case 'ascii': - return asciiSlice(this, start, end) +/***/ }), - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) +/***/ 35860: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - case 'base64': - return base64Slice(this, start, end) +"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. - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} +module.exports = PassThrough; -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true +var Transform = __webpack_require__(13054); -function swap (b, n, m) { - const i = b[n] - b[n] = b[m] - b[m] = i -} +__webpack_require__(56698)(PassThrough, Transform); -Buffer.prototype.swap16 = function swap16 () { - const len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (let i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); } -Buffer.prototype.swap32 = function swap32 () { - const len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (let i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; -Buffer.prototype.swap64 = function swap64 () { - const len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (let i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} +/***/ }), -Buffer.prototype.toString = function toString () { - const length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} +/***/ 6736: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -Buffer.prototype.toLocaleString = Buffer.prototype.toString +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); +// 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. -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} -Buffer.prototype.inspect = function inspect () { - let str = '' - const max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} -if (customInspectSymbol) { - Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect -} +module.exports = Readable; +/**/ -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } +var Duplex; +/**/ - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } +Readable.ReadableState = ReadableState; +/**/ - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } +var EE = (__webpack_require__(37007).EventEmitter); - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 +/**/ - if (this === target) return 0 - let x = thisEnd - thisStart - let y = end - start - const len = Math.min(x, y) +var Stream = __webpack_require__(71181); +/**/ - const thisCopy = this.slice(thisStart, thisEnd) - const targetCopy = target.slice(start, end) - for (let i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } +var Buffer = (__webpack_require__(48287).Buffer); - if (x < y) return -1 - if (y < x) return 1 - return 0 -} +var OurUint8Array = __webpack_require__.g.Uint8Array || function () {}; -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } +var debugUtil = __webpack_require__(92382); - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) - } +var debug; - throw new TypeError('val must be string, number or Buffer') +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; } +/**/ -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - let indexSize = 1 - let arrLength = arr.length - let valLength = val.length - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } +var BufferList = __webpack_require__(12389); - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } +var destroyImpl = __webpack_require__(41468); - let i - if (dir) { - let foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - let found = true - for (let j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } +var _require = __webpack_require__(8775), + getHighWaterMark = _require.getHighWaterMark; - return -1 -} +var _require$codes = (__webpack_require__(92260)/* .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. -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} +__webpack_require__(56698)(Readable, Stream); -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - const remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - const strLen = string.length +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 (length > strLen / 2) { - length = strLen / 2 - } - let i - for (i = 0; i < length; ++i) { - const parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i + 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 utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || __webpack_require__(92818); + 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. -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} + 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 -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} + 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" -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} + 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() -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } + 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. - const remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; // Should close be emitted on destroy. Defaults to true. - if (!encoding) encoding = 'utf8' + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - let loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) + this.autoDestroy = !!options.autoDestroy; // has it been destroyed - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + 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. - case 'ascii': - case 'latin1': - case 'binary': - return asciiWrite(this, string, offset, length) + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + this.readingMore = false; + this.decoder = null; + this.encoding = null; - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } + if (options.encoding) { + if (!StringDecoder) StringDecoder = (__webpack_require__(83141)/* .StringDecoder */ .I); + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; } } -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) +function Readable(options) { + Duplex = Duplex || __webpack_require__(92818); + 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); } -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) +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; -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - const res = [] +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. - let i = start - while (i < end) { - const firstByte = buf[i] - let codePoint = null - let bytesPerSequence = (firstByte > 0xEF) - ? 4 - : (firstByte > 0xDF) - ? 3 - : (firstByte > 0xBF) - ? 2 - : 1 - if (i + bytesPerSequence <= end) { - let secondByte, thirdByte, fourthByte, tempCodePoint +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; } - } - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF + skipChunkCheck = true; } - - res.push(codePoint) - i += bytesPerSequence + } else { + skipChunkCheck = true; } - return decodeCodePointsArray(res) -} + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; // Unshift should *always* be something directly out of read() -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -const MAX_ARGUMENTS_LENGTH = 0x1000 -function decodeCodePointsArray (codePoints) { - const len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; - // Decode in chunks to avoid "call stack size exceeded". - let res = '' - let i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} +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. -function asciiSlice (buf, start, end) { - let ret = '' - end = Math.min(buf.length, end) - for (let i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret + return !state.ended && (state.length < state.highWaterMark || state.length === 0); } -function latin1Slice (buf, start, end) { - let ret = '' - end = Math.min(buf.length, end) - - for (let i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) +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); } - return ret -} -function hexSlice (buf, start, end) { - const len = buf.length + maybeReadMore(stream, state); +} - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len +function chunkInvalid(state, chunk) { + var er; - let out = '' - for (let i = start; i < end; ++i) { - out += hexSliceLookupTable[buf[i]] + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); } - return out -} -function utf16leSlice (buf, start, end) { - const bytes = buf.slice(start, end) - let res = '' - // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) - for (let i = 0; i < bytes.length - 1; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res + return er; } -Buffer.prototype.slice = function slice (start, end) { - const len = this.length - start = ~~start - end = end === undefined ? len : ~~end +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; // backwards compatibility. - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = (__webpack_require__(83141)/* .StringDecoder */ .I); + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - if (end < start) end = start + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - const newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - Object.setPrototypeOf(newBuf, Buffer.prototype) + var p = this._readableState.buffer.head; + var content = ''; - return newBuf -} + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} + this._readableState.buffer.clear(); -Buffer.prototype.readUintLE = -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; // Don't raise the hwm > 1GB - let val = this[offset] - let mul = 1 - let i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - return val -} +var MAX_HWM = 0x40000000; -Buffer.prototype.readUintBE = -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) +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++; } - let val = this[offset + --byteLength] - let mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } + return n; +} // This function is designed to be inlinable, so please take care when making +// changes to the function body. - return val -} -Buffer.prototype.readUint8 = -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; -Buffer.prototype.readUint16LE = -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} + 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. -Buffer.prototype.readUint16BE = -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} -Buffer.prototype.readUint32LE = -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} + if (!state.ended) { + state.needReadable = true; + return 0; + } -Buffer.prototype.readUint32BE = -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) + return state.length; +} // you can override either this method, or the async _read(n) below. - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} -Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) { - offset = offset >>> 0 - validateNumber(offset, 'offset') - const first = this[offset] - const last = this[offset + 7] - if (first === undefined || last === undefined) { - boundsError(offset, this.length - 8) +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; } - const lo = first + - this[++offset] * 2 ** 8 + - this[++offset] * 2 ** 16 + - this[++offset] * 2 ** 24 + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - const hi = this[++offset] + - this[++offset] * 2 ** 8 + - this[++offset] * 2 ** 16 + - last * 2 ** 24 + 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. - return BigInt(lo) + (BigInt(hi) << BigInt(32)) -}) -Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) { - offset = offset >>> 0 - validateNumber(offset, 'offset') - const first = this[offset] - const last = this[offset + 7] - if (first === undefined || last === undefined) { - boundsError(offset, this.length - 8) - } + 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. + - const hi = first * 2 ** 24 + - this[++offset] * 2 ** 16 + - this[++offset] * 2 ** 8 + - this[++offset] + 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. - const lo = this[++offset] * 2 ** 24 + - this[++offset] * 2 ** 16 + - this[++offset] * 2 ** 8 + - last + if (state.length === 0) state.needReadable = true; // call internal read method - return (BigInt(hi) << BigInt(32)) + BigInt(lo) -}) + this._read(state.highWaterMark); -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + 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. - let val = this[offset] - let mul = 1 - let i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul + if (!state.reading) n = howMuchToRead(nOrig, state); } - mul *= 0x80 - if (val >= mul) val -= Math.pow(2, 8 * byteLength) + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; - return val -} + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + 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. - let i = byteLength - let mul = 1 - let val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul + if (nOrig !== n && state.ended) endReadable(this); } - mul *= 0x80 - if (val >= mul) val -= Math.pow(2, 8 * byteLength) + if (ret !== null) this.emit('data', ret); + return ret; +}; - return val -} +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} + if (state.decoder) { + var chunk = state.decoder.end(); -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - const val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - const val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} + state.ended = true; -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) + 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; - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} + 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. -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; -Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) { - offset = offset >>> 0 - validateNumber(offset, 'offset') - const first = this[offset] - const last = this[offset + 7] - if (first === undefined || last === undefined) { - boundsError(offset, this.length - 8) + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); } +} - const val = this[offset + 4] + - this[offset + 5] * 2 ** 8 + - this[offset + 6] * 2 ** 16 + - (last << 24) // Overflow - - return (BigInt(val) << BigInt(32)) + - BigInt(first + - this[++offset] * 2 ** 8 + - this[++offset] * 2 ** 16 + - this[++offset] * 2 ** 24) -}) +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); -Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) { - offset = offset >>> 0 - validateNumber(offset, 'offset') - const first = this[offset] - const last = this[offset + 7] - if (first === undefined || last === undefined) { - boundsError(offset, this.length - 8) - } + 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. - const val = (first << 24) + // Overflow - this[++offset] * 2 ** 16 + - this[++offset] * 2 ** 8 + - this[++offset] - return (BigInt(val) << BigInt(32)) + - BigInt(this[++offset] * 2 ** 24 + - this[++offset] * 2 ** 16 + - this[++offset] * 2 ** 8 + - last) -}) + 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. -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } } -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} +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; + } -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} + 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. -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} -Buffer.prototype.writeUintLE = -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; - let mul = 1 - let i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - return offset + byteLength -} + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; -Buffer.prototype.writeUintBE = -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } + case 1: + state.pipes = [state.pipes, dest]; + break; - let i = byteLength - 1 - let mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF + default: + state.pipes.push(dest); + break; } - return offset + byteLength -} + 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); -Buffer.prototype.writeUint8 = -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); -Buffer.prototype.writeUint16LE = -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } -Buffer.prototype.writeUint16BE = -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} + 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. -Buffer.prototype.writeUint32LE = -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} -Buffer.prototype.writeUint32BE = -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; -function wrtBigUInt64LE (buf, value, offset, min, max) { - checkIntBI(value, min, max, buf, offset, 7) + function cleanup() { + debug('cleanup'); // cleanup event handlers once the pipe is broken - let lo = Number(value & BigInt(0xffffffff)) - buf[offset++] = lo - lo = lo >> 8 - buf[offset++] = lo - lo = lo >> 8 - buf[offset++] = lo - lo = lo >> 8 - buf[offset++] = lo - let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) - buf[offset++] = hi - hi = hi >> 8 - buf[offset++] = hi - hi = hi >> 8 - buf[offset++] = hi - hi = hi >> 8 - buf[offset++] = hi - return offset -} + 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. -function wrtBigUInt64BE (buf, value, offset, min, max) { - checkIntBI(value, min, max, buf, offset, 7) + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } - let lo = Number(value & BigInt(0xffffffff)) - buf[offset + 7] = lo - lo = lo >> 8 - buf[offset + 6] = lo - lo = lo >> 8 - buf[offset + 5] = lo - lo = lo >> 8 - buf[offset + 4] = lo - let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)) - buf[offset + 3] = hi - hi = hi >> 8 - buf[offset + 2] = hi - hi = hi >> 8 - buf[offset + 1] = hi - hi = hi >> 8 - buf[offset] = hi - return offset + 8 -} + src.on('data', ondata); -Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) { - return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) -}) + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); -Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) { - return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) -}) + 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++; + } -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - const limit = Math.pow(2, (8 * byteLength) - 1) + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - let i = 0 - let mul = 1 - let sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } + 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. - return offset + byteLength -} -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - const limit = Math.pow(2, (8 * byteLength) - 1) + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - checkInt(this, value, offset, byteLength, limit - 1, -limit) + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); } - let i = byteLength - 1 - let mul = 1 - let sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } + dest.once('close', onclose); - return offset + byteLength -} + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} + dest.once('finish', onfinish); -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} + dest.emit('pipe', src); // start the flow if it hasn't been started already. -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } -Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) { - return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) -}) + return dest; +}; -Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) { - return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) -}) +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; } -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} + if (state.pipesCount === 0) return this; // just one destination. most common case. -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} + 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. -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + } - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 + return this; + } // try to find the right one. - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } + 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 - const len = end - start - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; - return len -} + 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 -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - const code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code + 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); } } - } else if (typeof val === 'number') { - val = val & 255 - } else if (typeof val === 'boolean') { - val = Number(val) } - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') + 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); } - if (end <= start) { - return 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); } - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 + return res; +}; - if (!val) val = 0 +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; - let i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - const bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - const len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } + 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(); } - - return this } -// CUSTOM ERRORS -// ============= +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. -// Simplified versions from Node, changed for Buffer-only usage -const errors = {} -function E (sym, getMessage, Base) { - errors[sym] = class NodeError extends Base { - constructor () { - super() - Object.defineProperty(this, 'message', { - value: getMessage.apply(this, arguments), - writable: true, - configurable: true - }) +Readable.prototype.resume = function () { + var state = this._readableState; - // Add the error code to the name to include it in the stack trace. - this.name = `${this.name} [${sym}]` - // Access the stack to generate the error message including the error code - // from the name. - this.stack // eslint-disable-line no-unused-expressions - // Reset the name to the actual name. - delete this.name - } + if (!state.flowing) { + debug('resume'); // we flow only if there is no one listening + // for readable, but we still have to call + // resume() - get code () { - return sym - } + state.flowing = !state.readableListening; + resume(this, state); + } - set code (value) { - Object.defineProperty(this, 'code', { - configurable: true, - enumerable: true, - value, - writable: true - }) - } + state.paused = false; + return this; +}; - toString () { - return `${this.name} [${sym}]: ${this.message}` - } +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); } } -E('ERR_BUFFER_OUT_OF_BOUNDS', - function (name) { - if (name) { - return `${name} is outside of buffer bounds` - } - - return 'Attempt to access memory outside buffer bounds' - }, RangeError) -E('ERR_INVALID_ARG_TYPE', - function (name, actual) { - return `The "${name}" argument must be of type number. Received type ${typeof actual}` - }, TypeError) -E('ERR_OUT_OF_RANGE', - function (str, range, input) { - let msg = `The value of "${str}" is out of range.` - let received = input - if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { - received = addNumericalSeparator(String(input)) - } else if (typeof input === 'bigint') { - received = String(input) - if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { - received = addNumericalSeparator(received) - } - received += 'n' - } - msg += ` It must be ${range}. Received ${received}` - return msg - }, RangeError) +function resume_(stream, state) { + debug('resume', state.reading); -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}` + if (!state.reading) { + stream.read(0); } - return `${val.slice(0, i)}${res}` + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); } -// CHECK FUNCTIONS -// =============== +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); -function checkBounds (buf, offset, byteLength) { - validateNumber(offset, 'offset') - if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { - boundsError(offset, buf.length - (byteLength + 1)) + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); } -} -function checkIntBI (value, min, max, buf, offset, byteLength) { - if (value > max || value < min) { - const n = typeof min === 'bigint' ? 'n' : '' - let range - if (byteLength > 3) { - if (min === 0 || min === BigInt(0)) { - range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}` - } else { - range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + - `${(byteLength + 1) * 8 - 1}${n}` - } - } else { - range = `>= ${min}${n} and <= ${max}${n}` - } - throw new errors.ERR_OUT_OF_RANGE('value', range, value) - } - checkBounds(buf, offset, byteLength) -} + this._readableState.paused = true; + return this; +}; -function validateNumber (value, name) { - if (typeof value !== 'number') { - throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value) - } -} +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); -function boundsError (value, length, type) { - if (Math.floor(value) !== value) { - validateNumber(value, type) - throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value) + 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. - if (length < 0) { - throw new errors.ERR_BUFFER_OUT_OF_BOUNDS() - } - throw new errors.ERR_OUT_OF_RANGE(type || 'offset', - `>= ${type ? 1 : 0} and <= ${length}`, - value) -} +Readable.prototype.wrap = function (stream) { + var _this = this; -// HELPER FUNCTIONS -// ================ + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); -const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} + _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. -function utf8ToBytes (string, units) { - units = units || Infinity - let codePoint - const length = string.length - let leadSurrogate = null - const bytes = [] - for (let i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) + 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. - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - // valid lead - leadSurrogate = codePoint + this._read = function (n) { + debug('wrapped _read', n); - continue - } + if (paused) { + paused = false; + stream.resume(); + } + }; - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } + return this; +}; - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = __webpack_require__(74743); } - leadSurrogate = null + return createReadableStreamAsyncIterator(this); + }; +} - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') +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. - return bytes -} +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 asciiToBytes (str) { - const byteArray = [] - for (let i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) +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 byteArray + return ret; } -function utf16leToBytes (str, units) { - let c, hi, lo - const byteArray = [] - for (let i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); } - - return byteArray } -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. -function blitBuffer (src, dst, offset, length) { - let i - for (i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] + 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(); + } + } } - return i } -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = __webpack_require__(45049); + } + + return from(Readable, iterable, opts); + }; } -// Create lookup table for `toString('hex')` -// See: https://github.com/feross/buffer/issues/219 -const hexSliceLookupTable = (function () { - const alphabet = '0123456789abcdef' - const table = new Array(256) - for (let i = 0; i < 16; ++i) { - const i16 = i * 16 - for (let j = 0; j < 16; ++j) { - table[i16 + j] = alphabet[i] + alphabet[j] - } +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; } - return table -})() -// Return not function with Error if BigInt not supported -function defineBigIntMethod (fn) { - return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn + return -1; } -function BufferBigIntNotDefined () { - throw new Error('BigInt not supported') -} +/***/ }), + +/***/ 13054: +/***/ ((module, __unused_webpack_exports, __webpack_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. -/***/ }), -/***/ 98767: -/***/ ((module) => { +module.exports = Transform; +var _require$codes = (__webpack_require__(92260)/* .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; -/** - * Expose `Emitter`. - */ +var Duplex = __webpack_require__(92818); -if (true) { - module.exports = Emitter; -} +__webpack_require__(56698)(Transform, Duplex); -/** - * Initialize a new `Emitter`. - * - * @api public - */ +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; -function Emitter(obj) { - if (obj) return mixin(obj); -}; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } -/** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ + 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; -function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); } - return obj; } -/** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.on = -Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks['$' + event] = this._callbacks['$' + event] || []) - .push(fn); - return this; -}; - -/** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ +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. -Emitter.prototype.once = function(event, fn){ - function on() { - this.off(event, on); - fn.apply(this, arguments); - } + 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. - on.fn = fn; - this.on(event, on); - return this; -}; + this._readableState.sync = false; -/** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ + 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. -Emitter.prototype.off = -Emitter.prototype.removeListener = -Emitter.prototype.removeAllListeners = -Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } + this.on('prefinish', prefinish); +} - // specific event - var callbacks = this._callbacks['$' + event]; - if (!callbacks) return this; +function prefinish() { + var _this = this; - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks['$' + event]; - return this; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); } +} - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } +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. - // Remove event specific arrays for event types that no - // one is subscribed for to avoid memory leak. - if (callbacks.length === 0) { - delete this._callbacks['$' + event]; - } - return this; +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); }; -/** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - -Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; - - var args = new Array(arguments.length - 1) - , callbacks = this._callbacks['$' + event]; +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; + 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. - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - return this; -}; +Transform.prototype._read = function (n) { + var ts = this._transformState; -/** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; -Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks['$' + event] || []; + 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; + } }; -/** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - -Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; +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); +} /***/ }), -/***/ 47185: +/***/ 62192: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -__webpack_require__(91867); -__webpack_require__(2586); -module.exports = __webpack_require__(34579).Array.from; +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); +// 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; +/* */ -/***/ 3597: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +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 -__webpack_require__(73871); -__webpack_require__(91867); -module.exports = __webpack_require__(46459); +function CorkedRequest(state) { + var _this = this; -/***/ }), + this.next = null; + this.entry = null; -/***/ 21035: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ -__webpack_require__(73871); -__webpack_require__(91867); -module.exports = __webpack_require__(89553); +/**/ -/***/ }), +var Duplex; +/**/ -/***/ 92742: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +Writable.WritableState = WritableState; +/**/ -var core = __webpack_require__(34579); -var $JSON = core.JSON || (core.JSON = { stringify: JSON.stringify }); -module.exports = function stringify(it) { // eslint-disable-line no-unused-vars - return $JSON.stringify.apply($JSON, arguments); +var internalUtil = { + deprecate: __webpack_require__(94643) }; +/**/ +/**/ -/***/ }), +var Stream = __webpack_require__(71181); +/**/ -/***/ 97272: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -__webpack_require__(52684); -module.exports = __webpack_require__(34579).Math.sign; +var Buffer = (__webpack_require__(48287).Buffer); +var OurUint8Array = __webpack_require__.g.Uint8Array || function () {}; -/***/ }), +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} -/***/ 56981: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} -__webpack_require__(72699); -module.exports = __webpack_require__(34579).Object.assign; +var destroyImpl = __webpack_require__(41468); +var _require = __webpack_require__(8775), + getHighWaterMark = _require.getHighWaterMark; -/***/ }), +var _require$codes = (__webpack_require__(92260)/* .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; -/***/ 33391: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +var errorOrDestroy = destroyImpl.errorOrDestroy; -__webpack_require__(31477); -var $Object = (__webpack_require__(34579).Object); -module.exports = function defineProperty(it, key, desc) { - return $Object.defineProperty(it, key, desc); -}; +__webpack_require__(56698)(Writable, Stream); +function nop() {} -/***/ }), +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || __webpack_require__(92818); + 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. -/***/ 98613: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream + // contains buffers or objects. -__webpack_require__(40961); -module.exports = __webpack_require__(34579).Object.keys; + 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. -/***/ 80112: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + this.needDrain = false; // at the start of calling end() -__webpack_require__(94058); -__webpack_require__(91867); -__webpack_require__(73871); -__webpack_require__(32878); -__webpack_require__(95971); -__webpack_require__(22526); -module.exports = __webpack_require__(34579).Promise; + this.ending = false; // when end() has been called, and returned + this.ended = false; // when 'finish' is emitted -/***/ }), + this.finished = false; // has it been destroyed -/***/ 80025: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + 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. -__webpack_require__(46840); -__webpack_require__(94058); -__webpack_require__(8174); -__webpack_require__(36461); -module.exports = __webpack_require__(34579).Symbol; + 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. -/***/ 52392: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + this.writing = false; // when true all writes will be buffered until .uncork() call -__webpack_require__(91867); -__webpack_require__(73871); -module.exports = (__webpack_require__(25103).f)('iterator'); + 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) -/***/ 85663: -/***/ ((module) => { + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) -module.exports = function (it) { - if (typeof it != 'function') throw TypeError(it + ' is not a function!'); - return it; -}; + 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 -/***/ 79003: -/***/ ((module) => { + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams -module.exports = function () { /* empty */ }; + 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') -/***/ 29142: -/***/ ((module) => { + this.autoDestroy = !!options.autoDestroy; // count buffered requests -module.exports = function (it, Constructor, name, forbiddenField) { - if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { - throw TypeError(name + ': incorrect invocation!'); - } return it; -}; + 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 = []; -/***/ 12159: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + while (current) { + out.push(current); + current = current.next; + } -var isObject = __webpack_require__(36727); -module.exports = function (it) { - if (!isObject(it)) throw TypeError(it + ' is not an object!'); - return it; + 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. -/***/ }), -/***/ 57428: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +var realHasInstance; -// false -> Array#indexOf -// true -> Array#includes -var toIObject = __webpack_require__(7932); -var toLength = __webpack_require__(78728); -var toAbsoluteIndex = __webpack_require__(16531); -module.exports = function (IS_INCLUDES) { - return function ($this, el, fromIndex) { - var O = toIObject($this); - var length = toLength(O.length); - var index = toAbsoluteIndex(fromIndex, length); - var value; - // Array#includes uses SameValueZero equality algorithm - // eslint-disable-next-line no-self-compare - if (IS_INCLUDES && el != el) while (length > index) { - value = O[index++]; - // eslint-disable-next-line no-self-compare - if (value != value) return true; - // Array#indexOf ignores holes, Array#includes - not - } else for (;length > index; index++) if (IS_INCLUDES || index in O) { - if (O[index] === el) return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; +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; }; -}; - - -/***/ }), - -/***/ 14677: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -// getting tag from 19.1.3.6 Object.prototype.toString() -var cof = __webpack_require__(32894); -var TAG = __webpack_require__(22939)('toStringTag'); -// ES3 wrong here -var ARG = cof(function () { return arguments; }()) == 'Arguments'; +} -// fallback for IE11 Script Access Denied error -var tryGet = function (it, key) { - try { - return it[key]; - } catch (e) { /* empty */ } -}; +function Writable(options) { + Duplex = Duplex || __webpack_require__(92818); // 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 -module.exports = function (it) { - var O, T, B; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T - // builtinTag case - : ARG ? cof(O) - // ES3 arguments fallback - : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; -}; + 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; + } -/***/ 32894: -/***/ ((module) => { + Stream.call(this); +} // Otherwise people can pipe Writable streams, which is just wrong. -var toString = {}.toString; -module.exports = function (it) { - return toString.call(it).slice(8, -1); +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 -/***/ }), - -/***/ 34579: -/***/ ((module) => { - -var core = module.exports = { version: '2.6.12' }; -if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef + 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; -/***/ 52445: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + 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); + } -"use strict"; + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } -var $defineProperty = __webpack_require__(4743); -var createDesc = __webpack_require__(83101); + return true; +} -module.exports = function (object, index, value) { - if (index in object) $defineProperty.f(object, index, createDesc(0, value)); - else object[index] = value; -}; +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); + } -/***/ 19216: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } -// optional / simple context binding -var aFunction = __webpack_require__(85663); -module.exports = function (fn, that, length) { - aFunction(fn); - if (that === undefined) return fn; - switch (length) { - case 1: return function (a) { - return fn.call(that, a); - }; - case 2: return function (a, b) { - return fn.call(that, a, b); - }; - case 3: return function (a, b, c) { - return fn.call(that, a, b, c); - }; + 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 function (/* ...args */) { - return fn.apply(that, arguments); - }; + return ret; }; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; -/***/ }), +Writable.prototype.uncork = function () { + var state = this._writableState; -/***/ 8333: -/***/ ((module) => { + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; -// 7.2.1 RequireObjectCoercible(argument) -module.exports = function (it) { - if (it == undefined) throw TypeError("Can't call method on " + it); - return it; +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); + } -/***/ 89666: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + return chunk; +} -// Thank's IE8 for his funny defineProperty -module.exports = !__webpack_require__(7929)(function () { - return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; -}); +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; + } + } -/***/ 97467: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + 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. -var isObject = __webpack_require__(36727); -var document = (__webpack_require__(33938).document); -// typeof document.createElement is 'object' in old IE -var is = isObject(document) && isObject(document.createElement); -module.exports = function (it) { - return is ? document.createElement(it) : {}; -}; + 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; + } -/***/ 73338: -/***/ ((module) => { + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } -// IE 8- don't enum bug keys -module.exports = ( - 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' -).split(','); + 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; -/***/ 70337: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + 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 -// all enumerable object keys, includes symbols -var getKeys = __webpack_require__(46162); -var gOPS = __webpack_require__(48195); -var pIE = __webpack_require__(86274); -module.exports = function (it) { - var result = getKeys(it); - var getSymbols = gOPS.f; - if (getSymbols) { - var symbols = getSymbols(it); - var isEnum = pIE.f; - var i = 0; - var key; - while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); - } return result; -}; + 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; +} -/***/ 83856: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +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; -var global = __webpack_require__(33938); -var core = __webpack_require__(34579); -var ctx = __webpack_require__(19216); -var hide = __webpack_require__(41818); -var has = __webpack_require__(27069); -var PROTOTYPE = 'prototype'; - -var $export = function (type, name, source) { - var IS_FORCED = type & $export.F; - var IS_GLOBAL = type & $export.G; - var IS_STATIC = type & $export.S; - var IS_PROTO = type & $export.P; - var IS_BIND = type & $export.B; - var IS_WRAP = type & $export.W; - var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); - var expProto = exports[PROTOTYPE]; - var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]; - var key, own, out; - if (IS_GLOBAL) source = name; - for (key in source) { - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - if (own && has(exports, key)) continue; - // export native or passed - out = own ? target[key] : source[key]; - // prevent global pollution for namespaces - exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] - // bind timers to global for call from export context - : IS_BIND && own ? ctx(out, global) - // wrap global constructors for prevent change them in library - : IS_WRAP && target[key] == out ? (function (C) { - var F = function (a, b, c) { - if (this instanceof C) { - switch (arguments.length) { - case 0: return new C(); - case 1: return new C(a); - case 2: return new C(a, b); - } return new C(a, b, c); - } return C.apply(this, arguments); - }; - F[PROTOTYPE] = C[PROTOTYPE]; - return F; - // make static versions for prototype methods - })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% - if (IS_PROTO) { - (exports.virtual || (exports.virtual = {}))[key] = out; - // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% - if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out); - } - } -}; -// type bitmap -$export.F = 1; // forced -$export.G = 2; // global -$export.S = 4; // static -$export.P = 8; // proto -$export.B = 16; // bind -$export.W = 32; // wrap -$export.U = 64; // safe -$export.R = 128; // real proto method for `library` -module.exports = $export; + 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. -/***/ 7929: -/***/ ((module) => { -module.exports = function (exec) { - try { - return !!exec(); - } catch (e) { - return true; +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; -/***/ 45576: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + 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; -var ctx = __webpack_require__(19216); -var call = __webpack_require__(95602); -var isArrayIter = __webpack_require__(45991); -var anObject = __webpack_require__(12159); -var toLength = __webpack_require__(78728); -var getIterFn = __webpack_require__(83728); -var BREAK = {}; -var RETURN = {}; -var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { - var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); - var f = ctx(fn, that, entries ? 2 : 1); - var index = 0; - var length, step, iterator, result; - if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); - // fast case for arrays with default iterator - if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { - result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); - if (result === BREAK || result === RETURN) return result; - } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { - result = call(iterator, f, step.value, entries); - if (result === BREAK || result === RETURN) return result; - } -}; -exports.BREAK = BREAK; -exports.RETURN = RETURN; + 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; -/***/ 33938: -/***/ ((module) => { + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } -// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 -var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self - // eslint-disable-next-line no-new-func - : Function('return this')(); -if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef + 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; + } -/***/ 27069: -/***/ ((module) => { + state.bufferedRequest = entry; + state.bufferProcessing = false; +} -var hasOwnProperty = {}.hasOwnProperty; -module.exports = function (it, key) { - return hasOwnProperty.call(it, key); +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); }; +Writable.prototype._writev = null; -/***/ }), - -/***/ 41818: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var dP = __webpack_require__(4743); -var createDesc = __webpack_require__(83101); -module.exports = __webpack_require__(89666) ? function (object, key, value) { - return dP.f(object, key, createDesc(1, value)); -} : function (object, key, value) { - object[key] = value; - return object; -}; +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 -/***/ 54881: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. -var document = (__webpack_require__(33938).document); -module.exports = document && document.documentElement; + 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; + } +}); -/***/ 33758: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} -module.exports = !__webpack_require__(89666) && !__webpack_require__(7929)(function () { - return Object.defineProperty(__webpack_require__(97467)('div'), 'a', { get: function () { return 7; } }).a != 7; -}); +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } -/***/ }), + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} -/***/ 46778: -/***/ ((module) => { +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'); + } + } +} -// fast apply, http://jsperf.lnkit.com/fast-apply/5 -module.exports = function (fn, args, that) { - var un = that === undefined; - switch (args.length) { - case 0: return un ? fn() - : fn.call(that); - case 1: return un ? fn(args[0]) - : fn.call(that, args[0]); - case 2: return un ? fn(args[0], args[1]) - : fn.call(that, args[0], args[1]); - case 3: return un ? fn(args[0], args[1], args[2]) - : fn.call(that, args[0], args[1], args[2]); - case 4: return un ? fn(args[0], args[1], args[2], args[3]) - : fn.call(that, args[0], args[1], args[2], args[3]); - } return fn.apply(that, args); -}; +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); -/***/ }), + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); -/***/ 50799: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + 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; -// fallback for non-array-like ES3 and non-enumerable old V8 strings -var cof = __webpack_require__(32894); -// eslint-disable-next-line no-prototype-builtins -module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { - return cof(it) == 'String' ? it.split('') : Object(it); -}; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; +} -/***/ }), +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); -/***/ 45991: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } -// check on default Array iterator -var Iterators = __webpack_require__(15449); -var ITERATOR = __webpack_require__(22939)('iterator'); -var ArrayProto = Array.prototype; + state.ended = true; + stream.writable = false; +} -module.exports = function (it) { - return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); -}; +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. -/***/ }), -/***/ 71421: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + state.corkedRequestsFree.next = corkReq; +} -// 7.2.2 IsArray(argument) -var cof = __webpack_require__(32894); -module.exports = Array.isArray || function isArray(arg) { - return cof(arg) == 'Array'; -}; +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 -/***/ }), -/***/ 36727: -/***/ ((module) => { + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; -module.exports = function (it) { - return typeof it === 'object' ? it !== null : typeof it === 'function'; +Writable.prototype._destroy = function (err, cb) { + cb(err); }; - /***/ }), -/***/ 95602: +/***/ 74743: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -// call something on iterator step with safe closing on error -var anObject = __webpack_require__(12159); -module.exports = function (iterator, fn, value, entries) { - try { - return entries ? fn(anObject(value)[0], value[1]) : fn(value); - // 7.4.6 IteratorClose(iterator, completion) - } catch (e) { - var ret = iterator['return']; - if (ret !== undefined) anObject(ret.call(iterator)); - throw e; - } -}; +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); -/***/ }), +var _Object$setPrototypeO; -/***/ 33945: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -"use strict"; +var finished = __webpack_require__(45826); -var create = __webpack_require__(98989); -var descriptor = __webpack_require__(83101); -var setToStringTag = __webpack_require__(25378); -var IteratorPrototype = {}; +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'); -// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() -__webpack_require__(41818)(IteratorPrototype, __webpack_require__(22939)('iterator'), function () { return this; }); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} -module.exports = function (Constructor, NAME, next) { - Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); - setToStringTag(Constructor, NAME + ' Iterator'); -}; +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)); + } + } +} -/***/ 45700: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} -"use strict"; +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } -var LIBRARY = __webpack_require__(16227); -var $export = __webpack_require__(83856); -var redefine = __webpack_require__(57470); -var hide = __webpack_require__(41818); -var Iterators = __webpack_require__(15449); -var $iterCreate = __webpack_require__(33945); -var setToStringTag = __webpack_require__(25378); -var getPrototypeOf = __webpack_require__(95089); -var ITERATOR = __webpack_require__(22939)('iterator'); -var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` -var FF_ITERATOR = '@@iterator'; -var KEYS = 'keys'; -var VALUES = 'values'; - -var returnThis = function () { return this; }; - -module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { - $iterCreate(Constructor, NAME, next); - var getMethod = function (kind) { - if (!BUGGY && kind in proto) return proto[kind]; - switch (kind) { - case KEYS: return function keys() { return new Constructor(this, kind); }; - case VALUES: return function values() { return new Constructor(this, kind); }; - } return function entries() { return new Constructor(this, kind); }; + iter[kHandlePromise](resolve, reject); + }, reject); }; - var TAG = NAME + ' Iterator'; - var DEF_VALUES = DEFAULT == VALUES; - var VALUES_BUG = false; - var proto = Base.prototype; - var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; - var $default = $native || getMethod(DEFAULT); - var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; - var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; - var methods, key, IteratorPrototype; - // Fix native - if ($anyNative) { - IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); - if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { - // Set @@toStringTag to native iterators - setToStringTag(IteratorPrototype, TAG, true); - // fix for some old engines - if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); - } - } - // fix Array#{values, @@iterator}.name in V8 / FF - if (DEF_VALUES && $native && $native.name !== VALUES) { - VALUES_BUG = true; - $default = function values() { return $native.call(this); }; - } - // Define iterator - if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { - hide(proto, ITERATOR, $default); - } - // Plug for library - Iterators[NAME] = $default; - Iterators[TAG] = returnThis; - if (DEFAULT) { - methods = { - values: DEF_VALUES ? $default : getMethod(VALUES), - keys: IS_SET ? $default : getMethod(KEYS), - entries: $entries - }; - if (FORCED) for (key in methods) { - if (!(key in proto)) redefine(proto, key, methods[key]); - } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); - } - return methods; -}; +} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, -/***/ }), + next: function next() { + var _this = this; -/***/ 96630: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + + if (error !== null) { + return Promise.reject(error); + } -var ITERATOR = __webpack_require__(22939)('iterator'); -var SAFE_CLOSING = false; + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } -try { - var riter = [7][ITERATOR](); - riter['return'] = function () { SAFE_CLOSING = true; }; - // eslint-disable-next-line no-throw-literal - Array.from(riter, function () { throw 2; }); -} catch (e) { /* empty */ } - -module.exports = function (exec, skipClosing) { - if (!skipClosing && !SAFE_CLOSING) return false; - var safe = false; - try { - var arr = [7]; - var iter = arr[ITERATOR](); - iter.next = function () { return { done: safe = true }; }; - arr[ITERATOR] = function () { return iter; }; - exec(arr); - } catch (e) { /* empty */ } - return safe; -}; + 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; -/***/ 85084: -/***/ ((module) => { + 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(); -module.exports = function (done, value) { - return { value: value, done: !!done }; -}; + 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; -/***/ 15449: -/***/ ((module) => { + // 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; + } -module.exports = {}; + 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(); -/***/ 16227: -/***/ ((module) => { + 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 -module.exports = true; + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } -/***/ }), + var resolve = iterator[kLastResolve]; -/***/ 99839: -/***/ ((module) => { + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } -// 20.2.2.28 Math.sign(x) -module.exports = Math.sign || function sign(x) { - // eslint-disable-next-line no-self-compare - return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; }; +module.exports = createReadableStreamAsyncIterator; /***/ }), -/***/ 77177: +/***/ 12389: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var META = __webpack_require__(65730)('meta'); -var isObject = __webpack_require__(36727); -var has = __webpack_require__(27069); -var setDesc = (__webpack_require__(4743).f); -var id = 0; -var isExtensible = Object.isExtensible || function () { - return true; -}; -var FREEZE = !__webpack_require__(7929)(function () { - return isExtensible(Object.preventExtensions({})); -}); -var setMeta = function (it) { - setDesc(it, META, { value: { - i: 'O' + ++id, // object ID - w: {} // weak collections IDs - } }); -}; -var fastKey = function (it, create) { - // return primitive with prefix - if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; - if (!has(it, META)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return 'F'; - // not necessary to add metadata - if (!create) return 'E'; - // add missing metadata - setMeta(it); - // return object ID - } return it[META].i; -}; -var getWeak = function (it, create) { - if (!has(it, META)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return true; - // not necessary to add metadata - if (!create) return false; - // add missing metadata - setMeta(it); - // return hash weak collections IDs - } return it[META].w; -}; -// add metadata on freeze-family methods calling -var onFreeze = function (it) { - if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); - return it; -}; -var meta = module.exports = { - KEY: META, - NEED: false, - fastKey: fastKey, - getWeak: getWeak, - onFreeze: onFreeze -}; - - -/***/ }), +"use strict"; -/***/ 81601: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var global = __webpack_require__(33938); -var macrotask = (__webpack_require__(62569).set); -var Observer = global.MutationObserver || global.WebKitMutationObserver; -var process = global.process; -var Promise = global.Promise; -var isNode = __webpack_require__(32894)(process) == 'process'; +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } -module.exports = function () { - var head, last, notify; - - var flush = function () { - var parent, fn; - if (isNode && (parent = process.domain)) parent.exit(); - while (head) { - fn = head.fn; - head = head.next; - try { - fn(); - } catch (e) { - if (head) notify(); - else last = undefined; - throw e; - } - } last = undefined; - if (parent) parent.enter(); - }; +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - // Node.js - if (isNode) { - notify = function () { - process.nextTick(flush); - }; - // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 - } else if (Observer && !(global.navigator && global.navigator.standalone)) { - var toggle = true; - var node = document.createTextNode(''); - new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new - notify = function () { - node.data = toggle = !toggle; - }; - // environments with maybe non-completely correct, but existent Promise - } else if (Promise && Promise.resolve) { - // Promise.resolve without an argument throws an error in LG WebOS 2 - var promise = Promise.resolve(undefined); - notify = function () { - promise.then(flush); - }; - // for other environments - macrotask based on: - // - setImmediate - // - MessageChannel - // - window.postMessag - // - onreadystatechange - // - setTimeout - } else { - notify = function () { - // strange IE + webpack dev server bug - use .call(global) - macrotask.call(global, flush); - }; - } +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - return function (fn) { - var task = { fn: fn, next: undefined }; - if (last) last.next = task; - if (!head) { - head = task; - notify(); - } last = task; - }; -}; +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, descriptor.key, descriptor); } } -/***/ }), +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } -/***/ 59304: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +var _require = __webpack_require__(48287), + Buffer = _require.Buffer; -"use strict"; +var _require2 = __webpack_require__(8460), + inspect = _require2.inspect; -// 25.4.1.5 NewPromiseCapability(C) -var aFunction = __webpack_require__(85663); +var custom = inspect && inspect.custom || 'inspect'; -function PromiseCapability(C) { - var resolve, reject; - this.promise = new C(function ($$resolve, $$reject) { - if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); - resolve = $$resolve; - reject = $$reject; - }); - this.resolve = aFunction(resolve); - this.reject = aFunction(reject); +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); } -module.exports.f = function (C) { - return new PromiseCapability(C); -}; - +module.exports = +/*#__PURE__*/ +function () { + function BufferList() { + _classCallCheck(this, BufferList); -/***/ }), + this.head = null; + this.tail = null; + this.length = 0; + } -/***/ 88082: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + _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; -"use strict"; + while (p = p.next) { + ret += s + p.data; + } -// 19.1.2.1 Object.assign(target, source, ...) -var DESCRIPTORS = __webpack_require__(89666); -var getKeys = __webpack_require__(46162); -var gOPS = __webpack_require__(48195); -var pIE = __webpack_require__(86274); -var toObject = __webpack_require__(66530); -var IObject = __webpack_require__(50799); -var $assign = Object.assign; - -// should work with symbols and should have deterministic property order (V8 bug) -module.exports = !$assign || __webpack_require__(7929)(function () { - var A = {}; - var B = {}; - // eslint-disable-next-line no-undef - var S = Symbol(); - var K = 'abcdefghijklmnopqrst'; - A[S] = 7; - K.split('').forEach(function (k) { B[k] = k; }); - return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; -}) ? function assign(target, source) { // eslint-disable-line no-unused-vars - var T = toObject(target); - var aLen = arguments.length; - var index = 1; - var getSymbols = gOPS.f; - var isEnum = pIE.f; - while (aLen > index) { - var S = IObject(arguments[index++]); - var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); - var length = keys.length; - var j = 0; - var key; - while (length > j) { - key = keys[j++]; - if (!DESCRIPTORS || isEnum.call(S, key)) T[key] = S[key]; + return ret; } - } return T; -} : $assign; - + }, { + 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; + } -/***/ 98989: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + return ret; + } // Consumes a specified amount of bytes or characters from the buffered data. -// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) -var anObject = __webpack_require__(12159); -var dPs = __webpack_require__(57856); -var enumBugKeys = __webpack_require__(73338); -var IE_PROTO = __webpack_require__(58989)('IE_PROTO'); -var Empty = function () { /* empty */ }; -var PROTOTYPE = 'prototype'; - -// Create object with fake `null` prototype: use iframe Object with cleared prototype -var createDict = function () { - // Thrash, waste and sodomy: IE GC bug - var iframe = __webpack_require__(97467)('iframe'); - var i = enumBugKeys.length; - var lt = '<'; - var gt = '>'; - var iframeDocument; - iframe.style.display = 'none'; - (__webpack_require__(54881).appendChild)(iframe); - iframe.src = 'javascript:'; // eslint-disable-line no-script-url - // createDict = iframe.contentWindow.Object; - // html.removeChild(iframe); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); - iframeDocument.close(); - createDict = iframeDocument.F; - while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; - return createDict(); -}; - -module.exports = Object.create || function create(O, Properties) { - var result; - if (O !== null) { - Empty[PROTOTYPE] = anObject(O); - result = new Empty(); - Empty[PROTOTYPE] = null; - // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO] = O; - } else result = createDict(); - return Properties === undefined ? result : dPs(result, Properties); -}; + }, { + 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. -/***/ 4743: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; -var anObject = __webpack_require__(12159); -var IE8_DOM_DEFINE = __webpack_require__(33758); -var toPrimitive = __webpack_require__(33206); -var dP = Object.defineProperty; + 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; -exports.f = __webpack_require__(89666) ? Object.defineProperty : function defineProperty(O, P, Attributes) { - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if (IE8_DOM_DEFINE) try { - return dP(O, P, Attributes); - } catch (e) { /* empty */ } - if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); - if ('value' in Attributes) O[P] = Attributes.value; - return O; -}; + 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; + } -/***/ 57856: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. -var dP = __webpack_require__(4743); -var anObject = __webpack_require__(12159); -var getKeys = __webpack_require__(46162); + }, { + 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; -module.exports = __webpack_require__(89666) ? Object.defineProperties : function defineProperties(O, Properties) { - anObject(O); - var keys = getKeys(Properties); - var length = keys.length; - var i = 0; - var P; - while (length > i) dP.f(O, P = keys[i++], Properties[P]); - return O; -}; + 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; + } -/***/ 76183: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + ++c; + } -var pIE = __webpack_require__(86274); -var createDesc = __webpack_require__(83101); -var toIObject = __webpack_require__(7932); -var toPrimitive = __webpack_require__(33206); -var has = __webpack_require__(27069); -var IE8_DOM_DEFINE = __webpack_require__(33758); -var gOPD = Object.getOwnPropertyDescriptor; + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. -exports.f = __webpack_require__(89666) ? gOPD : function getOwnPropertyDescriptor(O, P) { - O = toIObject(O); - P = toPrimitive(P, true); - if (IE8_DOM_DEFINE) try { - return gOPD(O, P); - } catch (e) { /* empty */ } - if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); -}; + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; +}(); /***/ }), -/***/ 94368: +/***/ 41468: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window -var toIObject = __webpack_require__(7932); -var gOPN = (__webpack_require__(33230).f); -var toString = {}.toString; +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); + // undocumented cb() API, needed for core, not for public API -var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames - ? Object.getOwnPropertyNames(window) : []; +function destroy(err, cb) { + var _this = this; -var getWindowNames = function (it) { - try { - return gOPN(it); - } catch (e) { - return windowNames.slice(); - } -}; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; -module.exports.f = function getOwnPropertyNames(it) { - return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); -}; + 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 -/***/ }), -/***/ 33230: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well -// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) -var $keys = __webpack_require__(12963); -var hiddenKeys = (__webpack_require__(73338).concat)('length', 'prototype'); -exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { - return $keys(O, hiddenKeys); -}; + 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; +} -/***/ 48195: -/***/ ((__unused_webpack_module, exports) => { +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} -exports.f = Object.getOwnPropertySymbols; +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; + } +} -/***/ 95089: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function emitErrorNT(self, err) { + self.emit('error', err); +} -// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) -var has = __webpack_require__(27069); -var toObject = __webpack_require__(66530); -var IE_PROTO = __webpack_require__(58989)('IE_PROTO'); -var ObjectProto = Object.prototype; +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 = Object.getPrototypeOf || function (O) { - O = toObject(O); - if (has(O, IE_PROTO)) return O[IE_PROTO]; - if (typeof O.constructor == 'function' && O instanceof O.constructor) { - return O.constructor.prototype; - } return O instanceof Object ? ObjectProto : null; +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy }; - /***/ }), -/***/ 12963: +/***/ 45826: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var has = __webpack_require__(27069); -var toIObject = __webpack_require__(7932); -var arrayIndexOf = __webpack_require__(57428)(false); -var IE_PROTO = __webpack_require__(58989)('IE_PROTO'); +"use strict"; +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). -module.exports = function (object, names) { - var O = toIObject(object); - var i = 0; - var result = []; - var key; - for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); - // Don't enum bug & hidden keys - while (names.length > i) if (has(O, key = names[i++])) { - ~arrayIndexOf(result, key) || result.push(key); - } - return result; -}; +var ERR_STREAM_PREMATURE_CLOSE = (__webpack_require__(92260)/* .codes */ .F).ERR_STREAM_PREMATURE_CLOSE; -/***/ }), +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; -/***/ 46162: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } -// 19.1.2.14 / 15.2.3.14 Object.keys(O) -var $keys = __webpack_require__(12963); -var enumBugKeys = __webpack_require__(73338); + callback.apply(this, args); + }; +} -module.exports = Object.keys || function keys(O) { - return $keys(O, enumBugKeys); -}; +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; -/***/ 86274: -/***/ ((__unused_webpack_module, exports) => { + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; -exports.f = {}.propertyIsEnumerable; + 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; -/***/ 12584: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; -// most Object methods by ES6 should accept primitives -var $export = __webpack_require__(83856); -var core = __webpack_require__(34579); -var fails = __webpack_require__(7929); -module.exports = function (KEY, exec) { - var fn = (core.Object || {})[KEY] || Object[KEY]; - var exp = {}; - exp[KEY] = exec(fn); - $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); -}; + 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); + } -/***/ 10931: -/***/ ((module) => { + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; -module.exports = function (exec) { - try { - return { e: false, v: exec() }; - } catch (e) { - return { e: true, v: e }; + 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); } -}; - - -/***/ }), -/***/ 87790: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var anObject = __webpack_require__(12159); -var isObject = __webpack_require__(36727); -var newPromiseCapability = __webpack_require__(59304); - -module.exports = function (C, x) { - anObject(C); - if (isObject(x) && x.constructor === C) return x; - var promiseCapability = newPromiseCapability.f(C); - var resolve = promiseCapability.resolve; - resolve(x); - return promiseCapability.promise; -}; + 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; /***/ }), -/***/ 83101: +/***/ 45049: /***/ ((module) => { -module.exports = function (bitmap, value) { - return { - enumerable: !(bitmap & 1), - configurable: !(bitmap & 2), - writable: !(bitmap & 4), - value: value - }; +module.exports = function () { + throw new Error('Readable.from is not available in the browser') }; /***/ }), -/***/ 48144: +/***/ 29434: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var hide = __webpack_require__(41818); -module.exports = function (target, src, safe) { - for (var key in src) { - if (safe && target[key]) target[key] = src[key]; - else hide(target, key, src[key]); - } return target; -}; - - -/***/ }), +"use strict"; +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). -/***/ 57470: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -module.exports = __webpack_require__(41818); +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} -/***/ }), +var _require$codes = (__webpack_require__(92260)/* .codes */ .F), + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; -/***/ 39967: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} -"use strict"; +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} -var global = __webpack_require__(33938); -var core = __webpack_require__(34579); -var dP = __webpack_require__(4743); -var DESCRIPTORS = __webpack_require__(89666); -var SPECIES = __webpack_require__(22939)('species'); - -module.exports = function (KEY) { - var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY]; - if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { - configurable: true, - get: function () { return this; } +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; }); -}; - - -/***/ }), - -/***/ 25378: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var def = (__webpack_require__(4743).f); -var has = __webpack_require__(27069); -var TAG = __webpack_require__(22939)('toStringTag'); - -module.exports = function (it, tag, stat) { - if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); -}; + if (eos === undefined) eos = __webpack_require__(45826); + 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(); +} -/***/ 58989: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function pipe(from, to) { + return from.pipe(to); +} -var shared = __webpack_require__(20250)('keys'); -var uid = __webpack_require__(65730); -module.exports = function (key) { - return shared[key] || (shared[key] = uid(key)); -}; +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]; -/***/ 20250: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } -var core = __webpack_require__(34579); -var global = __webpack_require__(33938); -var SHARED = '__core-js_shared__'; -var store = global[SHARED] || (global[SHARED] = {}); - -(module.exports = function (key, value) { - return store[key] || (store[key] = value !== undefined ? value : {}); -})('versions', []).push({ - version: core.version, - mode: __webpack_require__(16227) ? 'pure' : 'global', - copyright: '© 2020 Denis Pushkarev (zloirock.ru)' -}); + 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; /***/ }), -/***/ 32707: +/***/ 8775: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -// 7.3.20 SpeciesConstructor(O, defaultConstructor) -var anObject = __webpack_require__(12159); -var aFunction = __webpack_require__(85663); -var SPECIES = __webpack_require__(22939)('species'); -module.exports = function (O, D) { - var C = anObject(O).constructor; - var S; - return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); -}; +"use strict"; -/***/ }), +var ERR_INVALID_OPT_VALUE = (__webpack_require__(92260)/* .codes */ .F).ERR_INVALID_OPT_VALUE; -/***/ 90510: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} -var toInteger = __webpack_require__(11052); -var defined = __webpack_require__(8333); -// true -> String#at -// false -> String#codePointAt -module.exports = function (TO_STRING) { - return function (that, pos) { - var s = String(defined(that)); - var i = toInteger(pos); - var l = s.length; - var a, b; - if (i < 0 || i >= l) return TO_STRING ? '' : undefined; - a = s.charCodeAt(i); - return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff - ? TO_STRING ? s.charAt(i) : a - : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; - }; -}; +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 -/***/ 62569: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var ctx = __webpack_require__(19216); -var invoke = __webpack_require__(46778); -var html = __webpack_require__(54881); -var cel = __webpack_require__(97467); -var global = __webpack_require__(33938); -var process = global.process; -var setTask = global.setImmediate; -var clearTask = global.clearImmediate; -var MessageChannel = global.MessageChannel; -var Dispatch = global.Dispatch; -var counter = 0; -var queue = {}; -var ONREADYSTATECHANGE = 'onreadystatechange'; -var defer, channel, port; -var run = function () { - var id = +this; - // eslint-disable-next-line no-prototype-builtins - if (queue.hasOwnProperty(id)) { - var fn = queue[id]; - delete queue[id]; - fn(); - } -}; -var listener = function (event) { - run.call(event.data); -}; -// Node.js 0.9+ & IE10+ has setImmediate, otherwise: -if (!setTask || !clearTask) { - setTask = function setImmediate(fn) { - var args = []; - var i = 1; - while (arguments.length > i) args.push(arguments[i++]); - queue[++counter] = function () { - // eslint-disable-next-line no-new-func - invoke(typeof fn == 'function' ? fn : Function(fn), args); - }; - defer(counter); - return counter; - }; - clearTask = function clearImmediate(id) { - delete queue[id]; - }; - // Node.js 0.8- - if (__webpack_require__(32894)(process) == 'process') { - defer = function (id) { - process.nextTick(ctx(run, id, 1)); - }; - // Sphere (JS game engine) Dispatch API - } else if (Dispatch && Dispatch.now) { - defer = function (id) { - Dispatch.now(ctx(run, id, 1)); - }; - // Browsers with MessageChannel, includes WebWorkers - } else if (MessageChannel) { - channel = new MessageChannel(); - port = channel.port2; - channel.port1.onmessage = listener; - defer = ctx(port.postMessage, port, 1); - // Browsers with postMessage, skip WebWorkers - // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' - } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { - defer = function (id) { - global.postMessage(id + '', '*'); - }; - global.addEventListener('message', listener, false); - // IE8- - } else if (ONREADYSTATECHANGE in cel('script')) { - defer = function (id) { - html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { - html.removeChild(this); - run.call(id); - }; - }; - // Rest old browsers - } else { - defer = function (id) { - setTimeout(ctx(run, id, 1), 0); - }; - } + return state.objectMode ? 16 : 16 * 1024; } + module.exports = { - set: setTask, - clear: clearTask + getHighWaterMark: getHighWaterMark }; - /***/ }), -/***/ 16531: +/***/ 71181: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var toInteger = __webpack_require__(11052); -var max = Math.max; -var min = Math.min; -module.exports = function (index, length) { - index = toInteger(index); - return index < 0 ? max(index + length, 0) : min(index, length); -}; +module.exports = __webpack_require__(37007).EventEmitter; /***/ }), -/***/ 11052: -/***/ ((module) => { +/***/ 61603: +/***/ ((module, exports, __webpack_require__) => { -// 7.1.4 ToInteger -var ceil = Math.ceil; -var floor = Math.floor; -module.exports = function (it) { - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); -}; +exports = module.exports = __webpack_require__(6736); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = __webpack_require__(62192); +exports.Duplex = __webpack_require__(92818); +exports.Transform = __webpack_require__(13054); +exports.PassThrough = __webpack_require__(35860); +exports.finished = __webpack_require__(45826); +exports.pipeline = __webpack_require__(29434); /***/ }), -/***/ 7932: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 17417: +/***/ ((module, exports, __webpack_require__) => { -// to indexed object, toObject with fallback for non-array-like ES3 strings -var IObject = __webpack_require__(50799); -var defined = __webpack_require__(8333); -module.exports = function (it) { - return IObject(defined(it)); -}; +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(48287) +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) +} -/***/ 78728: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +SafeBuffer.prototype = Object.create(Buffer.prototype) -// 7.1.15 ToLength -var toInteger = __webpack_require__(11052); -var min = Math.min; -module.exports = function (it) { - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 -}; +// 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 +} -/***/ 66530: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} -// 7.1.13 ToObject(argument) -var defined = __webpack_require__(8333); -module.exports = function (it) { - return Object(defined(it)); -}; +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} /***/ }), -/***/ 33206: +/***/ 9957: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -// 7.1.1 ToPrimitive(input [, PreferredType]) -var isObject = __webpack_require__(36727); -// instead of the ES6 spec version, we didn't implement @@toPrimitive case -// and the second argument - flag - preferred type is a string -module.exports = function (it, S) { - if (!isObject(it)) return it; - var fn, val; - if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; - if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - throw TypeError("Can't convert object to primitive value"); -}; - +"use strict"; -/***/ }), -/***/ 65730: -/***/ ((module) => { +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = __webpack_require__(66743); -var id = 0; -var px = Math.random(); -module.exports = function (key) { - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); -}; +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); /***/ }), -/***/ 26640: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var global = __webpack_require__(33938); -var navigator = global.navigator; - -module.exports = navigator && navigator.userAgent || ''; - - -/***/ }), +/***/ 251: +/***/ ((__unused_webpack_module, exports) => { -/***/ 76347: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] -var global = __webpack_require__(33938); -var core = __webpack_require__(34579); -var LIBRARY = __webpack_require__(16227); -var wksExt = __webpack_require__(25103); -var defineProperty = (__webpack_require__(4743).f); -module.exports = function (name) { - var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); - if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); -}; + i += d + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} -/***/ }), + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} -/***/ 25103: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} -exports.f = __webpack_require__(22939); +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + value = Math.abs(value) -/***/ }), + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } -/***/ 22939: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } -var store = __webpack_require__(20250)('wks'); -var uid = __webpack_require__(65730); -var Symbol = (__webpack_require__(33938).Symbol); -var USE_SYMBOL = typeof Symbol == 'function'; + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} -var $exports = module.exports = function (name) { - return store[name] || (store[name] = - USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); -}; + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} -$exports.store = store; + buffer[offset + i - d] |= s * 128 +} /***/ }), -/***/ 83728: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 56698: +/***/ ((module) => { -var classof = __webpack_require__(14677); -var ITERATOR = __webpack_require__(22939)('iterator'); -var Iterators = __webpack_require__(15449); -module.exports = (__webpack_require__(34579).getIteratorMethod) = function (it) { - if (it != undefined) return it[ITERATOR] - || it['@@iterator'] - || Iterators[classof(it)]; -}; +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 + } + } +} /***/ }), -/***/ 46459: +/***/ 4866: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var anObject = __webpack_require__(12159); -var get = __webpack_require__(83728); -module.exports = (__webpack_require__(34579).getIterator) = function (it) { - var iterFn = get(it); - if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!'); - return anObject(iterFn.call(it)); -}; +/* provided dependency */ var process = __webpack_require__(65606); +// https://github.com/electron/electron/issues/2288 +function isElectron() { + // Renderer process + if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') { + return true; + } + // Main process + if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) { + return true; + } -/***/ }), + // Detect the user agent when the `nodeIntegration` option is set to false + if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) { + return true; + } -/***/ 89553: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + return false; +} -var classof = __webpack_require__(14677); -var ITERATOR = __webpack_require__(22939)('iterator'); -var Iterators = __webpack_require__(15449); -module.exports = (__webpack_require__(34579).isIterable) = function (it) { - var O = Object(it); - return O[ITERATOR] !== undefined - || '@@iterator' in O - // eslint-disable-next-line no-prototype-builtins - || Iterators.hasOwnProperty(classof(O)); -}; +module.exports = isElectron; /***/ }), -/***/ 2586: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; +/***/ 44191: +/***/ ((module) => { -var ctx = __webpack_require__(19216); -var $export = __webpack_require__(83856); -var toObject = __webpack_require__(66530); -var call = __webpack_require__(95602); -var isArrayIter = __webpack_require__(45991); -var toLength = __webpack_require__(78728); -var createProperty = __webpack_require__(52445); -var getIterFn = __webpack_require__(83728); - -$export($export.S + $export.F * !__webpack_require__(96630)(function (iter) { Array.from(iter); }), 'Array', { - // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) - from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { - var O = toObject(arrayLike); - var C = typeof this == 'function' ? this : Array; - var aLen = arguments.length; - var mapfn = aLen > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var index = 0; - var iterFn = getIterFn(O); - var length, result, step, iterator; - if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); - // if object isn't iterable or it's array with default iterator - use simple case - if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { - for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { - createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); - } - } else { - length = toLength(O.length); - for (result = new C(length); length > index; index++) { - createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); - } - } - result.length = index; - return result; +module.exports = function (glob, opts) { + if (typeof glob !== 'string') { + throw new TypeError('Expected a string'); } -}); + var str = String(glob); -/***/ }), - -/***/ 3882: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + // The regexp we are building, as a string. + var reStr = ""; -"use strict"; + // Whether we are matching so called "extended" globs (like bash) and should + // support single character matching, matching ranges of characters, group + // matching, etc. + var extended = opts ? !!opts.extended : false; -var addToUnscopables = __webpack_require__(79003); -var step = __webpack_require__(85084); -var Iterators = __webpack_require__(15449); -var toIObject = __webpack_require__(7932); - -// 22.1.3.4 Array.prototype.entries() -// 22.1.3.13 Array.prototype.keys() -// 22.1.3.29 Array.prototype.values() -// 22.1.3.30 Array.prototype[@@iterator]() -module.exports = __webpack_require__(45700)(Array, 'Array', function (iterated, kind) { - this._t = toIObject(iterated); // target - this._i = 0; // next index - this._k = kind; // kind -// 22.1.5.2.1 %ArrayIteratorPrototype%.next() -}, function () { - var O = this._t; - var kind = this._k; - var index = this._i++; - if (!O || index >= O.length) { - this._t = undefined; - return step(1); - } - if (kind == 'keys') return step(0, index); - if (kind == 'values') return step(0, O[index]); - return step(0, [index, O[index]]); -}, 'values'); - -// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) -Iterators.Arguments = Iterators.Array; - -addToUnscopables('keys'); -addToUnscopables('values'); -addToUnscopables('entries'); + // Whether or not to capture those stars, it means wrapping them with parentheses + // It's not necessary if globstart is turned on + var capture = opts ? !!opts.capture : false; + var nonGreedy = opts ? !!opts.nonGreedy : false; -/***/ }), + // When globstar is _false_ (default), '/foo/*' is translated a regexp like + // '^\/foo\/.*$' which will match any string beginning with '/foo/' + // When globstar is _true_, '/foo/*' is translated to regexp like + // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT + // which does not have a '/' to the right of it. + // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but + // these will not '/foo/bar/baz', '/foo/bar/baz.txt' + // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when + // globstar is _false_ + var globstar = opts ? !!opts.globstar : false; -/***/ 52684: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { + // If we are doing extended matching, this boolean is true when we are inside + // a group (eg {*.html,*.js}), and false otherwise. + var inGroup = false; -// 20.2.2.28 Math.sign(x) -var $export = __webpack_require__(83856); + // RegExp flags (eg "i" ) to pass in to RegExp constructor. + var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; -$export($export.S, 'Math', { sign: __webpack_require__(99839) }); + var c; + for (var i = 0, len = str.length; i < len; i++) { + c = str[i]; + switch (c) { + case "/": + case "$": + case "^": + case "+": + case ".": + case "(": + case ")": + case "=": + case "!": + case "|": + reStr += "\\" + c; + break; -/***/ }), + case "?": + if (extended) { + reStr += "."; + break; + } -/***/ 72699: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { + case "[": + case "]": + if (extended) { + reStr += c; + break; + } -// 19.1.3.1 Object.assign(target, source) -var $export = __webpack_require__(83856); + case "{": + if (extended) { + inGroup = true; + reStr += "("; + break; + } -$export($export.S + $export.F, 'Object', { assign: __webpack_require__(88082) }); + case "}": + if (extended) { + inGroup = false; + reStr += ")"; + break; + } + case ",": + if (inGroup) { + reStr += "|"; + break; + } + reStr += "\\" + c; + break; -/***/ }), + case "*": + // Move over all consecutive "*"'s. + // Also store the previous and next characters + var prevChar = str[i - 1]; + var starCount = 1; + while(str[i + 1] === "*") { + starCount++; + i++; + } + var nextChar = str[i + 1]; -/***/ 31477: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { + if (!globstar) { + // globstar is disabled, so treat any number of "*" as one + var s = nonGreedy ? ".*?" : ".*"; -var $export = __webpack_require__(83856); -// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) -$export($export.S + $export.F * !__webpack_require__(89666), 'Object', { defineProperty: (__webpack_require__(4743).f) }); + if (capture) { + s = "(" + s + ")"; + } + reStr += s; + } else { + // globstar is enabled, so determine if this is a globstar segment + var isGlobstar = starCount > 1 // multiple "*"'s + && (prevChar === "/" || prevChar === undefined) // from the start of the segment + && (nextChar === "/" || nextChar === undefined) // to the end of the segment -/***/ }), + if (isGlobstar) { + // it's a globstar, so match zero or more path segments + reStr += "((?:[^/]*(?:\/|$))*)"; + i++; // move over the "/" + } else { + // it's not a globstar, so only match one path segment + reStr += "([^/]*)"; + } + } + break; -/***/ 40961: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { + default: + reStr += c; + } + } -// 19.1.2.14 Object.keys(O) -var toObject = __webpack_require__(66530); -var $keys = __webpack_require__(46162); + // When regexp 'g' flag is specified don't + // constrain the regular expression with ^ & $ + if (!flags || !~flags.indexOf('g')) { + reStr = "^" + reStr + "$"; + } -__webpack_require__(12584)('keys', function () { - return function keys(it) { - return $keys(toObject(it)); - }; -}); + return new RegExp(reStr, flags); +}; /***/ }), -/***/ 94058: -/***/ (() => { +/***/ 20181: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; -/***/ }), +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; -/***/ 32878: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; -"use strict"; +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; -var LIBRARY = __webpack_require__(16227); -var global = __webpack_require__(33938); -var ctx = __webpack_require__(19216); -var classof = __webpack_require__(14677); -var $export = __webpack_require__(83856); -var isObject = __webpack_require__(36727); -var aFunction = __webpack_require__(85663); -var anInstance = __webpack_require__(29142); -var forOf = __webpack_require__(45576); -var speciesConstructor = __webpack_require__(32707); -var task = (__webpack_require__(62569).set); -var microtask = __webpack_require__(81601)(); -var newPromiseCapabilityModule = __webpack_require__(59304); -var perform = __webpack_require__(10931); -var userAgent = __webpack_require__(26640); -var promiseResolve = __webpack_require__(87790); -var PROMISE = 'Promise'; -var TypeError = global.TypeError; -var process = global.process; -var versions = process && process.versions; -var v8 = versions && versions.v8 || ''; -var $Promise = global[PROMISE]; -var isNode = classof(process) == 'process'; -var empty = function () { /* empty */ }; -var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; -var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; - -var USE_NATIVE = !!function () { - try { - // correct subclassing with @@species support - var promise = $Promise.resolve(1); - var FakePromise = (promise.constructor = {})[__webpack_require__(22939)('species')] = function (exec) { - exec(empty, empty); - }; - // unhandled rejections tracking support, NodeJS Promise without it fails @@species test - return (isNode || typeof PromiseRejectionEvent == 'function') - && promise.then(empty) instanceof FakePromise - // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables - // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 - // we can't detect it synchronously, so just check versions - && v8.indexOf('6.6') !== 0 - && userAgent.indexOf('Chrome/66') === -1; - } catch (e) { /* empty */ } -}(); +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; -// helpers -var isThenable = function (it) { - var then; - return isObject(it) && typeof (then = it.then) == 'function' ? then : false; -}; -var notify = function (promise, isReject) { - if (promise._n) return; - promise._n = true; - var chain = promise._c; - microtask(function () { - var value = promise._v; - var ok = promise._s == 1; - var i = 0; - var run = function (reaction) { - var handler = ok ? reaction.ok : reaction.fail; - var resolve = reaction.resolve; - var reject = reaction.reject; - var domain = reaction.domain; - var result, then, exited; - try { - if (handler) { - if (!ok) { - if (promise._h == 2) onHandleUnhandled(promise); - promise._h = 1; - } - if (handler === true) result = value; - else { - if (domain) domain.enter(); - result = handler(value); // may throw - if (domain) { - domain.exit(); - exited = true; - } - } - if (result === reaction.promise) { - reject(TypeError('Promise-chain cycle')); - } else if (then = isThenable(result)) { - then.call(result, resolve, reject); - } else resolve(result); - } else reject(value); - } catch (e) { - if (domain && !exited) domain.exit(); - reject(e); - } - }; - while (chain.length > i) run(chain[i++]); // variable length - can't use forEach - promise._c = []; - promise._n = false; - if (isReject && !promise._h) onUnhandled(promise); - }); -}; -var onUnhandled = function (promise) { - task.call(global, function () { - var value = promise._v; - var unhandled = isUnhandled(promise); - var result, handler, console; - if (unhandled) { - result = perform(function () { - if (isNode) { - process.emit('unhandledRejection', value, promise); - } else if (handler = global.onunhandledrejection) { - handler({ promise: promise, reason: value }); - } else if ((console = global.console) && console.error) { - console.error('Unhandled promise rejection', value); - } - }); - // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should - promise._h = isNode || isUnhandled(promise) ? 2 : 1; - } promise._a = undefined; - if (unhandled && result.e) throw result.v; - }); -}; -var isUnhandled = function (promise) { - return promise._h !== 1 && (promise._a || promise._c).length === 0; -}; -var onHandleUnhandled = function (promise) { - task.call(global, function () { - var handler; - if (isNode) { - process.emit('rejectionHandled', promise); - } else if (handler = global.onrejectionhandled) { - handler({ promise: promise, reason: promise._v }); - } - }); -}; -var $reject = function (value) { - var promise = this; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - promise._v = value; - promise._s = 2; - if (!promise._a) promise._a = promise._c.slice(); - notify(promise, true); -}; -var $resolve = function (value) { - var promise = this; - var then; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - try { - if (promise === value) throw TypeError("Promise can't be resolved itself"); - if (then = isThenable(value)) { - microtask(function () { - var wrapper = { _w: promise, _d: false }; // wrap - try { - then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); - } catch (e) { - $reject.call(wrapper, e); - } - }); - } else { - promise._v = value; - promise._s = 1; - notify(promise, false); - } - } catch (e) { - $reject.call({ _w: promise, _d: false }, e); // wrap - } -}; +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; -// constructor polyfill -if (!USE_NATIVE) { - // 25.4.3.1 Promise(executor) - $Promise = function Promise(executor) { - anInstance(this, $Promise, PROMISE, '_h'); - aFunction(executor); - Internal.call(this); - try { - executor(ctx($resolve, this, 1), ctx($reject, this, 1)); - } catch (err) { - $reject.call(this, err); - } - }; - // eslint-disable-next-line no-unused-vars - Internal = function Promise(executor) { - this._c = []; // <- awaiting reactions - this._a = undefined; // <- checked in isUnhandled reactions - this._s = 0; // <- state - this._d = false; // <- done - this._v = undefined; // <- value - this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled - this._n = false; // <- notify - }; - Internal.prototype = __webpack_require__(48144)($Promise.prototype, { - // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) - then: function then(onFulfilled, onRejected) { - var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); - reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; - reaction.fail = typeof onRejected == 'function' && onRejected; - reaction.domain = isNode ? process.domain : undefined; - this._c.push(reaction); - if (this._a) this._a.push(reaction); - if (this._s) notify(this, false); - return reaction.promise; - }, - // 25.4.5.1 Promise.prototype.catch(onRejected) - 'catch': function (onRejected) { - return this.then(undefined, onRejected); - } - }); - OwnPromiseCapability = function () { - var promise = new Internal(); - this.promise = promise; - this.resolve = ctx($resolve, promise, 1); - this.reject = ctx($reject, promise, 1); - }; - newPromiseCapabilityModule.f = newPromiseCapability = function (C) { - return C === $Promise || C === Wrapper - ? new OwnPromiseCapability(C) - : newGenericPromiseCapability(C); - }; -} +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; -$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); -__webpack_require__(25378)($Promise, PROMISE); -__webpack_require__(39967)(PROMISE); -Wrapper = __webpack_require__(34579)[PROMISE]; +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; -// statics -$export($export.S + $export.F * !USE_NATIVE, PROMISE, { - // 25.4.4.5 Promise.reject(r) - reject: function reject(r) { - var capability = newPromiseCapability(this); - var $$reject = capability.reject; - $$reject(r); - return capability.promise; - } -}); -$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { - // 25.4.4.6 Promise.resolve(x) - resolve: function resolve(x) { - return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); - } -}); -$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(96630)(function (iter) { - $Promise.all(iter)['catch'](empty); -})), PROMISE, { - // 25.4.4.1 Promise.all(iterable) - all: function all(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var resolve = capability.resolve; - var reject = capability.reject; - var result = perform(function () { - var values = []; - var index = 0; - var remaining = 1; - forOf(iterable, false, function (promise) { - var $index = index++; - var alreadyCalled = false; - values.push(undefined); - remaining++; - C.resolve(promise).then(function (value) { - if (alreadyCalled) return; - alreadyCalled = true; - values[$index] = value; - --remaining || resolve(values); - }, reject); - }); - --remaining || resolve(values); - }); - if (result.e) reject(result.v); - return capability.promise; - }, - // 25.4.4.4 Promise.race(iterable) - race: function race(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var reject = capability.reject; - var result = perform(function () { - forOf(iterable, false, function (promise) { - C.resolve(promise).then(capability.resolve, reject); - }); - }); - if (result.e) reject(result.v); - return capability.promise; - } -}); +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; -/***/ }), +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); -/***/ 91867: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { +/** Used for built-in method references. */ +var objectProto = Object.prototype; -"use strict"; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; -var $at = __webpack_require__(90510)(true); - -// 21.1.3.27 String.prototype[@@iterator]() -__webpack_require__(45700)(String, 'String', function (iterated) { - this._t = String(iterated); // target - this._i = 0; // next index -// 21.1.5.2.1 %StringIteratorPrototype%.next() -}, function () { - var O = this._t; - var index = this._i; - var point; - if (index >= O.length) return { value: undefined, done: true }; - point = $at(O, index); - this._i += point.length; - return { value: point, done: false }; -}); +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; +/** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ +var now = function() { + return root.Date.now(); +}; -/***/ }), +/** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ +function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } -/***/ 46840: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } -"use strict"; + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + result = wait - timeSinceLastCall; -// ECMAScript 6 symbols shim -var global = __webpack_require__(33938); -var has = __webpack_require__(27069); -var DESCRIPTORS = __webpack_require__(89666); -var $export = __webpack_require__(83856); -var redefine = __webpack_require__(57470); -var META = (__webpack_require__(77177).KEY); -var $fails = __webpack_require__(7929); -var shared = __webpack_require__(20250); -var setToStringTag = __webpack_require__(25378); -var uid = __webpack_require__(65730); -var wks = __webpack_require__(22939); -var wksExt = __webpack_require__(25103); -var wksDefine = __webpack_require__(76347); -var enumKeys = __webpack_require__(70337); -var isArray = __webpack_require__(71421); -var anObject = __webpack_require__(12159); -var isObject = __webpack_require__(36727); -var toObject = __webpack_require__(66530); -var toIObject = __webpack_require__(7932); -var toPrimitive = __webpack_require__(33206); -var createDesc = __webpack_require__(83101); -var _create = __webpack_require__(98989); -var gOPNExt = __webpack_require__(94368); -var $GOPD = __webpack_require__(76183); -var $GOPS = __webpack_require__(48195); -var $DP = __webpack_require__(4743); -var $keys = __webpack_require__(46162); -var gOPD = $GOPD.f; -var dP = $DP.f; -var gOPN = gOPNExt.f; -var $Symbol = global.Symbol; -var $JSON = global.JSON; -var _stringify = $JSON && $JSON.stringify; -var PROTOTYPE = 'prototype'; -var HIDDEN = wks('_hidden'); -var TO_PRIMITIVE = wks('toPrimitive'); -var isEnum = {}.propertyIsEnumerable; -var SymbolRegistry = shared('symbol-registry'); -var AllSymbols = shared('symbols'); -var OPSymbols = shared('op-symbols'); -var ObjectProto = Object[PROTOTYPE]; -var USE_NATIVE = typeof $Symbol == 'function' && !!$GOPS.f; -var QObject = global.QObject; -// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 -var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; - -// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 -var setSymbolDesc = DESCRIPTORS && $fails(function () { - return _create(dP({}, 'a', { - get: function () { return dP(this, 'a', { value: 7 }).a; } - })).a != 7; -}) ? function (it, key, D) { - var protoDesc = gOPD(ObjectProto, key); - if (protoDesc) delete ObjectProto[key]; - dP(it, key, D); - if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); -} : dP; - -var wrap = function (tag) { - var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); - sym._k = tag; - return sym; -}; - -var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { - return typeof it == 'symbol'; -} : function (it) { - return it instanceof $Symbol; -}; - -var $defineProperty = function defineProperty(it, key, D) { - if (it === ObjectProto) $defineProperty(OPSymbols, key, D); - anObject(it); - key = toPrimitive(key, true); - anObject(D); - if (has(AllSymbols, key)) { - if (!D.enumerable) { - if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); - it[HIDDEN][key] = true; - } else { - if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; - D = _create(D, { enumerable: createDesc(0, false) }); - } return setSymbolDesc(it, key, D); - } return dP(it, key, D); -}; -var $defineProperties = function defineProperties(it, P) { - anObject(it); - var keys = enumKeys(P = toIObject(P)); - var i = 0; - var l = keys.length; - var key; - while (l > i) $defineProperty(it, key = keys[i++], P[key]); - return it; -}; -var $create = function create(it, P) { - return P === undefined ? _create(it) : $defineProperties(_create(it), P); -}; -var $propertyIsEnumerable = function propertyIsEnumerable(key) { - var E = isEnum.call(this, key = toPrimitive(key, true)); - if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; - return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; -}; -var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { - it = toIObject(it); - key = toPrimitive(key, true); - if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; - var D = gOPD(it, key); - if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; - return D; -}; -var $getOwnPropertyNames = function getOwnPropertyNames(it) { - var names = gOPN(toIObject(it)); - var result = []; - var i = 0; - var key; - while (names.length > i) { - if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); - } return result; -}; -var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { - var IS_OP = it === ObjectProto; - var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); - var result = []; - var i = 0; - var key; - while (names.length > i) { - if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); - } return result; -}; - -// 19.4.1.1 Symbol([description]) -if (!USE_NATIVE) { - $Symbol = function Symbol() { - if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); - var tag = uid(arguments.length > 0 ? arguments[0] : undefined); - var $set = function (value) { - if (this === ObjectProto) $set.call(OPSymbols, value); - if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; - setSymbolDesc(this, tag, createDesc(1, value)); - }; - if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); - return wrap(tag); - }; - redefine($Symbol[PROTOTYPE], 'toString', function toString() { - return this._k; - }); + return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; + } - $GOPD.f = $getOwnPropertyDescriptor; - $DP.f = $defineProperty; - (__webpack_require__(33230).f) = gOPNExt.f = $getOwnPropertyNames; - (__webpack_require__(86274).f) = $propertyIsEnumerable; - $GOPS.f = $getOwnPropertySymbols; + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; - if (DESCRIPTORS && !__webpack_require__(16227)) { - redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } - wksExt.f = function (name) { - return wrap(wks(name)); - }; -} - -$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } -for (var es6Symbols = ( - // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 - 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' -).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); + function trailingEdge(time) { + timerId = undefined; -for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } -$export($export.S + $export.F * !USE_NATIVE, 'Symbol', { - // 19.4.2.1 Symbol.for(key) - 'for': function (key) { - return has(SymbolRegistry, key += '') - ? SymbolRegistry[key] - : SymbolRegistry[key] = $Symbol(key); - }, - // 19.4.2.5 Symbol.keyFor(sym) - keyFor: function keyFor(sym) { - if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); - for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; - }, - useSetter: function () { setter = true; }, - useSimple: function () { setter = false; } -}); + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } -$export($export.S + $export.F * !USE_NATIVE, 'Object', { - // 19.1.2.2 Object.create(O [, Properties]) - create: $create, - // 19.1.2.4 Object.defineProperty(O, P, Attributes) - defineProperty: $defineProperty, - // 19.1.2.3 Object.defineProperties(O, Properties) - defineProperties: $defineProperties, - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - getOwnPropertyDescriptor: $getOwnPropertyDescriptor, - // 19.1.2.7 Object.getOwnPropertyNames(O) - getOwnPropertyNames: $getOwnPropertyNames, - // 19.1.2.8 Object.getOwnPropertySymbols(O) - getOwnPropertySymbols: $getOwnPropertySymbols -}); + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } -// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives -// https://bugs.chromium.org/p/v8/issues/detail?id=3443 -var FAILS_ON_PRIMITIVES = $fails(function () { $GOPS.f(1); }); + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); -$export($export.S + $export.F * FAILS_ON_PRIMITIVES, 'Object', { - getOwnPropertySymbols: function getOwnPropertySymbols(it) { - return $GOPS.f(toObject(it)); - } -}); + lastArgs = arguments; + lastThis = this; + lastCallTime = time; -// 24.3.2 JSON.stringify(value [, replacer [, space]]) -$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { - var S = $Symbol(); - // MS Edge converts symbol values to JSON as {} - // WebKit converts symbol values to JSON as null - // V8 throws on boxed symbols - return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; -})), 'JSON', { - stringify: function stringify(it) { - var args = [it]; - var i = 1; - var replacer, $replacer; - while (arguments.length > i) args.push(arguments[i++]); - $replacer = replacer = args[1]; - if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined - if (!isArray(replacer)) replacer = function (key, value) { - if (typeof $replacer == 'function') value = $replacer.call(this, key, value); - if (!isSymbol(value)) return value; - }; - args[1] = replacer; - return _stringify.apply($JSON, args); + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; } -}); + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; +} -// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) -$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(41818)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); -// 19.4.3.5 Symbol.prototype[@@toStringTag] -setToStringTag($Symbol, 'Symbol'); -// 20.2.1.9 Math[@@toStringTag] -setToStringTag(Math, 'Math', true); -// 24.3.3 JSON[@@toStringTag] -setToStringTag(global.JSON, 'JSON', true); +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} -/***/ }), +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} -/***/ 95971: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} -"use strict"; -// https://github.com/tc39/proposal-promise-finally - -var $export = __webpack_require__(83856); -var core = __webpack_require__(34579); -var global = __webpack_require__(33938); -var speciesConstructor = __webpack_require__(32707); -var promiseResolve = __webpack_require__(87790); - -$export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { - var C = speciesConstructor(this, core.Promise || global.Promise); - var isFunction = typeof onFinally == 'function'; - return this.then( - isFunction ? function (x) { - return promiseResolve(C, onFinally()).then(function () { return x; }); - } : onFinally, - isFunction ? function (e) { - return promiseResolve(C, onFinally()).then(function () { throw e; }); - } : onFinally - ); -} }); +module.exports = debounce; /***/ }), -/***/ 22526: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { +/***/ 88276: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -// https://github.com/tc39/proposal-promise-try -var $export = __webpack_require__(83856); -var newPromiseCapability = __webpack_require__(59304); -var perform = __webpack_require__(10931); - -$export($export.S, 'Promise', { 'try': function (callbackfn) { - var promiseCapability = newPromiseCapability.f(this); - var result = perform(callbackfn); - (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); - return promiseCapability.promise; -} }); +var inherits = __webpack_require__(56698) +var HashBase = __webpack_require__(4729) +var Buffer = (__webpack_require__(92861).Buffer) +var ARRAY16 = new Array(16) -/***/ }), +function MD5 () { + HashBase.call(this, 64) -/***/ 8174: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 +} -__webpack_require__(76347)('asyncIterator'); +inherits(MD5, HashBase) +MD5.prototype._update = function () { + var M = ARRAY16 + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4) -/***/ }), + var a = this._a + var b = this._b + var c = this._c + var d = this._d -/***/ 36461: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7) + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12) + c = fnF(c, d, a, b, M[2], 0x242070db, 17) + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) + c = fnF(c, d, a, b, M[6], 0xa8304613, 17) + b = fnF(b, c, d, a, M[7], 0xfd469501, 22) + a = fnF(a, b, c, d, M[8], 0x698098d8, 7) + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) + a = fnF(a, b, c, d, M[12], 0x6b901122, 7) + d = fnF(d, a, b, c, M[13], 0xfd987193, 12) + c = fnF(c, d, a, b, M[14], 0xa679438e, 17) + b = fnF(b, c, d, a, M[15], 0x49b40821, 22) -__webpack_require__(76347)('observable'); + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) + d = fnG(d, a, b, c, M[6], 0xc040b340, 9) + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) + d = fnG(d, a, b, c, M[10], 0x02441453, 9) + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) + d = fnH(d, a, b, c, M[8], 0x8771f681, 11) + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) + b = fnH(b, c, d, a, M[6], 0x04881d05, 23) + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) -/***/ }), + a = fnI(a, b, c, d, M[0], 0xf4292244, 6) + d = fnI(d, a, b, c, M[7], 0x432aff97, 10) + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) + c = fnI(c, d, a, b, M[6], 0xa3014314, 15) + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) -/***/ 73871: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { + this._a = (this._a + a) | 0 + this._b = (this._b + b) | 0 + this._c = (this._c + c) | 0 + this._d = (this._d + d) | 0 +} -__webpack_require__(3882); -var global = __webpack_require__(33938); -var hide = __webpack_require__(41818); -var Iterators = __webpack_require__(15449); -var TO_STRING_TAG = __webpack_require__(22939)('toStringTag'); +MD5.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } -var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + - 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + - 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + - 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + - 'TextTrackList,TouchList').split(','); + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() -for (var i = 0; i < DOMIterables.length; i++) { - var NAME = DOMIterables[i]; - var Collection = global[NAME]; - var proto = Collection && Collection.prototype; - if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); - Iterators[NAME] = Iterators.Array; + // produce result + var buffer = Buffer.allocUnsafe(16) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + return buffer } +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} -/***/ }), +function fnF (a, b, c, d, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 +} -/***/ 78028: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function fnG (a, b, c, d, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 +} -var MD5 = __webpack_require__(62318) +function fnH (a, b, c, d, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 +} -module.exports = function (buffer) { - return new MD5().update(buffer).digest() +function fnI (a, b, c, d, m, k, s) { + return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 } +module.exports = MD5 + /***/ }), -/***/ 34673: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* export default binding */ __WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony default export */ function __WEBPACK_DEFAULT_EXPORT__(element) { - if ( - element.ownerDocument.designMode && - element.ownerDocument.designMode.toLowerCase() === 'on' - ) { - return true - } +/***/ 58859: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - switch (element.tagName.toLowerCase()) { - case 'input': - return isEditableInput(element) - case 'textarea': - return true - } +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; - if (isContentEditable(element)) { - return true - } +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 +); - return false +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, '$&_'); } -function isContentEditable (element) { - if ( - element.contentEditable && - element.contentEditable.toLowerCase() === 'true' - ) { - return true - } - if ( - element.contentEditable && - element.contentEditable.toLowerCase() === 'inherit' && - element.parentNode - ) { - return isContentEditable(element.parentNode) - } - return false -} +var utilInspect = __webpack_require__(42634); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; -function isEditableInput (input) { - switch (input.type) { - case 'text': - return true - case 'email': - return true - case 'password': - return true - case 'search': - return true - case 'tel': - return true - case 'url': - return true - default: - return false - } -} +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) { + 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; -/***/ 17187: -/***/ ((module) => { + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } -"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. + 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); -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} + 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); + } -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} + 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 (obj === __webpack_require__.g) { + 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); +}; -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; +function wrapQuotes(s, defaultStyle, opts) { + var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'"; + return quoteChar + s + quoteChar; } -function EventEmitter() { - EventEmitter.init.call(this); +function quote(s) { + return $replace.call(String(s), /"/g, '"'); } -module.exports = EventEmitter; -module.exports.once = once; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} +function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); +// 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; } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; + 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 _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; } -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has(obj, key) { + return hasOwn.call(obj, key); +} -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); +function toStr(obj) { + return objectToString.call(obj); +} - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; +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; +} - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event +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; } } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; + return -1; +} - if (handler === undefined) +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; +} - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; +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; +} - checkListener(listener); +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); +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; +} - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; } - existing = events[type]; - } + 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; +} - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); +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'; +} - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); +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; } - } + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} - return target; +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)); } -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; +function markBoxed(str) { + return 'Object(' + str + ')'; +} -EventEmitter.prototype.on = EventEmitter.prototype.addListener; +function weakCollectionOf(type) { + return type + ' { ? }'; +} -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; } -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; +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) + }; } -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; +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; +} -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; +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]; + } + } -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; + 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; +} - checkListener(listener); - events = this._events; - if (events === undefined) - return this; +/***/ }), - list = events[type]; - if (list === undefined) - return this; +/***/ 43627: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); +// 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. - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - if (position < 0) - return this; - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } +var isWindows = process.platform === 'win32'; +var util = __webpack_require__(40537); - if (list.length === 1) - events[type] = list[0]; - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); +// resolves . and .. elements in a path array with directory names there +// must be no slashes or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + var res = []; + for (var i = 0; i < parts.length; i++) { + var p = parts[i]; + + // ignore empty parts + if (!p || p === '.') + continue; + + if (p === '..') { + if (res.length && res[res.length - 1] !== '..') { + res.pop(); + } else if (allowAboveRoot) { + res.push('..'); } + } else { + res.push(p); + } + } - return this; - }; + return res; +} -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +// returns an array with empty elements removed from either end of the input +// array or the original array if no elements need to be removed +function trimArray(arr) { + var lastIndex = arr.length - 1; + var start = 0; + for (; start <= lastIndex; start++) { + if (arr[start]) + break; + } -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; + var end = lastIndex; + for (; end >= 0; end--) { + if (arr[end]) + break; + } - events = this._events; - if (events === undefined) - return this; + if (start === 0 && end === lastIndex) + return arr; + if (start > end) + return []; + return arr.slice(start, end + 1); +} + +// Regex to split a windows path into three parts: [*, device, slash, +// tail] windows-only +var splitDeviceRe = + /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + +// Regex to split the tail part of the above into [*, dir, basename, ext] +var splitTailRe = + /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/; + +var win32 = {}; + +// Function to split a filename into [root, dir, basename, ext] +function win32SplitPath(filename) { + // Separate device+slash from tail + var result = splitDeviceRe.exec(filename), + device = (result[1] || '') + (result[2] || ''), + tail = result[3] || ''; + // Split the tail into dir, basename and extension + var result2 = splitTailRe.exec(tail), + dir = result2[1], + basename = result2[2], + ext = result2[3]; + return [device, dir, basename, ext]; +} + +function win32StatPath(path) { + var result = splitDeviceRe.exec(path), + device = result[1] || '', + isUnc = !!device && device[1] !== ':'; + return { + device: device, + isUnc: isUnc, + isAbsolute: isUnc || !!result[2], // UNC paths are always absolute + tail: result[3] + }; +} - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } +function normalizeUNCRoot(device) { + return '\\\\' + device.replace(/^[\\\/]+/, '').replace(/[\\\/]+/g, '\\'); +} - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; +// path.resolve([from ...], to) +win32.resolve = function() { + var resolvedDevice = '', + resolvedTail = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1; i--) { + var path; + if (i >= 0) { + path = arguments[i]; + } else if (!resolvedDevice) { + path = process.cwd(); + } else { + // Windows has the concept of drive-specific current working + // directories. If we've resolved a drive letter but not yet an + // absolute path, get cwd for that drive. We're sure the device is not + // an unc path at this points, because unc paths are always absolute. + path = ({"NODE_ENV":"production"})['=' + resolvedDevice]; + // Verify that a drive-local cwd was found and that it actually points + // to our drive. If not, default to the drive's root. + if (!path || path.substr(0, 3).toLowerCase() !== + resolvedDevice.toLowerCase() + '\\') { + path = resolvedDevice + '\\'; } + } - listeners = events[type]; + // Skip empty and invalid entries + if (!util.isString(path)) { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } + var result = win32StatPath(path), + device = result.device, + isUnc = result.isUnc, + isAbsolute = result.isAbsolute, + tail = result.tail; - return this; - }; + if (device && + resolvedDevice && + device.toLowerCase() !== resolvedDevice.toLowerCase()) { + // This path points to another device so it is not applicable + continue; + } -function _listeners(target, type, unwrap) { - var events = target._events; + if (!resolvedDevice) { + resolvedDevice = device; + } + if (!resolvedAbsolute) { + resolvedTail = tail + '\\' + resolvedTail; + resolvedAbsolute = isAbsolute; + } - if (events === undefined) - return []; + if (resolvedDevice && resolvedAbsolute) { + break; + } + } - var evlistener = events[type]; - if (evlistener === undefined) - return []; + // Convert slashes to backslashes when `resolvedDevice` points to an UNC + // root. Also squash multiple slashes into a single one where appropriate. + if (isUnc) { + resolvedDevice = normalizeUNCRoot(resolvedDevice); + } - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + // At this point the path should be resolved to a full absolute path, + // but handle relative paths to be safe (might happen when process.cwd() + // fails) - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} + // Normalize the tail path + resolvedTail = normalizeArray(resolvedTail.split(/[\\\/]+/), + !resolvedAbsolute).join('\\'); -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); + return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) || + '.'; }; -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); +win32.normalize = function(path) { + var result = win32StatPath(path), + device = result.device, + isUnc = result.isUnc, + isAbsolute = result.isAbsolute, + tail = result.tail, + trailingSlash = /[\\\/]$/.test(tail); + + // Normalize the tail path + tail = normalizeArray(tail.split(/[\\\/]+/), !isAbsolute).join('\\'); + + if (!tail && !isAbsolute) { + tail = '.'; + } + if (tail && trailingSlash) { + tail += '\\'; } + + // Convert slashes to backslashes when `device` points to an UNC root. + // Also squash multiple slashes into a single one where appropriate. + if (isUnc) { + device = normalizeUNCRoot(device); + } + + return device + (isAbsolute ? '\\' : '') + tail; }; -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - if (events !== undefined) { - var evlistener = events[type]; +win32.isAbsolute = function(path) { + return win32StatPath(path).isAbsolute; +}; - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; +win32.join = function() { + var paths = []; + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + if (!util.isString(arg)) { + throw new TypeError('Arguments to path.join must be strings'); + } + if (arg) { + paths.push(arg); } } - return 0; -} + var joined = paths.join('\\'); -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; + // Make sure that the joined path doesn't start with two slashes, because + // normalize() will mistake it for an UNC path then. + // + // This step is skipped when it is very clear that the user actually + // intended to point at an UNC path. This is assumed when the first + // non-empty string arguments starts with exactly two slashes followed by + // at least one more non-slash character. + // + // Note that for normalize() to treat a path as an UNC path it needs to + // have at least 2 components, so we don't filter for that here. + // This means that the user can use join to construct UNC paths from + // a server name and a share name; for example: + // path.join('//server', 'share') -> '\\\\server\\share\') + if (!/^[\\\/]{2}[^\\\/]/.test(paths[0])) { + joined = joined.replace(/^[\\\/]{2,}/, '\\'); + } + + return win32.normalize(joined); }; -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} +// path.relative(from, to) +// it will solve the relative path from 'from' to 'to', for instance: +// from = 'C:\\orandea\\test\\aaa' +// to = 'C:\\orandea\\impl\\bbb' +// The output of the function should be: '..\\..\\impl\\bbb' +win32.relative = function(from, to) { + from = win32.resolve(from); + to = win32.resolve(to); -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} + // windows is not case sensitive + var lowerFrom = from.toLowerCase(); + var lowerTo = to.toLowerCase(); -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } + var toParts = trimArray(to.split('\\')); - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); - }; + var lowerFromParts = trimArray(lowerFrom.split('\\')); + var lowerToParts = trimArray(lowerTo.split('\\')); - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + var length = Math.min(lowerFromParts.length, lowerToParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (lowerFromParts[i] !== lowerToParts[i]) { + samePartsLength = i; + break; } - }); -} + } -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + if (samePartsLength == 0) { + return to; } -} -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); - } else { - emitter.on(name, listener); - } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + var outputParts = []; + for (var i = samePartsLength; i < lowerFromParts.length; i++) { + outputParts.push('..'); } -} + outputParts = outputParts.concat(toParts.slice(samePartsLength)); -/***/ }), + return outputParts.join('\\'); +}; -/***/ 3349: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; +win32._makeLong = function(path) { + // Note: this will *probably* throw somewhere. + if (!util.isString(path)) + return path; -var Buffer = (__webpack_require__(50213).Buffer) -var Transform = (__webpack_require__(70326).Transform) -var inherits = __webpack_require__(35717) + if (!path) { + return ''; + } -function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') + var resolvedPath = win32.resolve(path); + + if (/^[a-zA-Z]\:\\/.test(resolvedPath)) { + // path is local filesystem path, which needs to be converted + // to long UNC path. + return '\\\\?\\' + resolvedPath; + } else if (/^\\\\[^?.]/.test(resolvedPath)) { + // path is network UNC path, which needs to be converted + // to long UNC path. + return '\\\\?\\UNC\\' + resolvedPath.substring(2); } -} -function HashBase (blockSize) { - Transform.call(this) + return path; +}; - this._block = Buffer.allocUnsafe(blockSize) - this._blockSize = blockSize - this._blockOffset = 0 - this._length = [0, 0, 0, 0] - this._finalized = false -} +win32.dirname = function(path) { + var result = win32SplitPath(path), + root = result[0], + dir = result[1]; -inherits(HashBase, Transform) + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } -HashBase.prototype._transform = function (chunk, encoding, callback) { - var error = null - try { - this.update(chunk, encoding) - } catch (err) { - error = err + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); } - callback(error) -} + return root + dir; +}; -HashBase.prototype._flush = function (callback) { - var error = null - try { - this.push(this.digest()) - } catch (err) { - error = err + +win32.basename = function(path, ext) { + var f = win32SplitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); } + return f; +}; - callback(error) -} -HashBase.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data') - if (this._finalized) throw new Error('Digest already called') - if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) +win32.extname = function(path) { + return win32SplitPath(path)[3]; +}; - // consume data - var block = this._block - var offset = 0 - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] - this._update() - this._blockOffset = 0 + +win32.format = function(pathObject) { + if (!util.isObject(pathObject)) { + throw new TypeError( + "Parameter 'pathObject' must be an object, not " + typeof pathObject + ); + } + + var root = pathObject.root || ''; + + if (!util.isString(root)) { + throw new TypeError( + "'pathObject.root' must be a string or undefined, not " + + typeof pathObject.root + ); } - while (offset < data.length) block[this._blockOffset++] = data[offset++] - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry - carry = (this._length[j] / 0x0100000000) | 0 - if (carry > 0) this._length[j] -= 0x0100000000 * carry + var dir = pathObject.dir; + var base = pathObject.base || ''; + if (!dir) { + return base; + } + if (dir[dir.length - 1] === win32.sep) { + return dir + base; } + return dir + win32.sep + base; +}; - return this -} -HashBase.prototype._update = function () { - throw new Error('_update is not implemented') -} +win32.parse = function(pathString) { + if (!util.isString(pathString)) { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = win32SplitPath(pathString); + if (!allParts || allParts.length !== 4) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + return { + root: allParts[0], + dir: allParts[0] + allParts[1].slice(0, -1), + base: allParts[2], + ext: allParts[3], + name: allParts[2].slice(0, allParts[2].length - allParts[3].length) + }; +}; -HashBase.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true - var digest = this._digest() - if (encoding !== undefined) digest = digest.toString(encoding) +win32.sep = '\\'; +win32.delimiter = ';'; - // reset state - this._block.fill(0) - this._blockOffset = 0 - for (var i = 0; i < 4; ++i) this._length[i] = 0 - return digest -} +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var posix = {}; -HashBase.prototype._digest = function () { - throw new Error('_digest is not implemented') + +function posixSplitPath(filename) { + return splitPathRe.exec(filename).slice(1); } -module.exports = HashBase +// path.resolve([from ...], to) +// posix version +posix.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; -/***/ }), + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); -/***/ 9786: -/***/ ((module) => { + // Skip empty and invalid entries + if (!util.isString(path)) { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } -"use strict"; + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path[0] === '/'; + } + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + // Normalize the path + resolvedPath = normalizeArray(resolvedPath.split('/'), + !resolvedAbsolute).join('/'); -var codes = {}; + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; +// path.normalize(path) +// posix version +posix.normalize = function(path) { + var isAbsolute = posix.isAbsolute(path), + trailingSlash = path && path[path.length - 1] === '/'; + + // Normalize the path + path = normalizeArray(path.split('/'), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; } - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +posix.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +posix.join = function() { + var path = ''; + for (var i = 0; i < arguments.length; i++) { + var segment = arguments[i]; + if (!util.isString(segment)) { + throw new TypeError('Arguments to path.join must be strings'); + } + if (segment) { + if (!path) { + path += segment; + } else { + path += '/' + segment; + } } } + return posix.normalize(path); +}; - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; +// path.relative(from, to) +// posix version +posix.relative = function(from, to) { + from = posix.resolve(from).substr(1); + to = posix.resolve(to).substr(1); + + var fromParts = trimArray(from.split('/')); + var toParts = trimArray(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; } + } - return NodeError; - }(Base); + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } - 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 + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + return outputParts.join('/'); +}; -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +posix._makeLong = function(path) { + return path; +}; -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 +posix.dirname = function(path) { + var result = posixSplitPath(path), + root = result[0], + dir = result[1]; + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); } - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + return root + dir; +}; -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; +posix.basename = function(path, ext) { + var f = posixSplitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); } + return f; +}; - 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' - var determiner; +posix.extname = function(path) { + return posixSplitPath(path)[3]; +}; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; + +posix.format = function(pathObject) { + if (!util.isObject(pathObject)) { + throw new TypeError( + "Parameter 'pathObject' must be an object, not " + typeof pathObject + ); } - var msg; + var root = pathObject.root || ''; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + if (!util.isString(root)) { + throw new TypeError( + "'pathObject.root' must be a string or undefined, not " + + typeof pathObject.root + ); } - msg += ". Received type ".concat(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.q = codes; + var dir = pathObject.dir ? pathObject.dir + posix.sep : ''; + var base = pathObject.base || ''; + return dir + base; +}; -/***/ }), +posix.parse = function(pathString) { + if (!util.isString(pathString)) { + throw new TypeError( + "Parameter 'pathString' must be a string, not " + typeof pathString + ); + } + var allParts = posixSplitPath(pathString); + if (!allParts || allParts.length !== 4) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + allParts[1] = allParts[1] || ''; + allParts[2] = allParts[2] || ''; + allParts[3] = allParts[3] || ''; -/***/ 62910: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + return { + root: allParts[0], + dir: allParts[0] + allParts[1].slice(0, -1), + base: allParts[2], + ext: allParts[3], + name: allParts[2].slice(0, allParts[2].length - allParts[3].length) + }; +}; -"use strict"; -/* provided dependency */ var process = __webpack_require__(70046); -// 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. -/**/ +posix.sep = '/'; +posix.delimiter = ':'; -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - } +if (isWindows) + module.exports = win32; +else /* posix */ + module.exports = posix; - return keys; -}; -/**/ +module.exports.posix = posix; +module.exports.win32 = win32; -module.exports = Duplex; +/***/ }), -var Readable = __webpack_require__(45789); +/***/ 78396: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -var Writable = __webpack_require__(70469); +exports.pbkdf2 = __webpack_require__(43832) +exports.pbkdf2Sync = __webpack_require__(21352) -__webpack_require__(35717)(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]; - } -} +/***/ 43832: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; +var Buffer = (__webpack_require__(92861).Buffer) - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; +var checkParameters = __webpack_require__(64196) +var defaultEncoding = __webpack_require__(2455) +var sync = __webpack_require__(21352) +var toBuffer = __webpack_require__(93382) - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } +var ZERO_BUF +var subtle = __webpack_require__.g.crypto && __webpack_require__.g.crypto.subtle +var toBrowser = { + sha: 'SHA-1', + 'sha-1': 'SHA-1', + sha1: 'SHA-1', + sha256: 'SHA-256', + 'sha-256': 'SHA-256', + sha384: 'SHA-384', + 'sha-384': 'SHA-384', + 'sha-512': 'SHA-512', + sha512: 'SHA-512' +} +var checks = [] +function checkNative (algo) { + if (__webpack_require__.g.process && !__webpack_require__.g.process.browser) { + return Promise.resolve(false) + } + if (!subtle || !subtle.importKey || !subtle.deriveBits) { + return Promise.resolve(false) + } + if (checks[algo] !== undefined) { + return checks[algo] } + ZERO_BUF = ZERO_BUF || Buffer.alloc(8) + var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) + .then(function () { + return true + }).catch(function () { + return false + }) + checks[algo] = prom + return prom } - -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(); +var nextTick +function getNextTick () { + if (nextTick) { + return nextTick } -}); -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; + if (__webpack_require__.g.process && __webpack_require__.g.process.nextTick) { + nextTick = __webpack_require__.g.process.nextTick + } else if (__webpack_require__.g.queueMicrotask) { + nextTick = __webpack_require__.g.queueMicrotask + } else if (__webpack_require__.g.setImmediate) { + nextTick = __webpack_require__.g.setImmediate + } else { + nextTick = __webpack_require__.g.setTimeout } -}); // 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); + return nextTick } - -function onEndNT(self) { - self.end(); +function browserPbkdf2 (password, salt, iterations, length, algo) { + return subtle.importKey( + 'raw', password, { name: 'PBKDF2' }, false, ['deriveBits'] + ).then(function (key) { + return subtle.deriveBits({ + name: 'PBKDF2', + salt: salt, + iterations: iterations, + hash: { + name: algo + } + }, key, length << 3) + }).then(function (res) { + return Buffer.from(res) + }) } -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 +function resolvePromise (promise, callback) { + promise.then(function (out) { + getNextTick()(function () { + callback(null, out) + }) + }, function (e) { + getNextTick()(function () { + callback(e) + }) + }) +} +module.exports = function (password, salt, iterations, keylen, digest, callback) { + if (typeof digest === 'function') { + callback = digest + digest = undefined + } + digest = digest || 'sha1' + var algo = toBrowser[digest.toLowerCase()] - this._readableState.destroyed = value; - this._writableState.destroyed = value; + if (!algo || typeof __webpack_require__.g.Promise !== 'function') { + getNextTick()(function () { + var out + try { + out = sync(password, salt, iterations, keylen, digest) + } catch (e) { + return callback(e) + } + callback(null, out) + }) + return } -}); -/***/ }), + checkParameters(iterations, keylen) + password = toBuffer(password, defaultEncoding, 'Password') + salt = toBuffer(salt, defaultEncoding, 'Salt') + if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') -/***/ 58994: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + resolvePromise(checkNative(algo).then(function (resp) { + if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo) -"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. + return sync(password, salt, iterations, keylen, digest) + }), callback) +} -module.exports = PassThrough; +/***/ }), -var Transform = __webpack_require__(70421); +/***/ 2455: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -__webpack_require__(35717)(PassThrough, Transform); +/* provided dependency */ var process = __webpack_require__(65606); +var defaultEncoding +/* istanbul ignore next */ +if (__webpack_require__.g.process && __webpack_require__.g.process.browser) { + defaultEncoding = 'utf-8' +} else if (__webpack_require__.g.process && __webpack_require__.g.process.version) { + var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); + defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' +} else { + defaultEncoding = 'utf-8' } +module.exports = defaultEncoding -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; /***/ }), -/***/ 45789: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 64196: +/***/ ((module) => { -"use strict"; -/* provided dependency */ var process = __webpack_require__(70046); -// 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 MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs +module.exports = function (iterations, keylen) { + if (typeof iterations !== 'number') { + throw new TypeError('Iterations not a number') + } -module.exports = Readable; -/**/ + if (iterations < 0) { + throw new TypeError('Bad iterations') + } -var Duplex; -/**/ + if (typeof keylen !== 'number') { + throw new TypeError('Key length not a number') + } -Readable.ReadableState = ReadableState; -/**/ + if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ + throw new TypeError('Bad key length') + } +} -var EE = (__webpack_require__(17187).EventEmitter); -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ +/***/ }), -/**/ +/***/ 21352: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +var md5 = __webpack_require__(20320) +var RIPEMD160 = __webpack_require__(66011) +var sha = __webpack_require__(62802) +var Buffer = (__webpack_require__(92861).Buffer) -var Stream = __webpack_require__(50677); -/**/ +var checkParameters = __webpack_require__(64196) +var defaultEncoding = __webpack_require__(2455) +var toBuffer = __webpack_require__(93382) + +var ZEROS = Buffer.alloc(128) +var sizes = { + md5: 16, + sha1: 20, + sha224: 28, + sha256: 32, + sha384: 48, + sha512: 64, + rmd160: 20, + ripemd160: 20 +} +function Hmac (alg, key, saltLen) { + var hash = getDigest(alg) + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 -var Buffer = (__webpack_require__(48764).Buffer); + if (key.length > blocksize) { + key = hash(key) + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } -var OurUint8Array = __webpack_require__.g.Uint8Array || function () {}; + var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]) + var opad = Buffer.allocUnsafe(blocksize + sizes[alg]) + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); + var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4) + ipad.copy(ipad1, 0, 0, blocksize) + this.ipad1 = ipad1 + this.ipad2 = ipad + this.opad = opad + this.alg = alg + this.blocksize = blocksize + this.hash = hash + this.size = sizes[alg] } -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +Hmac.prototype.run = function (data, ipad) { + data.copy(ipad, this.blocksize) + var h = this.hash(ipad) + h.copy(this.opad, this.blocksize) + return this.hash(this.opad) } -/**/ +function getDigest (alg) { + function shaFunc (data) { + return sha(alg).update(data).digest() + } + function rmd160Func (data) { + return new RIPEMD160().update(data).digest() + } -var debugUtil = __webpack_require__(31616); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; + if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func + if (alg === 'md5') return md5 + return shaFunc } -/**/ +function pbkdf2 (password, salt, iterations, keylen, digest) { + checkParameters(iterations, keylen) + password = toBuffer(password, defaultEncoding, 'Password') + salt = toBuffer(salt, defaultEncoding, 'Salt') -var BufferList = __webpack_require__(98354); - -var destroyImpl = __webpack_require__(35072); + digest = digest || 'sha1' -var _require = __webpack_require__(31222), - getHighWaterMark = _require.getHighWaterMark; + var hmac = new Hmac(digest, password, salt.length) -var _require$codes = (__webpack_require__(9786)/* .codes */ .q), - 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 DK = Buffer.allocUnsafe(keylen) + var block1 = Buffer.allocUnsafe(salt.length + 4) + salt.copy(block1, 0, 0, salt.length) + var destPos = 0 + var hLen = sizes[digest] + var l = Math.ceil(keylen / hLen) -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length) -__webpack_require__(35717)(Readable, Stream); + var T = hmac.run(block1, hmac.ipad1) + var U = T -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + for (var j = 1; j < iterations; j++) { + U = hmac.run(U, hmac.ipad2) + for (var k = 0; k < hLen; k++) T[k] ^= U[k] + } -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. + T.copy(DK, destPos) + destPos += hLen + } - 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]]; + return DK } -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || __webpack_require__(62910); - 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 +module.exports = pbkdf2 - 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. +/***/ 93382: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. +var Buffer = (__webpack_require__(92861).Buffer) - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. +module.exports = function (thing, encoding, name) { + if (Buffer.isBuffer(thing)) { + return thing + } else if (typeof thing === 'string') { + return Buffer.from(thing, encoding) + } else if (ArrayBuffer.isView(thing)) { + return Buffer.from(thing.buffer) + } else { + throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView') + } +} - 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. +/***/ 65606: +/***/ ((module) => { - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s +// shim for using process in browser +var process = module.exports = {}; - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. - this.readingMore = false; - this.decoder = null; - this.encoding = null; +var cachedSetTimeout; +var cachedClearTimeout; - if (options.encoding) { - if (!StringDecoder) StringDecoder = (__webpack_require__(32553)/* .StringDecoder */ .s); - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); } +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } -function Readable(options) { - Duplex = Duplex || __webpack_require__(62910); - 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 +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } - 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); } +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; -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; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); } +} - 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 +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; -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. +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; +function noop() {} -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; +process.listeners = function (name) { return [] } - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; - 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); -}; +/***/ 74765: +/***/ ((module) => { -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; +"use strict"; - 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); - } +var replace = String.prototype.replace; +var percentTwenties = /%20/g; - 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; +var Format = { + RFC1738: 'RFC1738', + RFC3986: 'RFC3986' +}; - 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); +module.exports = { + 'default': Format.RFC3986, + formatters: { + RFC1738: function (value) { + return replace.call(value, percentTwenties, '+'); + }, + RFC3986: function (value) { + return String(value); } - } - } 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. + }, + RFC1738: Format.RFC1738, + RFC3986: Format.RFC3986 +}; - 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); - } +/***/ 55373: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - maybeReadMore(stream, state); -} +"use strict"; -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); - } +var stringify = __webpack_require__(98636); +var parse = __webpack_require__(62642); +var formats = __webpack_require__(74765); - return er; -} +module.exports = { + formats: formats, + parse: parse, + stringify: stringify +}; -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. +/***/ }), -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = (__webpack_require__(32553)/* .StringDecoder */ .s); - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 +/***/ 62642: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: +"use strict"; - var p = this._readableState.buffer.head; - var content = ''; - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } +var utils = __webpack_require__(37720); - this._readableState.buffer.clear(); +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB +var defaults = { + allowDots: false, + allowPrototypes: false, + allowSparse: false, + arrayLimit: 20, + charset: 'utf-8', + charsetSentinel: false, + comma: false, + decoder: utils.decode, + delimiter: '&', + depth: 5, + ignoreQueryPrefix: false, + interpretNumericEntities: false, + parameterLimit: 1000, + parseArrays: true, + plainObjects: false, + strictNullHandling: false +}; + +var interpretNumericEntities = function (str) { + return str.replace(/&#(\d+);/g, function ($0, numberStr) { + return String.fromCharCode(parseInt(numberStr, 10)); + }); +}; +var parseArrayValue = function (val, options) { + if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { + return val.split(','); + } -var MAX_HWM = 0x40000000; + return val; +}; -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++; - } +// 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('✓') - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. +// 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 = {}; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + var skipIndex = -1; // Keep track of where the utf8 sentinel was found + var i; -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; + 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; + } + } + } - 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. + 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; - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough + var key, 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'); + val = utils.maybeMap( + parseArrayValue(part.slice(pos + 1), options), + function (encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, 'value'); + } + ); + } - if (!state.ended) { - state.needReadable = true; - return 0; - } + if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { + val = interpretNumericEntities(val); + } - return state.length; -} // you can override either this method, or the async _read(n) below. + if (part.indexOf('[]=') > -1) { + val = isArray(val) ? [val] : val; + } + + if (has.call(obj, key)) { + obj[key] = utils.combine(obj[key], val); + } else { + obj[key] = val; + } + } + return obj; +}; -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. +var parseObject = function (chain, val, options, valuesParsed) { + var leaf = valuesParsed ? val : parseArrayValue(val, options); - 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; - } + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. + if (root === '[]' && options.parseArrays) { + obj = [].concat(leaf); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if (!options.parseArrays && cleanRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== cleanRoot + && String(index) === cleanRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else if (cleanRoot !== '__proto__') { + obj[cleanRoot] = leaf; + } + } - 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. + leaf = obj; + } + return leaf; +}; - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some +var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } - 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. + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + // The regex chunks - 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. + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; - if (state.length === 0) state.needReadable = true; // call internal read method + // Get the parent - this._read(state.highWaterMark); + var segment = options.depth > 0 && brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; - 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. + // Stash the parent if it exists - if (!state.reading) n = howMuchToRead(nOrig, state); - } + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; + keys.push(parent); + } - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } + // Loop through children appending to the array until we hit depth - 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. + var i = 0; + while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } - if (nOrig !== n && state.ended) endReadable(this); - } + // If there's a remainder, just add whatever is left - if (ret !== null) this.emit('data', ret); - return ret; + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options, valuesParsed); }; -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } - if (state.decoder) { - var chunk = state.decoder.end(); + if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; + 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 charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; - state.ended = true; + return { + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + 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, + 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, + 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, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; - 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; +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; } - } -} // 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; + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} + // Iterate over the keys and setup the new object -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); + 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 (!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. + if (options.allowSparse === true) { + return obj; + } + return utils.compact(obj); +}; - 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); - } -} +/***/ 98636: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -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; - } +"use strict"; - 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. +var getSideChannel = __webpack_require__(920); +var utils = __webpack_require__(37720); +var formats = __webpack_require__(74765); +var has = Object.prototype.hasOwnProperty; -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } }; -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; +var isArray = Array.isArray; +var split = String.prototype.split; +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, + charset: 'utf-8', + charsetSentinel: false, + delimiter: '&', + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + 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, + strictNullHandling, + skipNulls, + 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; + } + } - default: - state.pipes.push(dest); - break; - } + 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; + }); + } - 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); + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; + } - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); + obj = ''; + } - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); + if (generateArrayPrefix === 'comma' && encodeValuesOnly) { + var valuesArray = split.call(String(obj), ','); + var valuesJoined = ''; + for (var i = 0; i < valuesArray.length; ++i) { + valuesJoined += (i === 0 ? '' : ',') + formatter(encoder(valuesArray[i], defaults.encoder, charset, 'value', format)); + } + return [formatter(keyValue) + (commaRoundTrip && isArray(obj) && valuesArray.length === 1 ? '[]' : '') + '=' + valuesJoined]; + } + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; } - } - 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 values = []; + if (typeof obj === 'undefined') { + return values; + } - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; + var objKeys; + if (generateArrayPrefix === 'comma' && isArray(obj)) { + // we need to join elements in + 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; + } - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix; - 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. + for (var j = 0; j < objKeys.length; ++j) { + var key = objKeys[j]; + var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } + if (skipNulls && value === null) { + continue; + } - src.on('data', ondata); + var keyPrefix = isArray(obj) + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']'); - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } - 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++; - } + return values; +}; - src.pause(); +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } - 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. + 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]; - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + 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 + }; +}; - dest.once('close', onclose); +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } + var objKeys; + var filter; - dest.once('finish', onfinish); + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to + var keys = []; + if (typeof obj !== 'object' || obj === null) { + return ''; + } - dest.emit('pipe', src); // start the flow if it hasn't been started already. + var arrayFormat; + if (opts && opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if (opts && 'indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = 'indices'; + } - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip; - return dest; -}; + if (!objKeys) { + objKeys = Object.keys(obj); + } -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; + if (options.sort) { + objKeys.sort(options.sort); + } - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); + var sideChannel = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (options.skipNulls && obj[key] === null) { + continue; + } + pushToArray(keys, stringify( + obj[key], + key, + generateArrayPrefix, + commaRoundTrip, + options.strictNullHandling, + options.skipNulls, + 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&'; + } } - }; -} -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. + return joined.length > 0 ? prefix + joined : ''; +}; - 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. +/***/ 37720: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +"use strict"; - 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 - }); - } +var formats = __webpack_require__(74765); - return this; - } // try to find the right one. +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } - 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 + return array; +}()); +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; + if (isArray(obj)) { + var compacted = []; - 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 + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } - 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); + item.obj[item.prop] = compacted; + } + } +}; - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } } - } - return res; + return obj; }; -Readable.prototype.addListener = Readable.prototype.on; +var merge = function merge(target, source, options) { + /* eslint no-param-reassign: 0 */ + if (!source) { + return target; + } -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); + if (typeof source !== 'object') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } - 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 target; + } - return res; -}; + if (!target || typeof target !== 'object') { + return [target].concat(source); + } -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } - 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); - } + 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.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } - return res; + 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; + } + return acc; + }, mergeTarget); }; -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; - 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(); - } -} +var decode = function (str, decoder, 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; + } +}; -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. +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'; + }); + } -Readable.prototype.resume = function () { - var state = this._readableState; + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.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)) // ( ) + ) { + out += string.charAt(i); + continue; + } - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } - state.flowing = !state.readableListening; - resume(this, state); - } + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } - state.paused = false; - return this; -}; + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + /* eslint operator-linebreak: [2, "before"] */ + out += hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } -function resume_(stream, state) { - debug('resume', state.reading); + return out; +}; - if (!state.reading) { - stream.read(0); - } +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); + 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.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } + compactQueue(queue); - this._readableState.paused = true; - return this; + return value; }; -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. +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; + } -Readable.prototype.wrap = function (stream) { - var _this = this; + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); +var combine = function combine(a, b) { + return [].concat(a, b); +}; - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); +var maybeMap = function maybeMap(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; } + return fn(val); +}; - _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 +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + maybeMap: maybeMap, + merge: merge +}; - 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. +/***/ 66011: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - 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. +"use strict"; +var Buffer = (__webpack_require__(48287).Buffer) +var inherits = __webpack_require__(56698) +var HashBase = __webpack_require__(4729) - 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. +var ARRAY16 = new Array(16) +var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +] - this._read = function (n) { - debug('wrapped _read', n); +var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +] - if (paused) { - paused = false; - stream.resume(); - } - }; +var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +] - return this; -}; +var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +] -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = __webpack_require__(30527); - } +var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] +var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] - return createReadableStreamAsyncIterator(this); - }; +function RIPEMD160 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 } -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. +inherits(RIPEMD160, HashBase) -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. +RIPEMD160.prototype._update = function () { + var words = ARRAY16 + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4) -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; -} + var al = this._a | 0 + var bl = this._b | 0 + var cl = this._c | 0 + var dl = this._d | 0 + var el = this._e | 0 + + var ar = this._a | 0 + var br = this._b | 0 + var cr = this._c | 0 + var dr = this._d | 0 + var er = this._e | 0 + + // computation + for (var i = 0; i < 80; i += 1) { + var tl + var tr + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]) + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]) + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]) + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]) + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]) + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]) + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]) + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]) + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]) + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]) + } -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); + al = el + el = dl + dl = rotl(cl, 10) + cl = bl + bl = tl - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); + ar = er + er = dr + dr = rotl(cr, 10) + cr = br + br = tr } + + // update state + var t = (this._b + cl + dr) | 0 + this._b = (this._c + dl + er) | 0 + this._c = (this._d + el + ar) | 0 + this._d = (this._e + al + br) | 0 + this._e = (this._a + bl + cr) | 0 + this._a = t } -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. +RIPEMD160.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() - 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; + // produce result + var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + buffer.writeInt32LE(this._e, 16) + return buffer +} - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) } -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = __webpack_require__(5327); - } +function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 +} - return from(Readable, iterable, opts); - }; +function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 } -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } +function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 +} - return -1; +function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 } -/***/ }), +function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 +} -/***/ 70421: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +module.exports = RIPEMD160 -"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; +/***/ 92861: +/***/ ((module, exports, __webpack_require__) => { -var _require$codes = (__webpack_require__(9786)/* .codes */ .q), - 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; +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(48287) +var Buffer = buffer.Buffer -var Duplex = __webpack_require__(62910); +// 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 +} -__webpack_require__(35717)(Transform, Duplex); +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') } + return Buffer(arg, encodingOrOffset, length) +} - 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; +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 +} - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } + return Buffer(size) } -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. +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} - 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. +/***/ 93904: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + + constructor (comp, options) { + options = parseOptions(options) + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + comp = comp.trim().split(/\s+/).join(' ') + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + debug('comp', this) + } - this.on('prefinish', prefinish); -} + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) -function prefinish() { - var _this = this; + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } } -} -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. + toString () { + return this.value + } + test (version) { + debug('Comparator.test', version, this.options.loose) -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; + if (this.semver === ANY || version === ANY) { + return true + } -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + return cmp(version, this.operator, this.semver, this.options) } -}; // 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. + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } -Transform.prototype._read = function (n) { - var ts = this._transformState; + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; + options = parseOptions(options) - 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; + // Special cases where nothing can possibly be lower + if (options.includePrerelease && + (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { + return false + } + if (!options.includePrerelease && + (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { + return false + } + + // Same direction increasing (> or >=) + if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { + return true + } + // Same direction decreasing (< or <=) + if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { + return true + } + // same SemVer and both sides are inclusive (<= or >=) + if ( + (this.semver.version === comp.semver.version) && + this.operator.includes('=') && comp.operator.includes('=')) { + return true + } + // opposite directions less than + if (cmp(this.semver, '<', comp.semver, options) && + this.operator.startsWith('>') && comp.operator.startsWith('<')) { + return true + } + // opposite directions greater than + if (cmp(this.semver, '>', comp.semver, options) && + this.operator.startsWith('<') && comp.operator.startsWith('>')) { + return true + } + return false } -}; +} -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; +module.exports = Comparator -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 +const parseOptions = __webpack_require__(98587) +const { safeRe: re, t } = __webpack_require__(99718) +const cmp = __webpack_require__(72111) +const debug = __webpack_require__(57272) +const SemVer = __webpack_require__(53908) +const Range = __webpack_require__(78311) - 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); -} /***/ }), -/***/ 70469: +/***/ 78311: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; -/* provided dependency */ var process = __webpack_require__(70046); -// 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. +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) + + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.format() + return this + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range + .trim() + .split(/\s+/) + .join(' ') + + // First, split on || + this.set = this.raw + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } -module.exports = Writable; -/* */ + this.format() + } -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 + format () { + this.range = this.set + .map((comps) => comps.join(' ').trim()) + .join('||') + .trim() + return this.range + } + toString () { + return this.range + } -function CorkedRequest(state) { - var _this = this; + parseRange (range) { + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = + (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | + (this.options.loose && FLAG_LOOSE) + const memoKey = memoOpts + ':' + range + const cached = cache.get(memoKey) + if (cached) { + return cached + } - this.next = null; - this.entry = null; + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) -/**/ + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + debug('tilde trim', range) + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + debug('caret trim', range) -var Duplex; -/**/ + // At this point, the range is completely trimmed and + // ready to be split into comparators. -Writable.WritableState = WritableState; -/**/ + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) -var internalUtil = { - deprecate: __webpack_require__(94927) -}; -/**/ + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) -/**/ + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] + } + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') + } -var Stream = __webpack_require__(50677); -/**/ + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result + } + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } -var Buffer = (__webpack_require__(48764).Buffer); + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } -var OurUint8Array = __webpack_require__.g.Uint8Array || function () {}; + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } } -var destroyImpl = __webpack_require__(35072); - -var _require = __webpack_require__(31222), - getHighWaterMark = _require.getHighWaterMark; +module.exports = Range -var _require$codes = (__webpack_require__(9786)/* .codes */ .q), - 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; +const LRU = __webpack_require__(38357) +const cache = new LRU({ max: 1000 }) -var errorOrDestroy = destroyImpl.errorOrDestroy; +const parseOptions = __webpack_require__(98587) +const Comparator = __webpack_require__(93904) +const debug = __webpack_require__(57272) +const SemVer = __webpack_require__(53908) +const { + safeRe: re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = __webpack_require__(99718) +const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __webpack_require__(16874) -__webpack_require__(35717)(Writable, Stream); +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' -function nop() {} +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || __webpack_require__(62910); - 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. + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. + testComparator = remainingComparators.pop() + } + + return result +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +// ~0.0.1 --> >=0.0.1 <0.1.0-0 +const replaceTildes = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceTilde(c, options)) + .join(' ') +} + +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } - 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() + debug('tilde return', ret) + return ret + }) +} - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +// ^0.0.1 --> >=0.0.1 <0.0.2-0 +// ^0.1.0 --> >=0.1.0 <0.2.0-0 +const replaceCarets = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceCaret(c, options)) + .join(' ') +} + +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } - this.finalCalled = false; // drain event flag. + debug('caret return', ret) + return ret + }) +} - this.needDrain = false; // at the start of calling end() +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp + .split(/\s+/) + .map((c) => replaceXRange(c, options)) + .join(' ') +} - this.ending = false; // when end() has been called, and returned +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp - this.ended = false; // when 'finish' is emitted + if (gtlt === '=' && anyX) { + gtlt = '' + } - this.finished = false; // has it been destroyed + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' - 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. + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } - 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. + if (gtlt === '<') { + pr = '-0' + } - 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. + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } - this.length = 0; // a flag to see when we're in the middle of a write. + debug('xRange return', ret) - this.writing = false; // when true all writes will be buffered until .uncork() call + return ret + }) +} - 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. +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp + .trim() + .replace(re[t.STAR], '') +} + +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp + .trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` + } - 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. + return `${from} ${to}`.trim() +} - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } - this.writecb = null; // the amount that is being written when _write is called. + // Version has a -pre, but it's not one of the ones we like. + return false + } - 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 + return true +} - 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. +/***/ 53908: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') +const debug = __webpack_require__(57272) +const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(16874) +const { safeRe: re, t } = __webpack_require__(99718) - this.autoDestroy = !!options.autoDestroy; // count buffered requests +const parseOptions = __webpack_require__(98587) +const { compareIdentifiers } = __webpack_require__(61123) +class SemVer { + constructor (version, options) { + options = parseOptions(options) - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) + } - this.corkedRequestsFree = new CorkedRequest(this); -} + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease - while (current) { - out.push(current); - current = current.next; - } + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) - return out; -}; + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } -(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. + this.raw = version + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] -var realHasInstance; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } -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; + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} -function Writable(options) { - Duplex = Duplex || __webpack_require__(62910); // 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 + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } - this.writable = true; + this.build = m[5] ? m[5].split('.') : [] + this.format() + } - 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; + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version } - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. + toString () { + return this.version + } + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; + if (other.version === this.version) { + return 0 + } -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + return this.compareMain(other) || this.comparePre(other) + } - 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. + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } -function validChunk(stream, state, chunk, cb) { - var er; + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } - 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); + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) } - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } - return true; + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier, identifierBase) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier, identifierBase) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier, identifierBase) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier, identifierBase) + this.inc('pre', identifier, identifierBase) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier, identifierBase) + } + this.inc('pre', identifier, identifierBase) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': { + const base = Number(identifierBase) ? 1 : 0 + + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + + if (this.prerelease.length === 0) { + this.prerelease = [base] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + if (identifier === this.prerelease.join('.') && identifierBase === false) { + throw new Error('invalid increment argument: identifier already exists') + } + this.prerelease.push(base) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + let prerelease = [identifier, base] + if (identifierBase === false) { + prerelease = [identifier] + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease + } + } else { + this.prerelease = prerelease + } + } + break + } + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.raw = this.format() + if (this.build.length) { + this.raw += `+${this.build.join('.')}` + } + return this + } } -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; +module.exports = SemVer - var isBuf = !state.objectMode && _isUint8Array(chunk); - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } +/***/ }), - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } +/***/ 57414: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - 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; -}; +const parse = __webpack_require__(30144) +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean -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); - } -}; +/***/ 72111: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -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; -}; +const eq = __webpack_require__(94641) +const neq = __webpack_require__(13999) +const gt = __webpack_require__(35580) +const gte = __webpack_require__(54089) +const lt = __webpack_require__(7059) +const lte = __webpack_require__(25200) + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b -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(); - } -}); + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } + case '': + case '=': + case '==': + return eq(a, b, loose) - return chunk; -} + case '!=': + return neq(a, b, loose) -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; + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) } -}); // 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. +} +module.exports = cmp -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; - } +/***/ }), + +/***/ 46170: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const parse = __webpack_require__(30144) +const { safeRe: re, t } = __webpack_require__(99718) + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version } - 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 (typeof version === 'number') { + version = String(version) + } - if (!ret) state.needDrain = true; + if (typeof version !== 'string') { + return null + } - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; + options = options || {} - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; + let match = null + if (!options.rtl) { + match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] + let next + while ((next = coerceRtlRegex.exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length } + // leave it in a clean state + coerceRtlRegex.lastIndex = -1 + } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); + if (match === null) { + return null } - return ret; -} + const major = match[2] + const minor = match[3] || '0' + const patch = match[4] || '0' + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' + const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' -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; + return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) } +module.exports = coerce -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 +/***/ 40909: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - finishMaybe(stream, state); - } +const SemVer = __webpack_require__(53908) +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) } +module.exports = compareBuild -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); - } +/***/ 11763: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} +const compare = __webpack_require__(50560) +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose -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 +/***/ 50560: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +const SemVer = __webpack_require__(53908) +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; +module.exports = compare - 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 +/***/ 51832: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - state.pendingcb++; - state.lastBufferedRequest = null; +const parse = __webpack_require__(30144) - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); +const diff = (version1, version2) => { + const v1 = parse(version1, null, true) + const v2 = parse(version2, null, true) + const comparison = v1.compare(v2) + + if (comparison === 0) { + return null + } + + const v1Higher = comparison > 0 + const highVersion = v1Higher ? v1 : v2 + const lowVersion = v1Higher ? v2 : v1 + const highHasPre = !!highVersion.prerelease.length + const lowHasPre = !!lowVersion.prerelease.length + + if (lowHasPre && !highHasPre) { + // Going from prerelease -> no prerelease requires some special casing + + // If the low version has only a major, then it will always be a major + // Some examples: + // 1.0.0-1 -> 1.0.0 + // 1.0.0-1 -> 1.1.1 + // 1.0.0-1 -> 2.0.0 + if (!lowVersion.patch && !lowVersion.minor) { + return 'major' } - 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. + // Otherwise it can be determined by checking the high version - if (state.writing) { - break; - } + if (highVersion.patch) { + // anything higher than a patch bump would result in the wrong version + return 'patch' } - if (entry === null) state.lastBufferedRequest = null; - } + if (highVersion.minor) { + // anything higher than a minor bump would result in the wrong version + return 'minor' + } - state.bufferedRequest = entry; - state.bufferProcessing = false; -} + // bumping major/minor/patch all have same result + return 'major' + } -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; + // add the `pre` prefix if we are going to a prerelease version + const prefix = highHasPre ? 'pre' : '' -Writable.prototype._writev = null; + if (v1.major !== v2.major) { + return prefix + 'major' + } -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + if (v1.minor !== v2.minor) { + return prefix + 'minor' + } - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + if (v1.patch !== v2.patch) { + return prefix + 'patch' } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + // high and low are preleases + return 'prerelease' +} - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. +module.exports = diff - 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; - } -}); +/***/ 94641: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} +const compare = __webpack_require__(50560) +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - errorOrDestroy(stream, err); - } +/***/ }), - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} +/***/ 35580: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -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'); - } - } -} +const compare = __webpack_require__(50560) +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); +/***/ }), - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); +/***/ 54089: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - 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; +const compare = __webpack_require__(50560) +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - return need; -} +/***/ }), + +/***/ 93007: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); +const SemVer = __webpack_require__(53908) - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); +const inc = (version, release, options, identifier, identifierBase) => { + if (typeof (options) === 'string') { + identifierBase = identifier + identifier = options + options = undefined } - state.ended = true; - stream.writable = false; + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier, identifierBase).version + } catch (er) { + return null + } } +module.exports = inc -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. +/***/ }), +/***/ 7059: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - state.corkedRequestsFree.next = corkReq; -} +const compare = __webpack_require__(50560) +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt -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 +/***/ }), +/***/ 25200: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; +const compare = __webpack_require__(50560) +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; /***/ }), -/***/ 30527: +/***/ 32938: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; -/* provided dependency */ var process = __webpack_require__(70046); +const SemVer = __webpack_require__(53908) +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major -var _Object$setPrototypeO; +/***/ }), -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +/***/ 46254: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var finished = __webpack_require__(28640); +const SemVer = __webpack_require__(53908) +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor -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]; +/***/ 13999: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' +const compare = __webpack_require__(50560) +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); + +/***/ }), + +/***/ 30144: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const parse = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version + } + try { + return new SemVer(version, options) + } catch (er) { + if (!throwErrors) { + return null } + throw er } } -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} +module.exports = parse -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]; - }, +/***/ 24493: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - next: function next() { - var _this = this; +const SemVer = __webpack_require__(53908) +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch - // 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)); - } +/***/ 31729: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - 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 +const parse = __webpack_require__(30144) +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} +module.exports = prerelease - 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(); +/***/ 9970: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } +const compare = __webpack_require__(50560) +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare - 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; - } +/***/ 74277: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); +const compareBuild = __webpack_require__(40909) +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort -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 +/***/ 97638: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } +const Range = __webpack_require__(78311) +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies - iterator[kError] = err; - return; - } - var resolve = iterator[kLastResolve]; +/***/ }), - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } +/***/ 43927: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; +const compareBuild = __webpack_require__(40909) +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort + + +/***/ }), + +/***/ 56953: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const parse = __webpack_require__(30144) +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid -module.exports = createReadableStreamAsyncIterator; /***/ }), -/***/ 98354: +/***/ 99589: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; +// just pre-load all the stuff that index.js lazily exports +const internalRe = __webpack_require__(99718) +const constants = __webpack_require__(16874) +const SemVer = __webpack_require__(53908) +const identifiers = __webpack_require__(61123) +const parse = __webpack_require__(30144) +const valid = __webpack_require__(56953) +const clean = __webpack_require__(57414) +const inc = __webpack_require__(93007) +const diff = __webpack_require__(51832) +const major = __webpack_require__(32938) +const minor = __webpack_require__(46254) +const patch = __webpack_require__(24493) +const prerelease = __webpack_require__(31729) +const compare = __webpack_require__(50560) +const rcompare = __webpack_require__(9970) +const compareLoose = __webpack_require__(11763) +const compareBuild = __webpack_require__(40909) +const sort = __webpack_require__(43927) +const rsort = __webpack_require__(74277) +const gt = __webpack_require__(35580) +const lt = __webpack_require__(7059) +const eq = __webpack_require__(94641) +const neq = __webpack_require__(13999) +const gte = __webpack_require__(54089) +const lte = __webpack_require__(25200) +const cmp = __webpack_require__(72111) +const coerce = __webpack_require__(46170) +const Comparator = __webpack_require__(93904) +const Range = __webpack_require__(78311) +const satisfies = __webpack_require__(97638) +const toComparators = __webpack_require__(77631) +const maxSatisfying = __webpack_require__(19628) +const minSatisfying = __webpack_require__(270) +const minVersion = __webpack_require__(41261) +const validRange = __webpack_require__(13874) +const outside = __webpack_require__(97075) +const gtr = __webpack_require__(75571) +const ltr = __webpack_require__(5342) +const intersects = __webpack_require__(76780) +const simplifyRange = __webpack_require__(72525) +const subset = __webpack_require__(75032) +module.exports = { + parse, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, +} -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } +/***/ 16874: +/***/ ((module) => { -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +// Max safe length for a build identifier. The max length minus 6 characters for +// the shortest version with a build 0.0.0+BUILD. +const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 + +const RELEASE_TYPES = [ + 'major', + 'premajor', + 'minor', + 'preminor', + 'patch', + 'prepatch', + 'prerelease', +] -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 0b001, + FLAG_LOOSE: 0b010, +} -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); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } +/***/ }), -var _require = __webpack_require__(48764), - Buffer = _require.Buffer; +/***/ 57272: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var _require2 = __webpack_require__(69386), - inspect = _require2.inspect; +/* provided dependency */ var process = __webpack_require__(65606); +const debug = ( + typeof process === 'object' && + ({"NODE_ENV":"production"}) && + ({"NODE_ENV":"production"}).NODE_DEBUG && + /\bsemver\b/i.test(({"NODE_ENV":"production"}).NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} -var custom = inspect && inspect.custom || 'inspect'; +module.exports = debug -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; +/***/ 61123: +/***/ ((module) => { + +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b } - _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; + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} - while (p = p.next) { - ret += s + p.data; - } +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) - 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; +module.exports = { + compareIdentifiers, + rcompareIdentifiers, +} - 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; +/***/ 98587: +/***/ ((module) => { - 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); - } +// parse out just the options we care about +const looseOption = Object.freeze({ loose: true }) +const emptyOpts = Object.freeze({ }) +const parseOptions = options => { + if (!options) { + return emptyOpts + } - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. + if (typeof options !== 'object') { + return looseOption + } - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; + return options +} +module.exports = parseOptions - 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; - } +/***/ 99718: +/***/ ((module, exports, __webpack_require__) => { - ++c; - } +const { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH, +} = __webpack_require__(16874) +const debug = __webpack_require__(57272) +exports = module.exports = {} + +// The actual regexps go on exports.re +const re = exports.re = [] +const safeRe = exports.safeRe = [] +const src = exports.src = [] +const t = exports.t = {} +let R = 0 + +const LETTERDASHNUMBER = '[a-zA-Z0-9-]' + +// Replace some greedy regex tokens to prevent regex dos issues. These regex are +// used internally via the safeRe object since all inputs in this library get +// normalized first to trim and collapse all extra whitespace. The original +// regexes are exported for userland consumption and lower level usage. A +// future breaking change could export the safer regex only with a note that +// all input should have extra whitespace removed. +const safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], +] - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. +const makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value + .split(`${token}*`).join(`${token}{0,${max}}`) + .split(`${token}+`).join(`${token}{1,${max}}`) + } + return value +} - }, { - 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; +const createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value) + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) + safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) +} - 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; +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. - 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); - } +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. - break; - } +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '\\d+') - ++c; - } +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. +createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); +// ## Main Version +// Three dot-separated numeric identifiers. - return BufferList; -}(); +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) -/***/ }), +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) -/***/ 35072: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. -"use strict"; -/* provided dependency */ var process = __webpack_require__(70046); - // undocumented cb() API, needed for core, not for public API +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`) -function destroy(err, cb) { - var _this = this; +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`) - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. - 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); - } - } +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) - 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 +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well +createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. - if (this._writableState) { - this._writableState.destroyed = true; - } +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) - 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); - } - }); +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. - return this; -} +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } +createToken('GTLT', '((?:<|>)?=?)') - 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; - } -} +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) -function emitErrorNT(self, err) { - self.emit('error', err); -} +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) -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); -} +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCEPLAIN', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) +createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) +createToken('COERCEFULL', src[t.COERCEPLAIN] + + `(?:${src[t.PRERELEASE]})?` + + `(?:${src[t.BUILD]})?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) +createToken('COERCERTLFULL', src[t.COERCEFULL], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; /***/ }), -/***/ 28640: +/***/ 38357: /***/ ((module, __unused_webpack_exports, __webpack_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 = (__webpack_require__(9786)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE); +// A linked list to keep track of recently-used-ness +const Yallist = __webpack_require__(4927) -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; +const MAX = Symbol('max') +const LENGTH = Symbol('length') +const LENGTH_CALCULATOR = Symbol('lengthCalculator') +const ALLOW_STALE = Symbol('allowStale') +const MAX_AGE = Symbol('maxAge') +const DISPOSE = Symbol('dispose') +const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') +const LRU_LIST = Symbol('lruList') +const CACHE = Symbol('cache') +const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } +const naiveLength = () => 1 - callback.apply(this, args); - }; -} +// lruList is a yallist where the head is the youngest +// item, and the tail is the oldest. the list contains the Hit +// objects as the entries. +// Each Hit object has a reference to its Yallist.Node. This +// never changes. +// +// cache is a Map (or PseudoMap) that matches the keys to +// the Yallist.Node object. +class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options } -function noop() {} + if (!options) + options = {} -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + const max = this[MAX] = options.max || Infinity -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; + const lc = options.length || naiveLength + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc + this[ALLOW_STALE] = options.stale || false + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0 + this[DISPOSE] = options.dispose + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false + this.reset() + } - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') - var writableEnded = stream._writableState && stream._writableState.finished; + this[MAX] = mL || Infinity + trim(this) + } + get max () { + return this[MAX] + } - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale + } + get allowStale () { + return this[ALLOW_STALE] + } - var readableEnded = stream._readableState && stream._readableState.endEmitted; + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; + this[MAX_AGE] = mA + trim(this) + } + get maxAge () { + return this[MAX_AGE] + } - var onerror = function onerror(err) { - callback.call(stream, err); - }; + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength - var onclose = function onclose() { - var err; + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC + this[LENGTH] = 0 + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) + this[LENGTH] += hit.length + }) + } + trim(this) + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev + forEachStep(this, fn, walker, thisp) + walker = prev } + } - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); + forEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next + forEachStep(this, fn, walker, thisp) + walker = next } - }; + } - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } - 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); + values () { + return this[LRU_LIST].toArray().map(k => k.value) } - 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); - }; -} + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) + } -module.exports = eos; + this[CACHE] = new Map() // hash of items by key + this[LRU_LIST] = new Yallist() // list of items in order of use recency + this[LENGTH] = 0 // length of items in the list + } -/***/ }), + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } -/***/ 5327: -/***/ ((module) => { + dumpLru () { + return this[LRU_LIST] + } -module.exports = function () { - throw new Error('Readable.from is not available in the browser') -}; + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE] + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') -/***/ }), + const now = maxAge ? Date.now() : 0 + const len = this[LENGTH_CALCULATOR](value, key) -/***/ 64218: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)) + return false + } -"use strict"; -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). + const node = this[CACHE].get(key) + const item = node.value + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value) + } -var eos; + item.now = now + item.maxAge = maxAge + item.value = value + this[LENGTH] += len - item.length + item.length = len + this.get(key) + trim(this) + return true + } -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} + const hit = new Entry(key, value, len, now, maxAge) -var _require$codes = (__webpack_require__(9786)/* .codes */ .q), - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value) -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} + return false + } -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} + this[LENGTH] += hit.length + this[LRU_LIST].unshift(hit) + this[CACHE].set(key, this[LRU_LIST].head) + trim(this) + return true + } -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = __webpack_require__(28640); - 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 + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value + return !isStale(this, hit) + } - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} + get (key) { + return get(this, key, true) + } -function call(fn) { - fn(); + peek (key) { + return get(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail + if (!node) + return null + + del(this, node) + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)) + } + + load (arr) { + // reset the cache + this.reset() + + const now = Date.now() + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l] + const expiresAt = hit.e || 0 + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v) + else { + const maxAge = expiresAt - now + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge) + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)) + } } -function pipe(from, to) { - return from.pipe(to); +const get = (self, key, doUse) => { + const node = self[CACHE].get(key) + if (node) { + const hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now() + self[LRU_LIST].unshiftNode(node) + } + } + return hit.value + } } -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); +const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) } -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; +const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev + del(self, walker) + walker = prev + } } +} - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; +const del = (self, node) => { + if (node) { + const hit = node.value + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value) - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); + self[LENGTH] -= hit.length + self[CACHE].delete(hit.key) + self[LRU_LIST].removeNode(node) + } +} + +class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key + this.value = value + this.length = length + this.now = now + this.maxAge = maxAge || 0 } +} - 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); +const forEachStep = (self, fn, node, thisp) => { + let hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + hit = undefined + } + if (hit) + fn.call(thisp, hit.value, hit.key, self) +} + +module.exports = LRUCache + + +/***/ }), + +/***/ 50723: +/***/ ((module) => { + +"use strict"; + +module.exports = function (Yallist) { + Yallist.prototype[Symbol.iterator] = function* () { + for (let walker = this.head; walker; walker = walker.next) { + yield walker.value + } + } } -module.exports = pipeline; /***/ }), -/***/ 31222: +/***/ 4927: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; +module.exports = Yallist -var ERR_INVALID_OPT_VALUE = (__webpack_require__(9786)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE); +Yallist.Node = Node +Yallist.create = Yallist -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} +function Yallist (list) { + var self = this + if (!(self instanceof Yallist)) { + self = new Yallist() + } -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + self.tail = null + self.head = null + self.length = 0 - 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); + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item) + }) + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]) } + } - return Math.floor(hwm); - } // Default value + return self +} +Yallist.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } - return state.objectMode ? 16 : 16 * 1024; -} + var next = node.next + var prev = node.prev -module.exports = { - getHighWaterMark: getHighWaterMark -}; + if (next) { + next.prev = prev + } -/***/ }), + if (prev) { + prev.next = next + } -/***/ 50677: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (node === this.head) { + this.head = next + } + if (node === this.tail) { + this.tail = prev + } -module.exports = __webpack_require__(17187).EventEmitter; + node.list.length-- + node.next = null + node.prev = null + node.list = null + return next +} -/***/ }), +Yallist.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } -/***/ 70326: -/***/ ((module, exports, __webpack_require__) => { + if (node.list) { + node.list.removeNode(node) + } -exports = module.exports = __webpack_require__(45789); -exports.Stream = exports; -exports.Readable = exports; -exports.Writable = __webpack_require__(70469); -exports.Duplex = __webpack_require__(62910); -exports.Transform = __webpack_require__(70421); -exports.PassThrough = __webpack_require__(58994); -exports.finished = __webpack_require__(28640); -exports.pipeline = __webpack_require__(64218); + var head = this.head + node.list = this + node.next = head + if (head) { + head.prev = node + } + this.head = node + if (!this.tail) { + this.tail = node + } + this.length++ +} -/***/ }), +Yallist.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } -/***/ 50213: -/***/ ((module, exports, __webpack_require__) => { + if (node.list) { + node.list.removeNode(node) + } -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = __webpack_require__(48764) -var Buffer = buffer.Buffer + var tail = this.tail + node.list = this + node.prev = tail + if (tail) { + tail.next = node + } -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] + this.tail = node + if (!this.head) { + this.head = node } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer + this.length++ } -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) +Yallist.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]) + } + return this.length } -SafeBuffer.prototype = Object.create(Buffer.prototype) +Yallist.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]) + } + return this.length +} -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) +Yallist.prototype.pop = function () { + if (!this.tail) { + return undefined + } -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') + var res = this.tail.value + this.tail = this.tail.prev + if (this.tail) { + this.tail.next = null + } else { + this.head = null } - return Buffer(arg, encodingOrOffset, length) + this.length-- + return res } -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') +Yallist.prototype.shift = function () { + if (!this.head) { + return undefined } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } + + var res = this.head.value + this.head = this.head.next + if (this.head) { + this.head.prev = null } else { - buf.fill(0) + this.tail = null } - return buf + this.length-- + return res } -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') +Yallist.prototype.forEach = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this) + walker = walker.next } - return Buffer(size) } -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') +Yallist.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this) + walker = walker.prev } - return buffer.SlowBuffer(size) } +Yallist.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next + } + if (i === n && walker !== null) { + return walker.value + } +} -/***/ }), - -/***/ 80645: -/***/ ((__unused_webpack_module, exports) => { - -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d +Yallist.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev + } + if (i === n && walker !== null) { + return walker.value + } +} - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} +Yallist.prototype.map = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.next + } + return res +} - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} +Yallist.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.prev + } + return res +} - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) +Yallist.prototype.reduce = function (fn, initial) { + var acc + var walker = this.head + if (arguments.length > 1) { + acc = initial + } else if (this.head) { + walker = this.head.next + acc = this.head.value } else { - m = m + Math.pow(2, mLen) - e = e - eBias + throw new TypeError('Reduce of empty list with no initial value') } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i) + walker = walker.next + } - value = Math.abs(value) + return acc +} - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax +Yallist.prototype.reduceReverse = function (fn, initial) { + var acc + var walker = this.tail + if (arguments.length > 1) { + acc = initial + } else if (this.tail) { + walker = this.tail.prev + acc = this.tail.value } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } + throw new TypeError('Reduce of empty list with no initial value') + } - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i) + walker = walker.prev } - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + return acc +} - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} +Yallist.prototype.toArray = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value + walker = walker.next + } + return arr +} - buffer[offset + i - d] |= s * 128 +Yallist.prototype.toArrayReverse = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value + walker = walker.prev + } + return arr } +Yallist.prototype.slice = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value) + } + return ret +} -/***/ }), +Yallist.prototype.sliceReverse = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value) + } + return ret +} -/***/ 35717: -/***/ ((module) => { +Yallist.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1 + } + if (start < 0) { + start = this.length + start; + } -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 - } + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next } -} + var ret = [] + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value) + walker = this.removeNode(walker) + } + if (walker === null) { + walker = this.tail + } -/***/ }), + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev + } -/***/ 33733: -/***/ ((module) => { + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]) + } + return ret; +} -module.exports = function (glob, opts) { - if (typeof glob !== 'string') { - throw new TypeError('Expected a string'); +Yallist.prototype.reverse = function () { + var head = this.head + var tail = this.tail + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev + walker.prev = walker.next + walker.next = p } + this.head = tail + this.tail = head + return this +} - var str = String(glob); +function insert (self, node, value) { + var inserted = node === self.head ? + new Node(value, null, node, self) : + new Node(value, node, node.next, self) - // The regexp we are building, as a string. - var reStr = ""; + if (inserted.next === null) { + self.tail = inserted + } + if (inserted.prev === null) { + self.head = inserted + } - // Whether we are matching so called "extended" globs (like bash) and should - // support single character matching, matching ranges of characters, group - // matching, etc. - var extended = opts ? !!opts.extended : false; + self.length++ - // Whether or not to capture those stars, it means wrapping them with parentheses - // It's not necessary if globstart is turned on - var capture = opts ? !!opts.capture : false; + return inserted +} - var nonGreedy = opts ? !!opts.nonGreedy : false; +function push (self, item) { + self.tail = new Node(item, self.tail, null, self) + if (!self.head) { + self.head = self.tail + } + self.length++ +} - // When globstar is _false_ (default), '/foo/*' is translated a regexp like - // '^\/foo\/.*$' which will match any string beginning with '/foo/' - // When globstar is _true_, '/foo/*' is translated to regexp like - // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT - // which does not have a '/' to the right of it. - // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but - // these will not '/foo/bar/baz', '/foo/bar/baz.txt' - // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when - // globstar is _false_ - var globstar = opts ? !!opts.globstar : false; +function unshift (self, item) { + self.head = new Node(item, null, self.head, self) + if (!self.tail) { + self.tail = self.head + } + self.length++ +} - // If we are doing extended matching, this boolean is true when we are inside - // a group (eg {*.html,*.js}), and false otherwise. - var inGroup = false; +function Node (value, prev, next, list) { + if (!(this instanceof Node)) { + return new Node(value, prev, next, list) + } - // RegExp flags (eg "i" ) to pass in to RegExp constructor. - var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; + this.list = list + this.value = value - var c; - for (var i = 0, len = str.length; i < len; i++) { - c = str[i]; + if (prev) { + prev.next = this + this.prev = prev + } else { + this.prev = null + } - switch (c) { - case "/": - case "$": - case "^": - case "+": - case ".": - case "(": - case ")": - case "=": - case "!": - case "|": - reStr += "\\" + c; - break; + if (next) { + next.prev = this + this.next = next + } else { + this.next = null + } +} - case "?": - if (extended) { - reStr += "."; - break; - } +try { + // add if support for Symbol.iterator is present + __webpack_require__(50723)(Yallist) +} catch (er) {} - case "[": - case "]": - if (extended) { - reStr += c; - break; - } - case "{": - if (extended) { - inGroup = true; - reStr += "("; - break; - } +/***/ }), - case "}": - if (extended) { - inGroup = false; - reStr += ")"; - break; - } +/***/ 75571: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - case ",": - if (inGroup) { - reStr += "|"; - break; - } - reStr += "\\" + c; - break; +// Determine if version is greater than all the versions possible in the range. +const outside = __webpack_require__(97075) +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr - case "*": - // Move over all consecutive "*"'s. - // Also store the previous and next characters - var prevChar = str[i - 1]; - var starCount = 1; - while(str[i + 1] === "*") { - starCount++; - i++; - } - var nextChar = str[i + 1]; - if (!globstar) { - // globstar is disabled, so treat any number of "*" as one - var s = nonGreedy ? ".*?" : ".*"; +/***/ }), - if (capture) { - s = "(" + s + ")"; - } +/***/ 76780: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - reStr += s; - } else { - // globstar is enabled, so determine if this is a globstar segment - var isGlobstar = starCount > 1 // multiple "*"'s - && (prevChar === "/" || prevChar === undefined) // from the start of the segment - && (nextChar === "/" || nextChar === undefined) // to the end of the segment +const Range = __webpack_require__(78311) +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2, options) +} +module.exports = intersects - if (isGlobstar) { - // it's a globstar, so match zero or more path segments - reStr += "((?:[^/]*(?:\/|$))*)"; - i++; // move over the "/" - } else { - // it's not a globstar, so only match one path segment - reStr += "([^/]*)"; - } - } - break; - default: - reStr += c; - } - } +/***/ }), - // When regexp 'g' flag is specified don't - // constrain the regular expression with ^ & $ - if (!flags || !~flags.indexOf('g')) { - reStr = "^" + reStr + "$"; - } +/***/ 5342: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - return new RegExp(reStr, flags); -}; +const outside = __webpack_require__(97075) +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr /***/ }), -/***/ 62318: +/***/ 19628: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; +const SemVer = __webpack_require__(53908) +const Range = __webpack_require__(78311) -var inherits = __webpack_require__(35717) -var HashBase = __webpack_require__(3349) -var Buffer = (__webpack_require__(89509).Buffer) +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying -var ARRAY16 = new Array(16) -function MD5 () { - HashBase.call(this, 64) +/***/ }), - // state - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 +/***/ 270: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const Range = __webpack_require__(78311) +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min } +module.exports = minSatisfying -inherits(MD5, HashBase) -MD5.prototype._update = function () { - var M = ARRAY16 - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4) +/***/ }), - var a = this._a - var b = this._b - var c = this._c - var d = this._d +/***/ 41261: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7) - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12) - c = fnF(c, d, a, b, M[2], 0x242070db, 17) - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) - c = fnF(c, d, a, b, M[6], 0xa8304613, 17) - b = fnF(b, c, d, a, M[7], 0xfd469501, 22) - a = fnF(a, b, c, d, M[8], 0x698098d8, 7) - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) - a = fnF(a, b, c, d, M[12], 0x6b901122, 7) - d = fnF(d, a, b, c, M[13], 0xfd987193, 12) - c = fnF(c, d, a, b, M[14], 0xa679438e, 17) - b = fnF(b, c, d, a, M[15], 0x49b40821, 22) +const SemVer = __webpack_require__(53908) +const Range = __webpack_require__(78311) +const gt = __webpack_require__(35580) - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) - d = fnG(d, a, b, c, M[6], 0xc040b340, 9) - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) - d = fnG(d, a, b, c, M[10], 0x02441453, 9) - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) +const minVersion = (range, loose) => { + range = new Range(range, loose) - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) - d = fnH(d, a, b, c, M[8], 0x8771f681, 11) - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) - b = fnH(b, c, d, a, M[6], 0x04881d05, 23) - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } - a = fnI(a, b, c, d, M[0], 0xf4292244, 6) - d = fnI(d, a, b, c, M[7], 0x432aff97, 10) - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) - c = fnI(c, d, a, b, M[6], 0xa3014314, 15) - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin + } + } - this._a = (this._a + a) | 0 - this._b = (this._b + b) | 0 - this._c = (this._c + c) | 0 - this._d = (this._d + d) | 0 + if (minver && range.test(minver)) { + return minver + } + + return null } +module.exports = minVersion -MD5.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80 - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64) - this._update() - this._blockOffset = 0 + +/***/ }), + +/***/ 97075: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const SemVer = __webpack_require__(53908) +const Comparator = __webpack_require__(93904) +const { ANY } = Comparator +const Range = __webpack_require__(78311) +const satisfies = __webpack_require__(97638) +const gt = __webpack_require__(35580) +const lt = __webpack_require__(7059) +const lte = __webpack_require__(25200) +const gte = __webpack_require__(54089) + +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') } - this._block.fill(0, this._blockOffset, 56) - this._block.writeUInt32LE(this._length[0], 56) - this._block.writeUInt32LE(this._length[1], 60) - this._update() + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } - // produce result - var buffer = Buffer.allocUnsafe(16) - buffer.writeInt32LE(this._a, 0) - buffer.writeInt32LE(this._b, 4) - buffer.writeInt32LE(this._c, 8) - buffer.writeInt32LE(this._d, 12) - return buffer -} + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. -function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) -} + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] -function fnF (a, b, c, d, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 -} + let high = null + let low = null -function fnG (a, b, c, d, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 -} + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) -function fnH (a, b, c, d, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 -} + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } -function fnI (a, b, c, d, m, k, s) { - return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true } -module.exports = MD5 +module.exports = outside /***/ }), -/***/ 25632: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 72525: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = __webpack_require__(97638) +const compare = __webpack_require__(50560) +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version + } + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null + } + } + if (first) { + set.push([first, null]) + } -exports.pbkdf2 = __webpack_require__(88638) -exports.pbkdf2Sync = __webpack_require__(91257) + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[0]) { + ranges.push(`<=${max}`) + } else { + ranges.push(`${min} - ${max}`) + } + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range +} /***/ }), -/***/ 88638: +/***/ 75032: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var Buffer = (__webpack_require__(89509).Buffer) +const Range = __webpack_require__(78311) +const Comparator = __webpack_require__(93904) +const { ANY } = Comparator +const satisfies = __webpack_require__(97638) +const compare = __webpack_require__(50560) -var checkParameters = __webpack_require__(77357) -var defaultEncoding = __webpack_require__(12368) -var sync = __webpack_require__(91257) -var toBuffer = __webpack_require__(57777) +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } -var ZERO_BUF -var subtle = __webpack_require__.g.crypto && __webpack_require__.g.crypto.subtle -var toBrowser = { - sha: 'SHA-1', - 'sha-1': 'SHA-1', - sha1: 'SHA-1', - sha256: 'SHA-256', - 'sha-256': 'SHA-256', - sha384: 'SHA-384', - 'sha-384': 'SHA-384', - 'sha-512': 'SHA-512', - sha512: 'SHA-512' -} -var checks = [] -function checkNative (algo) { - if (__webpack_require__.g.process && !__webpack_require__.g.process.browser) { - return Promise.resolve(false) + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) { + continue OUTER + } + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false + } } - if (!subtle || !subtle.importKey || !subtle.deriveBits) { - return Promise.resolve(false) + return true +} + +const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] +const minimumVersion = [new Comparator('>=0.0.0')] + +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true } - if (checks[algo] !== undefined) { - return checks[algo] + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease + } else { + sub = minimumVersion + } } - ZERO_BUF = ZERO_BUF || Buffer.alloc(8) - var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) - .then(function () { + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { return true - }).catch(function () { - return false - }) - checks[algo] = prom - return prom -} -var nextTick -function getNextTick () { - if (nextTick) { - return nextTick + } else { + dom = minimumVersion + } } - if (__webpack_require__.g.process && __webpack_require__.g.process.nextTick) { - nextTick = __webpack_require__.g.process.nextTick - } else if (__webpack_require__.g.queueMicrotask) { - nextTick = __webpack_require__.g.queueMicrotask - } else if (__webpack_require__.g.setImmediate) { - nextTick = __webpack_require__.g.setImmediate - } else { - nextTick = __webpack_require__.g.setTimeout + + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.semver) + } } - return nextTick -} -function browserPbkdf2 (password, salt, iterations, length, algo) { - return subtle.importKey( - 'raw', password, { name: 'PBKDF2' }, false, ['deriveBits'] - ).then(function (key) { - return subtle.deriveBits({ - name: 'PBKDF2', - salt: salt, - iterations: iterations, - hash: { - name: algo - } - }, key, length << 3) - }).then(function (res) { - return Buffer.from(res) - }) -} -function resolvePromise (promise, callback) { - promise.then(function (out) { - getNextTick()(function () { - callback(null, out) - }) - }, function (e) { - getNextTick()(function () { - callback(e) - }) - }) -} -module.exports = function (password, salt, iterations, keylen, digest, callback) { - if (typeof digest === 'function') { - callback = digest - digest = undefined + if (eqSet.size > 1) { + return null } - digest = digest || 'sha1' - var algo = toBrowser[digest.toLowerCase()] + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) { + return null + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null + } + } - if (!algo || typeof __webpack_require__.g.Promise !== 'function') { - getNextTick()(function () { - var out - try { - out = sync(password, salt, iterations, keylen, digest) - } catch (e) { - return callback(e) + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null + } + + if (lt && !satisfies(eq, String(lt), options)) { + return null + } + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false } - callback(null, out) - }) - return - } + } - checkParameters(iterations, keylen) - password = toBuffer(password, defaultEncoding, 'Password') - salt = toBuffer(salt, defaultEncoding, 'Salt') - if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') + return true + } - resolvePromise(checkNative(algo).then(function (resp) { - if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo) + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false + } + } - return sync(password, salt, iterations, keylen, digest) - }), callback) -} + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false + } -/***/ }), + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false + } -/***/ 12368: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + return true +} -/* provided dependency */ var process = __webpack_require__(70046); -var defaultEncoding -/* istanbul ignore next */ -if (__webpack_require__.g.process && __webpack_require__.g.process.browser) { - defaultEncoding = 'utf-8' -} else if (__webpack_require__.g.process && __webpack_require__.g.process.version) { - var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a +} - defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' -} else { - defaultEncoding = 'utf-8' +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a } -module.exports = defaultEncoding + +module.exports = subset /***/ }), -/***/ 77357: -/***/ ((module) => { +/***/ 77631: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs +const Range = __webpack_require__(78311) -module.exports = function (iterations, keylen) { - if (typeof iterations !== 'number') { - throw new TypeError('Iterations not a number') - } +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) - if (iterations < 0) { - throw new TypeError('Bad iterations') - } +module.exports = toComparators - if (typeof keylen !== 'number') { - throw new TypeError('Key length not a number') - } - if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ - throw new TypeError('Bad key length') +/***/ }), + +/***/ 13874: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const Range = __webpack_require__(78311) +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null } } +module.exports = validRange /***/ }), -/***/ 91257: +/***/ 96897: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var md5 = __webpack_require__(78028) -var RIPEMD160 = __webpack_require__(79785) -var sha = __webpack_require__(89072) -var Buffer = (__webpack_require__(89509).Buffer) +"use strict"; -var checkParameters = __webpack_require__(77357) -var defaultEncoding = __webpack_require__(12368) -var toBuffer = __webpack_require__(57777) -var ZEROS = Buffer.alloc(128) -var sizes = { - md5: 16, - sha1: 20, - sha224: 28, - sha256: 32, - sha384: 48, - sha512: 64, - rmd160: 20, - ripemd160: 20 -} +var GetIntrinsic = __webpack_require__(70453); +var define = __webpack_require__(30041); +var hasDescriptors = __webpack_require__(30592)(); +var gOPD = __webpack_require__(75795); -function Hmac (alg, key, saltLen) { - var hash = getDigest(alg) - var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 +var $TypeError = __webpack_require__(69675); +var $floor = GetIntrinsic('%Math.floor%'); - if (key.length > blocksize) { - key = hash(key) - } else if (key.length < blocksize) { - key = Buffer.concat([key, ZEROS], blocksize) - } +/** @typedef {(...args: unknown[]) => unknown} Func */ - var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]) - var opad = Buffer.allocUnsafe(blocksize + sizes[alg]) - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36 - opad[i] = key[i] ^ 0x5C - } +/** @type {(fn: T, length: number, loose?: boolean) => T} */ +module.exports = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } - var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4) - ipad.copy(ipad1, 0, 0, blocksize) - this.ipad1 = ipad1 - this.ipad2 = ipad - this.opad = opad - this.alg = alg - this.blocksize = blocksize - this.hash = hash - this.size = sizes[alg] -} + var loose = arguments.length > 2 && !!arguments[2]; -Hmac.prototype.run = function (data, ipad) { - data.copy(ipad, this.blocksize) - var h = this.hash(ipad) - h.copy(this.opad, this.blocksize) - return this.hash(this.opad) -} + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } -function getDigest (alg) { - function shaFunc (data) { - return sha(alg).update(data).digest() - } - function rmd160Func (data) { - return new RIPEMD160().update(data).digest() - } + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'length', length, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'length', length); + } + } + return fn; +}; - if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func - if (alg === 'md5') return md5 - return shaFunc -} -function pbkdf2 (password, salt, iterations, keylen, digest) { - checkParameters(iterations, keylen) - password = toBuffer(password, defaultEncoding, 'Password') - salt = toBuffer(salt, defaultEncoding, 'Salt') +/***/ }), - digest = digest || 'sha1' +/***/ 90392: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - var hmac = new Hmac(digest, password, salt.length) +var Buffer = (__webpack_require__(92861).Buffer) - var DK = Buffer.allocUnsafe(keylen) - var block1 = Buffer.allocUnsafe(salt.length + 4) - salt.copy(block1, 0, 0, salt.length) +// prototype class for hash functions +function Hash (blockSize, finalSize) { + this._block = Buffer.alloc(blockSize) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 +} - var destPos = 0 - var hLen = sizes[digest] - var l = Math.ceil(keylen / hLen) +Hash.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8' + data = Buffer.from(data, enc) + } - for (var i = 1; i <= l; i++) { - block1.writeUInt32BE(i, salt.length) + var block = this._block + var blockSize = this._blockSize + var length = data.length + var accum = this._len - var T = hmac.run(block1, hmac.ipad1) - var U = T + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize + var remainder = Math.min(length - offset, blockSize - assigned) - for (var j = 1; j < iterations; j++) { - U = hmac.run(U, hmac.ipad2) - for (var k = 0; k < hLen; k++) T[k] ^= U[k] + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i] } - T.copy(DK, destPos) - destPos += hLen + accum += remainder + offset += remainder + + if ((accum % blockSize) === 0) { + this._update(block) + } } - return DK + this._len += length + return this } -module.exports = pbkdf2 +Hash.prototype.digest = function (enc) { + var rem = this._len % this._blockSize + this._block[rem] = 0x80 -/***/ }), + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1) -/***/ 57777: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (rem >= this._finalSize) { + this._update(this._block) + this._block.fill(0) + } -var Buffer = (__webpack_require__(89509).Buffer) + var bits = this._len * 8 -module.exports = function (thing, encoding, name) { - if (Buffer.isBuffer(thing)) { - return thing - } else if (typeof thing === 'string') { - return Buffer.from(thing, encoding) - } else if (ArrayBuffer.isView(thing)) { - return Buffer.from(thing.buffer) + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4) + + // uint64 } else { - throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView') + var lowBits = (bits & 0xffffffff) >>> 0 + var highBits = (bits - lowBits) / 0x100000000 + + this._block.writeUInt32BE(highBits, this._blockSize - 8) + this._block.writeUInt32BE(lowBits, this._blockSize - 4) } + + this._update(this._block) + var hash = this._hash() + + return enc ? hash.toString(enc) : hash } +Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') +} -/***/ }), +module.exports = Hash -/***/ 70046: -/***/ ((module) => { -// shim for using process in browser -var process = module.exports = {}; +/***/ }), -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. +/***/ 62802: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var cachedSetTimeout; -var cachedClearTimeout; +var exports = module.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase() -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); + var Algorithm = exports[algorithm] + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() } -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } +exports.sha = __webpack_require__(27816) +exports.sha1 = __webpack_require__(63737) +exports.sha224 = __webpack_require__(26710) +exports.sha256 = __webpack_require__(24107) +exports.sha384 = __webpack_require__(32827) +exports.sha512 = __webpack_require__(82890) -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } +/***/ }), + +/***/ 27816: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + +var inherits = __webpack_require__(56698) +var Hash = __webpack_require__(90392) +var Buffer = (__webpack_require__(92861).Buffer) + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha, Hash) +Sha.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + return this } -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } +function rotl5 (num) { + return (num << 5) | (num >>> 27) } -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d } -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; +Sha.prototype._update = function (M) { + var W = this._w -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 -function noop() {} + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 -process.listeners = function (name) { return [] } + e = d + d = c + c = rotl30(b) + b = a + a = t + } -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; +Sha.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) -/***/ }), + return H +} -/***/ 79785: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +module.exports = Sha -"use strict"; -var Buffer = (__webpack_require__(48764).Buffer) -var inherits = __webpack_require__(35717) -var HashBase = __webpack_require__(3349) +/***/ }), -var ARRAY16 = new Array(16) +/***/ 63737: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var zl = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -] +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ -var zr = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -] +var inherits = __webpack_require__(56698) +var Hash = __webpack_require__(90392) +var Buffer = (__webpack_require__(92861).Buffer) -var sl = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 ] -var sr = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -] +var W = new Array(80) -var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] -var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] +function Sha1 () { + this.init() + this._w = W -function RIPEMD160 () { - HashBase.call(this, 64) + Hash.call(this, 64, 56) +} - // state +inherits(Sha1, Hash) + +Sha1.prototype.init = function () { this._a = 0x67452301 this._b = 0xefcdab89 this._c = 0x98badcfe this._d = 0x10325476 this._e = 0xc3d2e1f0 + + return this } -inherits(RIPEMD160, HashBase) +function rotl1 (num) { + return (num << 1) | (num >>> 31) +} -RIPEMD160.prototype._update = function () { - var words = ARRAY16 - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4) +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} - var al = this._a | 0 - var bl = this._b | 0 - var cl = this._c | 0 - var dl = this._d | 0 - var el = this._e | 0 +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} - var ar = this._a | 0 - var br = this._b | 0 - var cr = this._c | 0 - var dr = this._d | 0 - var er = this._e | 0 +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} - // computation - for (var i = 0; i < 80; i += 1) { - var tl - var tr - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]) - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]) - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]) - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]) - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]) - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]) - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]) - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]) - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]) - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]) - } +Sha1.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 - al = el - el = dl - dl = rotl(cl, 10) - cl = bl - bl = tl + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) - ar = er - er = dr - dr = rotl(cr, 10) - cr = br - br = tr + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t } - // update state - var t = (this._b + cl + dr) | 0 - this._b = (this._c + dl + er) | 0 - this._c = (this._d + el + ar) | 0 - this._d = (this._e + al + br) | 0 - this._e = (this._a + bl + cr) | 0 - this._a = t + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 } -RIPEMD160.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80 - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64) - this._update() - this._blockOffset = 0 - } +Sha1.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) - this._block.fill(0, this._blockOffset, 56) - this._block.writeUInt32LE(this._length[0], 56) - this._block.writeUInt32LE(this._length[1], 60) - this._update() + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) - // produce result - var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20) - buffer.writeInt32LE(this._a, 0) - buffer.writeInt32LE(this._b, 4) - buffer.writeInt32LE(this._c, 8) - buffer.writeInt32LE(this._d, 12) - buffer.writeInt32LE(this._e, 16) - return buffer + return H } -function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) -} +module.exports = Sha1 -function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 -} -function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 -} +/***/ }), -function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 +/***/ 26710: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = __webpack_require__(56698) +var Sha256 = __webpack_require__(24107) +var Hash = __webpack_require__(90392) +var Buffer = (__webpack_require__(92861).Buffer) + +var W = new Array(64) + +function Sha224 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) } -function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 +inherits(Sha224, Sha256) + +Sha224.prototype.init = function () { + this._a = 0xc1059ed8 + this._b = 0x367cd507 + this._c = 0x3070dd17 + this._d = 0xf70e5939 + this._e = 0xffc00b31 + this._f = 0x68581511 + this._g = 0x64f98fa7 + this._h = 0xbefa4fa4 + + return this } -function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 +Sha224.prototype._hash = function () { + var H = Buffer.allocUnsafe(28) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + + return H } -module.exports = RIPEMD160 +module.exports = Sha224 /***/ }), -/***/ 89509: -/***/ ((module, exports, __webpack_require__) => { +/***/ 24107: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/* eslint-disable node/no-deprecated-api */ -var buffer = __webpack_require__(48764) -var Buffer = buffer.Buffer +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ -// 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 -} +var inherits = __webpack_require__(56698) +var Hash = __webpack_require__(90392) +var Buffer = (__webpack_require__(92861).Buffer) -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} +var K = [ + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 +] -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) +var W = new Array(64) -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} +function Sha256 () { + this.init() -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 -} + this._w = W // new Array(64) -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) + Hash.call(this, 64, 56) } -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) +inherits(Sha256, Hash) + +Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 + + return this } +function ch (x, y, z) { + return z ^ (x & (y ^ z)) +} -/***/ }), +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} -/***/ 24189: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) +} -var Buffer = (__webpack_require__(89509).Buffer) +function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) +} -// prototype class for hash functions -function Hash (blockSize, finalSize) { - this._block = Buffer.alloc(blockSize) - this._finalSize = finalSize - this._blockSize = blockSize - this._len = 0 +function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) } -Hash.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8' - data = Buffer.from(data, enc) - } +function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) +} - var block = this._block - var blockSize = this._blockSize - var length = data.length - var accum = this._len +Sha256.prototype._update = function (M) { + var W = this._w - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize - var remainder = Math.min(length - offset, blockSize - assigned) + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i] - } + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 - accum += remainder - offset += remainder + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + maj(a, b, c)) | 0 - if ((accum % blockSize) === 0) { - this._update(block) - } + h = g + g = f + f = e + e = (d + T1) | 0 + d = c + c = b + b = a + a = (T1 + T2) | 0 } - this._len += length - return this + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 } -Hash.prototype.digest = function (enc) { - var rem = this._len % this._blockSize +Sha256.prototype._hash = function () { + var H = Buffer.allocUnsafe(32) - this._block[rem] = 0x80 + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1) + return H +} - if (rem >= this._finalSize) { - this._update(this._block) - this._block.fill(0) - } +module.exports = Sha256 - var bits = this._len * 8 - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4) +/***/ }), - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0 - var highBits = (bits - lowBits) / 0x100000000 +/***/ 32827: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - this._block.writeUInt32BE(highBits, this._blockSize - 8) - this._block.writeUInt32BE(lowBits, this._blockSize - 4) - } +var inherits = __webpack_require__(56698) +var SHA512 = __webpack_require__(82890) +var Hash = __webpack_require__(90392) +var Buffer = (__webpack_require__(92861).Buffer) - this._update(this._block) - var hash = this._hash() +var W = new Array(160) - return enc ? hash.toString(enc) : hash -} +function Sha384 () { + this.init() + this._w = W -Hash.prototype._update = function () { - throw new Error('_update must be implemented by subclass') + Hash.call(this, 128, 112) } -module.exports = Hash +inherits(Sha384, SHA512) +Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d + this._bh = 0x629a292a + this._ch = 0x9159015a + this._dh = 0x152fecd8 + this._eh = 0x67332667 + this._fh = 0x8eb44a87 + this._gh = 0xdb0c2e0d + this._hh = 0x47b5481d -/***/ }), + this._al = 0xc1059ed8 + this._bl = 0x367cd507 + this._cl = 0x3070dd17 + this._dl = 0xf70e5939 + this._el = 0xffc00b31 + this._fl = 0x68581511 + this._gl = 0x64f98fa7 + this._hl = 0xbefa4fa4 -/***/ 89072: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + return this +} -var exports = module.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase() +Sha384.prototype._hash = function () { + var H = Buffer.allocUnsafe(48) - var Algorithm = exports[algorithm] - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } - return new Algorithm() + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + + return H } -exports.sha = __webpack_require__(74448) -exports.sha1 = __webpack_require__(18336) -exports.sha224 = __webpack_require__(48432) -exports.sha256 = __webpack_require__(67499) -exports.sha384 = __webpack_require__(51686) -exports.sha512 = __webpack_require__(87816) +module.exports = Sha384 /***/ }), -/***/ 74448: +/***/ 82890: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ - -var inherits = __webpack_require__(35717) -var Hash = __webpack_require__(24189) -var Buffer = (__webpack_require__(89509).Buffer) +var inherits = __webpack_require__(56698) +var Hash = __webpack_require__(90392) +var Buffer = (__webpack_require__(92861).Buffer) var K = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ] -var W = new Array(80) +var W = new Array(160) -function Sha () { +function Sha512 () { this.init() this._w = W - Hash.call(this, 64, 56) + Hash.call(this, 128, 112) } -inherits(Sha, Hash) - -Sha.prototype.init = function () { - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 - this._e = 0xc3d2e1f0 - - return this -} +inherits(Sha512, Hash) -function rotl5 (num) { - return (num << 5) | (num >>> 27) -} +Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 -function rotl30 (num) { - return (num << 30) | (num >>> 2) -} + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 -function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d + return this } -Sha.prototype._update = function (M) { - var W = this._w - - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20) - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 - - e = d - d = c - c = rotl30(b) - b = a - a = t - } - - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 +function Ch (x, y, z) { + return z ^ (x & (y ^ z)) } -Sha.prototype._hash = function () { - var H = Buffer.allocUnsafe(20) +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} - H.writeInt32BE(this._a | 0, 0) - H.writeInt32BE(this._b | 0, 4) - H.writeInt32BE(this._c | 0, 8) - H.writeInt32BE(this._d | 0, 12) - H.writeInt32BE(this._e | 0, 16) +function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) +} - return H +function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) } -module.exports = Sha +function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) +} +function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) +} -/***/ }), +function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) +} -/***/ 18336: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) +} -/* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ +function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 +} -var inherits = __webpack_require__(35717) -var Hash = __webpack_require__(24189) -var Buffer = (__webpack_require__(89509).Buffer) +Sha512.prototype._update = function (M) { + var W = this._w -var K = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 -] + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 -var W = new Array(80) + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 -function Sha1 () { - this.init() - this._w = W + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) - Hash.call(this, 64, 56) -} + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) -inherits(Sha1, Hash) + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] -Sha1.prototype.init = function () { - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 - this._e = 0xc3d2e1f0 + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] - return this -} + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 -function rotl1 (num) { - return (num << 1) | (num >>> 31) -} + W[i] = Wih + W[i + 1] = Wil + } -function rotl5 (num) { - return (num << 5) | (num >>> 27) -} + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] -function rotl30 (num) { - return (num << 30) | (num >>> 2) -} + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) -function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d -} + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) -Sha1.prototype._update = function (M) { - var W = this._w + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20) - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 - e = d - d = c - c = rotl30(b) - b = a - a = t + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 } - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 } -Sha1.prototype._hash = function () { - var H = Buffer.allocUnsafe(20) +Sha512.prototype._hash = function () { + var H = Buffer.allocUnsafe(64) - H.writeInt32BE(this._a | 0, 0) - H.writeInt32BE(this._b | 0, 4) - H.writeInt32BE(this._c | 0, 8) - H.writeInt32BE(this._d | 0, 12) - H.writeInt32BE(this._e | 0, 16) + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) return H } -module.exports = Sha1 +module.exports = Sha512 /***/ }), -/***/ 48432: +/***/ 920: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet +"use strict"; + + +var GetIntrinsic = __webpack_require__(70453); +var callBound = __webpack_require__(38075); +var inspect = __webpack_require__(58859); + +var $TypeError = GetIntrinsic('%TypeError%'); +var $WeakMap = GetIntrinsic('%WeakMap%', true); +var $Map = GetIntrinsic('%Map%', true); + +var $weakMapGet = callBound('WeakMap.prototype.get', true); +var $weakMapSet = callBound('WeakMap.prototype.set', true); +var $weakMapHas = callBound('WeakMap.prototype.has', true); +var $mapGet = callBound('Map.prototype.get', true); +var $mapSet = callBound('Map.prototype.set', true); +var $mapHas = callBound('Map.prototype.has', true); + +/* + * 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. */ +var listGetNode = function (list, key) { // eslint-disable-line consistent-return + for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + curr.next = list.next; + list.next = curr; // eslint-disable-line no-param-reassign + return curr; + } + } +}; + +var listGet = function (objects, key) { + var node = listGetNode(objects, key); + return node && node.value; +}; +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 = { // eslint-disable-line no-param-reassign + key: key, + next: objects.next, + value: value + }; + } +}; +var listHas = function (objects, key) { + return !!listGetNode(objects, key); +}; + +module.exports = function getSideChannel() { + var $wm; + var $m; + var $o; + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + get: function (key) { // eslint-disable-line consistent-return + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapGet($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listGet($o, key); + } + } + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapHas($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listHas($o, key); + } + } + return false; + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if ($Map) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key, value); + } else { + 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 = { key: {}, next: null }; + } + listSet($o, key, value); + } + } + }; + return channel; +}; + + +/***/ }), + +/***/ 83141: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -var inherits = __webpack_require__(35717) -var Sha256 = __webpack_require__(67499) -var Hash = __webpack_require__(24189) -var Buffer = (__webpack_require__(89509).Buffer) +"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 W = new Array(64) -function Sha224 () { - this.init() - this._w = W // new Array(64) +/**/ - Hash.call(this, 64, 56) -} +var Buffer = (__webpack_require__(92861).Buffer); +/**/ -inherits(Sha224, Sha256) +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; + } +}; -Sha224.prototype.init = function () { - this._a = 0xc1059ed8 - this._b = 0x367cd507 - this._c = 0x3070dd17 - this._d = 0xf70e5939 - this._e = 0xffc00b31 - this._f = 0x68581511 - this._g = 0x64f98fa7 - this._h = 0xbefa4fa4 +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; + } + } +}; - return this +// 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; } -Sha224.prototype._hash = function () { - var H = Buffer.allocUnsafe(28) - - H.writeInt32BE(this._a, 0) - H.writeInt32BE(this._b, 4) - H.writeInt32BE(this._c, 8) - H.writeInt32BE(this._d, 12) - H.writeInt32BE(this._e, 16) - H.writeInt32BE(this._f, 20) - H.writeInt32BE(this._g, 24) - - return H +// 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); } -module.exports = Sha224 - - -/***/ }), - -/***/ 67499: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -/** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ +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 || ''; +}; -var inherits = __webpack_require__(35717) -var Hash = __webpack_require__(24189) -var Buffer = (__webpack_require__(89509).Buffer) +StringDecoder.prototype.end = utf8End; -var K = [ - 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, - 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, - 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, - 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, - 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, - 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, - 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, - 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, - 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, - 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, - 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, - 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, - 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, - 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, - 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, - 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 -] +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; -var W = new Array(64) +// 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; +}; -function Sha256 () { - this.init() +// 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; +} - this._w = W // new Array(64) +// 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; +} - Hash.call(this, 64, 56) +// 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'; + } + } + } } -inherits(Sha256, Hash) +// 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; +} -Sha256.prototype.init = function () { - this._a = 0x6a09e667 - this._b = 0xbb67ae85 - this._c = 0x3c6ef372 - this._d = 0xa54ff53a - this._e = 0x510e527f - this._f = 0x9b05688c - this._g = 0x1f83d9ab - this._h = 0x5be0cd19 +// 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); +} - return this +// 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; } -function ch (x, y, z) { - return z ^ (x & (y ^ z)) +// 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); } -function maj (x, y, z) { - return (x & y) | (z & (x | y)) +// 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 sigma0 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) +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 sigma1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) +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; } -function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); } -function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; } -Sha256.prototype._update = function (M) { - var W = this._w +/***/ }), - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 - var f = this._f | 0 - var g = this._g | 0 - var h = this._h | 0 +/***/ 51380: +/***/ ((module) => { - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 +"use strict"; - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 - var T2 = (sigma0(a) + maj(a, b, c)) | 0 - h = g - g = f - f = e - e = (d + T1) | 0 - d = c - c = b - b = a - a = (T1 + T2) | 0 +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function Agent() { + this._defaults = []; +} +for (var _i = 0, _arr = ['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts']; _i < _arr.length; _i++) { + const fn = _arr[_i]; + // Default setting for all requests from this agent + Agent.prototype[fn] = function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + this._defaults.push({ + fn, + args + }); + return this; + }; +} +Agent.prototype._setDefaults = function (request) { + var _iterator = _createForOfIteratorHelper(this._defaults), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + const def = _step.value; + request[def.fn](...def.args); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); } +}; +module.exports = Agent; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJBZ2VudCIsIl9kZWZhdWx0cyIsIl9pIiwiX2FyciIsImxlbmd0aCIsImZuIiwicHJvdG90eXBlIiwiX2xlbiIsImFyZ3VtZW50cyIsImFyZ3MiLCJBcnJheSIsIl9rZXkiLCJwdXNoIiwiX3NldERlZmF1bHRzIiwicmVxdWVzdCIsIl9pdGVyYXRvciIsIl9jcmVhdGVGb3JPZkl0ZXJhdG9ySGVscGVyIiwiX3N0ZXAiLCJzIiwibiIsImRvbmUiLCJkZWYiLCJ2YWx1ZSIsImVyciIsImUiLCJmIiwibW9kdWxlIiwiZXhwb3J0cyJdLCJzb3VyY2VzIjpbIi4uL3NyYy9hZ2VudC1iYXNlLmpzIl0sInNvdXJjZXNDb250ZW50IjpbImZ1bmN0aW9uIEFnZW50KCkge1xuICB0aGlzLl9kZWZhdWx0cyA9IFtdO1xufVxuXG5mb3IgKGNvbnN0IGZuIG9mIFtcbiAgJ3VzZScsXG4gICdvbicsXG4gICdvbmNlJyxcbiAgJ3NldCcsXG4gICdxdWVyeScsXG4gICd0eXBlJyxcbiAgJ2FjY2VwdCcsXG4gICdhdXRoJyxcbiAgJ3dpdGhDcmVkZW50aWFscycsXG4gICdzb3J0UXVlcnknLFxuICAncmV0cnknLFxuICAnb2snLFxuICAncmVkaXJlY3RzJyxcbiAgJ3RpbWVvdXQnLFxuICAnYnVmZmVyJyxcbiAgJ3NlcmlhbGl6ZScsXG4gICdwYXJzZScsXG4gICdjYScsXG4gICdrZXknLFxuICAncGZ4JyxcbiAgJ2NlcnQnLFxuICAnZGlzYWJsZVRMU0NlcnRzJ1xuXSkge1xuICAvLyBEZWZhdWx0IHNldHRpbmcgZm9yIGFsbCByZXF1ZXN0cyBmcm9tIHRoaXMgYWdlbnRcbiAgQWdlbnQucHJvdG90eXBlW2ZuXSA9IGZ1bmN0aW9uICguLi5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xDQUFBSCxJQUFBLEdBQUFJLElBQUEsTUFBQUEsSUFBQSxHQUFBSixJQUFBLEVBQUFJLElBQUE7TUFBSkYsSUFBSSxDQUFBRSxJQUFBLElBQUFILFNBQUEsQ0FBQUcsSUFBQTtJQUFBO0lBQ3JDLElBQUksQ0FBQ1YsU0FBUyxDQUFDVyxJQUFJLENBQUM7TUFBRVAsRUFBRTtNQUFFSTtJQUFLLENBQUMsQ0FBQztJQUNqQyxPQUFPLElBQUk7RUFDYixDQUFDO0FBQ0g7QUFFQVQsS0FBSyxDQUFDTSxTQUFTLENBQUNPLFlBQVksR0FBRyxVQUFVQyxPQUFPLEVBQUU7RUFBQSxJQUFBQyxTQUFBLEdBQUFDLDBCQUFBLENBQzlCLElBQUksQ0FBQ2YsU0FBUztJQUFBZ0IsS0FBQTtFQUFBO0lBQWhDLEtBQUFGLFNBQUEsQ0FBQUcsQ0FBQSxNQUFBRCxLQUFBLEdBQUFGLFNBQUEsQ0FBQUksQ0FBQSxJQUFBQyxJQUFBLEdBQWtDO01BQUEsTUFBdkJDLEdBQUcsR0FBQUosS0FBQSxDQUFBSyxLQUFBO01BQ1pSLE9BQU8sQ0FBQ08sR0FBRyxDQUFDaEIsRUFBRSxDQUFDLENBQUMsR0FBR2dCLEdBQUcsQ0FBQ1osSUFBSSxDQUFDO0lBQzlCO0VBQUMsU0FBQWMsR0FBQTtJQUFBUixTQUFBLENBQUFTLENBQUEsQ0FBQUQsR0FBQTtFQUFBO0lBQUFSLFNBQUEsQ0FBQVUsQ0FBQTtFQUFBO0FBQ0gsQ0FBQztBQUVEQyxNQUFNLENBQUNDLE9BQU8sR0FBRzNCLEtBQUsifQ== - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 - this._f = (f + this._f) | 0 - this._g = (g + this._g) | 0 - this._h = (h + this._h) | 0 -} +/***/ }), -Sha256.prototype._hash = function () { - var H = Buffer.allocUnsafe(32) +/***/ 15734: +/***/ ((module, exports, __webpack_require__) => { - H.writeInt32BE(this._a, 0) - H.writeInt32BE(this._b, 4) - H.writeInt32BE(this._c, 8) - H.writeInt32BE(this._d, 12) - H.writeInt32BE(this._e, 16) - H.writeInt32BE(this._f, 20) - H.writeInt32BE(this._g, 24) - H.writeInt32BE(this._h, 28) +"use strict"; - return H -} -module.exports = Sha256 +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +/** + * Root reference for iframes. + */ +let root; +if (typeof window !== 'undefined') { + // Browser window + root = window; +} else if (typeof self === 'undefined') { + // Other environments + console.warn('Using browser-only version of superagent in non-browser environment'); + root = void 0; +} else { + // Web Worker + root = self; +} +const Emitter = __webpack_require__(5971); +const safeStringify = __webpack_require__(78463); +const qs = __webpack_require__(55373); +const RequestBase = __webpack_require__(31948); +const _require = __webpack_require__(33048), + isObject = _require.isObject, + mixin = _require.mixin, + hasOwn = _require.hasOwn; +const ResponseBase = __webpack_require__(19450); +const Agent = __webpack_require__(51380); -/***/ }), +/** + * Noop. + */ -/***/ 51686: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +function noop() {} -var inherits = __webpack_require__(35717) -var SHA512 = __webpack_require__(87816) -var Hash = __webpack_require__(24189) -var Buffer = (__webpack_require__(89509).Buffer) +/** + * Expose `request`. + */ -var W = new Array(160) +module.exports = function (method, url) { + // callback + if (typeof url === 'function') { + return new exports.Request('GET', method).end(url); + } -function Sha384 () { - this.init() - this._w = W + // url first + if (arguments.length === 1) { + return new exports.Request('GET', method); + } + return new exports.Request(method, url); +}; +exports = module.exports; +const request = exports; +exports.Request = Request; - Hash.call(this, 128, 112) -} +/** + * Determine XHR. + */ -inherits(Sha384, SHA512) +request.getXHR = () => { + if (root.XMLHttpRequest) { + return new root.XMLHttpRequest(); + } + throw new Error('Browser-only version of superagent could not find XHR'); +}; -Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d - this._bh = 0x629a292a - this._ch = 0x9159015a - this._dh = 0x152fecd8 - this._eh = 0x67332667 - this._fh = 0x8eb44a87 - this._gh = 0xdb0c2e0d - this._hh = 0x47b5481d +/** + * Removes leading and trailing whitespace, added to support IE. + * + * @param {String} s + * @return {String} + * @api private + */ - this._al = 0xc1059ed8 - this._bl = 0x367cd507 - this._cl = 0x3070dd17 - this._dl = 0xf70e5939 - this._el = 0xffc00b31 - this._fl = 0x68581511 - this._gl = 0x64f98fa7 - this._hl = 0xbefa4fa4 +const trim = ''.trim ? s => s.trim() : s => s.replace(/(^\s*|\s*$)/g, ''); - return this +/** + * Serialize the given `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +function serialize(object) { + if (!isObject(object)) return object; + const pairs = []; + for (const key in object) { + if (hasOwn(object, key)) pushEncodedKeyValuePair(pairs, key, object[key]); + } + return pairs.join('&'); } -Sha384.prototype._hash = function () { - var H = Buffer.allocUnsafe(48) +/** + * Helps 'serialize' with serializing arrays. + * Mutates the pairs array. + * + * @param {Array} pairs + * @param {String} key + * @param {Mixed} val + */ - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset) - H.writeInt32BE(l, offset + 4) +function pushEncodedKeyValuePair(pairs, key, value) { + if (value === undefined) return; + if (value === null) { + pairs.push(encodeURI(key)); + return; + } + if (Array.isArray(value)) { + var _iterator = _createForOfIteratorHelper(value), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + const v = _step.value; + pushEncodedKeyValuePair(pairs, key, v); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + } else if (isObject(value)) { + for (const subkey in value) { + if (hasOwn(value, subkey)) pushEncodedKeyValuePair(pairs, `${key}[${subkey}]`, value[subkey]); + } + } else { + pairs.push(encodeURI(key) + '=' + encodeURIComponent(value)); } +} - writeInt64BE(this._ah, this._al, 0) - writeInt64BE(this._bh, this._bl, 8) - writeInt64BE(this._ch, this._cl, 16) - writeInt64BE(this._dh, this._dl, 24) - writeInt64BE(this._eh, this._el, 32) - writeInt64BE(this._fh, this._fl, 40) +/** + * Expose serialization method. + */ + +request.serializeObject = serialize; + +/** + * Parse the given x-www-form-urlencoded `str`. + * + * @param {String} str + * @return {Object} + * @api private + */ - return H +function parseString(string_) { + const object = {}; + const pairs = string_.split('&'); + let pair; + let pos; + for (let i = 0, length_ = pairs.length; i < length_; ++i) { + pair = pairs[i]; + pos = pair.indexOf('='); + if (pos === -1) { + object[decodeURIComponent(pair)] = ''; + } else { + object[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1)); + } + } + return object; } -module.exports = Sha384 +/** + * Expose parser. + */ +request.parseString = parseString; -/***/ }), +/** + * Default MIME type map. + * + * superagent.types.xml = 'application/xml'; + * + */ -/***/ 87816: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +request.types = { + html: 'text/html', + json: 'application/json', + xml: 'text/xml', + urlencoded: 'application/x-www-form-urlencoded', + form: 'application/x-www-form-urlencoded', + 'form-data': 'application/x-www-form-urlencoded' +}; -var inherits = __webpack_require__(35717) -var Hash = __webpack_require__(24189) -var Buffer = (__webpack_require__(89509).Buffer) +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ -var K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -] +request.serialize = { + 'application/x-www-form-urlencoded': qs.stringify, + 'application/json': safeStringify +}; -var W = new Array(160) +/** + * Default parsers. + * + * superagent.parse['application/xml'] = function(str){ + * return { object parsed from str }; + * }; + * + */ -function Sha512 () { - this.init() - this._w = W +request.parse = { + 'application/x-www-form-urlencoded': parseString, + 'application/json': JSON.parse +}; - Hash.call(this, 128, 112) +/** + * Parse the given header `str` into + * an object containing the mapped fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseHeader(string_) { + const lines = string_.split(/\r?\n/); + const fields = {}; + let index; + let line; + let field; + let value; + for (let i = 0, length_ = lines.length; i < length_; ++i) { + line = lines[i]; + index = line.indexOf(':'); + if (index === -1) { + // could be empty line, just skip it + continue; + } + field = line.slice(0, index).toLowerCase(); + value = trim(line.slice(index + 1)); + fields[field] = value; + } + return fields; } -inherits(Sha512, Hash) +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ -Sha512.prototype.init = function () { - this._ah = 0x6a09e667 - this._bh = 0xbb67ae85 - this._ch = 0x3c6ef372 - this._dh = 0xa54ff53a - this._eh = 0x510e527f - this._fh = 0x9b05688c - this._gh = 0x1f83d9ab - this._hh = 0x5be0cd19 +function isJSON(mime) { + // should match /json or +json + // but not /json-seq + return /[/+]json($|[^-\w])/i.test(mime); +} - this._al = 0xf3bcc908 - this._bl = 0x84caa73b - this._cl = 0xfe94f82b - this._dl = 0x5f1d36f1 - this._el = 0xade682d1 - this._fl = 0x2b3e6c1f - this._gl = 0xfb41bd6b - this._hl = 0x137e2179 +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * Examples: + * + * Aliasing `superagent` as `request` is nice: + * + * request = superagent; + * + * We can use the promise-like API, or pass callbacks: + * + * request.get('/').end(function(res){}); + * request.get('/', function(res){}); + * + * Sending data can be chained: + * + * request + * .post('/user') + * .send({ name: 'tj' }) + * .end(function(res){}); + * + * Or passed to `.send()`: + * + * request + * .post('/user') + * .send({ name: 'tj' }, function(res){}); + * + * Or passed to `.post()`: + * + * request + * .post('/user', { name: 'tj' }) + * .end(function(res){}); + * + * Or further reduced to a single call for simple cases: + * + * request + * .post('/user', { name: 'tj' }, function(res){}); + * + * @param {XMLHTTPRequest} xhr + * @param {Object} options + * @api private + */ - return this +function Response(request_) { + this.req = request_; + this.xhr = this.req.xhr; + // responseText is accessible only if responseType is '' or 'text' and on older browsers + this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null; + this.statusText = this.req.xhr.statusText; + let status = this.xhr.status; + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + if (status === 1223) { + status = 204; + } + this._setStatusProperties(status); + this.headers = parseHeader(this.xhr.getAllResponseHeaders()); + this.header = this.headers; + // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but + // getResponseHeader still works. so we get content-type even if getting + // other headers fails. + this.header['content-type'] = this.xhr.getResponseHeader('content-type'); + this._setHeaderProperties(this.header); + if (this.text === null && request_._responseType) { + this.body = this.xhr.response; + } else { + this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response); + } } +mixin(Response.prototype, ResponseBase.prototype); -function Ch (x, y, z) { - return z ^ (x & (y ^ z)) -} +/** + * Parse the given body `str`. + * + * Used for auto-parsing of bodies. Parsers + * are defined on the `superagent.parse` object. + * + * @param {String} str + * @return {Mixed} + * @api private + */ -function maj (x, y, z) { - return (x & y) | (z & (x | y)) -} +Response.prototype._parseBody = function (string_) { + let parse = request.parse[this.type]; + if (this.req._parser) { + return this.req._parser(this, string_); + } + if (!parse && isJSON(this.type)) { + parse = request.parse['application/json']; + } + return parse && string_ && (string_.length > 0 || string_ instanceof Object) ? parse(string_) : null; +}; -function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) -} +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ -function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) -} +Response.prototype.toError = function () { + const req = this.req; + const method = req.method; + const url = req.url; + const message = `cannot ${method} ${url} (${this.status})`; + const error = new Error(message); + error.status = this.status; + error.method = method; + error.url = url; + return error; +}; -function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) -} +/** + * Expose `Response`. + */ -function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) -} +request.Response = Response; -function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) -} +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String} url + * @api public + */ -function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) -} +function Request(method, url) { + const self = this; + this._query = this._query || []; + this.method = method; + this.url = url; + this.header = {}; // preserves header name case + this._header = {}; // coerces header names to lowercase + this.on('end', () => { + let error = null; + let res = null; + try { + res = new Response(self); + } catch (err) { + error = new Error('Parser is unable to parse the response'); + error.parse = true; + error.original = err; + // issue #675: return the raw response if the response parsing fails + if (self.xhr) { + // ie9 doesn't have 'response' property + error.rawResponse = typeof self.xhr.responseType === 'undefined' ? self.xhr.responseText : self.xhr.response; + // issue #876: return the http status code if the response parsing fails + error.status = self.xhr.status ? self.xhr.status : null; + error.statusCode = error.status; // backwards-compat only + } else { + error.rawResponse = null; + error.status = null; + } + return self.callback(error); + } + self.emit('response', res); + let new_error; + try { + if (!self._isResponseOK(res)) { + new_error = new Error(res.statusText || res.text || 'Unsuccessful HTTP response'); + } + } catch (err) { + new_error = err; // ok() callback can throw + } -function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 + // #1000 don't catch errors from the callback to avoid double calling it + if (new_error) { + new_error.original = error; + new_error.response = res; + new_error.status = new_error.status || res.status; + self.callback(new_error, res); + } else { + self.callback(null, res); + } + }); } -Sha512.prototype._update = function (M) { - var W = this._w - - var ah = this._ah | 0 - var bh = this._bh | 0 - var ch = this._ch | 0 - var dh = this._dh | 0 - var eh = this._eh | 0 - var fh = this._fh | 0 - var gh = this._gh | 0 - var hh = this._hh | 0 +/** + * Mixin `Emitter` and `RequestBase`. + */ - var al = this._al | 0 - var bl = this._bl | 0 - var cl = this._cl | 0 - var dl = this._dl | 0 - var el = this._el | 0 - var fl = this._fl | 0 - var gl = this._gl | 0 - var hl = this._hl | 0 +// eslint-disable-next-line new-cap +Emitter(Request.prototype); +mixin(Request.prototype, RequestBase.prototype); - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4) - W[i + 1] = M.readInt32BE(i * 4 + 4) - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2] - var xl = W[i - 15 * 2 + 1] - var gamma0 = Gamma0(xh, xl) - var gamma0l = Gamma0l(xl, xh) +/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ - xh = W[i - 2 * 2] - xl = W[i - 2 * 2 + 1] - var gamma1 = Gamma1(xh, xl) - var gamma1l = Gamma1l(xl, xh) +Request.prototype.type = function (type) { + this.set('Content-Type', request.types[type] || type); + return this; +}; - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2] - var Wi7l = W[i - 7 * 2 + 1] +/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ - var Wi16h = W[i - 16 * 2] - var Wi16l = W[i - 16 * 2 + 1] +Request.prototype.accept = function (type) { + this.set('Accept', request.types[type] || type); + return this; +}; - var Wil = (gamma0l + Wi7l) | 0 - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 - Wil = (Wil + gamma1l) | 0 - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 - Wil = (Wil + Wi16l) | 0 - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 +/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} [pass] optional in case of using 'bearer' as type + * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic') + * @return {Request} for chaining + * @api public + */ - W[i] = Wih - W[i + 1] = Wil +Request.prototype.auth = function (user, pass, options) { + if (arguments.length === 1) pass = ''; + if (typeof pass === 'object' && pass !== null) { + // pass is optional and can be replaced with options + options = pass; + pass = ''; } + if (!options) { + options = { + type: typeof btoa === 'function' ? 'basic' : 'auto' + }; + } + const encoder = options.encoder ? options.encoder : string => { + if (typeof btoa === 'function') { + return btoa(string); + } + throw new Error('Cannot use basic auth, btoa is not a function'); + }; + return this._auth(user, pass, options, encoder); +}; - for (var j = 0; j < 160; j += 2) { - Wih = W[j] - Wil = W[j + 1] - - var majh = maj(ah, bh, ch) - var majl = maj(al, bl, cl) - - var sigma0h = sigma0(ah, al) - var sigma0l = sigma0(al, ah) - var sigma1h = sigma1(eh, el) - var sigma1l = sigma1(el, eh) +/** + * Add query-string `val`. + * + * Examples: + * + * request.get('/shoes') + * .query('size=10') + * .query({ color: 'blue' }) + * + * @param {Object|String} val + * @return {Request} for chaining + * @api public + */ - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K[j] - var Kil = K[j + 1] +Request.prototype.query = function (value) { + if (typeof value !== 'string') value = serialize(value); + if (value) this._query.push(value); + return this; +}; - var chh = Ch(eh, fh, gh) - var chl = Ch(el, fl, gl) +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `options` (or filename). + * + * ``` js + * request.post('/upload') + * .attach('content', new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String|Object} options + * @return {Request} for chaining + * @api public + */ - var t1l = (hl + sigma1l) | 0 - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 - t1l = (t1l + chl) | 0 - t1h = (t1h + chh + getCarry(t1l, chl)) | 0 - t1l = (t1l + Kil) | 0 - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 - t1l = (t1l + Wil) | 0 - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 +Request.prototype.attach = function (field, file, options) { + if (file) { + if (this._data) { + throw new Error("superagent can't mix .send() and .attach()"); + } + this._getFormData().append(field, file, options || file.name); + } + return this; +}; +Request.prototype._getFormData = function () { + if (!this._formData) { + this._formData = new root.FormData(); + } + return this._formData; +}; - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0 - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ - hh = gh - hl = gl - gh = fh - gl = fl - fh = eh - fl = el - el = (dl + t1l) | 0 - eh = (dh + t1h + getCarry(el, dl)) | 0 - dh = ch - dl = cl - ch = bh - cl = bl - bh = ah - bl = al - al = (t1l + t2l) | 0 - ah = (t1h + t2h + getCarry(al, t1l)) | 0 +Request.prototype.callback = function (error, res) { + if (this._shouldRetry(error, res)) { + return this._retry(); } + const fn = this._callback; + this.clearTimeout(); + if (error) { + if (this._maxRetries) error.retries = this._retries - 1; + this.emit('error', error); + } + fn(error, res); +}; - this._al = (this._al + al) | 0 - this._bl = (this._bl + bl) | 0 - this._cl = (this._cl + cl) | 0 - this._dl = (this._dl + dl) | 0 - this._el = (this._el + el) | 0 - this._fl = (this._fl + fl) | 0 - this._gl = (this._gl + gl) | 0 - this._hl = (this._hl + hl) | 0 - - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 -} +/** + * Invoke callback with x-domain error. + * + * @api private + */ -Sha512.prototype._hash = function () { - var H = Buffer.allocUnsafe(64) +Request.prototype.crossDomainError = function () { + const error = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); + error.crossDomain = true; + error.status = this.status; + error.method = this.method; + error.url = this.url; + this.callback(error); +}; - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset) - H.writeInt32BE(l, offset + 4) - } +// This only warns, because the request is still likely to work +Request.prototype.agent = function () { + console.warn('This is not supported in browser version of superagent'); + return this; +}; +Request.prototype.ca = Request.prototype.agent; +Request.prototype.buffer = Request.prototype.ca; - writeInt64BE(this._ah, this._al, 0) - writeInt64BE(this._bh, this._bl, 8) - writeInt64BE(this._ch, this._cl, 16) - writeInt64BE(this._dh, this._dl, 24) - writeInt64BE(this._eh, this._el, 32) - writeInt64BE(this._fh, this._fl, 40) - writeInt64BE(this._gh, this._gl, 48) - writeInt64BE(this._hh, this._hl, 56) +// This throws, because it can't send/receive data as expected +Request.prototype.write = () => { + throw new Error('Streaming is not supported in browser version of superagent'); +}; +Request.prototype.pipe = Request.prototype.write; - return H -} +/** + * Check if `obj` is a host object, + * we don't want to serialize these :) + * + * @param {Object} obj host object + * @return {Boolean} is a host object + * @api private + */ +Request.prototype._isHost = function (object) { + // Native objects stringify to [object File], [object Blob], [object FormData], etc. + return object && typeof object === 'object' && !Array.isArray(object) && Object.prototype.toString.call(object) !== '[object Object]'; +}; -module.exports = Sha512 +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ +Request.prototype.end = function (fn) { + if (this._endCalled) { + console.warn('Warning: .end() was called twice. This is not supported in superagent'); + } + this._endCalled = true; -/***/ }), + // store callback + this._callback = fn || noop; -/***/ 32553: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + // querystring + this._finalizeQueryString(); + this._end(); +}; +Request.prototype._setUploadTimeout = function () { + const self = this; -"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. + // upload timeout it's wokrs only if deadline timeout is off + if (this._uploadTimeout && !this._uploadTimeoutTimer) { + this._uploadTimeoutTimer = setTimeout(() => { + self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT'); + }, this._uploadTimeout); + } +}; +// eslint-disable-next-line complexity +Request.prototype._end = function () { + if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called')); + const self = this; + this.xhr = request.getXHR(); + const xhr = this.xhr; + let data = this._formData || this._data; + this._setTimeouts(); + // state change + xhr.addEventListener('readystatechange', () => { + const readyState = xhr.readyState; + if (readyState >= 2 && self._responseTimeoutTimer) { + clearTimeout(self._responseTimeoutTimer); + } + if (readyState !== 4) { + return; + } -/**/ + // In IE9, reads to any property (e.g. status) off of an aborted XHR will + // result in the error "Could not complete the operation due to error c00c023f" + let status; + try { + status = xhr.status; + } catch (err) { + status = 0; + } + if (!status) { + if (self.timedout || self._aborted) return; + return self.crossDomainError(); + } + self.emit('end'); + }); -var Buffer = (__webpack_require__(89509).Buffer); -/**/ + // progress + const handleProgress = (direction, e) => { + if (e.total > 0) { + e.percent = e.loaded / e.total * 100; + if (e.percent === 100) { + clearTimeout(self._uploadTimeoutTimer); + } + } + e.direction = direction; + self.emit('progress', e); + }; + if (this.hasListeners('progress')) { + try { + xhr.addEventListener('progress', handleProgress.bind(null, 'download')); + if (xhr.upload) { + xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload')); + } + } catch (err) { + // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. + // Reported here: + // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context + } + } + if (xhr.upload) { + this._setUploadTimeout(); + } -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; + // initiate request + try { + if (this.username && this.password) { + xhr.open(this.method, this.url, true, this.username, this.password); + } else { + xhr.open(this.method, this.url, true); + } + } catch (err) { + // see #1149 + return this.callback(err); } -}; -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; + // CORS + if (this._withCredentials) xhr.withCredentials = true; + + // body + if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) { + // serialize stuff + const contentType = this._header['content-type']; + let serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; + if (!serialize && isJSON(contentType)) { + serialize = request.serialize['application/json']; } + if (serialize) data = serialize(data); } -}; -// 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; + // set header fields + for (const field in this.header) { + if (this.header[field] === null) continue; + if (hasOwn(this.header, field)) xhr.setRequestHeader(field, this.header[field]); + } + if (this._responseType) { + xhr.responseType = this._responseType; + } + + // send stuff + this.emit('request', this); + + // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) + // We need null here if data is undefined + xhr.send(typeof data === 'undefined' ? null : data); +}; +request.agent = () => new Agent(); +for (var _i = 0, _arr = ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE']; _i < _arr.length; _i++) { + const method = _arr[_i]; + Agent.prototype[method.toLowerCase()] = function (url, fn) { + const request_ = new request.Request(method, url); + this._setDefaults(request_); + if (fn) { + request_.end(fn); + } + return request_; + }; } +Agent.prototype.del = Agent.prototype.delete; -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.s = 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; +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.get = (url, data, fn) => { + const request_ = request('GET', url); + if (typeof data === 'function') { + fn = data; + data = null; } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} + if (data) request_.query(data); + if (fn) request_.end(fn); + return request_; +}; -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; +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.head = (url, data, fn) => { + const request_ = request('HEAD', url); + if (typeof data === 'function') { + fn = data; + data = null; } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; + if (data) request_.query(data); + if (fn) request_.end(fn); + return request_; }; -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; +/** + * OPTIONS query to `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ -// 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); +request.options = (url, data, fn) => { + const request_ = request('OPTIONS', url); + if (typeof data === 'function') { + fn = data; + data = null; } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; }; -// 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; -} +/** + * DELETE `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ -// 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; +function del(url, data, fn) { + const request_ = request('DELETE', url); + if (typeof data === 'function') { + fn = data; + data = null; } - return 0; + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; } +request.del = del; +request.delete = del; -// 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'; +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.patch = (url, data, fn) => { + const request_ = request('PATCH', url); + if (typeof data === 'function') { + fn = data; + data = null; } - 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'; - } - } + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; +}; + +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.post = (url, data, fn) => { + const request_ = request('POST', url); + if (typeof data === 'function') { + fn = data; + data = null; } -} + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; +}; -// 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); +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.put = (url, data, fn) => { + const request_ = request('PUT', url); + if (typeof data === 'function') { + fn = data; + data = null; } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJyb290Iiwid2luZG93Iiwic2VsZiIsImNvbnNvbGUiLCJ3YXJuIiwiRW1pdHRlciIsInJlcXVpcmUiLCJzYWZlU3RyaW5naWZ5IiwicXMiLCJSZXF1ZXN0QmFzZSIsIl9yZXF1aXJlIiwiaXNPYmplY3QiLCJtaXhpbiIsImhhc093biIsIlJlc3BvbnNlQmFzZSIsIkFnZW50Iiwibm9vcCIsIm1vZHVsZSIsImV4cG9ydHMiLCJtZXRob2QiLCJ1cmwiLCJSZXF1ZXN0IiwiZW5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O0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTdELE9BQU8sQ0FBQytLLEdBQUcsR0FBRyxDQUFDcEwsR0FBRyxFQUFFb0osSUFBSSxFQUFFekIsRUFBRSxLQUFLO0VBQy9CLE1BQU16RCxRQUFRLEdBQUc3RCxPQUFPLENBQUMsS0FBSyxFQUFFTCxHQUFHLENBQUM7RUFDcEMsSUFBSSxPQUFPb0osSUFBSSxLQUFLLFVBQVUsRUFBRTtJQUM5QnpCLEVBQUUsR0FBR3lCLElBQUk7SUFDVEEsSUFBSSxHQUFHLElBQUk7RUFDYjtFQUVBLElBQUlBLElBQUksRUFBRWxGLFFBQVEsQ0FBQ3dHLElBQUksQ0FBQ3RCLElBQUksQ0FBQztFQUM3QixJQUFJekIsRUFBRSxFQUFFekQsUUFBUSxDQUFDaEUsR0FBRyxDQUFDeUgsRUFBRSxDQUFDO0VBQ3hCLE9BQU96RCxRQUFRO0FBQ2pCLENBQUMifQ== -// 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; -} +/***/ 31948: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -// 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); -} +"use strict"; +/* provided dependency */ var process = __webpack_require__(65606); -// 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); -} +const semver = __webpack_require__(22623); -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; -} +/** + * Module of mixed-in functions shared between node and client code + */ +const _require = __webpack_require__(33048), + isObject = _require.isObject, + hasOwn = _require.hasOwn; -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} +/** + * Expose `RequestBase`. + */ + +module.exports = RequestBase; + +/** + * Initialize a new `RequestBase`. + * + * @api public + */ + +function RequestBase() {} + +/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.clearTimeout = function () { + clearTimeout(this._timer); + clearTimeout(this._responseTimeoutTimer); + clearTimeout(this._uploadTimeoutTimer); + delete this._timer; + delete this._responseTimeoutTimer; + delete this._uploadTimeoutTimer; + return this; +}; + +/** + * Override default response body parser + * + * This function will be called to convert incoming data into request.body + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.parse = function (fn) { + this._parser = fn; + return this; +}; + +/** + * Set format of binary response body. + * In browser valid formats are 'blob' and 'arraybuffer', + * which return Blob and ArrayBuffer, respectively. + * + * In Node all values result in Buffer. + * + * Examples: + * + * req.get('/') + * .responseType('blob') + * .end(callback); + * + * @param {String} val + * @return {Request} for chaining + * @api public + */ -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} +RequestBase.prototype.responseType = function (value) { + this._responseType = value; + return this; +}; -/***/ }), +/** + * Override default request body serializer + * + * This function will be called to convert data set via .send or .attach into payload to send + * + * @param {Function} + * @api public + */ -/***/ 37903: -/***/ ((module) => { +RequestBase.prototype.serialize = function (fn) { + this._serializer = fn; + return this; +}; -function Agent() { - this._defaults = []; -} +/** + * Set timeouts. + * + * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time. + * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections. + * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off + * + * Value of 0 or false means no timeout. + * + * @param {Number|Object} ms or {response, deadline} + * @return {Request} for chaining + * @api public + */ -["use", "on", "once", "set", "query", "type", "accept", "auth", "withCredentials", "sortQuery", "retry", "ok", "redirects", - "timeout", "buffer", "serialize", "parse", "ca", "key", "pfx", "cert"].forEach(function(fn) { - /** Default setting for all requests from this agent */ - Agent.prototype[fn] = function(/*varargs*/) { - this._defaults.push({fn:fn, arguments:arguments}); +RequestBase.prototype.timeout = function (options) { + if (!options || typeof options !== 'object') { + this._timeout = options; + this._responseTimeout = 0; + this._uploadTimeout = 0; return this; } -}); + for (const option in options) { + if (hasOwn(options, option)) { + switch (option) { + case 'deadline': + this._timeout = options.deadline; + break; + case 'response': + this._responseTimeout = options.response; + break; + case 'upload': + this._uploadTimeout = options.upload; + break; + default: + console.warn('Unknown timeout option', option); + } + } + } + return this; +}; -Agent.prototype._setDefaults = function(req) { - this._defaults.forEach(function(def) { - req[def.fn].apply(req, def.arguments); - }); +/** + * Set number of retry attempts on error. + * + * Failed requests will be retried 'count' times if timeout or err.code >= 500. + * + * @param {Number} count + * @param {Function} [fn] + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.retry = function (count, fn) { + // Default to 1 if no count passed or true + if (arguments.length === 0 || count === true) count = 1; + if (count <= 0) count = 0; + this._maxRetries = count; + this._retries = 0; + this._retryCallback = fn; + return this; }; -module.exports = Agent; +// +// NOTE: we do not include ESOCKETTIMEDOUT because that is from `request` package +// +// +// NOTE: we do not include EADDRINFO because it was removed from libuv in 2014 +// +// +// +// +// TODO: expose these as configurable defaults +// +const ERROR_CODES = new Set(['ETIMEDOUT', 'ECONNRESET', 'EADDRINUSE', 'ECONNREFUSED', 'EPIPE', 'ENOTFOUND', 'ENETUNREACH', 'EAI_AGAIN']); +const STATUS_CODES = new Set([408, 413, 429, 500, 502, 503, 504, 521, 522, 524]); +// TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) +// const METHODS = new Set(['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE']); -/***/ }), +/** + * Determine if a request should be retried. + * (Inspired by https://github.com/sindresorhus/got#retry) + * + * @param {Error} err an error + * @param {Response} [res] response + * @returns {Boolean} if segment should be retried + */ +RequestBase.prototype._shouldRetry = function (error, res) { + if (!this._maxRetries || this._retries++ >= this._maxRetries) { + return false; + } + if (this._retryCallback) { + try { + const override = this._retryCallback(error, res); + if (override === true) return true; + if (override === false) return false; + // undefined falls back to defaults + } catch (err) { + console.error(err); + } + } -/***/ 80569: -/***/ (function(module, exports, __webpack_require__) { + // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) + /* + if ( + this.req && + this.req.method && + !METHODS.has(this.req.method.toUpperCase()) + ) + return false; + */ + if (res && res.status && STATUS_CODES.has(res.status)) return true; + if (error) { + if (error.code && ERROR_CODES.has(error.code)) return true; + // Superagent timeout + if (error.timeout && error.code === 'ECONNABORTED') return true; + if (error.crossDomain) return true; + } + return false; +}; /** - * Root reference for iframes. + * Retry request + * + * @return {Request} for chaining + * @api private */ -var root; -if (typeof window !== 'undefined') { // Browser window - root = window; -} else if (typeof self !== 'undefined') { // Web Worker - root = self; -} else { // Other environments - console.warn("Using browser-only version of superagent in non-browser environment"); - root = this; -} +RequestBase.prototype._retry = function () { + this.clearTimeout(); -var Emitter = __webpack_require__(98767); -var RequestBase = __webpack_require__(28899); -var isObject = __webpack_require__(54960); -var ResponseBase = __webpack_require__(81097); -var Agent = __webpack_require__(37903); + // node + if (this.req) { + this.req = null; + this.req = this.request(); + } + this._aborted = false; + this.timedout = false; + this.timedoutError = null; + return this._end(); +}; /** - * Noop. + * Promise support + * + * @param {Function} resolve + * @param {Function} [reject] + * @return {Request} */ -function noop(){}; +RequestBase.prototype.then = function (resolve, reject) { + if (!this._fullfilledPromise) { + const self = this; + if (this._endCalled) { + console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises'); + } + this._fullfilledPromise = new Promise((resolve, reject) => { + self.on('abort', () => { + if (this._maxRetries && this._maxRetries > this._retries) { + return; + } + if (this.timedout && this.timedoutError) { + reject(this.timedoutError); + return; + } + const error = new Error('Aborted'); + error.code = 'ABORTED'; + error.status = this.status; + error.method = this.method; + error.url = this.url; + reject(error); + }); + self.end((error, res) => { + if (error) reject(error);else resolve(res); + }); + }); + } + return this._fullfilledPromise.then(resolve, reject); +}; +RequestBase.prototype.catch = function (callback) { + return this.then(undefined, callback); +}; /** - * Expose `request`. + * Allow for extension */ -var request = exports = module.exports = function(method, url) { - // callback - if ('function' == typeof url) { - return new exports.Request('GET', method).end(url); +RequestBase.prototype.use = function (fn) { + fn(this); + return this; +}; +RequestBase.prototype.ok = function (callback) { + if (typeof callback !== 'function') throw new Error('Callback required'); + this._okCallback = callback; + return this; +}; +RequestBase.prototype._isResponseOK = function (res) { + if (!res) { + return false; } - - // url first - if (1 == arguments.length) { - return new exports.Request('GET', method); + if (this._okCallback) { + return this._okCallback(res); } - - return new exports.Request(method, url); -} - -exports.Request = Request; + return res.status >= 200 && res.status < 300; +}; /** - * Determine XHR. + * Get request header `field`. + * Case-insensitive. + * + * @param {String} field + * @return {String} + * @api public */ -request.getXHR = function () { - if (root.XMLHttpRequest - && (!root.location || 'file:' != root.location.protocol - || !root.ActiveXObject)) { - return new XMLHttpRequest; - } else { - try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} - try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} - try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} - try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} - } - throw Error("Browser-only version of superagent could not find XHR"); +RequestBase.prototype.get = function (field) { + return this._header[field.toLowerCase()]; }; /** - * Removes leading and trailing whitespace, added to support IE. + * Get case-insensitive header `field` value. + * This is a deprecated internal API. Use `.get(field)` instead. * - * @param {String} s + * (getHeader is no longer used internally by the superagent code base) + * + * @param {String} field * @return {String} * @api private + * @deprecated */ -var trim = ''.trim - ? function(s) { return s.trim(); } - : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; +RequestBase.prototype.getHeader = RequestBase.prototype.get; /** - * Serialize the given `obj`. + * Set header `field` to `val`, or multiple fields with one object. + * Case-insensitive. * - * @param {Object} obj - * @return {String} - * @api private + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public */ -function serialize(obj) { - if (!isObject(obj)) return obj; - var pairs = []; - for (var key in obj) { - pushEncodedKeyValuePair(pairs, key, obj[key]); +RequestBase.prototype.set = function (field, value) { + if (isObject(field)) { + for (const key in field) { + if (hasOwn(field, key)) this.set(key, field[key]); + } + return this; } - return pairs.join('&'); -} + this._header[field.toLowerCase()] = value; + this.header[field] = value; + return this; +}; /** - * Helps 'serialize' with serializing arrays. - * Mutates the pairs array. + * Remove header `field`. + * Case-insensitive. * - * @param {Array} pairs - * @param {String} key - * @param {Mixed} val + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field field name */ +RequestBase.prototype.unset = function (field) { + delete this._header[field.toLowerCase()]; + delete this.header[field]; + return this; +}; -function pushEncodedKeyValuePair(pairs, key, val) { - if (val != null) { - if (Array.isArray(val)) { - val.forEach(function(v) { - pushEncodedKeyValuePair(pairs, key, v); - }); - } else if (isObject(val)) { - for(var subkey in val) { - pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]); - } - } else { - pairs.push(encodeURIComponent(key) - + '=' + encodeURIComponent(val)); +/** + * Write the field `name` and `val`, or multiple fields with one object + * for "multipart/form-data" request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * + * request.post('/upload') + * .field({ foo: 'bar', baz: 'qux' }) + * .end(callback); + * ``` + * + * @param {String|Object} name name of field + * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field + * @param {String} options extra options, e.g. 'blob' + * @return {Request} for chaining + * @api public + */ +RequestBase.prototype.field = function (name, value, options) { + // name should be either a string or an object. + if (name === null || undefined === name) { + throw new Error('.field(name, val) name can not be empty'); + } + if (this._data) { + throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"); + } + if (isObject(name)) { + for (const key in name) { + if (hasOwn(name, key)) this.field(key, name[key]); } - } else if (val === null) { - pairs.push(encodeURIComponent(key)); + return this; } -} - -/** - * Expose serialization method. - */ - -request.serializeObject = serialize; - -/** - * Parse the given x-www-form-urlencoded `str`. - * - * @param {String} str - * @return {Object} - * @api private - */ - -function parseString(str) { - var obj = {}; - var pairs = str.split('&'); - var pair; - var pos; - - for (var i = 0, len = pairs.length; i < len; ++i) { - pair = pairs[i]; - pos = pair.indexOf('='); - if (pos == -1) { - obj[decodeURIComponent(pair)] = ''; - } else { - obj[decodeURIComponent(pair.slice(0, pos))] = - decodeURIComponent(pair.slice(pos + 1)); + if (Array.isArray(value)) { + for (const i in value) { + if (hasOwn(value, i)) this.field(name, value[i]); } + return this; } - return obj; -} - -/** - * Expose parser. - */ + // val should be defined now + if (value === null || undefined === value) { + throw new Error('.field(name, val) val can not be empty'); + } + if (typeof value === 'boolean') { + value = String(value); + } -request.parseString = parseString; + // fix https://github.com/ladjs/superagent/issues/1680 + if (options) this._getFormData().append(name, value, options);else this._getFormData().append(name, value); + return this; +}; /** - * Default MIME type map. - * - * superagent.types.xml = 'application/xml'; + * Abort the request, and clear potential timeout. * + * @return {Request} request + * @api public */ +RequestBase.prototype.abort = function () { + if (this._aborted) { + return this; + } + this._aborted = true; + if (this.xhr) this.xhr.abort(); // browser + if (this.req) { + // Node v13 has major differences in `abort()` + // https://github.com/nodejs/node/blob/v12.x/lib/internal/streams/end-of-stream.js + // https://github.com/nodejs/node/blob/v13.x/lib/internal/streams/end-of-stream.js + // https://github.com/nodejs/node/blob/v14.x/lib/internal/streams/end-of-stream.js + // (if you run a diff across these you will see the differences) + // + // References: + // + // + // + // Thanks to @shadowgate15 and @niftylettuce + if (semver.gte(process.version, 'v13.0.0') && semver.lt(process.version, 'v14.0.0')) { + // Note that the reason this doesn't work is because in v13 as compared to v14 + // there is no `callback = nop` set in end-of-stream.js above + throw new Error('Superagent does not work in v13 properly with abort() due to Node.js core changes'); + } + this.req.abort(); // node + } -request.types = { - html: 'text/html', - json: 'application/json', - xml: 'text/xml', - urlencoded: 'application/x-www-form-urlencoded', - 'form': 'application/x-www-form-urlencoded', - 'form-data': 'application/x-www-form-urlencoded' + this.clearTimeout(); + this.emit('abort'); + return this; +}; +RequestBase.prototype._auth = function (user, pass, options, base64Encoder) { + switch (options.type) { + case 'basic': + this.set('Authorization', `Basic ${base64Encoder(`${user}:${pass}`)}`); + break; + case 'auto': + this.username = user; + this.password = pass; + break; + case 'bearer': + // usage would be .auth(accessToken, { type: 'bearer' }) + this.set('Authorization', `Bearer ${user}`); + break; + default: + break; + } + return this; }; /** - * Default serialization map. - * - * superagent.serialize['application/xml'] = function(obj){ - * return 'generated xml here'; - * }; + * Enable transmission of cookies with x-domain requests. * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * @param {Boolean} [on=true] - Set 'withCredentials' state + * @return {Request} for chaining + * @api public */ -request.serialize = { - 'application/x-www-form-urlencoded': serialize, - 'application/json': JSON.stringify +RequestBase.prototype.withCredentials = function (on) { + // This is browser-only functionality. Node side is no-op. + if (on === undefined) on = true; + this._withCredentials = on; + return this; }; /** - * Default parsers. - * - * superagent.parse['application/xml'] = function(str){ - * return { object parsed from str }; - * }; - * - */ + * Set the max redirects to `n`. Does nothing in browser XHR implementation. + * + * @param {Number} n + * @return {Request} for chaining + * @api public + */ -request.parse = { - 'application/x-www-form-urlencoded': parseString, - 'application/json': JSON.parse +RequestBase.prototype.redirects = function (n) { + this._maxRedirects = n; + return this; }; /** - * Parse the given header `str` into - * an object containing the mapped fields. + * Maximum size of buffered response body, in bytes. Counts uncompressed size. + * Default 200MB. * - * @param {String} str - * @return {Object} - * @api private + * @param {Number} n number of bytes + * @return {Request} for chaining */ - -function parseHeader(str) { - var lines = str.split(/\r?\n/); - var fields = {}; - var index; - var line; - var field; - var val; - - for (var i = 0, len = lines.length; i < len; ++i) { - line = lines[i]; - index = line.indexOf(':'); - if (index === -1) { // could be empty line, just skip it - continue; - } - field = line.slice(0, index).toLowerCase(); - val = trim(line.slice(index + 1)); - fields[field] = val; +RequestBase.prototype.maxResponseSize = function (n) { + if (typeof n !== 'number') { + throw new TypeError('Invalid argument'); } - - return fields; -} + this._maxResponseSize = n; + return this; +}; /** - * Check if `mime` is json or has +json structured syntax suffix. + * Convert to a plain javascript object (not JSON string) of scalar properties. + * Note as this method is designed to return a useful non-this value, + * it cannot be chained. * - * @param {String} mime - * @return {Boolean} - * @api private + * @return {Object} describing method, url, and data of this request + * @api public */ -function isJSON(mime) { - // should match /json or +json - // but not /json-seq - return /[\/+]json($|[^-\w])/.test(mime); -} +RequestBase.prototype.toJSON = function () { + return { + method: this.method, + url: this.url, + data: this._data, + headers: this._header + }; +}; /** - * Initialize a new `Response` with the given `xhr`. - * - * - set flags (.ok, .error, etc) - * - parse header + * Send `data` as the request body, defaulting the `.type()` to "json" when + * an object is given. * * Examples: * - * Aliasing `superagent` as `request` is nice: + * // manual json + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}') + * .end(callback) * - * request = superagent; + * // auto json + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) * - * We can use the promise-like API, or pass callbacks: + * // manual x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) * - * request.get('/').end(function(res){}); - * request.get('/', function(res){}); + * // auto x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) * - * Sending data can be chained: + * // defaults to x-www-form-urlencoded + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) * - * request - * .post('/user') - * .send({ name: 'tj' }) - * .end(function(res){}); + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ + +// eslint-disable-next-line complexity +RequestBase.prototype.send = function (data) { + const isObject_ = isObject(data); + let type = this._header['content-type']; + if (this._formData) { + throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"); + } + if (isObject_ && !this._data) { + if (Array.isArray(data)) { + this._data = []; + } else if (!this._isHost(data)) { + this._data = {}; + } + } else if (data && this._data && this._isHost(this._data)) { + throw new Error("Can't merge these send calls"); + } + + // merge + if (isObject_ && isObject(this._data)) { + for (const key in data) { + if (typeof data[key] == 'bigint' && !data[key].toJSON) throw new Error('Cannot serialize BigInt value to json'); + if (hasOwn(data, key)) this._data[key] = data[key]; + } + } else if (typeof data === 'bigint') throw new Error("Cannot send value of type BigInt");else if (typeof data === 'string') { + // default to x-www-form-urlencoded + if (!type) this.type('form'); + type = this._header['content-type']; + if (type) type = type.toLowerCase().trim(); + if (type === 'application/x-www-form-urlencoded') { + this._data = this._data ? `${this._data}&${data}` : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + if (!isObject_ || this._isHost(data)) { + return this; + } + + // default to json + if (!type) this.type('json'); + return this; +}; + +/** + * Sort `querystring` by the sort function * - * Or passed to `.send()`: * - * request - * .post('/user') - * .send({ name: 'tj' }, function(res){}); + * Examples: * - * Or passed to `.post()`: + * // default order + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery() + * .end(callback) * - * request - * .post('/user', { name: 'tj' }) - * .end(function(res){}); + * // customized sort function + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery(function(a, b){ + * return a.length - b.length; + * }) + * .end(callback) * - * Or further reduced to a single call for simple cases: * - * request - * .post('/user', { name: 'tj' }, function(res){}); + * @param {Function} sort + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.sortQuery = function (sort) { + // _sort default to true but otherwise can be a function or boolean + this._sort = typeof sort === 'undefined' ? true : sort; + return this; +}; + +/** + * Compose querystring to append to req.url * - * @param {XMLHTTPRequest} xhr - * @param {Object} options * @api private */ - -function Response(req) { - this.req = req; - this.xhr = this.req.xhr; - // responseText is accessible only if responseType is '' or 'text' and on older browsers - this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') - ? this.xhr.responseText - : null; - this.statusText = this.req.xhr.statusText; - var status = this.xhr.status; - // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request - if (status === 1223) { - status = 204; +RequestBase.prototype._finalizeQueryString = function () { + const query = this._query.join('&'); + if (query) { + this.url += (this.url.includes('?') ? '&' : '?') + query; } - this._setStatusProperties(status); - this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); - // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but - // getResponseHeader still works. so we get content-type even if getting - // other headers fails. - this.header['content-type'] = this.xhr.getResponseHeader('content-type'); - this._setHeaderProperties(this.header); + this._query.length = 0; // Makes the call idempotent - if (null === this.text && req._responseType) { - this.body = this.xhr.response; - } else { - this.body = this.req.method != 'HEAD' - ? this._parseBody(this.text ? this.text : this.xhr.response) - : null; + if (this._sort) { + const index = this.url.indexOf('?'); + if (index >= 0) { + const queryArray = this.url.slice(index + 1).split('&'); + if (typeof this._sort === 'function') { + queryArray.sort(this._sort); + } else { + queryArray.sort(); + } + this.url = this.url.slice(0, index) + '?' + queryArray.join('&'); + } } -} +}; -ResponseBase(Response.prototype); +// For backwards compat only +RequestBase.prototype._appendQueryString = () => { + console.warn('Unsupported'); +}; /** - * Parse the given body `str`. - * - * Used for auto-parsing of bodies. Parsers - * are defined on the `superagent.parse` object. + * Invoke callback with timeout error. * - * @param {String} str - * @return {Mixed} * @api private */ -Response.prototype._parseBody = function(str) { - var parse = request.parse[this.type]; - if (this.req._parser) { - return this.req._parser(this, str); +RequestBase.prototype._timeoutError = function (reason, timeout, errno) { + if (this._aborted) { + return; } - if (!parse && isJSON(this.type)) { - parse = request.parse['application/json']; + const error = new Error(`${reason + timeout}ms exceeded`); + error.timeout = timeout; + error.code = 'ECONNABORTED'; + error.errno = errno; + this.timedout = true; + this.timedoutError = error; + this.abort(); + this.callback(error); +}; +RequestBase.prototype._setTimeouts = function () { + const self = this; + + // deadline + if (this._timeout && !this._timer) { + this._timer = setTimeout(() => { + self._timeoutError('Timeout of ', self._timeout, 'ETIME'); + }, this._timeout); + } + + // response timeout + if (this._responseTimeout && !this._responseTimeoutTimer) { + this._responseTimeoutTimer = setTimeout(() => { + self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT'); + }, this._responseTimeout); } - return parse && str && (str.length || str instanceof Object) - ? parse(str) - : null; }; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJzZW12ZXIiLCJyZXF1aXJlIiwiX3JlcXVpcmUiLC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yxHQUFHQSxLQUFLO0VBQ25CLElBQUksQ0FBQ3JGLFFBQVEsR0FBRyxJQUFJO0VBQ3BCLElBQUksQ0FBQ0MsYUFBYSxHQUFHYixLQUFLO0VBQzFCLElBQUksQ0FBQ21ELEtBQUssQ0FBQyxDQUFDO0VBQ1osSUFBSSxDQUFDdkIsUUFBUSxDQUFDNUIsS0FBSyxDQUFDO0FBQ3RCLENBQUM7QUFFRHBDLFdBQVcsQ0FBQ0MsU0FBUyxDQUFDcUksWUFBWSxHQUFHLFlBQVk7RUFDL0MsTUFBTS9FLElBQUksR0FBRyxJQUFJOztFQUVqQjtFQUNBLElBQUksSUFBSSxDQUFDdkMsUUFBUSxJQUFJLENBQUMsSUFBSSxDQUFDYixNQUFNLEVBQUU7SUFDakMsSUFBSSxDQUFDQSxNQUFNLEdBQUdvSSxVQUFVLENBQUMsTUFBTTtNQUM3QmhGLElBQUksQ0FBQzRFLGFBQWEsQ0FBQyxhQUFhLEVBQUU1RSxJQUFJLENBQUN2QyxRQUFRLEVBQUUsT0FBTyxDQUFDO0lBQzNELENBQUMsRUFBRSxJQUFJLENBQUNBLFFBQVEsQ0FBQztFQUNuQjs7RUFFQTtFQUNBLElBQUksSUFBSSxDQUFDQyxnQkFBZ0IsSUFBSSxDQUFDLElBQUksQ0FBQ2IscUJBQXFCLEVBQUU7SUFDeEQsSUFBSSxDQUFDQSxxQkFBcUIsR0FBR21JLFVBQVUsQ0FBQyxNQUFNO01BQzVDaEYsSUFBSSxDQUFDNEUsYUFBYSxDQUNoQixzQkFBc0IsRUFDdEI1RSxJQUFJLENBQUN0QyxnQkFBZ0IsRUFDckIsV0FDRixDQUFDO0lBQ0gsQ0FBQyxFQUFFLElBQUksQ0FBQ0EsZ0JBQWdCLENBQUM7RUFDM0I7QUFDRixDQUFDIn0= -/** - * Return an `Error` representative of this response. - * - * @return {Error} - * @api public - */ +/***/ }), -Response.prototype.toError = function(){ - var req = this.req; - var method = req.method; - var url = req.url; +/***/ 19450: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; - var err = new Error(msg); - err.status = this.status; - err.method = method; - err.url = url; +"use strict"; - return err; -}; /** - * Expose `Response`. + * Module dependencies. */ -request.Response = Response; +const utils = __webpack_require__(33048); /** - * Initialize a new `Request` with the given `method` and `url`. - * - * @param {String} method - * @param {String} url - * @api public + * Expose `ResponseBase`. */ -function Request(method, url) { - var self = this; - this._query = this._query || []; - this.method = method; - this.url = url; - this.header = {}; // preserves header name case - this._header = {}; // coerces header names to lowercase - this.on('end', function(){ - var err = null; - var res = null; - - try { - res = new Response(self); - } catch(e) { - err = new Error('Parser is unable to parse the response'); - err.parse = true; - err.original = e; - // issue #675: return the raw response if the response parsing fails - if (self.xhr) { - // ie9 doesn't have 'response' property - err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response; - // issue #876: return the http status code if the response parsing fails - err.status = self.xhr.status ? self.xhr.status : null; - err.statusCode = err.status; // backwards-compat only - } else { - err.rawResponse = null; - err.status = null; - } - - return self.callback(err); - } - - self.emit('response', res); - - var new_err; - try { - if (!self._isResponseOK(res)) { - new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); - } - } catch(custom_err) { - new_err = custom_err; // ok() callback can throw - } - - // #1000 don't catch errors from the callback to avoid double calling it - if (new_err) { - new_err.original = err; - new_err.response = res; - new_err.status = res.status; - self.callback(new_err, res); - } else { - self.callback(null, res); - } - }); -} +module.exports = ResponseBase; /** - * Mixin `Emitter` and `RequestBase`. + * Initialize a new `ResponseBase`. + * + * @api public */ -Emitter(Request.prototype); -RequestBase(Request.prototype); +function ResponseBase() {} /** - * Set Content-Type to `type`, mapping values from `request.types`. - * - * Examples: - * - * superagent.types.xml = 'application/xml'; - * - * request.post('/') - * .type('xml') - * .send(xmlstring) - * .end(callback); - * - * request.post('/') - * .type('application/xml') - * .send(xmlstring) - * .end(callback); + * Get case-insensitive `field` value. * - * @param {String} type - * @return {Request} for chaining + * @param {String} field + * @return {String} * @api public */ -Request.prototype.type = function(type){ - this.set('Content-Type', request.types[type] || type); - return this; +ResponseBase.prototype.get = function (field) { + return this.header[field.toLowerCase()]; }; /** - * Set Accept to `type`, mapping values from `request.types`. - * - * Examples: - * - * superagent.types.json = 'application/json'; + * Set header related properties: * - * request.get('/agent') - * .accept('json') - * .end(callback); + * - `.type` the content type without params * - * request.get('/agent') - * .accept('application/json') - * .end(callback); + * A response of "Content-Type: text/plain; charset=utf-8" + * will provide you with a `.type` of "text/plain". * - * @param {String} accept - * @return {Request} for chaining - * @api public + * @param {Object} header + * @api private */ -Request.prototype.accept = function(type){ - this.set('Accept', request.types[type] || type); - return this; -}; +ResponseBase.prototype._setHeaderProperties = function (header) { + // TODO: moar! + // TODO: make this a util -/** - * Set Authorization field value with `user` and `pass`. - * - * @param {String} user - * @param {String} [pass] optional in case of using 'bearer' as type - * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic') - * @return {Request} for chaining - * @api public - */ + // content-type + const ct = header['content-type'] || ''; + this.type = utils.type(ct); -Request.prototype.auth = function(user, pass, options){ - if (1 === arguments.length) pass = ''; - if (typeof pass === 'object' && pass !== null) { // pass is optional and can be replaced with options - options = pass; - pass = ''; - } - if (!options) { - options = { - type: 'function' === typeof btoa ? 'basic' : 'auto', - }; + // params + const parameters = utils.params(ct); + for (const key in parameters) { + if (Object.prototype.hasOwnProperty.call(parameters, key)) this[key] = parameters[key]; } + this.links = {}; - var encoder = function(string) { - if ('function' === typeof btoa) { - return btoa(string); + // links + try { + if (header.link) { + this.links = utils.parseLinks(header.link); } - throw new Error('Cannot use basic auth, btoa is not a function'); - }; - - return this._auth(user, pass, options, encoder); + } catch (err) { + // ignore + } }; /** - * Add query-string `val`. + * Set flags such as `.ok` based on `status`. * - * Examples: + * For example a 2xx response will give you a `.ok` of __true__ + * whereas 5xx will be __false__ and `.error` will be __true__. The + * `.clientError` and `.serverError` are also available to be more + * specific, and `.statusType` is the class of error ranging from 1..5 + * sometimes useful for mapping respond colors etc. * - * request.get('/shoes') - * .query('size=10') - * .query({ color: 'blue' }) + * "sugar" properties are also defined for common cases. Currently providing: * - * @param {Object|String} val - * @return {Request} for chaining - * @api public + * - .noContent + * - .badRequest + * - .unauthorized + * - .notAcceptable + * - .notFound + * + * @param {Number} status + * @api private */ -Request.prototype.query = function(val){ - if ('string' != typeof val) val = serialize(val); - if (val) this._query.push(val); - return this; -}; +ResponseBase.prototype._setStatusProperties = function (status) { + const type = Math.trunc(status / 100); + + // status / class + this.statusCode = status; + this.status = this.statusCode; + this.statusType = type; + + // basics + this.info = type === 1; + this.ok = type === 2; + this.redirect = type === 3; + this.clientError = type === 4; + this.serverError = type === 5; + this.error = type === 4 || type === 5 ? this.toError() : false; + + // sugar + this.created = status === 201; + this.accepted = status === 202; + this.noContent = status === 204; + this.badRequest = status === 400; + this.unauthorized = status === 401; + this.notAcceptable = status === 406; + this.forbidden = status === 403; + this.notFound = status === 404; + this.unprocessableEntity = status === 422; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJ1dGlscyIsInJlcXVpcmUiLCJtb2R1bGUiLCJleHBvcnRzIiwiUmVzcG9uc2VCYXNlIiwicHJvdG90eXBlIiwiZ2V0IiwiZmllbGQiLCJoZWFkZXIiLCJ0b0xvd2VyQ2FzZSIsIl9zZXRIZWFkZXJQcm9wZXJ0aWVzIiwiY3QiLCJ0eXBlIiwicGFyYW1ldGVycyIsInBhcmFtcyIsImtleSIsIk9iamVjdCIsImhhc093blByb3BlcnR5IiwiY2FsbCIsImxpbmtzIiwibGluayIsInBhcnNlTGlua3MiLCJlcnIiLCJfc2V0U3RhdHVzUHJvcGVydGllcyIsInN0YXR1cyIsIk1hdGgiLCJ0cnVuYyIsInN0YXR1c0NvZGUiLCJzdGF0dXNUeXBlIiwiaW5mbyIsIm9rIiwicmVkaXJlY3QiLCJjbGllbnRFcnJvciIsInNlc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yxHQUFHZCxNQUFNLEtBQUssR0FBRztFQUMvQixJQUFJLENBQUNlLFVBQVUsR0FBR2YsTUFBTSxLQUFLLEdBQUc7RUFDaEMsSUFBSSxDQUFDZ0IsWUFBWSxHQUFHaEIsTUFBTSxLQUFLLEdBQUc7RUFDbEMsSUFBSSxDQUFDaUIsYUFBYSxHQUFHakIsTUFBTSxLQUFLLEdBQUc7RUFDbkMsSUFBSSxDQUFDa0IsU0FBUyxHQUFHbEIsTUFBTSxLQUFLLEdBQUc7RUFDL0IsSUFBSSxDQUFDbUIsUUFBUSxHQUFHbkIsTUFBTSxLQUFLLEdBQUc7RUFDOUIsSUFBSSxDQUFDb0IsbUJBQW1CLEdBQUdwQixNQUFNLEtBQUssR0FBRztBQUMzQyxDQUFDIn0= + +/***/ }), + +/***/ 33048: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } /** - * Queue the given `file` as an attachment to the specified `field`, - * with optional `options` (or filename). + * Return the mime type for the given `str`. * - * ``` js - * request.post('/upload') - * .attach('content', new Blob(['hey!'], { type: "text/html"})) - * .end(callback); - * ``` + * @param {String} str + * @return {String} + * @api private + */ + +exports.type = string_ => string_.split(/ *; */).shift(); + +/** + * Return header field parameters. * - * @param {String} field - * @param {Blob|File} file - * @param {String|Object} options - * @return {Request} for chaining - * @api public + * @param {String} str + * @return {Object} + * @api private */ -Request.prototype.attach = function(field, file, options){ - if (file) { - if (this._data) { - throw Error("superagent can't mix .send() and .attach()"); +exports.params = value => { + const object = {}; + var _iterator = _createForOfIteratorHelper(value.split(/ *; */)), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + const string_ = _step.value; + const parts = string_.split(/ *= */); + const key = parts.shift(); + const value = parts.shift(); + if (key && value) object[key] = value; } - - this._getFormData().append(field, file, options || file.name); + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); } - return this; + return object; }; -Request.prototype._getFormData = function(){ - if (!this._formData) { - this._formData = new root.FormData(); +/** + * Parse Link header fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +exports.parseLinks = value => { + const object = {}; + var _iterator2 = _createForOfIteratorHelper(value.split(/ *, */)), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + const string_ = _step2.value; + const parts = string_.split(/ *; */); + const url = parts[0].slice(1, -1); + const rel = parts[1].split(/ *= */)[1].slice(1, -1); + object[rel] = url; + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); } - return this._formData; + return object; }; /** - * Invoke the callback with `err` and `res` - * and handle arity check. + * Strip content related fields from `header`. * - * @param {Error} err - * @param {Response} res + * @param {Object} header + * @return {Object} header * @api private */ -Request.prototype.callback = function(err, res){ - if (this._shouldRetry(err, res)) { - return this._retry(); - } - - var fn = this._callback; - this.clearTimeout(); - - if (err) { - if (this._maxRetries) err.retries = this._retries - 1; - this.emit('error', err); +exports.cleanHeader = (header, changesOrigin) => { + delete header['content-type']; + delete header['content-length']; + delete header['transfer-encoding']; + delete header.host; + // secuirty + if (changesOrigin) { + delete header.authorization; + delete header.cookie; } - - fn(err, res); + return header; }; /** - * Invoke callback with x-domain error. + * Check if `obj` is an object. * + * @param {Object} object + * @return {Boolean} * @api private */ - -Request.prototype.crossDomainError = function(){ - var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); - err.crossDomain = true; - - err.status = this.status; - err.method = this.method; - err.url = this.url; - - this.callback(err); -}; - -// This only warns, because the request is still likely to work -Request.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){ - console.warn("This is not supported in browser version of superagent"); - return this; -}; - -// This throws, because it can't send/receive data as expected -Request.prototype.pipe = Request.prototype.write = function(){ - throw Error("Streaming is not supported in browser version of superagent"); +exports.isObject = object => { + return object !== null && typeof object === 'object'; }; /** - * Check if `obj` is a host object, - * we don't want to serialize these :) + * Object.hasOwn fallback/polyfill. * - * @param {Object} obj - * @return {Boolean} + * @type {(object: object, property: string) => boolean} object * @api private */ -Request.prototype._isHost = function _isHost(obj) { - // Native objects stringify to [object File], [object Blob], [object FormData], etc. - return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]'; -} +exports.hasOwn = Object.hasOwn || function (object, property) { + if (object == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + return Object.prototype.hasOwnProperty.call(new Object(object), property); +}; +exports.mixin = (target, source) => { + for (const key in source) { + if (exports.hasOwn(source, key)) { + target[key] = source[key]; + } + } +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJleHBvcnRz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SUFBSSxFQUFFO0lBQ2xCLE1BQU0sSUFBSTRCLFNBQVMsQ0FBQyw0Q0FBNEMsQ0FBQztFQUNuRTtFQUVBLE9BQU9GLE1BQU0sQ0FBQ0csU0FBUyxDQUFDQyxjQUFjLENBQUNDLElBQUksQ0FBQyxJQUFJTCxNQUFNLENBQUMxQixNQUFNLENBQUMsRUFBRTJCLFFBQVEsQ0FBQztBQUMzRSxDQUFDO0FBRUhsQyxPQUFPLENBQUN1QyxLQUFLLEdBQUcsQ0FBQ0MsTUFBTSxFQUFFQyxNQUFNLEtBQUs7RUFDbEMsS0FBSyxNQUFNMUIsR0FBRyxJQUFJMEIsTUFBTSxFQUFFO0lBQ3hCLElBQUl6QyxPQUFPLENBQUNnQyxNQUFNLENBQUNTLE1BQU0sRUFBRTFCLEdBQUcsQ0FBQyxFQUFFO01BQy9CeUIsTUFBTSxDQUFDekIsR0FBRyxDQUFDLEdBQUcwQixNQUFNLENBQUMxQixHQUFHLENBQUM7SUFDM0I7RUFDRjtBQUNGLENBQUMifQ== + +/***/ }), + +/***/ 54493: +/***/ ((module) => { /** - * Initiate request, invoking callback `fn(res)` - * with an instanceof `Response`. + * Copyright (c) 2014-present, Facebook, Inc. * - * @param {Function} fn - * @return {Request} for chaining - * @api public + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. */ -Request.prototype.end = function(fn){ - if (this._endCalled) { - console.warn("Warning: .end() was called twice. This is not supported in superagent"); - } - this._endCalled = true; +var runtime = (function (exports) { + "use strict"; - // store callback - this._callback = fn || noop; + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }; + var undefined; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - // querystring - this._finalizeQueryString(); + function define(obj, key, value) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + return obj[key]; + } + try { + // IE 8 has a broken Object.defineProperty that only works on DOM objects. + define({}, ""); + } catch (err) { + define = function(obj, key, value) { + return obj[key] = value; + }; + } - return this._end(); -}; + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); -Request.prototype._end = function() { - var self = this; - var xhr = (this.xhr = request.getXHR()); - var data = this._formData || this._data; + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }); - this._setTimeouts(); + return generator; + } + exports.wrap = wrap; - // state change - xhr.onreadystatechange = function(){ - var readyState = xhr.readyState; - if (readyState >= 2 && self._responseTimeoutTimer) { - clearTimeout(self._responseTimeoutTimer); - } - if (4 != readyState) { - return; + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; } + } - // In IE9, reads to any property (e.g. status) off of an aborted XHR will - // result in the error "Could not complete the operation due to error c00c023f" - var status; - try { status = xhr.status } catch(e) { status = 0; } + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; - if (!status) { - if (self.timedout || self._aborted) return; - return self.crossDomainError(); - } - self.emit('end'); + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + define(IteratorPrototype, iteratorSymbol, function () { + return this; + }); + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = GeneratorFunctionPrototype; + defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: true }); + defineProperty( + GeneratorFunctionPrototype, + "constructor", + { value: GeneratorFunction, configurable: true } + ); + GeneratorFunction.displayName = define( + GeneratorFunctionPrototype, + toStringTagSymbol, + "GeneratorFunction" + ); + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + define(prototype, method, function(arg) { + return this._invoke(method, arg); + }); + }); + } + + exports.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; }; - // progress - var handleProgress = function(direction, e) { - if (e.total > 0) { - e.percent = e.loaded / e.total * 100; + exports.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + define(genFun, toStringTagSymbol, "GeneratorFunction"); } - e.direction = direction; - self.emit('progress', e); + genFun.prototype = Object.create(Gp); + return genFun; }; - if (this.hasListeners('progress')) { - try { - xhr.onprogress = handleProgress.bind(null, 'download'); - if (xhr.upload) { - xhr.upload.onprogress = handleProgress.bind(null, 'upload'); + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + exports.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return PromiseImpl.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return PromiseImpl.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. + result.value = unwrapped; + resolve(result); + }, function(error) { + // If a rejected Promise was yielded, throw the rejection back + // into the async generator function so it can be handled there. + return invoke("throw", error, resolve, reject); + }); } - } catch(e) { - // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. - // Reported here: - // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context } - } - // initiate request - try { - if (this.username && this.password) { - xhr.open(this.method, this.url, true, this.username, this.password); - } else { - xhr.open(this.method, this.url, true); - } - } catch (err) { - // see #1149 - return this.callback(err); - } + var previousPromise; - // CORS - if (this._withCredentials) xhr.withCredentials = true; + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } - // body - if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) { - // serialize stuff - var contentType = this._header['content-type']; - var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; - if (!serialize && isJSON(contentType)) { - serialize = request.serialize['application/json']; + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); } - if (serialize) data = serialize(data); - } - - // set header fields - for (var field in this.header) { - if (null == this.header[field]) continue; - - if (this.header.hasOwnProperty(field)) - xhr.setRequestHeader(field, this.header[field]); - } - if (this._responseType) { - xhr.responseType = this._responseType; + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + defineProperty(this, "_invoke", { value: enqueue }); } - // send stuff - this.emit('request', this); + defineIteratorMethods(AsyncIterator.prototype); + define(AsyncIterator.prototype, asyncIteratorSymbol, function () { + return this; + }); + exports.AsyncIterator = AsyncIterator; - // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) - // We need null here if data is undefined - xhr.send(typeof data !== 'undefined' ? data : null); - return this; -}; + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { + if (PromiseImpl === void 0) PromiseImpl = Promise; -request.agent = function() { - return new Agent(); -}; + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList), + PromiseImpl + ); -["GET", "POST", "OPTIONS", "PATCH", "PUT", "DELETE"].forEach(function(method) { - Agent.prototype[method.toLowerCase()] = function(url, fn) { - var req = new request.Request(method, url); - this._setDefaults(req); - if (fn) { - req.end(fn); - } - return req; + return exports.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); }; -}); -Agent.prototype.del = Agent.prototype['delete']; + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; -/** - * GET `url` with optional callback `fn(res)`. - * - * @param {String} url - * @param {Mixed|Function} [data] or fn - * @param {Function} [fn] - * @return {Request} - * @api public - */ + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } -request.get = function(url, data, fn) { - var req = request('GET', url); - if ('function' == typeof data) (fn = data), (data = null); - if (data) req.query(data); - if (fn) req.end(fn); - return req; -}; + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } -/** - * HEAD `url` with optional callback `fn(res)`. - * - * @param {String} url - * @param {Mixed|Function} [data] or fn - * @param {Function} [fn] - * @return {Request} - * @api public - */ + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } -request.head = function(url, data, fn) { - var req = request('HEAD', url); - if ('function' == typeof data) (fn = data), (data = null); - if (data) req.query(data); - if (fn) req.end(fn); - return req; -}; + context.method = method; + context.arg = arg; -/** - * OPTIONS query to `url` with optional callback `fn(res)`. - * - * @param {String} url - * @param {Mixed|Function} [data] or fn - * @param {Function} [fn] - * @return {Request} - * @api public - */ + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } -request.options = function(url, data, fn) { - var req = request('OPTIONS', url); - if ('function' == typeof data) (fn = data), (data = null); - if (data) req.send(data); - if (fn) req.end(fn); - return req; -}; + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; -/** - * DELETE `url` with optional `data` and callback `fn(res)`. - * - * @param {String} url - * @param {Mixed} [data] - * @param {Function} [fn] - * @return {Request} - * @api public - */ + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } -function del(url, data, fn) { - var req = request('DELETE', url); - if ('function' == typeof data) (fn = data), (data = null); - if (data) req.send(data); - if (fn) req.end(fn); - return req; -} + context.dispatchException(context.arg); -request['del'] = del; -request['delete'] = del; + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } -/** - * PATCH `url` with optional `data` and callback `fn(res)`. - * - * @param {String} url - * @param {Mixed} [data] - * @param {Function} [fn] - * @return {Request} - * @api public - */ + state = GenStateExecuting; -request.patch = function(url, data, fn) { - var req = request('PATCH', url); - if ('function' == typeof data) (fn = data), (data = null); - if (data) req.send(data); - if (fn) req.end(fn); - return req; -}; + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; -/** - * POST `url` with optional `data` and callback `fn(res)`. - * - * @param {String} url - * @param {Mixed} [data] - * @param {Function} [fn] - * @return {Request} - * @api public - */ + if (record.arg === ContinueSentinel) { + continue; + } -request.post = function(url, data, fn) { - var req = request('POST', url); - if ('function' == typeof data) (fn = data), (data = null); - if (data) req.send(data); - if (fn) req.end(fn); - return req; -}; + return { + value: record.arg, + done: context.done + }; -/** - * PUT `url` with optional `data` and callback `fn(res)`. - * - * @param {String} url - * @param {Mixed|Function} [data] or fn - * @param {Function} [fn] - * @return {Request} - * @api public - */ + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } -request.put = function(url, data, fn) { - var req = request('PUT', url); - if ('function' == typeof data) (fn = data), (data = null); - if (data) req.send(data); - if (fn) req.end(fn); - return req; -}; + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var methodName = context.method; + var method = delegate.iterator[methodName]; + if (method === undefined) { + // A .throw or .return when the delegate iterator has no .throw + // method, or a missing .next mehtod, always terminate the + // yield* loop. + context.delegate = null; + // Note: ["return"] must be used for ES3 parsing compatibility. + if (methodName === "throw" && delegate.iterator["return"]) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined; + maybeInvokeDelegate(delegate, context); -/***/ }), + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + if (methodName !== "return") { + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a '" + methodName + "' method"); + } -/***/ 54960: -/***/ ((module) => { + return ContinueSentinel; + } -"use strict"; + var record = tryCatch(method, delegate.iterator, context.arg); + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } -/** - * Check if `obj` is an object. - * - * @param {Object} obj - * @return {Boolean} - * @api private - */ + var info = record.arg; -function isObject(obj) { - return null !== obj && 'object' === typeof obj; -} + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; -module.exports = isObject; + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined; + } + } else { + // Re-yield the result returned by the delegate method. + return info; + } -/***/ }), + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } -/***/ 28899: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); -"use strict"; + define(Gp, toStringTagSymbol, "Generator"); + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + define(Gp, iteratorSymbol, function() { + return this; + }); -/** - * Module of mixed-in functions shared between node and client code - */ -var isObject = __webpack_require__(54960); + define(Gp, "toString", function() { + return "[object Generator]"; + }); -/** - * Expose `RequestBase`. - */ + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; -module.exports = RequestBase; + if (1 in locs) { + entry.catchLoc = locs[1]; + } -/** - * Initialize a new `RequestBase`. - * - * @api public - */ + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } -function RequestBase(obj) { - if (obj) return mixin(obj); -} + this.tryEntries.push(entry); + } -/** - * Mixin the prototype properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } -function mixin(obj) { - for (var key in RequestBase.prototype) { - obj[key] = RequestBase.prototype[key]; + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); } - return obj; -} -/** - * Clear previous timeout. - * - * @return {Request} for chaining - * @api public - */ + exports.keys = function(val) { + var object = Object(val); + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); -RequestBase.prototype.clearTimeout = function _clearTimeout(){ - clearTimeout(this._timer); - clearTimeout(this._responseTimeoutTimer); - delete this._timer; - delete this._responseTimeoutTimer; - return this; -}; + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } -/** - * Override default response body parser - * - * This function will be called to convert incoming data into request.body - * - * @param {Function} - * @api public - */ + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; -RequestBase.prototype.parse = function parse(fn){ - this._parser = fn; - return this; -}; + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } -/** - * Set format of binary response body. - * In browser valid formats are 'blob' and 'arraybuffer', - * which return Blob and ArrayBuffer, respectively. - * - * In Node all values result in Buffer. - * - * Examples: - * - * req.get('/') - * .responseType('blob') - * .end(callback); - * - * @param {String} val - * @return {Request} for chaining - * @api public - */ + if (typeof iterable.next === "function") { + return iterable; + } -RequestBase.prototype.responseType = function(val){ - this._responseType = val; - return this; -}; + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } -/** - * Override default request body serializer - * - * This function will be called to convert data set via .send or .attach into payload to send - * - * @param {Function} - * @api public - */ + next.value = undefined; + next.done = true; -RequestBase.prototype.serialize = function serialize(fn){ - this._serializer = fn; - return this; -}; + return next; + }; -/** - * Set timeouts. - * - * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time. - * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections. - * - * Value of 0 or false means no timeout. - * - * @param {Number|Object} ms or {response, deadline} - * @return {Request} for chaining - * @api public - */ + return next.next = next; + } + } -RequestBase.prototype.timeout = function timeout(options){ - if (!options || 'object' !== typeof options) { - this._timeout = options; - this._responseTimeout = 0; - return this; + // Return an iterator with no values. + return { next: doneResult }; } + exports.values = values; - for(var option in options) { - switch(option) { - case 'deadline': - this._timeout = options.deadline; - break; - case 'response': - this._responseTimeout = options.response; - break; - default: - console.warn("Unknown timeout option", option); - } + function doneResult() { + return { value: undefined, done: true }; } - return this; -}; -/** - * Set number of retry attempts on error. - * - * Failed requests will be retried 'count' times if timeout or err.code >= 500. - * - * @param {Number} count - * @param {Function} [fn] - * @return {Request} for chaining - * @api public - */ + Context.prototype = { + constructor: Context, -RequestBase.prototype.retry = function retry(count, fn){ - // Default to 1 if no count passed or true - if (arguments.length === 0 || count === true) count = 1; - if (count <= 0) count = 0; - this._maxRetries = count; - this._retries = 0; - this._retryCallback = fn; - return this; -}; + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; -var ERROR_CODES = [ - 'ECONNRESET', - 'ETIMEDOUT', - 'EADDRINFO', - 'ESOCKETTIMEDOUT' -]; + this.method = "next"; + this.arg = undefined; -/** - * Determine if a request should be retried. - * (Borrowed from segmentio/superagent-retry) - * - * @param {Error} err - * @param {Response} [res] - * @returns {Boolean} - */ -RequestBase.prototype._shouldRetry = function(err, res) { - if (!this._maxRetries || this._retries++ >= this._maxRetries) { - return false; - } - if (this._retryCallback) { - try { - var override = this._retryCallback(err, res); - if (override === true) return true; - if (override === false) return false; - // undefined falls back to defaults - } catch(e) { - console.error(e); - } - } - if (res && res.status && res.status >= 500 && res.status != 501) return true; - if (err) { - if (err.code && ~ERROR_CODES.indexOf(err.code)) return true; - // Superagent timeout - if (err.timeout && err.code == 'ECONNABORTED') return true; - if (err.crossDomain) return true; - } - return false; -}; + this.tryEntries.forEach(resetTryEntry); -/** - * Retry request - * - * @return {Request} for chaining - * @api private - */ + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, -RequestBase.prototype._retry = function() { + dispatchException: function(exception) { + if (this.done) { + throw exception; + } - this.clearTimeout(); + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; - // node - if (this.req) { - this.req = null; - this.req = this.request(); - } + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined; + } - this._aborted = false; - this.timedout = false; + return !! caught; + } - return this._end(); -}; + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; -/** - * Promise support - * - * @param {Function} resolve - * @param {Function} [reject] - * @return {Request} - */ + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } -RequestBase.prototype.then = function then(resolve, reject) { - if (!this._fullfilledPromise) { - var self = this; - if (this._endCalled) { - console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"); - } - this._fullfilledPromise = new Promise(function(innerResolve, innerReject) { - self.end(function(err, res) { - if (err) innerReject(err); - else innerResolve(res); - }); - }); - } - return this._fullfilledPromise.then(resolve, reject); -}; + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); -RequestBase.prototype['catch'] = function(cb) { - return this.then(undefined, cb); -}; + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } -/** - * Allow for extension - */ + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } -RequestBase.prototype.use = function use(fn) { - fn(this); - return this; -}; + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } -RequestBase.prototype.ok = function(cb) { - if ('function' !== typeof cb) throw Error("Callback required"); - this._okCallback = cb; - return this; -}; + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, -RequestBase.prototype._isResponseOK = function(res) { - if (!res) { - return false; - } + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } - if (this._okCallback) { - return this._okCallback(res); - } + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } - return res.status >= 200 && res.status < 300; -}; + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; -/** - * Get request header `field`. - * Case-insensitive. - * - * @param {String} field - * @return {String} - * @api public - */ + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } -RequestBase.prototype.get = function(field){ - return this._header[field.toLowerCase()]; -}; + return this.complete(record); + }, -/** - * Get case-insensitive header `field` value. - * This is a deprecated internal API. Use `.get(field)` instead. - * - * (getHeader is no longer used internally by the superagent code base) - * - * @param {String} field - * @return {String} - * @api private - * @deprecated - */ + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } -RequestBase.prototype.getHeader = RequestBase.prototype.get; + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } -/** - * Set header `field` to `val`, or multiple fields with one object. - * Case-insensitive. - * - * Examples: - * - * req.get('/') - * .set('Accept', 'application/json') - * .set('X-API-Key', 'foobar') - * .end(callback); - * - * req.get('/') - * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) - * .end(callback); - * - * @param {String|Object} field - * @param {String} val - * @return {Request} for chaining - * @api public - */ + return ContinueSentinel; + }, -RequestBase.prototype.set = function(field, val){ - if (isObject(field)) { - for (var key in field) { - this.set(key, field[key]); - } - return this; - } - this._header[field.toLowerCase()] = val; - this.header[field] = val; - return this; -}; + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, -/** - * Remove header `field`. - * Case-insensitive. - * - * Example: - * - * req.get('/') - * .unset('User-Agent') - * .end(callback); - * - * @param {String} field - */ -RequestBase.prototype.unset = function(field){ - delete this._header[field.toLowerCase()]; - delete this.header[field]; - return this; -}; + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } -/** - * Write the field `name` and `val`, or multiple fields with one object - * for "multipart/form-data" request bodies. - * - * ``` js - * request.post('/upload') - * .field('foo', 'bar') - * .end(callback); - * - * request.post('/upload') - * .field({ foo: 'bar', baz: 'qux' }) - * .end(callback); - * ``` - * - * @param {String|Object} name - * @param {String|Blob|File|Buffer|fs.ReadStream} val - * @return {Request} for chaining - * @api public - */ -RequestBase.prototype.field = function(name, val) { - // name should be either a string or an object. - if (null === name || undefined === name) { - throw new Error('.field(name, val) name can not be empty'); - } + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, - if (this._data) { - console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"); - } + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined; + } - if (isObject(name)) { - for (var key in name) { - this.field(key, name[key]); + return ContinueSentinel; } - return this; - } + }; - if (Array.isArray(val)) { - for (var i in val) { - this.field(name, val[i]); - } - return this; - } + // Regardless of whether this script is executing as a CommonJS module + // or not, return the runtime object so that we can declare the variable + // regeneratorRuntime in the outer scope, which allows this module to be + // injected easily by `bin/regenerator --include-runtime script.js`. + return exports; - // val should be defined now - if (null === val || undefined === val) { - throw new Error('.field(name, val) val can not be empty'); - } - if ('boolean' === typeof val) { - val = '' + val; - } - this._getFormData().append(name, val); - return this; -}; +}( + // If this script is executing as a CommonJS module, use module.exports + // as the regeneratorRuntime namespace. Otherwise create a new empty + // object. Either way, the resulting object will be used to initialize + // the regeneratorRuntime variable at the top of this file. + true ? module.exports : 0 +)); -/** - * Abort the request, and clear potential timeout. - * - * @return {Request} - * @api public - */ -RequestBase.prototype.abort = function(){ - if (this._aborted) { - return this; +try { + regeneratorRuntime = runtime; +} catch (accidentalStrictMode) { + // This module should not be running in strict mode, so the above + // assignment should always work unless something is misconfigured. Just + // in case runtime.js accidentally runs in strict mode, in modern engines + // we can explicitly access globalThis. In older engines we can escape + // strict mode using a global Function call. This could conceivably fail + // if a Content Security Policy forbids using Function, but in that case + // the proper solution is to fix the accidental strict mode problem. If + // you've misconfigured your bundler to force strict mode and applied a + // CSP to forbid Function, and you're not willing to fix either of those + // problems, please detail your unique predicament in a GitHub issue. + if (typeof globalThis === "object") { + globalThis.regeneratorRuntime = runtime; + } else { + Function("r", "regeneratorRuntime = r")(runtime); } - this._aborted = true; - this.xhr && this.xhr.abort(); // browser - this.req && this.req.abort(); // node - this.clearTimeout(); - this.emit('abort'); - return this; -}; +} -RequestBase.prototype._auth = function(user, pass, options, base64Encoder) { - switch (options.type) { - case 'basic': - this.set('Authorization', 'Basic ' + base64Encoder(user + ':' + pass)); - break; - case 'auto': - this.username = user; - this.password = pass; - break; +/***/ }), - case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' }) - this.set('Authorization', 'Bearer ' + user); - break; - } - return this; -}; +/***/ 77465: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -/** - * Enable transmission of cookies with x-domain requests. - * - * Note that for this to work the origin must not be - * using "Access-Control-Allow-Origin" with a wildcard, - * and also must set "Access-Control-Allow-Credentials" - * to "true". - * - * @api public - */ +const createWorker = __webpack_require__(12477); -RequestBase.prototype.withCredentials = function(on) { - // This is browser-only functionality. Node side is no-op. - if (on == undefined) on = true; - this._withCredentials = on; - return this; +const recognize = async (image, langs, options) => { + const worker = await createWorker(langs, 1, options); + return worker.recognize(image) + .finally(async () => { + await worker.terminate(); + }); }; -/** - * Set the max redirects to `n`. Does noting in browser XHR implementation. - * - * @param {Number} n - * @return {Request} for chaining - * @api public - */ - -RequestBase.prototype.redirects = function(n){ - this._maxRedirects = n; - return this; +const detect = async (image, options) => { + const worker = await createWorker('osd', 0, options); + return worker.detect(image) + .finally(async () => { + await worker.terminate(); + }); }; -/** - * Maximum size of buffered response body, in bytes. Counts uncompressed size. - * Default 200MB. - * - * @param {Number} n - * @return {Request} for chaining - */ -RequestBase.prototype.maxResponseSize = function(n){ - if ('number' !== typeof n) { - throw TypeError("Invalid argument"); - } - this._maxResponseSize = n; - return this; +module.exports = { + recognize, + detect, }; -/** - * Convert to a plain javascript object (not JSON string) of scalar properties. - * Note as this method is designed to return a useful non-this value, - * it cannot be chained. - * - * @return {Object} describing method, url, and data of this request - * @api public - */ -RequestBase.prototype.toJSON = function() { - return { - method: this.method, - url: this.url, - data: this._data, - headers: this._header, - }; -}; +/***/ }), -/** - * Send `data` as the request body, defaulting the `.type()` to "json" when - * an object is given. - * - * Examples: - * - * // manual json - * request.post('/user') - * .type('json') - * .send('{"name":"tj"}') - * .end(callback) - * - * // auto json - * request.post('/user') - * .send({ name: 'tj' }) - * .end(callback) - * - * // manual x-www-form-urlencoded - * request.post('/user') - * .type('form') - * .send('name=tj') - * .end(callback) - * - * // auto x-www-form-urlencoded - * request.post('/user') - * .type('form') - * .send({ name: 'tj' }) - * .end(callback) +/***/ 89742: +/***/ ((module) => { + +/* + * OEM = OCR Engine Mode, and there are 4 possible modes. * - * // defaults to x-www-form-urlencoded - * request.post('/user') - * .send('name=tobi') - * .send('species=ferret') - * .end(callback) + * By default tesseract.js uses LSTM_ONLY mode. * - * @param {String|Object} data - * @return {Request} for chaining - * @api public */ +module.exports = { + TESSERACT_ONLY: 0, + LSTM_ONLY: 1, + TESSERACT_LSTM_COMBINED: 2, + DEFAULT: 3, +}; -RequestBase.prototype.send = function(data){ - var isObj = isObject(data); - var type = this._header['content-type']; - if (this._formData) { - console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"); - } +/***/ }), - if (isObj && !this._data) { - if (Array.isArray(data)) { - this._data = []; - } else if (!this._isHost(data)) { - this._data = {}; - } - } else if (data && this._data && this._isHost(this._data)) { - throw Error("Can't merge these send calls"); - } +/***/ 30949: +/***/ ((module) => { - // merge - if (isObj && isObject(this._data)) { - for (var key in data) { - this._data[key] = data[key]; - } - } else if ('string' == typeof data) { - // default to x-www-form-urlencoded - if (!type) this.type('form'); - type = this._header['content-type']; - if ('application/x-www-form-urlencoded' == type) { - this._data = this._data - ? this._data + '&' + data - : data; - } else { - this._data = (this._data || '') + data; - } - } else { - this._data = data; - } +/* + * PSM = Page Segmentation Mode + */ +module.exports = { + OSD_ONLY: '0', + AUTO_OSD: '1', + AUTO_ONLY: '2', + AUTO: '3', + SINGLE_COLUMN: '4', + SINGLE_BLOCK_VERT_TEXT: '5', + SINGLE_BLOCK: '6', + SINGLE_LINE: '7', + SINGLE_WORD: '8', + CIRCLE_WORD: '9', + SINGLE_CHAR: '10', + SPARSE_TEXT: '11', + SPARSE_TEXT_OSD: '12', + RAW_LINE: '13', +}; - if (!isObj || this._isHost(data)) { - return this; - } - // default to json - if (!type) this.type('json'); - return this; -}; +/***/ }), -/** - * Sort `querystring` by the sort function - * - * - * Examples: - * - * // default order - * request.get('/user') - * .query('name=Nick') - * .query('search=Manny') - * .sortQuery() - * .end(callback) - * - * // customized sort function - * request.get('/user') - * .query('name=Nick') - * .query('search=Manny') - * .sortQuery(function(a, b){ - * return a.length - b.length; - * }) - * .end(callback) - * - * - * @param {Function} sort - * @return {Request} for chaining - * @api public - */ +/***/ 84500: +/***/ ((module) => { -RequestBase.prototype.sortQuery = function(sort) { - // _sort default to true but otherwise can be a function or boolean - this._sort = typeof sort === 'undefined' ? true : sort; - return this; +module.exports = { + /* + * Use BlobURL for worker script by default + * TODO: remove this option + * + */ + workerBlobURL: true, + logger: () => {}, }; -/** - * Compose querystring to append to req.url - * - * @api private - */ -RequestBase.prototype._finalizeQueryString = function(){ - var query = this._query.join('&'); - if (query) { - this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query; - } - this._query.length = 0; // Makes the call idempotent - if (this._sort) { - var index = this.url.indexOf('?'); - if (index >= 0) { - var queryArr = this.url.substring(index + 1).split('&'); - if ('function' === typeof this._sort) { - queryArr.sort(this._sort); - } else { - queryArr.sort(); - } - this.url = this.url.substring(0, index) + '?' + queryArr.join('&'); - } - } -}; +/***/ }), -// For backwards compat only -RequestBase.prototype._appendQueryString = function() {console.trace("Unsupported");} +/***/ 32646: +/***/ ((module) => { + +/* + * languages with existing tesseract traineddata + * https://tesseract-ocr.github.io/tessdoc/Data-Files#data-files-for-version-400-november-29-2016 + */ /** - * Invoke callback with timeout error. - * - * @api private + * @typedef {object} Languages + * @property {string} AFR Afrikaans + * @property {string} AMH Amharic + * @property {string} ARA Arabic + * @property {string} ASM Assamese + * @property {string} AZE Azerbaijani + * @property {string} AZE_CYRL Azerbaijani - Cyrillic + * @property {string} BEL Belarusian + * @property {string} BEN Bengali + * @property {string} BOD Tibetan + * @property {string} BOS Bosnian + * @property {string} BUL Bulgarian + * @property {string} CAT Catalan; Valencian + * @property {string} CEB Cebuano + * @property {string} CES Czech + * @property {string} CHI_SIM Chinese - Simplified + * @property {string} CHI_TRA Chinese - Traditional + * @property {string} CHR Cherokee + * @property {string} CYM Welsh + * @property {string} DAN Danish + * @property {string} DEU German + * @property {string} DZO Dzongkha + * @property {string} ELL Greek, Modern (1453-) + * @property {string} ENG English + * @property {string} ENM English, Middle (1100-1500) + * @property {string} EPO Esperanto + * @property {string} EST Estonian + * @property {string} EUS Basque + * @property {string} FAS Persian + * @property {string} FIN Finnish + * @property {string} FRA French + * @property {string} FRK German Fraktur + * @property {string} FRM French, Middle (ca. 1400-1600) + * @property {string} GLE Irish + * @property {string} GLG Galician + * @property {string} GRC Greek, Ancient (-1453) + * @property {string} GUJ Gujarati + * @property {string} HAT Haitian; Haitian Creole + * @property {string} HEB Hebrew + * @property {string} HIN Hindi + * @property {string} HRV Croatian + * @property {string} HUN Hungarian + * @property {string} IKU Inuktitut + * @property {string} IND Indonesian + * @property {string} ISL Icelandic + * @property {string} ITA Italian + * @property {string} ITA_OLD Italian - Old + * @property {string} JAV Javanese + * @property {string} JPN Japanese + * @property {string} KAN Kannada + * @property {string} KAT Georgian + * @property {string} KAT_OLD Georgian - Old + * @property {string} KAZ Kazakh + * @property {string} KHM Central Khmer + * @property {string} KIR Kirghiz; Kyrgyz + * @property {string} KOR Korean + * @property {string} KUR Kurdish + * @property {string} LAO Lao + * @property {string} LAT Latin + * @property {string} LAV Latvian + * @property {string} LIT Lithuanian + * @property {string} MAL Malayalam + * @property {string} MAR Marathi + * @property {string} MKD Macedonian + * @property {string} MLT Maltese + * @property {string} MSA Malay + * @property {string} MYA Burmese + * @property {string} NEP Nepali + * @property {string} NLD Dutch; Flemish + * @property {string} NOR Norwegian + * @property {string} ORI Oriya + * @property {string} PAN Panjabi; Punjabi + * @property {string} POL Polish + * @property {string} POR Portuguese + * @property {string} PUS Pushto; Pashto + * @property {string} RON Romanian; Moldavian; Moldovan + * @property {string} RUS Russian + * @property {string} SAN Sanskrit + * @property {string} SIN Sinhala; Sinhalese + * @property {string} SLK Slovak + * @property {string} SLV Slovenian + * @property {string} SPA Spanish; Castilian + * @property {string} SPA_OLD Spanish; Castilian - Old + * @property {string} SQI Albanian + * @property {string} SRP Serbian + * @property {string} SRP_LATN Serbian - Latin + * @property {string} SWA Swahili + * @property {string} SWE Swedish + * @property {string} SYR Syriac + * @property {string} TAM Tamil + * @property {string} TEL Telugu + * @property {string} TGK Tajik + * @property {string} TGL Tagalog + * @property {string} THA Thai + * @property {string} TIR Tigrinya + * @property {string} TUR Turkish + * @property {string} UIG Uighur; Uyghur + * @property {string} UKR Ukrainian + * @property {string} URD Urdu + * @property {string} UZB Uzbek + * @property {string} UZB_CYRL Uzbek - Cyrillic + * @property {string} VIE Vietnamese + * @property {string} YID Yiddish */ -RequestBase.prototype._timeoutError = function(reason, timeout, errno){ - if (this._aborted) { - return; - } - var err = new Error(reason + timeout + 'ms exceeded'); - err.timeout = timeout; - err.code = 'ECONNABORTED'; - err.errno = errno; - this.timedout = true; - this.abort(); - this.callback(err); +/** + * @type {Languages} + */ +module.exports = { + AFR: 'afr', + AMH: 'amh', + ARA: 'ara', + ASM: 'asm', + AZE: 'aze', + AZE_CYRL: 'aze_cyrl', + BEL: 'bel', + BEN: 'ben', + BOD: 'bod', + BOS: 'bos', + BUL: 'bul', + CAT: 'cat', + CEB: 'ceb', + CES: 'ces', + CHI_SIM: 'chi_sim', + CHI_TRA: 'chi_tra', + CHR: 'chr', + CYM: 'cym', + DAN: 'dan', + DEU: 'deu', + DZO: 'dzo', + ELL: 'ell', + ENG: 'eng', + ENM: 'enm', + EPO: 'epo', + EST: 'est', + EUS: 'eus', + FAS: 'fas', + FIN: 'fin', + FRA: 'fra', + FRK: 'frk', + FRM: 'frm', + GLE: 'gle', + GLG: 'glg', + GRC: 'grc', + GUJ: 'guj', + HAT: 'hat', + HEB: 'heb', + HIN: 'hin', + HRV: 'hrv', + HUN: 'hun', + IKU: 'iku', + IND: 'ind', + ISL: 'isl', + ITA: 'ita', + ITA_OLD: 'ita_old', + JAV: 'jav', + JPN: 'jpn', + KAN: 'kan', + KAT: 'kat', + KAT_OLD: 'kat_old', + KAZ: 'kaz', + KHM: 'khm', + KIR: 'kir', + KOR: 'kor', + KUR: 'kur', + LAO: 'lao', + LAT: 'lat', + LAV: 'lav', + LIT: 'lit', + MAL: 'mal', + MAR: 'mar', + MKD: 'mkd', + MLT: 'mlt', + MSA: 'msa', + MYA: 'mya', + NEP: 'nep', + NLD: 'nld', + NOR: 'nor', + ORI: 'ori', + PAN: 'pan', + POL: 'pol', + POR: 'por', + PUS: 'pus', + RON: 'ron', + RUS: 'rus', + SAN: 'san', + SIN: 'sin', + SLK: 'slk', + SLV: 'slv', + SPA: 'spa', + SPA_OLD: 'spa_old', + SQI: 'sqi', + SRP: 'srp', + SRP_LATN: 'srp_latn', + SWA: 'swa', + SWE: 'swe', + SYR: 'syr', + TAM: 'tam', + TEL: 'tel', + TGK: 'tgk', + TGL: 'tgl', + THA: 'tha', + TIR: 'tir', + TUR: 'tur', + UIG: 'uig', + UKR: 'ukr', + URD: 'urd', + UZB: 'uzb', + UZB_CYRL: 'uzb_cyrl', + VIE: 'vie', + YID: 'yid', }; -RequestBase.prototype._setTimeouts = function() { - var self = this; - // deadline - if (this._timeout && !this._timer) { - this._timer = setTimeout(function(){ - self._timeoutError('Timeout of ', self._timeout, 'ETIME'); - }, this._timeout); - } - // response timeout - if (this._responseTimeout && !this._responseTimeoutTimer) { - this._responseTimeoutTimer = setTimeout(function(){ - self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT'); - }, this._responseTimeout); +/***/ }), + +/***/ 19500: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const getId = __webpack_require__(1028); + +let jobCounter = 0; + +module.exports = ({ + id: _id, + action, + payload = {}, +}) => { + let id = _id; + if (typeof id === 'undefined') { + id = getId('Job', jobCounter); + jobCounter += 1; } + + return { + id, + action, + payload, + }; }; /***/ }), -/***/ 81097: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; +/***/ 40882: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const createJob = __webpack_require__(19500); +const { log } = __webpack_require__(8787); +const getId = __webpack_require__(1028); -/** - * Module dependencies. - */ +let schedulerCounter = 0; -var utils = __webpack_require__(64506); +module.exports = () => { + const id = getId('Scheduler', schedulerCounter); + const workers = {}; + const runningWorkers = {}; + let jobQueue = []; -/** - * Expose `ResponseBase`. - */ + schedulerCounter += 1; -module.exports = ResponseBase; + const getQueueLen = () => jobQueue.length; + const getNumWorkers = () => Object.keys(workers).length; -/** - * Initialize a new `ResponseBase`. - * - * @api public - */ + const dequeue = () => { + if (jobQueue.length !== 0) { + const wIds = Object.keys(workers); + for (let i = 0; i < wIds.length; i += 1) { + if (typeof runningWorkers[wIds[i]] === 'undefined') { + jobQueue[0](workers[wIds[i]]); + break; + } + } + } + }; -function ResponseBase(obj) { - if (obj) return mixin(obj); -} + const queue = (action, payload) => ( + new Promise((resolve, reject) => { + const job = createJob({ action, payload }); + jobQueue.push(async (w) => { + jobQueue.shift(); + runningWorkers[w.id] = job; + try { + resolve(await w[action].apply(this, [...payload, job.id])); + } catch (err) { + reject(err); + } finally { + delete runningWorkers[w.id]; + dequeue(); + } + }); + log(`[${id}]: Add ${job.id} to JobQueue`); + log(`[${id}]: JobQueue length=${jobQueue.length}`); + dequeue(); + }) + ); -/** - * Mixin the prototype properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ + const addWorker = (w) => { + workers[w.id] = w; + log(`[${id}]: Add ${w.id}`); + log(`[${id}]: Number of workers=${getNumWorkers()}`); + dequeue(); + return w.id; + }; -function mixin(obj) { - for (var key in ResponseBase.prototype) { - obj[key] = ResponseBase.prototype[key]; - } - return obj; -} + const addJob = async (action, ...payload) => { + if (getNumWorkers() === 0) { + throw Error(`[${id}]: You need to have at least one worker before adding jobs`); + } + return queue(action, payload); + }; -/** - * Get case-insensitive `field` value. - * - * @param {String} field - * @return {String} - * @api public - */ + const terminate = async () => { + Object.keys(workers).forEach(async (wid) => { + await workers[wid].terminate(); + }); + jobQueue = []; + }; -ResponseBase.prototype.get = function(field) { - return this.header[field.toLowerCase()]; + return { + addWorker, + addJob, + terminate, + getQueueLen, + getNumWorkers, + }; }; -/** - * Set header related properties: - * - * - `.type` the content type without params - * - * A response of "Content-Type: text/plain; charset=utf-8" - * will provide you with a `.type` of "text/plain". - * - * @param {Object} header - * @api private - */ - -ResponseBase.prototype._setHeaderProperties = function(header){ - // TODO: moar! - // TODO: make this a util - // content-type - var ct = header['content-type'] || ''; - this.type = utils.type(ct); +/***/ }), - // params - var params = utils.params(ct); - for (var key in params) this[key] = params[key]; +/***/ 12477: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - this.links = {}; +const resolvePaths = __webpack_require__(65981); +const circularize = __webpack_require__(64760); +const createJob = __webpack_require__(19500); +const { log } = __webpack_require__(8787); +const getId = __webpack_require__(1028); +const OEM = __webpack_require__(89742); +const { + defaultOptions, + spawnWorker, + terminateWorker, + onMessage, + loadImage, + send, +} = __webpack_require__(65321); + +let workerCounter = 0; + +module.exports = async (langs = 'eng', oem = OEM.LSTM_ONLY, _options = {}, config = {}) => { + const id = getId('Worker', workerCounter); + const { + logger, + errorHandler, + ...options + } = resolvePaths({ + ...defaultOptions, + ..._options, + }); + const resolves = {}; + const rejects = {}; + + // Current langs, oem, and config file. + // Used if the user ever re-initializes the worker using `worker.reinitialize`. + const currentLangs = typeof langs === 'string' ? langs.split('+') : langs; + let currentOem = oem; + let currentConfig = config; + const lstmOnlyCore = [OEM.DEFAULT, OEM.LSTM_ONLY].includes(oem) && !options.legacyCore; + + let workerResReject; + let workerResResolve; + const workerRes = new Promise((resolve, reject) => { + workerResResolve = resolve; + workerResReject = reject; + }); + const workerError = (event) => { workerResReject(event.message); }; - // links - try { - if (header.link) { - this.links = utils.parseLinks(header.link); - } - } catch (err) { - // ignore - } -}; + let worker = spawnWorker(options); + worker.onerror = workerError; -/** - * Set flags such as `.ok` based on `status`. - * - * For example a 2xx response will give you a `.ok` of __true__ - * whereas 5xx will be __false__ and `.error` will be __true__. The - * `.clientError` and `.serverError` are also available to be more - * specific, and `.statusType` is the class of error ranging from 1..5 - * sometimes useful for mapping respond colors etc. - * - * "sugar" properties are also defined for common cases. Currently providing: - * - * - .noContent - * - .badRequest - * - .unauthorized - * - .notAcceptable - * - .notFound - * - * @param {Number} status - * @api private - */ + workerCounter += 1; -ResponseBase.prototype._setStatusProperties = function(status){ - var type = status / 100 | 0; + const setResolve = (promiseId, res) => { + resolves[promiseId] = res; + }; - // status / class - this.status = this.statusCode = status; - this.statusType = type; + const setReject = (promiseId, rej) => { + rejects[promiseId] = rej; + }; - // basics - this.info = 1 == type; - this.ok = 2 == type; - this.redirect = 3 == type; - this.clientError = 4 == type; - this.serverError = 5 == type; - this.error = (4 == type || 5 == type) - ? this.toError() - : false; + const startJob = ({ id: jobId, action, payload }) => ( + new Promise((resolve, reject) => { + log(`[${id}]: Start ${jobId}, action=${action}`); + // Using both `action` and `jobId` in case user provides non-unique `jobId`. + const promiseId = `${action}-${jobId}`; + setResolve(promiseId, resolve); + setReject(promiseId, reject); + send(worker, { + workerId: id, + jobId, + action, + payload, + }); + }) + ); - // sugar - this.created = 201 == status; - this.accepted = 202 == status; - this.noContent = 204 == status; - this.badRequest = 400 == status; - this.unauthorized = 401 == status; - this.notAcceptable = 406 == status; - this.forbidden = 403 == status; - this.notFound = 404 == status; - this.unprocessableEntity = 422 == status; -}; + const load = () => ( + console.warn('`load` is depreciated and should be removed from code (workers now come pre-loaded)') + ); + const loadInternal = (jobId) => ( + startJob(createJob({ + id: jobId, action: 'load', payload: { options: { lstmOnly: lstmOnlyCore, corePath: options.corePath, logging: options.logging } }, + })) + ); -/***/ }), + const writeText = (path, text, jobId) => ( + startJob(createJob({ + id: jobId, + action: 'FS', + payload: { method: 'writeFile', args: [path, text] }, + })) + ); -/***/ 64506: -/***/ ((__unused_webpack_module, exports) => { + const readText = (path, jobId) => ( + startJob(createJob({ + id: jobId, + action: 'FS', + payload: { method: 'readFile', args: [path, { encoding: 'utf8' }] }, + })) + ); -"use strict"; + const removeFile = (path, jobId) => ( + startJob(createJob({ + id: jobId, + action: 'FS', + payload: { method: 'unlink', args: [path] }, + })) + ); + const FS = (method, args, jobId) => ( + startJob(createJob({ + id: jobId, + action: 'FS', + payload: { method, args }, + })) + ); -/** - * Return the mime type for the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ + const loadLanguage = () => ( + console.warn('`loadLanguage` is depreciated and should be removed from code (workers now come with language pre-loaded)') + ); -exports.type = function(str){ - return str.split(/ *; */).shift(); -}; + const loadLanguageInternal = (_langs, jobId) => startJob(createJob({ + id: jobId, + action: 'loadLanguage', + payload: { + langs: _langs, + options: { + langPath: options.langPath, + dataPath: options.dataPath, + cachePath: options.cachePath, + cacheMethod: options.cacheMethod, + gzip: options.gzip, + lstmOnly: [OEM.LSTM_ONLY, OEM.TESSERACT_LSTM_COMBINED].includes(currentOem) + && !options.legacyLang, + }, + }, + })); -/** - * Return header field parameters. - * - * @param {String} str - * @return {Object} - * @api private - */ + const initialize = () => ( + console.warn('`initialize` is depreciated and should be removed from code (workers now come pre-initialized)') + ); -exports.params = function(str){ - return str.split(/ *; */).reduce(function(obj, str){ - var parts = str.split(/ *= */); - var key = parts.shift(); - var val = parts.shift(); + const initializeInternal = (_langs, _oem, _config, jobId) => ( + startJob(createJob({ + id: jobId, + action: 'initialize', + payload: { langs: _langs, oem: _oem, config: _config }, + })) + ); - if (key && val) obj[key] = val; - return obj; - }, {}); -}; + const reinitialize = (langs = 'eng', oem, config, jobId) => { // eslint-disable-line -/** - * Parse Link header fields. - * - * @param {String} str - * @return {Object} - * @api private - */ + if (lstmOnlyCore && [OEM.TESSERACT_ONLY, OEM.TESSERACT_LSTM_COMBINED].includes(oem)) throw Error('Legacy model requested but code missing.'); -exports.parseLinks = function(str){ - return str.split(/ *, */).reduce(function(obj, str){ - var parts = str.split(/ *; */); - var url = parts[0].slice(1, -1); - var rel = parts[1].split(/ *= */)[1].slice(1, -1); - obj[rel] = url; - return obj; - }, {}); -}; + const _oem = oem || currentOem; + currentOem = _oem; -/** - * Strip content related fields from `header`. - * - * @param {Object} header - * @return {Object} header - * @api private - */ + const _config = config || currentConfig; + currentConfig = _config; -exports.cleanHeader = function(header, changesOrigin){ - delete header['content-type']; - delete header['content-length']; - delete header['transfer-encoding']; - delete header['host']; - // secuirty - if (changesOrigin) { - delete header['authorization']; - delete header['cookie']; - } - return header; -}; + // Only load langs that are not already loaded. + // This logic fails if the user downloaded the LSTM-only English data for a language + // and then uses `worker.reinitialize` to switch to the Legacy engine. + // However, the correct data will still be downloaded after initialization fails + // and this can be avoided entirely if the user loads the correct data ahead of time. + const langsArr = typeof langs === 'string' ? langs.split('+') : langs; + const _langs = langsArr.filter((x) => !currentLangs.includes(x)); + currentLangs.push(..._langs); + if (_langs.length > 0) { + return loadLanguageInternal(_langs, jobId) + .then(() => initializeInternal(langs, _oem, _config, jobId)); + } -/***/ }), + return initializeInternal(langs, _oem, _config, jobId); + }; -/***/ 89145: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + const setParameters = (params = {}, jobId) => ( + startJob(createJob({ + id: jobId, + action: 'setParameters', + payload: { params }, + })) + ); -"use strict"; + const recognize = async (image, opts = {}, output = { + blocks: true, text: true, hocr: true, tsv: true, + }, jobId) => ( + startJob(createJob({ + id: jobId, + action: 'recognize', + payload: { image: await loadImage(image), options: opts, output }, + })) + ); -/* globals chrome */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.captureClientAPI = exports.CaptureScreenshotService = exports.scaleDataURI = exports.getScreenshotRatio = exports.imageSizeFromDataURI = void 0; -const web_extension_1 = __importDefault(__webpack_require__(61171)); -const utils_1 = __webpack_require__(63370); -const ts_utils_1 = __webpack_require__(55452); -function imageSizeFromDataURI(dataURI) { - return createImageBitmap(utils_1.dataURItoBlob(dataURI)) - .then((img) => ({ - width: img.width, - height: img.height + const getPDF = (title = 'Tesseract OCR Result', textonly = false, jobId) => { + console.log('`getPDF` function is depreciated. `recognize` option `savePDF` should be used instead.'); + return startJob(createJob({ + id: jobId, + action: 'getPDF', + payload: { title, textonly }, })); -} -exports.imageSizeFromDataURI = imageSizeFromDataURI; -function getScreenshotRatio(dataURI, tabId, devicePixelRatio) { - return Promise.all([ - imageSizeFromDataURI(dataURI), - web_extension_1.default.tabs.get(tabId) - ]) - .then(tuple => { - const [size, tab] = tuple; - return tab.width * devicePixelRatio / size.width; - }); -} -exports.getScreenshotRatio = getScreenshotRatio; -function scaleDataURI(dataURI, scale) { - if (scale === 1) - return Promise.resolve(dataURI); - return imageSizeFromDataURI(dataURI) - .then(size => { - const canvas = createCanvas(size.width, size.height, scale); - return drawOnCanvas({ - canvas, - dataURI, - x: 0, - y: 0, - width: size.width * scale, - height: size.height * scale - }) - .then(() => canvas.toDataURL()); - }); -} -exports.scaleDataURI = scaleDataURI; -function pCompose(list) { - return list.reduce((prev, fn) => { - return prev.then(fn); - }, Promise.resolve()); -} -class CaptureScreenshotService { - constructor(params) { - this.params = params; - this.captureVisibleTab = - typeof chrome !== 'undefined' && - typeof chrome.tabs !== 'undefined' && - typeof chrome.tabs.MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND === 'number' - ? ts_utils_1.throttlePromiseFunc(this.params.captureVisibleTab, chrome.tabs.MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND * 1000 + 100) - : this.params.captureVisibleTab; - } - saveScreen(screenshotStorage, tabId, fileName, devicePixelRatio) { - return this.captureScreenBlob(tabId, devicePixelRatio) - .then(screenBlob => { - return screenshotStorage.overwrite(fileName, screenBlob) - .then(() => { - return screenshotStorage.getLink(fileName); - }) - .then((url) => { - return ({ url, fileName }); - }, (e) => { - return Promise.reject(e); - }); - }); - } - saveFullScreen(screenshotStorage, tabId, fileName, clientAPI) { - return this.captureFullScreen(tabId, clientAPI, { blob: true }) - .then(screenBlob => { - return screenshotStorage.overwrite(fileName, screenBlob) - .then(() => screenshotStorage.getLink(fileName)) - .then(url => ({ url, fileName })); - }); - } - captureScreen(tabId, devicePixelRatio, presetScreenshotRatio) { - const is2ndArgFunction = typeof presetScreenshotRatio === 'function'; - const hasScreenshotRatio = !!presetScreenshotRatio && !is2ndArgFunction; - const pDataURI = this.captureVisibleTab(null, { format: 'png' }); - const pRatio = hasScreenshotRatio ? Promise.resolve(presetScreenshotRatio) - : pDataURI.then((dataURI) => getScreenshotRatio(dataURI, tabId, devicePixelRatio)); - return Promise.all([pDataURI, pRatio]) - .then(tuple => { - const [dataURI, screenshotRatio] = tuple; - // Note: leak the info about screenshotRatio on purpose - if (!hasScreenshotRatio && is2ndArgFunction) - presetScreenshotRatio(screenshotRatio); - if (screenshotRatio === 1) - return dataURI; - return scaleDataURI(dataURI, screenshotRatio); - }); - } - captureFullScreen(tabId, { startCapture, scrollPage, endCapture } = exports.captureClientAPI, options = {}) { - const opts = Object.assign({ blob: false }, options); - return withPageInfo(startCapture, endCapture, pageInfo => { - const devicePixelRatio = pageInfo.devicePixelRatio; - // Note: cut down page width and height - // reference: https://stackoverflow.com/questions/6081483/maximum-size-of-a-canvas-element/11585939#11585939 - const maxSide = Math.floor(32767 / devicePixelRatio); - pageInfo.pageWidth = Math.min(maxSide, pageInfo.pageWidth); - pageInfo.pageHeight = Math.min(maxSide, pageInfo.pageHeight); - const captureScreen = this.createCaptureScreenWithCachedScreenshotRatio(devicePixelRatio); - const canvas = createCanvas(pageInfo.pageWidth, pageInfo.pageHeight, devicePixelRatio); - const scrollOffsets = getAllScrollOffsets(pageInfo); - const todos = scrollOffsets.map((offset, i) => () => { - return scrollPage(offset, { index: i, total: scrollOffsets.length }) - .then(realOffset => { - return captureScreen(tabId) - .then(dataURI => drawOnCanvas({ - canvas, - dataURI, - x: realOffset.x * devicePixelRatio, - y: realOffset.y * devicePixelRatio, - width: pageInfo.windowWidth * devicePixelRatio, - height: pageInfo.windowHeight * devicePixelRatio - })); - }); - }); - const convert = opts.blob ? utils_1.dataURItoBlob : (x) => x; - return pCompose(todos) - .then(() => convert(canvas.toDataURL())); - }); - } - captureScreenInSelectionSimple(tabId, { rect, devicePixelRatio }, options = {}) { - const opts = Object.assign({ blob: false }, options); - const convert = opts.blob ? utils_1.dataURItoBlob : (x) => x; - const canvas = createCanvas(rect.width, rect.height, devicePixelRatio); - return this.captureScreen(tabId, devicePixelRatio) - .then(dataURI => drawOnCanvas({ - canvas, - dataURI, - x: -1 * rect.x * devicePixelRatio, - y: -1 * rect.y * devicePixelRatio - })) - .then(() => convert(canvas.toDataURL())); - } - captureScreenInSelection(tabId, { rect, devicePixelRatio }, { startCapture, scrollPage, endCapture }, options = {}) { - const opts = Object.assign({ blob: false }, options); - const convert = opts.blob ? utils_1.dataURItoBlob : (x) => x; - return withPageInfo(startCapture, endCapture, pageInfo => { - const maxSide = Math.floor(32767 / devicePixelRatio); - pageInfo.pageWidth = Math.min(maxSide, pageInfo.pageWidth); - pageInfo.pageHeight = Math.min(maxSide, pageInfo.pageHeight); - const captureScreen = this.createCaptureScreenWithCachedScreenshotRatio(devicePixelRatio); - const canvas = createCanvas(rect.width, rect.height, devicePixelRatio); - const scrollOffsets = getAllScrollOffsetsForRect(rect, pageInfo); - const todos = scrollOffsets.map((offset, i) => () => { - return scrollPage(offset, { index: i, total: scrollOffsets.length }) - .then(realOffset => { - return captureScreen(tabId) - .then(dataURI => drawOnCanvas({ - canvas, - dataURI, - x: (realOffset.x - rect.x) * devicePixelRatio, - y: (realOffset.y - rect.y) * devicePixelRatio, - width: pageInfo.windowWidth * devicePixelRatio, - height: pageInfo.windowHeight * devicePixelRatio - })); - }); - }); - return pCompose(todos) - .then(() => convert(canvas.toDataURL())); - }); - } - createCaptureScreenWithCachedScreenshotRatio(devicePixelRatio) { - let screenshotRatio; - return (tabId) => { - return this.captureScreen(tabId, devicePixelRatio, screenshotRatio || function (ratio) { screenshotRatio = ratio; }); - }; - } - captureScreenBlob(tabId, devicePixelRatio) { - return this.captureScreen(tabId, devicePixelRatio).then(utils_1.dataURItoBlob); - } -} -exports.CaptureScreenshotService = CaptureScreenshotService; -function getAllScrollOffsets({ pageWidth, pageHeight, windowWidth, windowHeight, topPadding = 150 }) { - const topPad = windowHeight > topPadding ? topPadding : 0; - const xStep = windowWidth; - const yStep = windowHeight - topPad; - const result = []; - // Note: bottom comes first so that when we render those screenshots one by one to the final canvas, - // those at top will overwrite top padding part of those at bottom, it is useful if that page has some fixed header - for (let y = pageHeight - windowHeight; y > -1 * yStep; y -= yStep) { - for (let x = 0; x < pageWidth; x += xStep) { - result.push({ x, y }); - } - } - return result; -} -function getAllScrollOffsetsForRect({ x, y, width, height }, { windowWidth, windowHeight, topPadding = 150 }) { - const topPad = windowHeight > topPadding ? topPadding : 0; - const xStep = windowWidth; - const yStep = windowHeight - topPad; - const result = []; - for (let sy = y + height - windowHeight; sy > y - yStep; sy -= yStep) { - for (let sx = x; sx < x + width; sx += xStep) { - result.push({ x: sx, y: sy }); - } - } - if (result.length === 0) { - result.push({ x: x, y: y + height - windowHeight }); - } - return result; -} -function createCanvas(width, height, pixelRatio = 1) { - if (typeof window === 'undefined') { - return new self.OffscreenCanvas(width * pixelRatio, height * pixelRatio); - } - const canvas = document.createElement('canvas'); - canvas.width = width * pixelRatio; - canvas.height = height * pixelRatio; - return canvas; -} -function drawOnCanvas({ canvas, dataURI, x, y, width, height }) { - return createImageBitmap(utils_1.dataURItoBlob(dataURI)) - .then((image) => { - canvas.getContext('2d').drawImage(image, 0, 0, image.width, image.height, x, y, width || image.width, height || image.height); - return { x, y, width, height }; - }); -} -function withPageInfo(startCapture, endCapture, callback) { - return startCapture() - .then(pageInfo => { - // Note: in case sender contains any non-serializable data - delete pageInfo.sender; - return callback(pageInfo) - .then(result => { - endCapture(pageInfo); - return result; - }); - }); -} -exports.captureClientAPI = { - getPageInfo: () => { - const body = document.body; - const widths = [ - document.documentElement.clientWidth, - document.documentElement.scrollWidth, - document.documentElement.offsetWidth, - body ? body.scrollWidth : 0, - body ? body.offsetWidth : 0 - ]; - const heights = [ - document.documentElement.clientHeight, - document.documentElement.scrollHeight, - document.documentElement.offsetHeight, - body ? body.scrollHeight : 0, - body ? body.offsetHeight : 0 - ]; - const data = { - pageWidth: Math.max(...widths), - pageHeight: Math.max(...heights), - windowWidth: window.innerWidth, - windowHeight: window.innerHeight, - hasBody: !!body, - originalX: window.scrollX, - originalY: window.scrollY, - originalOverflowStyle: document.documentElement.style.overflow, - originalBodyOverflowYStyle: body && body.style.overflowY, - devicePixelRatio: window.devicePixelRatio - }; - return data; - }, - startCapture: ({ hideScrollbar = true } = {}) => { - const body = document.body; - const pageInfo = exports.captureClientAPI.getPageInfo(); - // Note: try to make pages with bad scrolling work, e.g., ones with - // `body { overflow-y: scroll; }` can break `window.scrollTo` - if (body) { - body.style.overflowY = 'visible'; - } - if (hideScrollbar) { - // Disable all scrollbars. We'll restore the scrollbar state when we're done - // taking the screenshots. - document.documentElement.style.overflow = 'hidden'; - } - return Promise.resolve(pageInfo); - }, - scrollPage: ({ x, y }, opts) => { - window.scrollTo(x, y); - return utils_1.delay(() => ({ - x: window.scrollX, - y: window.scrollY - }), 100); - }, - endCapture: (pageInfo) => { - const { originalX, originalY, hasBody, originalOverflowStyle, originalBodyOverflowYStyle } = pageInfo; - if (hasBody) { - document.body.style.overflowY = originalBodyOverflowYStyle !== null && originalBodyOverflowYStyle !== void 0 ? originalBodyOverflowYStyle : ''; - } - document.documentElement.style.overflow = originalOverflowStyle; - window.scrollTo(originalX, originalY); - return Promise.resolve(true); - } -}; - + }; -/***/ }), + const detect = async (image, jobId) => { + if (lstmOnlyCore) throw Error('`worker.detect` requires Legacy model, which was not loaded.'); -/***/ 18463: -/***/ ((__unused_webpack_module, exports) => { + return startJob(createJob({ + id: jobId, + action: 'detect', + payload: { image: await loadImage(image) }, + })); + }; -"use strict"; + const terminate = async () => { + if (worker !== null) { + /* + await startJob(createJob({ + id: jobId, + action: 'terminate', + })); + */ + terminateWorker(worker); + worker = null; + } + return Promise.resolve(); + }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.withConsecutive = exports.consecutive = void 0; -function consecutive(c) { - if (typeof c === 'boolean') { - return { - interval: 0, - count: c ? 1 : 0 - }; + onMessage(worker, ({ + workerId, jobId, status, action, data, + }) => { + const promiseId = `${action}-${jobId}`; + if (status === 'resolve') { + log(`[${workerId}]: Complete ${jobId}`); + let d = data; + if (action === 'recognize') { + d = circularize(data); + } else if (action === 'getPDF') { + d = Array.from({ ...data, length: Object.keys(data).length }); + } + resolves[promiseId]({ jobId, data: d }); + } else if (status === 'reject') { + rejects[promiseId](data); + if (action === 'load') workerResReject(data); + if (errorHandler) { + errorHandler(data); + } else { + throw Error(data); + } + } else if (status === 'progress') { + logger({ ...data, userJobId: jobId }); } - return c; -} -exports.consecutive = consecutive; -const timeout = (duration) => { - return new Promise(resolve => { - setTimeout(resolve, duration); - }); -}; -function withConsecutive(c, fn) { - const { interval, count } = consecutive(c); - let counter = count; - const next = (pass) => { - if (!pass) - throw new Error('failed to run consecutive'); - if (counter-- <= 0) - return Promise.resolve(true); - return timeout(interval).then(fn).then(next); - }; - return fn() - .then(next); -} -exports.withConsecutive = withConsecutive; + }); + + const resolveObj = { + id, + worker, + setResolve, + setReject, + load, + writeText, + readText, + removeFile, + FS, + loadLanguage, + initialize, + reinitialize, + setParameters, + recognize, + getPDF, + detect, + terminate, + }; + + loadInternal() + .then(() => loadLanguageInternal(langs)) + .then(() => initializeInternal(langs, oem, config)) + .then(() => workerResResolve(resolveObj)) + .catch(() => {}); + + return workerRes; +}; /***/ }), -/***/ 43232: -/***/ ((__unused_webpack_module, exports) => { +/***/ 34995: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; +/** + * + * Entry point for tesseract.js, should be the entry when bundling. + * + * @fileoverview entry point for tesseract.js + * @author Kevin Kwok + * @author Guillermo Webster + * @author Jerome Wu + */ +__webpack_require__(54493); +const createScheduler = __webpack_require__(40882); +const createWorker = __webpack_require__(12477); +const Tesseract = __webpack_require__(77465); +const languages = __webpack_require__(32646); +const OEM = __webpack_require__(89742); +const PSM = __webpack_require__(30949); +const { setLogging } = __webpack_require__(8787); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.STATE_STORAGE_KEY = exports.CS_IPC_TIMEOUT = exports.SCREENSHOT_DELAY = exports.UNTITLED_ID = exports.LAST_DESKTOP_SCREENSHOT_FILE_NAME = exports.LAST_SCREENSHOT_FILE_NAME = exports.TEST_CASE_STATUS = exports.CONTENT_SCRIPT_STATUS = exports.PLAYER_MODE = exports.PLAYER_STATUS = exports.RECORDER_STATUS = exports.INSPECTOR_STATUS = exports.APP_STATUS = void 0; -const mk = (list) => list.reduce((prev, key) => { - prev[key] = key; - return prev; -}, {}); -exports.APP_STATUS = mk([ - 'NORMAL', - 'INSPECTOR', - 'RECORDER', - 'PLAYER' -]); -exports.INSPECTOR_STATUS = mk([ - 'PENDING', - 'INSPECTING', - 'STOPPED' -]); -exports.RECORDER_STATUS = mk([ - 'PENDING', - 'RECORDING', - 'STOPPED' -]); -exports.PLAYER_STATUS = mk([ - 'PLAYING', - 'PAUSED', - 'STOPPED' -]); -exports.PLAYER_MODE = mk([ - 'TEST_CASE', - 'TEST_SUITE' -]); -exports.CONTENT_SCRIPT_STATUS = mk([ - 'NORMAL', - 'RECORDING', - 'INSPECTING', - 'PLAYING' -]); -exports.TEST_CASE_STATUS = mk([ - 'NORMAL', - 'SUCCESS', - 'ERROR', - 'ERROR_IN_SUB' -]); -exports.LAST_SCREENSHOT_FILE_NAME = '__lastscreenshot'; -exports.LAST_DESKTOP_SCREENSHOT_FILE_NAME = '__last_desktop_screenshot'; -exports.UNTITLED_ID = '__untitled__'; -// Note: in Ubuntu, you have to take some delay after activating some tab, otherwise there are chances -// Chrome still think the panel is the window you want to take screenshot, and weird enough in Ubuntu, -// You can't take screenshot of tabs with 'chrome-extension://' schema, even if it's your own extension -exports.SCREENSHOT_DELAY = /Linux/i.test(self.navigator.userAgent) ? 200 : 0; -exports.CS_IPC_TIMEOUT = 3000; -exports.STATE_STORAGE_KEY = 'background_state'; +module.exports = { + languages, + OEM, + PSM, + createScheduler, + createWorker, + setLogging, + ...Tesseract, +}; /***/ }), -/***/ 24874: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 64760: +/***/ ((module) => { -"use strict"; +/** + * In the recognition result of tesseract, there + * is a deep JSON object for details, it has around + * + * The result of dump.js is a big JSON tree + * which can be easily serialized (for instance + * to be sent from a webworker to the main app + * or through Node's IPC), but we want + * a (circular) DOM-like interface for walking + * through the data. + * + * @fileoverview DOM-like interface for walking through data + * @author Kevin Kwok + * @author Guillermo Webster + * @author Jerome Wu + */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.elementByElementFromPoint = exports.viewportCoordinateByElementFromPoint = exports.isElementFromPoint = exports.getElementByLocator = exports.isLocator = exports.assertLocator = exports.getElementByXPath = exports.getElementsByXPath = exports.getAncestor = exports.hasAncestor = exports.isEditable = exports.scaleRect = exports.getPixel = exports.rgbToHex = exports.subImage = exports.imageDataFromUrl = exports.imageBlobFromSVG = exports.canvasFromSVG = exports.svgToBase64 = exports.svgNodetoString = exports.isFirefox = exports.preloadImage = exports.accurateOffset = exports.offset = exports.isPositionFixed = exports.cssSelector = exports.isVisible = exports.domText = exports.scrollTop = exports.scrollLeft = exports.bindContentEditableChange = exports.bindDrag = exports.pixel = exports.setStyle = exports.getStyle = void 0; -const glob_1 = __webpack_require__(64341); -const utils_1 = __webpack_require__(63370); -exports.getStyle = function (dom) { - if (!dom) - throw new Error('getStyle: dom does not exist'); - return getComputedStyle(dom); -}; -exports.setStyle = function (dom, style) { - if (!dom) - throw new Error('setStyle: dom does not exist'); - for (var i = 0, keys = Object.keys(style), len = keys.length; i < len; i++) { - dom.style[keys[i]] = style[keys[i]]; - } - return dom; -}; -exports.pixel = function (num) { - if ((num + '').indexOf('px') !== -1) - return num; - return (num || 0) + 'px'; -}; -exports.bindDrag = (options) => { - const { onDragStart, onDragEnd, onDrag, $el, preventGlobalClick = true, doc = document } = options; - let isDragging = false; - let startPos = { x: 0, y: 0 }; - const onMouseDown = (e) => { - isDragging = true; - startPos = { x: e.screenX, y: e.screenY }; - onDragStart(e); - }; - const onMouseUp = (e) => { - if (!isDragging) - return; - isDragging = false; - const dx = e.screenX - startPos.x; - const dy = e.screenY - startPos.y; - onDragEnd(e, { dx, dy }); - }; - const onMouseMove = (e) => { - if (!isDragging) - return; - const dx = e.screenX - startPos.x; - const dy = e.screenY - startPos.y; - onDrag(e, { dx, dy }); - e.preventDefault(); - e.stopPropagation(); - }; - const onClick = (e) => { - e.preventDefault(); - e.stopPropagation(); - }; - if (preventGlobalClick) { - doc.addEventListener('click', onClick, true); - } - doc.addEventListener('mousemove', onMouseMove, true); - doc.addEventListener('mouseup', onMouseUp, true); - $el.addEventListener('mousedown', onMouseDown, true); - return () => { - doc.removeEventListener('click', onClick, true); - doc.removeEventListener('mousemove', onMouseMove, true); - doc.removeEventListener('mouseup', onMouseUp, true); - $el.removeEventListener('mousedown', onMouseDown, true); - }; -}; -exports.bindContentEditableChange = (options) => { - const { onChange, doc = document } = options; - let currentCE = null; - let oldContent = null; - const onFocus = (e) => { - if (!e.target || e.target.contentEditable !== 'true') - return; - currentCE = e.target; - oldContent = currentCE.innerHTML; - }; - const onBlur = (e) => { - if (e.target !== currentCE) { - // Do nothing - } - else if (currentCE && currentCE.innerHTML !== oldContent) { - onChange(e); - } - currentCE = null; - oldContent = null; - }; - doc.addEventListener('focus', onFocus, true); - doc.addEventListener('blur', onBlur, true); - return () => { - doc.removeEventListener('focus', onFocus, true); - doc.removeEventListener('blur', onBlur, true); - }; -}; -exports.scrollLeft = function (document) { - return document.documentElement.scrollLeft; -}; -exports.scrollTop = function (document) { - return document.documentElement.scrollTop; -}; -exports.domText = ($dom) => { - const it = $dom.innerText ? $dom.innerText.trim() : ''; - const tc = $dom.textContent; - const pos = tc.toUpperCase().indexOf(it.toUpperCase()); - return pos === -1 ? it : tc.substr(pos, it.length); -}; -exports.isVisible = function (el) { - if (el === window.document) - return true; - if (!el) - return true; - const style = window.getComputedStyle(el); - if (style.display === 'none' || style.opacity === '0' || style.visibility === 'hidden') - return false; - return exports.isVisible(el.parentNode); -}; -exports.cssSelector = function (dom) { - if (!dom) - return ''; - if (dom.nodeType !== 1) - return ''; - if (dom.tagName === 'BODY') - return 'body'; - if (dom.id) - return '#' + dom.id; - var classes = dom.className.split(/\s+/g) - .filter(function (item) { - return item && item.length; - }); - var children = Array.from(dom.parentNode ? dom.parentNode.childNodes : []) - .filter(function ($el) { - return $el.nodeType === 1; - }); - var sameTag = children.filter(function ($el) { - return $el.tagName === dom.tagName; - }); - var sameClass = children.filter(function ($el) { - var cs = $el.className.split(/\s+/g); - return utils_1.and(...classes.map(function (c) { - return cs.indexOf(c) !== -1; - })); - }); - var extra = ''; - if (sameTag.length === 1) { - extra = ''; - } - else if (classes.length && sameClass.length === 1) { - extra = '.' + classes.join('.'); - } - else { - extra = ':nth-child(' + (1 + children.findIndex(function (item) { return item === dom; })) + ')'; - } - var me = dom.tagName.toLowerCase() + extra; - // Note: browser will add an extra 'tbody' when tr directly in table, which will cause an wrong selector, - // so the hack is to remove all tbody here - var ret = exports.cssSelector(dom.parentNode) + ' > ' + me; - return ret; - // return ret.replace(/\s*>\s*tbody\s*>?/g, ' ') -}; -exports.isPositionFixed = ($dom) => { - if (!$dom || $dom === document.documentElement || $dom === document.body) - return false; - return getComputedStyle($dom)['position'] === 'fixed' || exports.isPositionFixed($dom.parentNode); -}; -exports.offset = function (dom) { - if (!dom) - return { left: 0, top: 0 }; - var rect = dom.getBoundingClientRect(); - return { - left: rect.left + window.scrollX, - top: rect.top + window.scrollY - }; -}; -function accurateOffset(dom) { - if (!dom) - return { left: 0, top: 0 }; - const doc = dom.ownerDocument; - if (!doc || dom === doc.documentElement) - return { left: 0, top: 0 }; - const parentOffset = accurateOffset(dom.offsetParent); - return { - left: parentOffset.left + dom.offsetLeft, - top: parentOffset.top + dom.offsetTop - }; -} -exports.accurateOffset = accurateOffset; -function preloadImage(url) { - return new Promise((resolve, reject) => { - const $img = new Image(); - $img.onload = () => { - resolve({ - $img, - width: $img.width, - height: $img.height +module.exports = (page) => { + const blocks = []; + const paragraphs = []; + const lines = []; + const words = []; + const symbols = []; + + if (page.blocks) { + page.blocks.forEach((block) => { + block.paragraphs.forEach((paragraph) => { + paragraph.lines.forEach((line) => { + line.words.forEach((word) => { + word.symbols.forEach((sym) => { + symbols.push({ + ...sym, page, block, paragraph, line, word, + }); }); - }; - $img.onerror = (e) => { - reject(e); - }; - $img.src = url; - }); -} -exports.preloadImage = preloadImage; -function isFirefox() { - return /Firefox/.test(window.navigator.userAgent); -} -exports.isFirefox = isFirefox; -function svgNodetoString(svgNode) { - return svgNode.outerHTML; -} -exports.svgNodetoString = svgNodetoString; -function svgToBase64(str) { - return 'data:image/svg+xml;base64,' + window.btoa(str); -} -exports.svgToBase64 = svgToBase64; -function canvasFromSVG(str) { - return new Promise((resolve, reject) => { - const c = document.createElement('canvas'); - const ctx = c.getContext('2d'); - const img = document.createElement('img'); - const b64 = svgToBase64(str); - const mw = str.match(/ { - const p = new Promise((resolve, reject) => { - try { - canvas.toBlob(resolve, mimeType, quality); - } - catch (e) { - reject(e); - } + words.push({ + ...word, page, block, paragraph, line, + }); + }); + lines.push({ + ...line, page, block, paragraph, + }); }); - return p; - }); -} -exports.imageBlobFromSVG = imageBlobFromSVG; -function imageDataFromUrl(url) { - return preloadImage(url) - .then(({ $img, width, height }) => { - const canvas = document.createElement('canvas'); - canvas.width = width; - canvas.height = height; - const context = canvas.getContext('2d'); - context.drawImage($img, 0, 0, width, height); - return context.getImageData(0, 0, width, height); - }); -} -exports.imageDataFromUrl = imageDataFromUrl; -function subImage(imageUrl, rect) { - return new Promise((resolve, reject) => { - const $img = new Image(); - $img.onload = () => { - const canvas = document.createElement('canvas'); - canvas.width = rect.width; - canvas.height = rect.height; - const context = canvas.getContext('2d'); - context.drawImage($img, 0, 0, $img.width, $img.height, -1 * rect.x, -1 * rect.y, $img.width, $img.height); - resolve(canvas.toDataURL()); - }; - $img.src = imageUrl; - }); -} -exports.subImage = subImage; -function rgbToHex(r, g, b) { - if (r > 255 || g > 255 || b > 255) { - throw 'Invalid color component'; - } - return ((r << 16) | (g << 8) | b).toString(16); -} -exports.rgbToHex = rgbToHex; -function getPixel(params) { - const { x, y, dataUrl } = params; - return new Promise((resolve, reject) => { - const $img = new Image(); - $img.onload = () => { - const imgWidth = $img.width; - const imgHeight = $img.height; - if (x < 0 || y < 0 || x > imgWidth || y > imgHeight) { - return reject(new Error(`${x}, ${y} is out of screenshot bound 0, 0 ~ ${imgWidth}, ${imgHeight}`)); - } - const canvas = document.createElement('canvas'); - canvas.width = x + 5; - canvas.height = y + 5; - const context = canvas.getContext('2d'); - context.drawImage($img, 0, 0, x + 5, y + 5, 0, 0, x + 5, y + 5); - let hex; - try { - const p = context.getImageData(x, y, 1, 1).data; - hex = '#' + ('000000' + rgbToHex(p[0], p[1], p[2])).slice(-6); - resolve(hex); - } - catch (err) { - const e = err; - reject(new Error(`Failed to get pixel color` + ((e === null || e === void 0 ? void 0 : e.message) ? `: ${e.message}.` : '.'))); - } - }; - $img.src = dataUrl; + paragraphs.push({ + ...paragraph, page, block, + }); + }); + blocks.push({ + ...block, page, + }); }); -} -exports.getPixel = getPixel; -function scaleRect(rect, scale) { - return { - x: scale * rect.x, - y: scale * rect.y, - width: scale * rect.width, - height: scale * rect.height, - }; -} -exports.scaleRect = scaleRect; -function isEditable(el) { - if (el.contentEditable === 'true') { - return true; - } - const tag = (el.tagName || '').toLowerCase(); - if (['input', 'textarea'].indexOf(tag) === -1) { - return false; - } - const disabled = el.disabled; - const readOnly = el.readOnly; - return !disabled && !readOnly; -} -exports.isEditable = isEditable; -function hasAncestor(el, checkAncestor) { - let node = el; - while (node) { - if (checkAncestor(node)) { - return true; - } - node = node.parentNode; - } - return false; -} -exports.hasAncestor = hasAncestor; -function getAncestor(el, checkAncestor) { - let node = el; - while (node) { - if (checkAncestor(node)) { - return node; - } - node = node.parentNode; - } - return null; -} -exports.getAncestor = getAncestor; -function getElementsByXPath(xpath) { - const snapshot = document.evaluate(xpath, document.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); - const list = []; - for (let i = 0, len = snapshot.snapshotLength; i < len; i++) { - list.push(snapshot.snapshotItem(i)); - } - return list; -} -exports.getElementsByXPath = getElementsByXPath; -function getElementByXPath(xpath) { - return getElementsByXPath(xpath)[0]; -} -exports.getElementByXPath = getElementByXPath; -function assertLocator(str) { - const i = str.indexOf('='); - // xpath - if ((/^\//.test(str))) - return true; - // efp - if (/^#elementfrompoint/i.test(str)) - return true; - // Above is all locators that doesn't require '=' - if (i === -1) - throw new Error('invalid locator, ' + str); - const method = str.substr(0, i); - const value = str.substr(i + 1); - if (!value || !value.length) - throw new Error('invalid locator, ' + str); - switch (method && method.toLowerCase()) { - case 'id': - case 'name': - case 'identifier': - case 'link': - case 'linktext': - case 'partiallinktext': - case 'css': - case 'xpath': - return true; - default: - throw new Error('invalid locator, ' + str); - } -} -exports.assertLocator = assertLocator; -function isLocator(str) { - try { - assertLocator(str); - return true; - } - catch (e) { - return false; - } -} -exports.isLocator = isLocator; -// Note: parse the locator and return the element found accordingly -function getElementByLocator(str, shouldWaitForVisible) { - const i = str.indexOf('='); - let el; - if ((/^\//.test(str))) { - el = getElementByXPath(str); - } - else if (/^#elementfrompoint/i.test(str.trim())) { - el = elementByElementFromPoint(str); - } - else if (i === -1) { - throw new Error('getElementByLocator: invalid locator, ' + str); - } - else { - const method = str.substr(0, i); - const value = str.substr(i + 1); - const lowerMethod = method && method.toLowerCase(); - switch (lowerMethod) { - case 'id': - el = document.getElementById(value); - break; - case 'name': - el = document.getElementsByName(value)[0]; - break; - case 'identifier': - el = document.getElementById(value) || document.getElementsByName(value)[0]; - break; - case 'link-notused': { - const links = [].slice.call(document.getElementsByTagName('a')); - // Note: there are cases such as 'link=exact:xxx' - let realVal = value.replace(/^exact:/, ''); - // Note: position support. eg. link=Download@POS=3 - let match = realVal.match(/^(.+)@POS=(\d+)$/i); - let index = 0; - if (match) { - realVal = match[1]; - index = parseInt(match[2]) - 1; - } - // Note: use textContent instead of innerText to avoid influence from text-transform - const candidates = links.filter(a => glob_1.globMatch(realVal, exports.domText(a))); - el = candidates[index]; - break; - } - case 'link': - case 'linktext': - case 'partiallinktext': { - const links = [].slice.call(document.getElementsByTagName('a')); - // Note: position support. eg. link=Download@POS=3 - let match = value.match(/^(.+)@POS=(\d+)$/i); - let realVal = value; - let index = 0; - if (match) { - realVal = match[1]; - index = parseInt(match[2]) - 1; - } - const pattern = lowerMethod === 'partiallinktext' ? `*${realVal}*` : realVal; - const candidates = links.filter(link => glob_1.globMatch(pattern, exports.domText(link), { flags: 'im' })); - el = candidates[index]; - break; - } - case 'css': - el = document.querySelector(value); - break; - case 'xpath': - el = getElementByXPath(value); - break; - default: - throw new Error('getElementByLocator: unsupported locator method, ' + method); - } - } - if (!el) { - throw new Error('getElementByLocator: fail to find element based on the locator, ' + str); - } - if (shouldWaitForVisible && !exports.isVisible(el)) { - throw new Error('getElementByLocator: element is found but not visible yet'); - } - return el; -} -exports.getElementByLocator = getElementByLocator; -function isElementFromPoint(str) { - return /^#elementfrompoint/i.test(str.trim()); -} -exports.isElementFromPoint = isElementFromPoint; -function viewportCoordinateByElementFromPoint(str) { - const reg = /^#elementfrompoint\s*\((\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\)/i; - const m = str.trim().match(reg); - if (!m) { - throw new Error(`Invalid '#elementfrompoint' expression`); - } - const viewportX = parseFloat(m[1]); - const viewportY = parseFloat(m[2]); - if (viewportX <= 0 || viewportY <= 0) { - throw new Error(`'#elementfrompoint' only accepts positive numbers`); - } - return [viewportX, viewportY]; -} -exports.viewportCoordinateByElementFromPoint = viewportCoordinateByElementFromPoint; -function elementByElementFromPoint(str) { - const [x, y] = viewportCoordinateByElementFromPoint(str); - const el = document.elementFromPoint(x, y); - return el; -} -exports.elementByElementFromPoint = elementByElementFromPoint; + } + + return { + ...page, blocks, paragraphs, lines, words, symbols, + }; +}; /***/ }), -/***/ 54105: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 3820: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var process = __webpack_require__(65606); +const isElectron = __webpack_require__(4866); -"use strict"; +module.exports = (key) => { + const env = {}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; + if (typeof WorkerGlobalScope !== 'undefined') { + env.type = 'webworker'; + } else if (isElectron()) { + env.type = 'electron'; + } else if (typeof document === 'object') { + env.type = 'browser'; + } else if (typeof process === 'object' && "function" === 'function') { + env.type = 'node'; + } + + if (typeof key === 'undefined') { + return env; + } + + return env[key]; }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getIpcCache = exports.IpcCache = void 0; -const ts_utils_1 = __webpack_require__(55452); -const consecutive_1 = __webpack_require__(18463); -const storage_1 = __importDefault(__webpack_require__(67585)); -const ipc_bg_cs_1 = __webpack_require__(31745); -var IpcStatus; -(function (IpcStatus) { - IpcStatus[IpcStatus["Off"] = 0] = "Off"; - IpcStatus[IpcStatus["On"] = 1] = "On"; -})(IpcStatus || (IpcStatus = {})); -const ipcCacheStorageKey = 'ipc_cache'; -class IpcCache { - constructor() { - this.cuidIpcMap = {}; - } - fetch() { - return storage_1.default.get(ipcCacheStorageKey).then(cache => cache || {}); - } - has(tabId, cuid) { - return this.fetch().then(cache => { - const item = cache[tabId]; - return !!item && (!cuid || item.cuid == cuid); - }); - } - get(tabId, timeout = 2000, before = Infinity) { - return ts_utils_1.until('ipc by tab id', () => { - return this.fetch().then((cache) => { - const ipcObj = cache[tabId]; - const enabled = ipcObj && ipcObj.status === IpcStatus.On; - const valid = enabled && (before === Infinity || before > ipcObj.timestamp); - if (!valid) { - return { - pass: false, - result: null - }; - } - return { - pass: true, - result: this.getCachedIpc(`${ipcObj.cuid}`, tabId), - }; - }); - }, 100, timeout); - } - domReadyGet(tabId, timeout = 60 * 1000, c = true) { - return ts_utils_1.retry(() => { - return this.get(tabId) - .then(ipc => { - // Note: must respond to DOM READY for multiple times in line, - // before we can be sure that it's ready - return consecutive_1.withConsecutive(c, () => { - return ipc.ask('DOM_READY', {}, 1000) - .then(() => true, () => false); - }) - .then(() => ipc); - }); - }, { - timeout, - retryInterval: 1000, - shouldRetry: (e) => true - })(); - } - set(tabId, ipc, cuid) { - return this.fetch().then(cache => { - cache[tabId] = { - ipc, - cuid, - status: 1, - timestamp: new Date().getTime() - }; - return storage_1.default.set(ipcCacheStorageKey, cache).then(() => { }); - }); - } - setStatus(tabId, status, updateTimestamp = false) { - return this.fetch().then(cache => { - const found = cache[tabId]; - if (!found) - return false; - found.status = status; - if (updateTimestamp) { - found.timestamp = new Date().getTime(); - } - return storage_1.default.set(ipcCacheStorageKey, cache); - }); - } - enable(tabId) { - return this.setStatus(tabId, IpcStatus.On, true); - } - disable(tabId) { - return this.setStatus(tabId, IpcStatus.Off); - } - getCuid(tabId) { - return this.fetch().then(cache => { - const found = cache[tabId]; - if (!found) - return null; - return found.cuid; - }); - } - del(tabId) { - return this.fetch().then(cache => { - delete cache[tabId]; - return storage_1.default.set(ipcCacheStorageKey, cache).then(() => { }); - }); - } - cleanup(tabIdDict) { - return this.fetch().then(cache => { - Object.keys(cache).forEach(tabId => { - if (!tabIdDict[tabId]) { - delete cache[tabId]; - } - }); - return storage_1.default.set(ipcCacheStorageKey, cache).then(() => cache); - }); - } - getCachedIpc(cuid, tabId) { - if (!this.cuidIpcMap[cuid]) { - this.cuidIpcMap[cuid] = ipc_bg_cs_1.openBgWithCs(cuid).ipcBg(tabId); - } - return this.cuidIpcMap[cuid]; - } -} -exports.IpcCache = IpcCache; -exports.getIpcCache = ts_utils_1.singletonGetter(() => new IpcCache); /***/ }), -/***/ 77242: -/***/ ((__unused_webpack_module, exports) => { +/***/ 1028: +/***/ ((module) => { + +module.exports = (prefix, cnt) => ( + `${prefix}-${cnt}-${Math.random().toString(16).slice(3, 8)}` +); + + +/***/ }), + +/***/ 8787: +/***/ (function(__unused_webpack_module, exports) { -"use strict"; +let logging = false; -// Log factory is quite simple, just a wrapper on console.log -// so that you can use the same API, at the same, achieve following features -// 1. Hide all logs in production -// 2. Extend it to save logs in local storage / or send it back to you backend (for debug or analysis) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.logFactory = void 0; -function logFactory(enabled) { - let isEnabled = !!enabled; - const obj = ['log', 'info', 'warn', 'error'].reduce((prev, method) => { - prev[method] = (...args) => { - if (!isEnabled) - return; - console[method]((new Date()).toISOString(), ' - ', ...args); - }; - return prev; - }, {}); - return Object.assign(obj.log, obj, { - enable: () => { isEnabled = true; }, - disable: () => { isEnabled = false; } - }); -} -exports.logFactory = logFactory; -const logger = logFactory("production" !== 'production'); -exports["default"] = logger; +exports.logging = logging; + +exports.setLogging = (_logging) => { + logging = _logging; +}; + +exports.log = (...args) => (logging ? console.log.apply(this, args) : null); /***/ }), -/***/ 55452: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 65981: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; +const isBrowser = __webpack_require__(3820)('type') === 'browser'; -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()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.throttlePromiseFunc = exports.urlWithQueries = exports.withCountDown = exports.countDown = exports.resolvePath = exports.isMac = exports.repeatStr = exports.pad2digits = exports.assertExhausted = exports.readFileAsText = exports.withConsecutive = exports.consecutive = exports.uniqueStrings = exports.unique = exports.normalizeHtmlId = exports.addInBetween = exports.pointToFitRect = exports.nodeByOffset = exports.toArray = exports.findNodeInForest = exports.findNodeInTree = exports.flatternTree = exports.flattenTreeWithPaths = exports.ancestorsInNodesList = exports.pathsInNodeList = exports.ancestorsInNode = exports.pathsInNode = exports.traverseTree = exports.TraverseTreeResult = exports.nodeCount = exports.isForestEqual = exports.isTreeEqual = exports.forestSlice = exports.treeSlice = exports.treeFilter = exports.treeMap = exports.errorClassFactory = exports.concurrent = exports.milliSecondsToStringInSecond = exports.objMap = exports.clone = exports.withPromise = exports.concatUint8Array = exports.sum = exports.strictParseBoolLike = exports.parseBoolLike = exports.guardVoidPromise = exports.flow = exports.retryWithCount = exports.retry = exports.throttle = exports.objFilter = exports.uniqueName = exports.getExtName = exports.withFileExtension = exports.withPostfix = exports.or = exports.and = exports.zipWith = exports.flatten = exports.uid = exports.without = exports.pickIfExist = exports.pick = exports.safeSetIn = exports.safeUpdateIn = exports.safeOn = exports.safeMap = exports.getIn = exports.setIn = exports.updateIn = exports.on = exports.map = exports.compose = exports.reduceRight = exports.partial = exports.range = exports.until = exports.delay = exports.snakeToCamel = exports.capitalInitial = exports.id = exports.singletonGetterByKey = exports.singletonGetter = void 0; -const log_1 = __importDefault(__webpack_require__(77242)); -function singletonGetter(factoryFn) { - let instance = null; - return (...args) => { - if (instance) - return instance; - instance = factoryFn(...args); - return instance; - }; -} -exports.singletonGetter = singletonGetter; -function singletonGetterByKey(getKey, factoryFn) { - let cache = {}; - return (...args) => { - const key = getKey(...args); - if (cache[key]) - return cache[key]; - cache[key] = factoryFn(...args); - return cache[key]; - }; -} -exports.singletonGetterByKey = singletonGetterByKey; -function id(x) { - return x; -} -exports.id = id; -function capitalInitial(str) { - return str.charAt(0).toUpperCase() + str.substr(1); -} -exports.capitalInitial = capitalInitial; -function snakeToCamel(kebabStr) { - const list = kebabStr.split('_'); - return list[0] + list.slice(1).map(capitalInitial).join(''); -} -exports.snakeToCamel = snakeToCamel; -exports.delay = (fn, timeout) => { - return new Promise((resolve, reject) => { - setTimeout(() => { - try { - resolve(fn()); - } - catch (e) { - reject(e); - } - }, timeout); - }); -}; -exports.until = (name, check, interval = 1000, expire = 10000) => { - const start = new Date().getTime(); - const go = () => __awaiter(void 0, void 0, void 0, function* () { - if (expire && new Date().getTime() - start >= expire) { - throw new Error(`until: ${name} expired!`); - } - const { pass, result } = yield Promise.resolve(check()); - if (pass) - return Promise.resolve(result); - return exports.delay(go, interval); - }); - return new Promise((resolve, reject) => { - try { - resolve(go()); - } - catch (e) { - reject(e); - } - }); -}; -exports.range = (start, end, step = 1) => { - const ret = []; - for (let i = start; i < end; i += step) { - ret.push(i); - } - return ret; -}; -exports.partial = (fn) => { - const len = fn.length; - let arbitary; - arbitary = (curArgs, leftArgCnt) => (...args) => { - if (args.length >= leftArgCnt) { - return fn.apply(null, curArgs.concat(args)); - } - return arbitary(curArgs.concat(args), leftArgCnt - args.length); - }; - return arbitary([], len); -}; -exports.reduceRight = (fn, initial, list) => { - let ret = initial; - for (let i = list.length - 1; i >= 0; i--) { - ret = fn(list[i], ret); - } - return ret; -}; -exports.compose = (...args) => { - return exports.reduceRight((cur, prev) => { - return (x) => cur(prev(x)); - }, (x) => x, args); -}; -exports.map = exports.partial((fn, list) => { - const result = []; - for (let i = 0, len = list.length; i < len; i++) { - result.push(fn(list[i])); - } - return result; -}); -exports.on = exports.partial((key, fn, dict) => { - if (Array.isArray(dict)) { - return [ - ...dict.slice(0, key), - fn(dict[key]), - ...dict.slice(key + 1) - ]; - } - return Object.assign({}, dict, { - [key]: fn(dict[key]) - }); -}); -exports.updateIn = exports.partial((keys, fn, obj) => { - const updater = exports.compose.apply(null, keys.map(key => key === '[]' ? exports.map : exports.on(key))); - return updater(fn)(obj); -}); -exports.setIn = exports.partial((keys, value, obj) => { - const updater = exports.compose.apply(null, keys.map(key => key === '[]' ? exports.map : exports.on(key))); - return updater(() => value)(obj); -}); -exports.getIn = exports.partial((keys, obj) => { - return keys.reduce((prev, key) => { - if (!prev) - return prev; - return prev[key]; - }, obj); -}); -exports.safeMap = exports.partial((fn, list) => { - const result = []; - const safeList = list || []; - for (let i = 0, len = safeList.length; i < len; i++) { - result.push(fn(safeList[i])); - } - return result; -}); -exports.safeOn = exports.partial((key, fn, dict) => { - if (Array.isArray(dict)) { - return [ - ...dict.slice(0, key), - fn(dict[key]), - ...dict.slice(key + 1) - ]; - } - return Object.assign({}, dict, { - [key]: fn((dict || {})[key]) - }); -}); -exports.safeUpdateIn = exports.partial((keys, fn, obj) => { - const updater = exports.compose.apply(null, keys.map(key => key === '[]' ? exports.safeMap : exports.safeOn(key))); - return updater(fn)(obj); -}); -exports.safeSetIn = exports.partial((keys, value, obj) => { - const updater = exports.compose.apply(null, keys.map(key => key === '[]' ? exports.safeMap : exports.safeOn(key))); - return updater(() => value)(obj); -}); -exports.pick = (keys, obj) => { - return keys.reduce((prev, key) => { - prev[key] = obj[key]; - return prev; - }, {}); -}; -exports.pickIfExist = (keys, obj) => { - return keys.reduce((prev, key) => { - if (obj[key] !== undefined) { - prev[key] = obj[key]; - } - return prev; - }, {}); -}; -exports.without = (keys, obj) => { - return Object.keys(obj).reduce((prev, key) => { - if (keys.indexOf(key) === -1) { - prev[key] = obj[key]; - } - return prev; - }, {}); -}; -exports.uid = () => { - return '' + (new Date().getTime()) + '.' + - Math.floor(Math.random() * 10000000).toString(16); -}; -exports.flatten = (list) => { - return [].concat.apply([], list); -}; -exports.zipWith = (fn, ...listOfList) => { - const len = Math.min(...listOfList.map(list => list.length)); - const res = []; - for (let i = 0; i < len; i++) { - res.push(fn(...listOfList.map(list => list[i]))); - } - return res; -}; -exports.and = (...list) => list.reduce((prev, cur) => prev && cur, true); -exports.or = (...list) => list.reduce((prev, cur) => prev || cur, false); -exports.withPostfix = (options) => { - const { reg, str, fn } = options; - const m = str.match(reg); - const extName = m ? m[0] : ''; - const baseName = m ? str.replace(reg, '') : str; - const result = fn(baseName, (name) => name + extName); - if (result === null || result === undefined) { - throw new Error('withPostfix: should not return null/undefined'); - } - if (typeof result.then === 'function') { - return result.then((name) => name + extName); - } - return result + extName; -}; -exports.withFileExtension = (origName, fn) => { - return exports.withPostfix({ - fn, - str: origName, - reg: /\.\w+$/ - }); -}; -function getExtName(fileName) { - return exports.withFileExtension(fileName, () => ''); -} -exports.getExtName = getExtName; -exports.uniqueName = (name, options) => { - const opts = Object.assign({ generate: (old, step = 1) => { - const reg = /_(\d+)$/; - const m = old.match(reg); - if (!m) - return `${old}_${step}`; - return old.replace(reg, (_, n) => `_${parseInt(n, 10) + step}`); - }, check: () => Promise.resolve(true), postfixReg: /\.\w+$/ }, (options || {})); - const { generate, check, postfixReg } = opts; - return exports.withPostfix({ - str: name, - reg: postfixReg, - fn: (baseName, getFullName) => { - const go = (fileName, step) => { - return Promise.resolve(check(getFullName(fileName))) - .then(pass => { - if (pass) - return fileName; - return go(generate(fileName, step), step); - }); - }; - return go(baseName, 1); - } - }); -}; -exports.objFilter = (filter, obj) => { - return Object.keys(obj).reduce((prev, key, i) => { - if (filter(obj[key], key, i)) { - prev[key] = obj[key]; - } - return prev; - }, {}); -}; -function throttle(fn, timeout) { - let lastTime = 0; - return (...args) => { - const now = new Date().getTime(); - if (now - lastTime < timeout) - return; - lastTime = now; - return fn(...args); - }; -} -exports.throttle = throttle; -exports.retry = (fn, options) => (...args) => { - const { timeout, onFirstFail, onFinal, shouldRetry, retryInterval } = Object.assign({ timeout: 5000, retryInterval: 1000, onFirstFail: (() => { }), onFinal: (() => { }), shouldRetry: (e) => false }, options); - let retryCount = 0; - let lastError; - let timerToClear; - let done = false; - const wrappedOnFinal = (...args) => { - done = true; - if (timerToClear) { - clearTimeout(timerToClear); - } - return onFinal(...args); - }; - const intervalMan = (function () { - let lastInterval; - const intervalFactory = (function () { - switch (typeof retryInterval) { - case 'function': - return retryInterval; - case 'number': - return ((retryCount, lastInterval) => retryInterval); - default: - throw new Error('retryInterval must be either a number or a function'); - } - })(); - return { - getLastInterval: () => lastInterval, - getInterval: () => { - const interval = intervalFactory(retryCount, lastInterval); - lastInterval = interval; - return interval; - } - }; - })(); - const onError = (e, _throwErr) => { - const throwErr = _throwErr || ((e) => Promise.reject(e)); - if (retryCount === 0) { - onFirstFail(e); - } - return new Promise(resolve => { - resolve(shouldRetry(e)); - }) - .then((should) => { - if (!should) { - wrappedOnFinal(e); - return throwErr(e); - } - lastError = e; - const p = new Promise((resolve, reject) => { - if (retryCount++ === 0) { - timerToClear = setTimeout(() => { - wrappedOnFinal(lastError); - reject(lastError); - }, timeout); - } - if (done) - return; - exports.delay(run, intervalMan.getInterval()) - .then(resolve, (e) => resolve(onError(e, (err) => reject(e)))); - }); - return p; - }); - }; - const run = () => { - return new Promise((resolve, reject) => { - try { - const res = fn(...args, { - retryCount, - retryInterval: intervalMan.getLastInterval() - }); - resolve(res); - } - catch (e) { - reject(e); - } - }) - .catch(onError); - }; - return run() - .then((result) => { - wrappedOnFinal(null, result); - return result; - }); -}; -function retryWithCount(options, fn) { - let n = 0; - return exports.retry(fn, { - timeout: 99999, - retryInterval: options.interval, - shouldRetry: () => ++n <= options.count - }); -} -exports.retryWithCount = retryWithCount; -function flow(...fns) { - const result = new Array(fns.length); - const finalPromise = fns.reduce((prev, fn, i) => { - return prev.then((res) => { - if (i > 0) { - result[i - 1] = res; - } - return fn(res); - }); - }, Promise.resolve()); - return finalPromise.then((res) => { - result[fns.length - 1] = res; - return result; - }); -} -exports.flow = flow; -function guardVoidPromise(fn) { - return (...args) => { - return new Promise((resolve, reject) => { - try { - resolve(fn(...args)); - } - catch (e) { - reject(e); - } - }) - .then(() => { }, (e) => { - log_1.default.error(e); - }); - }; -} -exports.guardVoidPromise = guardVoidPromise; -function parseBoolLike(value, fallback = false) { - if (typeof value === 'boolean') { - return value; - } - if (typeof value === 'number') { - return !!value; - } - if (value === undefined) { - return fallback; - } - try { - const val = JSON.parse(value.toLowerCase()); - return !!val; - } - catch (e) { - return fallback; - } -} -exports.parseBoolLike = parseBoolLike; -function strictParseBoolLike(value) { - if (typeof value === 'boolean') { - return value; - } - const result = JSON.parse(value.toLowerCase()); - if (typeof result !== 'boolean') { - throw new Error('Not a boolean'); - } - return result; -} -exports.strictParseBoolLike = strictParseBoolLike; -function sum(...list) { - return list.reduce((x, y) => x + y, 0); -} -exports.sum = sum; -function concatUint8Array(...arrays) { - const totalLength = sum(...arrays.map(arr => arr.length)); - const result = new Uint8Array(totalLength); - for (let i = 0, offset = 0, len = arrays.length; i < len; i += 1) { - result.set(arrays[i], offset); - offset += arrays[i].length; +const resolveURL = isBrowser ? s => (new URL(s, window.location.href)).href : s => s; // eslint-disable-line + +module.exports = (options) => { + const opts = { ...options }; + ['corePath', 'workerPath', 'langPath'].forEach((key) => { + if (options[key]) { + opts[key] = resolveURL(opts[key]); } - return result; -} -exports.concatUint8Array = concatUint8Array; -function withPromise(factory) { - return new Promise((resolve) => { - resolve(factory()); - }); -} -exports.withPromise = withPromise; -function clone(data) { - if (data === undefined) - return undefined; - return JSON.parse(JSON.stringify(data)); -} -exports.clone = clone; -exports.objMap = (fn, obj) => { - const keys = typeof obj === 'object' ? Object.keys(obj) : []; - return keys.reduce((prev, key, i) => { - prev[key] = fn(obj[key], key, i, obj); - return prev; - }, {}); -}; -function milliSecondsToStringInSecond(ms) { - return (ms / 1000).toFixed(2) + 's'; -} -exports.milliSecondsToStringInSecond = milliSecondsToStringInSecond; -exports.concurrent = function (max) { - var queue = []; - var running = 0; - var free = function () { - running--; - check(); - }; - const check = function () { - if (running >= max || queue.length <= 0) - return; - var tuple = queue.shift(); - var resolve = tuple.resolve; - running++; - resolve(free); - }; - const wait = function () { - return new Promise(function (resolve, reject) { - queue.push({ resolve, reject }); - check(); - }); - }; - const wrap = function (fn, context) { - return function () { - const args = [].slice.apply(arguments); - return wait() - .then(function (done) { - return fn.apply(context, args) - .then(function (ret) { - done(); - return ret; - }, function (error) { - done(); - throw error; - }); - }); - }; - }; - return wrap; + }); + return opts; }; -function errorClassFactory(name) { - return class extends Error { - constructor(...args) { - super(...args); - this.code = name; - if (this.message) { - this.message = name + ': ' + this.message; - } - else { - this.message = name; - } - } - }; -} -exports.errorClassFactory = errorClassFactory; -function treeMap(mapper, tree, paths = []) { - return Object.assign(Object.assign({}, mapper(tree, paths)), { children: tree.children.map((subnode, i) => { - return treeMap(mapper, subnode, [...paths, i]); - }) }); -} -exports.treeMap = treeMap; -function treeFilter(predicate, tree, paths = []) { - if (predicate(tree, paths)) { - return tree; - } - const children = tree.children.map((subnode, i) => { - return treeFilter(predicate, subnode, [...paths, i]); - }); - const validChildren = children.filter((item) => item); - return validChildren.length === 0 ? null : Object.assign(Object.assign({}, tree), { children: validChildren }); -} -exports.treeFilter = treeFilter; -function treeSlice(max, tree) { - let root = null; - let count = 0; - traverseTree((data, paths) => { - if (++count > max) { - return TraverseTreeResult.Stop; - } - if (paths.length === 0) { - root = Object.assign(Object.assign({}, data), { children: [] }); - } - else { - const finalIndex = paths[paths.length - 1]; - const parent = paths.slice(0, -1).reduce((node, index) => { - return node.children[index]; - }, root); - parent.children[finalIndex] = Object.assign(Object.assign({}, data), { children: [] }); - } - return TraverseTreeResult.Normal; - }, tree); - return root; -} -exports.treeSlice = treeSlice; -function forestSlice(max, forest) { - const newTree = { children: forest }; - const result = treeSlice(max + 1, newTree); - return result ? result.children : []; -} -exports.forestSlice = forestSlice; -function isTreeEqual(isNodeEqual, a, b) { - const aChildren = a.children || []; - const bChildren = b.children || []; - const alen = aChildren.length; - const blen = bChildren.length; - if (alen !== blen) { - return false; - } - if (!isNodeEqual(a, b)) { - return false; - } - for (let i = 0; i < alen; i++) { - if (!isTreeEqual(isNodeEqual, a.children[i], b.children[i])) { - return false; - } - } - return true; -} -exports.isTreeEqual = isTreeEqual; -function isForestEqual(isNodeEqual, a, b) { - if (a.length !== b.length) { - return false; - } - for (let i = 0, len = a.length; i < len; i++) { - if (!isTreeEqual(isNodeEqual, a[i], b[i])) { - return false; - } - } - return true; -} -exports.isForestEqual = isForestEqual; -function nodeCount(tree) { - let count = 0; - traverseTree(() => { - count++; - return TraverseTreeResult.Normal; - }, tree); - return count; -} -exports.nodeCount = nodeCount; -var TraverseTreeResult; -(function (TraverseTreeResult) { - TraverseTreeResult[TraverseTreeResult["Normal"] = 0] = "Normal"; - TraverseTreeResult[TraverseTreeResult["Skip"] = 1] = "Skip"; - TraverseTreeResult[TraverseTreeResult["Stop"] = 2] = "Stop"; -})(TraverseTreeResult = exports.TraverseTreeResult || (exports.TraverseTreeResult = {})); -function traverseTree(fn, node, paths = []) { - const intent = fn(node, paths); - if (intent !== TraverseTreeResult.Normal) { - return intent; - } - const childCount = node.children ? node.children.length : 0; - const children = node.children || []; - for (let i = 0; i < childCount; i++) { - if (traverseTree(fn, children[i], [...paths, i]) === TraverseTreeResult.Stop) { - return TraverseTreeResult.Stop; - } - } - return TraverseTreeResult.Normal; -} -exports.traverseTree = traverseTree; -function pathsInNode(predicate, root) { - let result = null; - traverseTree((node, paths) => { - if (predicate(node, paths)) { - result = paths; - return TraverseTreeResult.Stop; - } - return TraverseTreeResult.Normal; - }, root); - return result ? result : null; -} -exports.pathsInNode = pathsInNode; -function ancestorsInNode(predicate, root) { - const paths = pathsInNode(predicate, root); - if (paths === null) { - return null; + + +/***/ }), + +/***/ 11848: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +const version = (__webpack_require__(76125)/* .version */ .rE); +const defaultOptions = __webpack_require__(84500); + +/* + * Default options for browser worker + */ +module.exports = { + ...defaultOptions, + workerPath: `https://cdn.jsdelivr.net/npm/tesseract.js@v${version}/dist/worker.min.js`, +}; + + +/***/ }), + +/***/ 65321: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/** + * + * Tesseract Worker adapter for browser + * + * @fileoverview Tesseract Worker adapter for browser + * @author Kevin Kwok + * @author Guillermo Webster + * @author Jerome Wu + */ +const defaultOptions = __webpack_require__(11848); +const spawnWorker = __webpack_require__(17456); +const terminateWorker = __webpack_require__(69548); +const onMessage = __webpack_require__(25381); +const send = __webpack_require__(35039); +const loadImage = __webpack_require__(59996); + +module.exports = { + defaultOptions, + spawnWorker, + terminateWorker, + onMessage, + send, + loadImage, +}; + + +/***/ }), + +/***/ 59996: +/***/ ((module) => { + +/** + * readFromBlobOrFile + * + * @name readFromBlobOrFile + * @function + * @access private + */ +const readFromBlobOrFile = (blob) => ( + new Promise((resolve, reject) => { + const fileReader = new FileReader(); + fileReader.onload = () => { + resolve(fileReader.result); + }; + fileReader.onerror = ({ target: { error: { code } } }) => { + reject(Error(`File could not be read! Code=${code}`)); + }; + fileReader.readAsArrayBuffer(blob); + }) +); + +/** + * loadImage + * + * @name loadImage + * @function load image from different source + * @access private + */ +const loadImage = async (image) => { + let data = image; + if (typeof image === 'undefined') { + return 'undefined'; + } + + if (typeof image === 'string') { + // Base64 Image + if (/data:image\/([a-zA-Z]*);base64,([^"]*)/.test(image)) { + data = atob(image.split(',')[1]) + .split('') + .map((c) => c.charCodeAt(0)); + } else { + const resp = await fetch(image); + data = await resp.arrayBuffer(); } - const ancestorPaths = paths.slice(0, -1); - const keys = addInBetween('children', ancestorPaths); - return ancestorPaths.map((_, index) => { - const subKeys = keys.slice(0, index * 2 + 1); - return exports.getIn(subKeys, root.children); - }); -} -exports.ancestorsInNode = ancestorsInNode; -function pathsInNodeList(predicate, nodes) { - for (let i = 0, len = nodes.length; i < len; i++) { - const paths = pathsInNode(predicate, nodes[i]); - if (paths !== null) { - return [i, ...paths]; - } + } else if (typeof HTMLElement !== 'undefined' && image instanceof HTMLElement) { + if (image.tagName === 'IMG') { + data = await loadImage(image.src); } - return null; -} -exports.pathsInNodeList = pathsInNodeList; -function ancestorsInNodesList(predicate, nodes) { - for (let i = 0, len = nodes.length; i < len; i++) { - const ancestors = ancestorsInNode(predicate, nodes[i]); - if (ancestors !== null) { - return [nodes[i], ...ancestors]; - } + if (image.tagName === 'VIDEO') { + data = await loadImage(image.poster); } - return null; -} -exports.ancestorsInNodesList = ancestorsInNodesList; -function flattenTreeWithPaths(tree) { - const result = []; - traverseTree((node, paths) => { - result.push({ - paths, - node: exports.without(['children'], node), + if (image.tagName === 'CANVAS') { + await new Promise((resolve) => { + image.toBlob(async (blob) => { + data = await readFromBlobOrFile(blob); + resolve(); }); - return TraverseTreeResult.Normal; - }, tree); - return result; -} -exports.flattenTreeWithPaths = flattenTreeWithPaths; -function flatternTree(tree) { - return flattenTreeWithPaths(tree).map(item => item.node); -} -exports.flatternTree = flatternTree; -function findNodeInTree(predicate, tree) { - let result = null; - traverseTree((node, paths) => { - if (predicate(node, paths)) { - result = node; - return TraverseTreeResult.Stop; - } - return TraverseTreeResult.Normal; - }, tree); - return result; -} -exports.findNodeInTree = findNodeInTree; -function findNodeInForest(predicate, forest) { - for (let i = 0, len = forest.length; i < len; i++) { - const result = findNodeInTree(predicate, forest[i]); - if (result) { - return result; - } - } - return null; -} -exports.findNodeInForest = findNodeInForest; -function toArray(list) { - return Array.isArray(list) ? list : [list]; -} -exports.toArray = toArray; -function nodeByOffset(params) { - const { tree, isTargetQualified, isCandidateQualified, offset } = params; - if (Math.floor(offset) !== offset) { - throw new Error(`offset must be integer. It's now ${offset}`); - } - let ret = null; - const trees = toArray(tree); - const cache = []; - const maxCache = 1 + Math.ceil(Math.abs(offset)); - // Note: if offset is negative, which means you're looking for some item ahead, - // we can get it from cache. Otherwise, use offsetLeft as counter until we reach the item. - // So `found` could only be tree if `offset` is a positive integer - let offsetLeft = Math.max(0, offset); - let found = false; - for (let i = 0, len = trees.length; i < len; i++) { - const traverseResult = traverseTree((node, paths) => { - const qualified = isCandidateQualified(node, paths); - if (!qualified) { - return TraverseTreeResult.Normal; - } - if (offset < 0) { - cache.push(node); - if (cache.length > maxCache) { - cache.shift(); - } - } - if (offset > 0 && found) { - offsetLeft -= 1; - if (offsetLeft === 0) { - ret = node; - return TraverseTreeResult.Stop; - } - } - if (isTargetQualified(node, paths)) { - if (offset <= 0) { - const index = cache.length - 1 + offset; - ret = index >= 0 ? cache[index] : null; - return TraverseTreeResult.Stop; - } - else { - found = true; - } - } - return TraverseTreeResult.Normal; - }, trees[i]); - if (traverseResult === TraverseTreeResult.Stop) { - break; - } - } - return ret; -} -exports.nodeByOffset = nodeByOffset; -function pointToFitRect(data) { - const { bound, size, point } = data; - const lBorder = bound.x; - const rBorder = bound.x + bound.width; - const tBorder = bound.y; - const bBorder = bound.y + bound.height; - const x = (() => { - if (point.x + size.width <= rBorder) { - return point.x; - } - if (point.x - size.width >= lBorder) { - return point.x - size.width; - } - return rBorder - size.width; - })(); - const y = (() => { - if (point.y + size.height <= bBorder) { - return point.y; - } - if (point.y - size.height >= tBorder) { - return point.y - size.height; - } - return bBorder - size.height; - })(); - return { x, y }; -} -exports.pointToFitRect = pointToFitRect; -function addInBetween(item, list) { - const result = []; - for (let i = 0, len = list.length; i < len; i++) { - if (i !== 0) { - result.push(item); - } - result.push(list[i]); + }); } - return result; -} -exports.addInBetween = addInBetween; -function normalizeHtmlId(str) { - return str.replace(/[^A-Za-z0-9_-]/g, '_'); -} -exports.normalizeHtmlId = normalizeHtmlId; -exports.unique = (list, getKey) => { - let cache = {}; - const result = list.reduce((prev, cur) => { - const key = getKey(cur); - if (!cache[key]) { - cache[key] = true; - prev.push(cur); - } - return prev; - }, []); - return result; + } else if (typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas) { + const blob = await image.convertToBlob(); + data = await readFromBlobOrFile(blob); + } else if (image instanceof File || image instanceof Blob) { + data = await readFromBlobOrFile(image); + } + + return new Uint8Array(data); }; -exports.uniqueStrings = (...list) => { - return exports.unique(list, x => x); + +module.exports = loadImage; + + +/***/ }), + +/***/ 25381: +/***/ ((module) => { + +module.exports = (worker, handler) => { + worker.onmessage = ({ data }) => { // eslint-disable-line + handler(data); + }; }; -function consecutive(c) { - if (typeof c === 'boolean') { - return { - interval: 0, - count: c ? 1 : 0 - }; - } - return c; -} -exports.consecutive = consecutive; -const timeout = (duration) => { - return new Promise(resolve => { - setTimeout(resolve, duration); - }); + + +/***/ }), + +/***/ 35039: +/***/ ((module) => { + +/** + * send + * + * @name send + * @function send packet to worker and create a job + * @access public + */ +module.exports = async (worker, packet) => { + worker.postMessage(packet); }; -function withConsecutive(c, fn) { - const { interval, count } = consecutive(c); - let counter = count; - const next = (pass) => { - if (!pass) - throw new Error('failed to run consecutive'); - if (counter-- <= 0) - return Promise.resolve(true); - return timeout(interval || 0).then(fn).then(next); - }; - return fn() - .then(next); -} -exports.withConsecutive = withConsecutive; -function readFileAsText(file) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = (readerEvent) => { - try { - const text = readerEvent.target.result; - resolve(text); - } - catch (e) { - reject(e); - } - }; - reader.readAsText(file); + + +/***/ }), + +/***/ 17456: +/***/ ((module) => { + +/** + * spawnWorker + * + * @name spawnWorker + * @function create a new Worker in browser + * @access public + */ +module.exports = ({ workerPath, workerBlobURL }) => { + let worker; + if (Blob && URL && workerBlobURL) { + const blob = new Blob([`importScripts("${workerPath}");`], { + type: 'application/javascript', }); -} -exports.readFileAsText = readFileAsText; -function assertExhausted(_, msg) { - throw new Error('switch case not exhausted' + (msg ? (': ' + msg) : '')); -} -exports.assertExhausted = assertExhausted; -function pad2digits(n) { - if (n >= 0 && n < 10) { - return '0' + n; - } - return '' + n; -} -exports.pad2digits = pad2digits; -function repeatStr(n, str) { - let s = ''; - for (let i = 0; i < n; i++) { - s += str; - } - return s; -} -exports.repeatStr = repeatStr; -function isMac() { - const userAgent = window.navigator.userAgent; - return !!/macintosh/i.test(userAgent) || (/mac os x/i.test(userAgent) && !/like mac os x/i.test(userAgent)); -} -exports.isMac = isMac; -function resolvePath(path, basePath, relativePath) { - const dirPath = path.dirname(basePath); - relativePath = relativePath.replace(/\\/g, '/'); - if (relativePath.indexOf('/') === 0) { - return path.normalize(relativePath).replace(/^(\/|\\)/, ''); - } - else { - return path.join(dirPath, relativePath); + worker = new Worker(URL.createObjectURL(blob)); + } else { + worker = new Worker(workerPath); + } + + return worker; +}; + + +/***/ }), + +/***/ 69548: +/***/ ((module) => { + +/** + * terminateWorker + * + * @name terminateWorker + * @function terminate worker + * @access public + */ +module.exports = (worker) => { + worker.terminate(); +}; + + +/***/ }), + +/***/ 94643: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; } + return fn.apply(this, arguments); + } + + return deprecated; } -exports.resolvePath = resolvePath; -function countDown(options) { - const { interval, timeout, onTick, onTimeout } = options; - let past = 0; - const timer = setInterval(() => { - past += interval; - try { - onTick({ past, total: timeout }); - } - catch (e) { - console.warn(e); - } - if (past >= timeout) { - clearInterval(timer); - if (typeof onTimeout === 'function') { - try { - onTimeout({ past, total: timeout }); - } - catch (e) { - console.warn(e); - } - } - } - }, options.interval); - return () => clearInterval(timer); + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!__webpack_require__.g.localStorage) return false; + } catch (_) { + return false; + } + var val = __webpack_require__.g.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; } -exports.countDown = countDown; -exports.withCountDown = (options) => { - const { interval, timeout, onTick } = options; - let past = 0; - return new Promise((resolve, reject) => { - const timer = setInterval(() => { - past += interval; - try { - onTick({ cancel, past, total: timeout }); - } - catch (e) { - console.error(e); - } - if (past >= timeout) - clearInterval(timer); - }, interval); - const cancel = () => clearInterval(timer); - const p = exports.delay(() => { }, timeout) - .then(() => clearInterval(timer)); - resolve(p); + + +/***/ }), + +/***/ 36622: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } }); -}; -function urlWithQueries(url, queries = {}) { - const hasQuery = Object.keys(queries).length > 0; - if (!hasQuery) { - return url; - } - const queryStr = Object.keys(queries).map(key => { var _a; return `${encodeURIComponent(key)}=${encodeURIComponent((_a = queries[key]) === null || _a === void 0 ? void 0 : _a.toString())}`; }).join('&'); - return `${url}?${queryStr}`; -} -exports.urlWithQueries = urlWithQueries; -function throttlePromiseFunc(fn, interval) { - if (interval <= 0) { - throw new Error("Interval must be positive number"); - } - let p = Promise.resolve(); - const generatedFunc = (...args) => { - const ret = p.then(() => { - console.log("in generatedFunc...", args); - return fn(...args); - }); - p = ret.then(() => exports.delay(() => { }, interval), () => exports.delay(() => { }, interval)); - return ret; - }; - return generatedFunc; + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } } -exports.throttlePromiseFunc = throttlePromiseFunc; /***/ }), -/***/ 62275: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 81135: +/***/ ((module) => { -"use strict"; +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const web_extension_1 = __importDefault(__webpack_require__(61171)); -const platform = web_extension_1.default.isFirefox() ? 'firefox' : 'chrome'; -exports["default"] = { - preinstall: { - version: '5.8.8', - macroFolder: '/Demo' - }, - nativeMessaging: { - idleTimeBeforeDisconnect: 1e4 // 10 seconds - }, - urlAfterUpgrade: 'https://ui.vision/x/idehelp?help=k_update', - urlAfterInstall: 'https://ui.vision/x/idehelp?help=k_welcome', - urlAfterUninstall: 'https://ui.vision/x/idehelp?help=k_why', - performanceLimit: { - fileCount: Infinity - }, - xmodulesLimit: { - unregistered: { - ocrCommandCount: 100, - xCommandCount: 25, - xFileMacroCount: 10, - proxyExecCount: 5, - upgradeUrl: 'https://ui.vision/x/idehelp?help=k_xupgrade' - }, - free: { - ocrCommandCount: 250, - xCommandCount: Infinity, - xFileMacroCount: 20, - proxyExecCount: 10, - upgradeUrl: 'https://ui.vision/x/idehelp?help=k_xupgradepro' - }, - pro: { - ocrCommandCount: 500, - xCommandCount: Infinity, - xFileMacroCount: Infinity, - proxyExecCount: Infinity, - upgradeUrl: 'https://ui.vision/x/idehelp?help=k_xupgrade_contactsupport' - } - }, - xfile: { - minVersionToReadBigFile: '1.0.10' - }, - ocr: { - apiList: [ - { - "id": "1", - "key": "kantu_only_53b8", - "url": "https://apipro1.ocr.space/parse/image" - }, - { - "id": "2", - "key": "kantu_only_53b8", - "url": "https://apipro2.ocr.space/parse/image" - }, - { - "id": "3", - "key": "kantu_only_53b8", - "url": "https://apipro3.ocr.space/parse/image" - } - ], - apiTimeout: 60 * 1000, - singleApiTimeout: 30 * 1000, - apiHealthyResponseTime: 20 * 1000, - resetTime: 24 * 3600 * 1000 - }, - license: { - api: { - url: 'https://license1.ocr.space/api/status' +/***/ }), + +/***/ 40537: +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +/* provided dependency */ var process = __webpack_require__(65606); +// 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 formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; } - }, - icons: { - normal: 'logo38.png', - inverted: 'inverted_logo_38.png' - }, - forceMigrationRemedy: false, - iframePostMessageTimeout: 500, - ui: { - commandItemHeight: 35 - }, - commandRunner: { - sendKeysMaxCharCount: 1000 + default: + return x; } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; }; -/***/ }), +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(__webpack_require__.g.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } -/***/ 39505: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + if (process.noDeprecation === true) { + return fn; + } -"use strict"; + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } -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()); - }); + return deprecated; }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.untilInjected = exports.evalViaInject = void 0; -const utils_1 = __webpack_require__(63370); -const ts_utils_1 = __webpack_require__(55452); -const web_extension_1 = __importDefault(__webpack_require__(61171)); -const log_1 = __importDefault(__webpack_require__(77242)); -const cs_postmessage_1 = __webpack_require__(5116); -function evalViaInject(code) { - return __awaiter(this, void 0, void 0, function* () { - const api = yield untilInjected(); - return api.eval(code); - }); + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = ({"NODE_ENV":"production"}).NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } } -exports.evalViaInject = evalViaInject; -function untilInjected() { - const api = { - eval: (code) => { - log_1.default('sending INJECT_RUN_EVAL'); - return cs_postmessage_1.postMessage(window, window, { cmd: 'INJECT_RUN_EVAL', args: { code } }, '*', 5000) - .then((data) => { - log_1.default('eval result', data); - return data.result; - }); - } - }; - const injected = !!document.body.getAttribute('data-injected'); - if (injected) { - return Promise.resolve(api); - } - utils_1.insertScript(web_extension_1.default.runtime.getURL('inject.js')); - return ts_utils_1.retry(() => { - log_1.default('sending INJECT_READY'); - return cs_postmessage_1.postMessage(window, window, { cmd: 'INJECT_READY' }, '*', 500); - }, { - shouldRetry: () => true, - timeout: 5000, - retryInterval: 0 - })() - .then(() => api) - .catch(e => { - log_1.default(e.stack); - throw new Error('fail to inject'); - }); + + +function stylizeNoColor(str, styleType) { + return str; } -exports.untilInjected = untilInjected; -/***/ }), +function arrayToHash(array) { + var hash = {}; -/***/ 67803: -/***/ ((__unused_webpack_module, exports) => { + array.forEach(function(val, idx) { + hash[val] = true; + }); -"use strict"; + return hash; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DevicePixelRatioService = void 0; -class DevicePixelRatioService { - constructor(params) { - this.params = params; - } - getDevicePixelRatioInfo() { - var _a; - const win = (_a = this.params.window) !== null && _a !== void 0 ? _a : window; - const currentRatio = win.devicePixelRatio; - return this.params.getZoom().then((zoom) => ({ - currentRatio, - baseRatio: currentRatio / zoom, - zoom - })); + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); } -} -exports.DevicePixelRatioService = DevicePixelRatioService; + return ret; + } + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } -/***/ }), + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); -/***/ 67525: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } -"use strict"; + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOrcMatchesHighlighter = exports.OcrMatchesHighlighter = void 0; -const dom_utils_1 = __webpack_require__(24874); -const ts_utils_1 = __webpack_require__(55452); -const types_1 = __webpack_require__(37161); -const index_1 = __webpack_require__(13549); -class OcrMatchesHighlighter { - constructor() { - this.$container = this.createContainer(); - } - clear() { - Array.from(this.$container.childNodes).forEach(node => node.remove()); - } - highlight(matches) { - this.clear(); - matches.forEach(match => { - this.createHighlightForMatch(match); - }); + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); } - createHighlightForMatch(match) { - match.words.forEach((word, i) => { - this.createHighlightForWord(word, { - highlight: match.highlight, - shouldScrollTo: false && 0 - }); - }); - if (match.highlight === types_1.OcrHighlightType.TopMatched) { - this.createRectForMatch(match); - } - } - createHighlightForWord(pw, options) { - const $mark = document.createElement('div'); - $mark.innerText = pw.word.WordText; - const styleByType = (() => { - switch (options.highlight) { - case types_1.OcrHighlightType.Identified: - return { - color: 'rgba(255, 0, 0, 1)', - backgroundColor: 'rgba(200, 200, 200, 0.75)' - }; - case types_1.OcrHighlightType.Matched: - return { - color: '#f00', - backgroundColor: 'rgba(255, 215, 15, 0.5)' - }; - case types_1.OcrHighlightType.TopMatched: - return { - color: '#fe1492', - backgroundColor: 'rgba(255, 215, 15, 0.5)' - }; - } - })(); - dom_utils_1.setStyle($mark, Object.assign({ boxSizing: 'border-box', position: 'absolute', left: `${pw.word.Left}px`, top: `${pw.word.Top}px`, width: `${pw.word.Width}px`, height: `${pw.word.Height}px`, lineHeight: `${pw.word.Height}px`, fontSize: `${pw.word.Height * 0.8}px`, fontWeight: 'bold', textAlign: 'center', pointerEvents: 'none' }, styleByType)); - this.$container.appendChild($mark); - if (options.shouldScrollTo) { - $mark.scrollIntoView({ block: 'center' }); - } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } - createRectForMatch(match, styles) { - const rect = index_1.ocrMatchRect(match); - const $rect = document.createElement('div'); - dom_utils_1.setStyle($rect, Object.assign({ boxSizing: 'border-box', position: 'absolute', left: `${rect.x}px`, top: `${rect.y}px`, width: `${rect.width}px`, height: `${rect.height}px`, border: `2px solid #fe1492`, background: `transparent`, pointerEvents: 'none' }, (styles || {}))); - this.$container.appendChild($rect); + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); } - createContainer() { - const $div = document.createElement('div'); - document.documentElement.appendChild($div); - return $div; + if (isError(value)) { + return formatError(value); } -} -exports.OcrMatchesHighlighter = OcrMatchesHighlighter; -exports.getOrcMatchesHighlighter = ts_utils_1.singletonGetter(() => new OcrMatchesHighlighter()); + } + var base = '', array = false, braces = ['{', '}']; -/***/ }), + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } -/***/ 13549: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } -"use strict"; + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.scaleOcrTextSearchMatch = exports.scaleOcrResponseCoordinates = exports.scaleOcrParseResultWord = exports.ocrMatchCenter = exports.ocrMatchRect = exports.allWordsWithPosition = exports.isWordPositionEqual = exports.hasWordMatch = exports.WordMatchType = exports.isWordEqual = exports.searchTextInOCRResponse = exports.iterateThroughParseResults = exports.wordIteratorFromParseResults = exports.guardOCRResponse = exports.runOCR = void 0; -const superagent_1 = __importDefault(__webpack_require__(80569)); -const types_1 = __webpack_require__(37161); -const utils_1 = __webpack_require__(63370); -const ts_utils_1 = __webpack_require__(55452); -function runOCR(options) { - const scaleStr = (options.scale + '').toLowerCase(); - const scale = ['true', 'false'].indexOf(scaleStr) !== -1 ? scaleStr : 'true'; - const engine = [1, 2].indexOf(options.engine || 0) !== -1 ? options.engine : 1; - const singleRun = () => { - return options.getApiUrlAndApiKey() - .then(server => { - const { url, key } = server; - const f = new FormData(); - f.append('apikey', key); - f.append('language', options.language); - f.append('scale', scale); - f.append('OCREngine', '' + engine); - f.append('isOverlayRequired', '' + options.isOverlayRequired); - if (options.isTable !== undefined) { - f.append('isTable', '' + options.isTable); - } - if (typeof options.image === 'string') { - f.append('file', utils_1.dataURItoBlob(options.image), 'unknown.png'); - } - else { - f.append('file', options.image.blob, options.image.name); - } - const startTime = new Date().getTime(); - if (options.willSendRequest) { - options.willSendRequest({ server, startTime }); - } - return utils_1.withTimeout(options.singleApiTimeout, () => { - return superagent_1.default.post(url) - .send(f); - }) - .then((res) => { - if (options.didGetResponse) { - return options.didGetResponse({ - server, - startTime, - endTime: new Date().getTime(), - response: res.body, - error: null - }) - .then(() => res, () => res); - } - return res; - }, (e) => { - const err = getApiError(e); - if (options.didGetResponse) { - return options.didGetResponse({ - server, - startTime, - endTime: new Date().getTime(), - response: null, - error: err - }) - .then(() => { throw err; }, () => { throw err; }); - } - throw e; - }) - .then(onApiReturn, onApiError) - .catch(e => { - if (/timeout/i.test(e.message)) { - throw new Error(`OCR request timeout ${(options.singleApiTimeout / 1000).toFixed(1)}s`); - } - else { - throw e; - } - }); - }); - }; - const run = ts_utils_1.retry(singleRun, { - // We don't want timeout mechanism from retry, so just make it big enough - timeout: options.singleApiTimeout * 10, - retryInterval: 0, - shouldRetry: options.shouldRetry || (() => false) - }); - return utils_1.withTimeout(options.totalTimeout, run) - .catch(e => { - if (/timeout/i.test(e.message)) { - throw new Error('OCR timeout'); - } - else { - throw e; - } - }); -} -exports.runOCR = runOCR; -function getApiError(e) { - if (e.response && typeof e.response.body === 'string') { - return new Error(e.response.body); - } - return e; -} -function onApiError(e) { - console.error(e); - throw getApiError(e); -} -function onApiReturn(res) { - guardOCRResponse(res.body); - return res.body; -} -function guardOCRResponse(data) { - switch (data.OCRExitCode) { - case types_1.OCRExitCode.AllParsed: - return; - case types_1.OCRExitCode.PartiallyParsed: - throw new Error([ - 'Parsed Partially (Only few pages out of all the pages parsed successfully)', - data.ErrorMessage || '', - data.ErrorDetails || '', - ] - .filter(s => s.length > 0) - .join('; ')); - case types_1.OCRExitCode.Failed: - throw new Error([ - 'OCR engine fails to parse an image', - data.ErrorMessage || '', - data.ErrorDetails || '', - ] - .filter(s => s.length > 0) - .join('; ')); - case types_1.OCRExitCode.Fatal: - throw new Error([ - 'Fatal error occurs during parsing', - data.ErrorMessage || '', - data.ErrorDetails || '', - ] - .filter(s => s.length > 0) - .join('; ')); - } -} -exports.guardOCRResponse = guardOCRResponse; -function wordIteratorFromParseResults(parseResults) { - let pageIndex = 0; - let lineIndex = 0; - let wordIndex = 0; - const next = () => { - const page = parseResults[pageIndex]; - const currentLines = page ? page.TextOverlay.Lines : []; - const line = page ? page.TextOverlay.Lines[lineIndex] : null; - const currentWords = line ? line.Words : []; - const word = line ? line.Words[wordIndex] : null; - if (!word) { - return { - done: true, - value: null - }; - } - const value = { - word, - position: { - pageIndex, - lineIndex, - wordIndex - } - }; - [pageIndex, lineIndex, wordIndex] = (() => { - let nextWordIndex = wordIndex + 1; - let nextLineIndex = lineIndex; - let nextPageIndex = pageIndex; - if (nextWordIndex >= currentWords.length) { - nextWordIndex = 0; - nextLineIndex += 1; - } - if (nextLineIndex >= currentLines.length) { - nextLineIndex = 0; - nextPageIndex += 1; - } - if (nextPageIndex >= parseResults.length) { - return [-1, -1, -1]; - } - return [nextPageIndex, nextLineIndex, nextWordIndex]; - })(); - return { - value, - done: false - }; - }; - return { next }; -} -exports.wordIteratorFromParseResults = wordIteratorFromParseResults; -function iterateThroughParseResults(parseResults, fn) { - const iterator = wordIteratorFromParseResults(parseResults); - while (true) { - const { done, value } = iterator.next(); - if (done) - break; - const shouldContinue = fn(value); - if (!shouldContinue) - break; + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); } -} -exports.iterateThroughParseResults = iterateThroughParseResults; -function searchTextInOCRResponse(data) { - const { text, index, parsedResults, exhaust } = data; - const isExactMatch = /^\[.*\]$/.test(text); - const realText = isExactMatch ? text.slice(1, -1) : text; - const words = realText.split(/\s+/g).map(s => s.trim()).filter(s => s.length > 0); - if (index < 0 || Math.round(index) !== index) { - throw new Error('index must be positive integer'); - } - let found = []; - let wordIndex = 0; - let matchIndex = 0; - iterateThroughParseResults(parsedResults, (wordWithPos) => { - const matchType = (() => { - if (isExactMatch) - return WordMatchType.Full; - if (words.length === 1) - return WordMatchType.AnyPart; - if (wordIndex === 0) - return WordMatchType.Postfix; - if (wordIndex === words.length - 1) - return WordMatchType.Prefix; - return WordMatchType.Full; - })(); - if (!hasWordMatch(words[wordIndex], wordWithPos.word.WordText, matchType)) { - found[matchIndex] = []; - wordIndex = 0; - return true; - } - found[matchIndex] = found[matchIndex] || []; - found[matchIndex].push(wordWithPos); - wordIndex += 1; - // Whether it's the last word - if (wordIndex >= words.length) { - matchIndex += 1; - wordIndex = 0; - const shouldContinue = exhaust || matchIndex <= index; - return shouldContinue; - } - return true; + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); - const all = found.filter(pWords => pWords.length === words.length) - .map(pWords => ({ - words: pWords, - // Note: similarity is useless in current implementation - similarity: 1 - })); - const hit = all[index] || null; - return { - hit, - all, - exhaust - }; -} -exports.searchTextInOCRResponse = searchTextInOCRResponse; -function isWordEqual(a, b) { - if (!a || !b) - return false; - return a.trim().toLowerCase() === b.trim().toLowerCase(); -} -exports.isWordEqual = isWordEqual; -var WordMatchType; -(function (WordMatchType) { - WordMatchType[WordMatchType["Full"] = 0] = "Full"; - WordMatchType[WordMatchType["Prefix"] = 1] = "Prefix"; - WordMatchType[WordMatchType["Postfix"] = 2] = "Postfix"; - WordMatchType[WordMatchType["AnyPart"] = 3] = "AnyPart"; -})(WordMatchType = exports.WordMatchType || (exports.WordMatchType = {})); -function hasWordMatch(pattern, target, matchType) { - if (!pattern || !target) - return false; - const lowerPattern = pattern.trim().toLowerCase(); - const lowerTarget = target.trim().toLowerCase(); - switch (matchType) { - case WordMatchType.Full: { - return lowerPattern === lowerTarget; - } - case WordMatchType.Prefix: { - return lowerTarget.indexOf(lowerPattern) === 0; - } - case WordMatchType.Postfix: { - const index = lowerTarget.indexOf(lowerPattern); - return index !== -1 && index === lowerTarget.length - lowerPattern.length; - } - case WordMatchType.AnyPart: { - return lowerTarget.indexOf(lowerPattern) !== -1; - } - } + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); } -exports.hasWordMatch = hasWordMatch; -function isWordPositionEqual(a, b) { - return a.pageIndex === b.pageIndex && - a.lineIndex === b.lineIndex && - a.wordIndex === b.wordIndex; + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); } -exports.isWordPositionEqual = isWordPositionEqual; -function allWordsWithPosition(parseResults, excludePositions) { - const result = []; - const isAtKnownPosition = (wordWithPos) => { - return excludePositions.reduce((prev, pos) => { - if (prev) - return true; - return isWordPositionEqual(pos, wordWithPos.position); - }, false); - }; - iterateThroughParseResults(parseResults, (wordWithPos) => { - if (!isAtKnownPosition(wordWithPos)) { - result.push(wordWithPos); - } - return true; - }); - return result; + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; } -exports.allWordsWithPosition = allWordsWithPosition; -function ocrMatchRect(match) { - const rectsByLine = match.words.reduce((prev, cur) => { - const key = `${cur.position.pageIndex}_${cur.position.lineIndex}`; - if (!prev[key]) { - prev[key] = { - x: cur.word.Left, - y: cur.word.Top, - width: cur.word.Width, - height: cur.word.Height - }; - } - else { - prev[key] = Object.assign(Object.assign({}, prev[key]), { width: Math.max(prev[key].width, cur.word.Left + cur.word.Width - prev[key].x), height: Math.max(prev[key].height, cur.word.Top + cur.word.Height - prev[key].y) }); - } - return prev; - }, {}); - const widestRect = Object.keys(rectsByLine).reduce((prev, key) => { - return prev.width < rectsByLine[key].width ? rectsByLine[key] : prev; - }, { x: 0, y: 0, width: 0, height: 0 }); - return widestRect; + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; } -exports.ocrMatchRect = ocrMatchRect; -function ocrMatchCenter(match) { - const rect = ocrMatchRect(match); - return { - x: rect.x + rect.width / 2, - y: rect.y + rect.height / 2 - }; + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; } -exports.ocrMatchCenter = ocrMatchCenter; -function scaleOcrParseResultWord(word, scale) { - return Object.assign(Object.assign({}, word), { Width: scale * word.Width, Height: scale * word.Height, Left: scale * word.Left, Top: scale * word.Top }); + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } -exports.scaleOcrParseResultWord = scaleOcrParseResultWord; -function scaleOcrResponseCoordinates(res, scale) { - const data = ts_utils_1.safeUpdateIn(['ParsedResults', '[]', 'TextOverlay', 'Lines', '[]', 'Words', '[]'], (word) => scaleOcrParseResultWord(word, scale), res); - return data; + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); } -exports.scaleOcrResponseCoordinates = scaleOcrResponseCoordinates; -function scaleOcrTextSearchMatch(match, scale) { - const data = ts_utils_1.safeUpdateIn(['words', '[]', 'word'], (word) => scaleOcrParseResultWord(word, scale), match); - return data; +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; } -exports.scaleOcrTextSearchMatch = scaleOcrTextSearchMatch; +exports.isBoolean = isBoolean; +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; -/***/ }), +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; -/***/ 37161: -/***/ ((__unused_webpack_module, exports) => { +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; -"use strict"; +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OcrHighlightType = exports.FileParseExitCode = exports.OCRExitCode = void 0; -var OCRExitCode; -(function (OCRExitCode) { - OCRExitCode[OCRExitCode["AllParsed"] = 1] = "AllParsed"; - OCRExitCode[OCRExitCode["PartiallyParsed"] = 2] = "PartiallyParsed"; - OCRExitCode[OCRExitCode["Failed"] = 3] = "Failed"; - OCRExitCode[OCRExitCode["Fatal"] = 4] = "Fatal"; -})(OCRExitCode = exports.OCRExitCode || (exports.OCRExitCode = {})); -var FileParseExitCode; -(function (FileParseExitCode) { - FileParseExitCode[FileParseExitCode["FileNotFound"] = 0] = "FileNotFound"; - FileParseExitCode[FileParseExitCode["Success"] = 1] = "Success"; - FileParseExitCode[FileParseExitCode["ParseError"] = -10] = "ParseError"; - FileParseExitCode[FileParseExitCode["Timeout"] = -20] = "Timeout"; - FileParseExitCode[FileParseExitCode["ValidationError"] = -30] = "ValidationError"; - FileParseExitCode[FileParseExitCode["UnknownError"] = -99] = "UnknownError"; -})(FileParseExitCode = exports.FileParseExitCode || (exports.FileParseExitCode = {})); -var OcrHighlightType; -(function (OcrHighlightType) { - OcrHighlightType[OcrHighlightType["Identified"] = 0] = "Identified"; - OcrHighlightType[OcrHighlightType["Matched"] = 1] = "Matched"; - OcrHighlightType[OcrHighlightType["TopMatched"] = 2] = "TopMatched"; -})(OcrHighlightType = exports.OcrHighlightType || (exports.OcrHighlightType = {})); +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; -/***/ }), +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; -/***/ 28411: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; -"use strict"; +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.polyfillTimeoutFunctions = void 0; -const log_1 = __importDefault(__webpack_require__(77242)); -const oldSetTimeout = window.setTimeout; -const oldClearTimeout = window.clearTimeout; -const oldSetInterval = window.setInterval; -const oldClearInterval = window.clearInterval; -function uid() { - return Math.floor(Math.random() * 1e8); +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); } -function polyfillTimeoutFunctions(csIpc) { - const timeoutRecords = {}; - function createSetTimeoutViaBackground(identity) { - const id = identity !== null && identity !== void 0 ? identity : uid(); - return function setTimeoutViaBackground(fn, timeout = 0, ...args) { - timeoutRecords[id] = true; - csIpc.ask('TIMEOUT', { id, timeout }).then((identity) => { - if (!timeoutRecords[identity]) { - return; - } - fn(...args); - }) - .catch((e) => { - log_1.default.error('Error in setTimeout', e.stack); - }); - return id; - }; - } - function clearTimeoutViaBackground(id) { - delete timeoutRecords[id]; - } - // Call both native setTimeout and setTimeoutViaBackground - // and take the first one resolved - function smartSetTimeout(fn, timeout = 0, ...args) { - let done = false; - const wrappedFn = (...args) => { - if (done) { - return null; - } - done = true; - return fn(...args); - }; - const id = oldSetTimeout(wrappedFn, timeout, ...args); - createSetTimeoutViaBackground(id)(wrappedFn, timeout, ...args); - return id; - } - const intervalRecords = {}; - function smartSetInterval(fn, timeout = 0, ...args) { - const id = uid(); - const wrappedFn = () => { - if (!intervalRecords[id]) { - return; - } - smartSetTimeout(wrappedFn, timeout); - fn(...args); - }; - intervalRecords[id] = true; - smartSetTimeout(wrappedFn, timeout); - return id; - } - function clearIntervalViaBackground(id) { - delete intervalRecords[id]; - } - const runBoth = (f1, f2) => { - return (...args) => { - f1(...args); - f2(...args); - }; - }; - window.setTimeout = smartSetTimeout; - window.clearTimeout = runBoth(clearTimeoutViaBackground, oldClearTimeout); - window.setInterval = smartSetInterval; - window.clearInterval = clearIntervalViaBackground; +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; } -exports.polyfillTimeoutFunctions = polyfillTimeoutFunctions; +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 = __webpack_require__(81135); -/***/ 9121: -/***/ ((__unused_webpack_module, exports) => { +function objectToString(o) { + return Object.prototype.toString.call(o); +} -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ViewportRectService = void 0; -class ViewportRectService { - constructor(params) { - this.params = params; - } - getViewportRectInScreen() { - return this.params.devicePixelRatioService.getDevicePixelRatioInfo().then(info => { - var _a; - const win = (_a = this.params.window) !== null && _a !== void 0 ? _a : window; - const innerScreenX = window.mozInnerScreenX; - const innerScreenY = window.mozInnerScreenY; - const innerWidth = window.innerWidth * info.zoom; - const innerHeight = window.innerHeight * info.zoom; - // Firefox has mozInnerScreenX/mozInnerScreenY tell the exact screen coordinates of viewport - if (typeof innerScreenX !== 'undefined') { - return { - x: innerScreenX, - y: innerScreenY, - width: innerWidth, - height: innerHeight - }; - } - // For Chrome, it's tricker to get the screen coordinates as there are no properties like InnerScreenX, - // so have to derive it from window.screenLeft and border/toolbar width/height, assuming download bar is already - // hidden when this method is called, and dev tool is not opened - // window.innerHeight is shrinked when you zoom in on page - const toolbarHeight = window.outerHeight - window.innerHeight * info.zoom; - // Window on Windows has a border, about 8px in width - const windowBorder = window.navigator.platform.match(/Win(.)*/ig) ? 8 : 0; - return { - x: win.screenLeft + windowBorder, - y: win.screenTop + toolbarHeight - windowBorder, - width: innerWidth, - height: innerHeight - }; - }); - } +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); } -exports.ViewportRectService = ViewportRectService; -/***/ }), +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; -/***/ 94927: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} -/** - * Module exports. - */ +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; -module.exports = deprecate; /** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. + * Inherit the prototype methods from one constructor into another. * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. */ +exports.inherits = __webpack_require__(36622); -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; } + return origin; +}; - return deprecated; +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); } -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!__webpack_require__.g.localStorage) return false; - } catch (_) { - return false; - } - var val = __webpack_require__.g.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} +/***/ }), + +/***/ 8460: +/***/ (() => { +/* (ignored) */ + +/***/ }), + +/***/ 92382: +/***/ (() => { + +/* (ignored) */ /***/ }), -/***/ 69386: +/***/ 42634: /***/ (() => { /* (ignored) */ /***/ }), -/***/ 31616: +/***/ 22623: /***/ (() => { /* (ignored) */ +/***/ }), + +/***/ 76125: +/***/ ((module) => { + +"use strict"; +module.exports = {"rE":"5.1.0"}; + /***/ }) /******/ }); @@ -24254,89 +33142,52 @@ var __webpack_exports__ = {}; "use strict"; -var _typeof2 = __webpack_require__(72444); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _toConsumableArray2 = __webpack_require__(85315); - -var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2); - -var _promise = __webpack_require__(46593); - -var _promise2 = _interopRequireDefault(_promise); - -var _from = __webpack_require__(24043); - -var _from2 = _interopRequireDefault(_from); - -var _extends2 = __webpack_require__(88239); - -var _extends3 = _interopRequireDefault(_extends2); - -var _web_extension = __webpack_require__(61171); - -var _web_extension2 = _interopRequireDefault(_web_extension); - -var _storage = __webpack_require__(67585); - -var _storage2 = _interopRequireDefault(_storage); - -var _ipc_cs = __webpack_require__(41471); - -var _ipc_cs2 = _interopRequireDefault(_ipc_cs); - -var _cs_postmessage = __webpack_require__(5116); - -var _inspector = __webpack_require__(14537); - -var _inspector2 = _interopRequireDefault(_inspector); - -var _constant = __webpack_require__(43232); - -var C = _interopRequireWildcard(_constant); - -var _utils = __webpack_require__(63370); - -var _dom_utils = __webpack_require__(24874); - -var _eval = __webpack_require__(39505); - -var _command_runner = __webpack_require__(77750); - -var _capture_screenshot = __webpack_require__(89145); - -var _encrypt = __webpack_require__(77930); - -var _log = __webpack_require__(77242); - -var _log2 = _interopRequireDefault(_log); - -var _select_area = __webpack_require__(19455); - -var _highlighter = __webpack_require__(67525); - -var _cs_timeout = __webpack_require__(28411); - -var _dpr = __webpack_require__(67803); - -var _viewport_rect = __webpack_require__(9121); - -var _config = __webpack_require__(62275); - -var _config2 = _interopRequireDefault(_config); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - +var _web_extension = _interopRequireDefault(__webpack_require__(41953)); +var _storage = _interopRequireDefault(__webpack_require__(88555)); +var _ipc_cs = _interopRequireDefault(__webpack_require__(96571)); +var _cs_postmessage = __webpack_require__(50366); +var _inspector = _interopRequireDefault(__webpack_require__(51152)); +var C = _interopRequireWildcard(__webpack_require__(95902)); +var _utils = __webpack_require__(46580); +var _dom_utils = __webpack_require__(92950); +var _eval = __webpack_require__(20652); +var _command_runner = __webpack_require__(31897); +var _capture_screenshot = __webpack_require__(6329); +var _encrypt = __webpack_require__(21208); +var _log = _interopRequireDefault(__webpack_require__(89130)); +var _select_area = __webpack_require__(35645); +var _highlighter = __webpack_require__(56553); +var _cs_timeout = __webpack_require__(41279); +var _dpr = __webpack_require__(98272); +var _viewport_rect = __webpack_require__(67203); +var _config = _interopRequireDefault(__webpack_require__(8747)); +var _global_state = __webpack_require__(8327); +var _intercept_log = _interopRequireDefault(__webpack_require__(36447)); +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +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(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), !0).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; } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } +(0, _intercept_log["default"])(); +console.log('content_script.js loaded:>>'); if (window.top === window && !(0, _dom_utils.isFirefox)()) { - (0, _cs_timeout.polyfillTimeoutFunctions)(_ipc_cs2.default); + (0, _cs_timeout.polyfillTimeoutFunctions)(_ipc_cs["default"]); } - var MASK_CLICK_FADE_TIMEOUT = 2000; var oops = true ? function () {} : 0; - var state = { status: C.CONTENT_SCRIPT_STATUS.NORMAL, // Note: it decides whether we're running commands @@ -24350,50 +33201,58 @@ var state = { config: {}, // Note: To achieve verifyText, we need contextmenu event on page plus menu item click event from background elementOnContextMenu: null +}; - // Note: Whether it's top or inner window, a content script has the need - // to send IPC message to background. But in our design, only the top window - // has access to the real csIpc, while inner frames have to bubble up the messages - // to the top window. - // So inner windows are provided with a fake csIpc, which post messages to its parent -};var superCsIpc = window.top === window ? _ipc_cs2.default : { +// Note: Whether it's top or inner window, a content script has the need +// to send IPC message to background. But in our design, only the top window +// has access to the real csIpc, while inner frames have to bubble up the messages +// to the top window. +// So inner windows are provided with a fake csIpc, which post messages to its parent +var superCsIpc = window.top === window ? _ipc_cs["default"] : { ask: function ask(ipcAction, ipcData) { return (0, _cs_postmessage.postMessage)(window.parent, window, { action: 'IPC_CALL', - data: { ipcAction: ipcAction, ipcData: ipcData } + data: { + ipcAction: ipcAction, + ipcData: ipcData + } }); } }; - var calcSelectFrameCmds = function calcSelectFrameCmds(frameStack) { var xs = state.recordingFrameStack; var ys = frameStack; var len = Math.min(xs.length, ys.length); - var tpl = { cmd: 'selectFrame', url: window.location.href }; + var tpl = { + cmd: 'selectFrame', + url: window.location.href + }; var ret = []; var i = 0; - for (i = 0; i < len; i++) { if (xs[i] !== ys[i]) { break; } } - if (i === 0) { // No need for relative=top, if state.recordingFrameStack is empty if (xs.length !== 0) { - ret.push((0, _extends3.default)({}, tpl, { target: 'relative=top' })); + ret.push(_objectSpread(_objectSpread({}, tpl), {}, { + target: 'relative=top' + })); } } else if (i < len) { for (var j = i; j < xs.length; j++) { - ret.push((0, _extends3.default)({}, tpl, { target: 'relative=parent' })); + ret.push(_objectSpread(_objectSpread({}, tpl), {}, { + target: 'relative=parent' + })); } } - for (var _j = i; _j < ys.length; _j++) { - ret.push((0, _extends3.default)({}, tpl, { target: ys[_j] })); + ret.push(_objectSpread(_objectSpread({}, tpl), {}, { + target: ys[_j] + })); } - return ret; }; @@ -24401,74 +33260,69 @@ var calcSelectFrameCmds = function calcSelectFrameCmds(frameStack) { // 1. mask on click // 2. mask on hover var getMask = function () { - var mask = void 0, - factory = void 0; - + var mask, factory; var addLogoImg = function addLogoImg($dom) { var $img = createLogoImg(); - - _inspector2.default.setStyle($img, { + _inspector["default"].setStyle($img, { position: 'absolute', top: '-25px', left: '0', width: '20px', height: '20px' }); - $dom.appendChild($img); }; - return function (remove) { if (remove && factory) { mask = null; return factory.clear(); } - if (mask) { return mask; } - - factory = _inspector2.default.maskFactory(); - - var maskClick = factory.gen({ background: 'green', border: '2px solid purple' }); - var maskHover = factory.gen({ background: '#ffa800', border: '2px solid purple' }); - + factory = _inspector["default"].maskFactory(); + var maskClick = factory.gen({ + background: 'green', + border: '2px solid purple' + }); + var maskHover = factory.gen({ + background: '#ffa800', + border: '2px solid purple' + }); addLogoImg(maskClick); addLogoImg(maskHover); - - mask = { maskClick: maskClick, maskHover: maskHover }; - + mask = { + maskClick: maskClick, + maskHover: maskHover + }; document.documentElement.appendChild(maskClick); document.documentElement.appendChild(maskHover); - return mask; }; }(); - var createLogoImg = function createLogoImg() { // Note: Ext.runtime.getURL is available in content script, but not injected js // So there are cases when content_script.js is run as injected js, where `Ext.runtime.getURL` // is not available // Weird enough, `Ext.runtime.getURL` always works well in macOS - var url = _web_extension2.default.runtime.getURL ? _web_extension2.default.runtime.getURL('logo.png') : ''; + var url = _web_extension["default"].runtime.getURL ? _web_extension["default"].runtime.getURL('logo.png') : ''; var img = new Image(); - img.src = url; return img; }; - var addWaitInCommand = function addWaitInCommand(cmdObj) { var cmd = cmdObj.cmd; - - switch (cmd) { case 'click': case 'clickAt': - return (0, _extends3.default)({}, cmdObj, { cmd: 'clickAndWait', value: '' }); - + return _objectSpread(_objectSpread({}, cmdObj), {}, { + cmd: 'clickAndWait', + value: '' + }); case 'select': - return (0, _extends3.default)({}, cmdObj, { cmd: 'selectAndWait' }); - + return _objectSpread(_objectSpread({}, cmdObj), {}, { + cmd: 'selectAndWait' + }); default: return cmdObj; } @@ -24481,36 +33335,32 @@ var reportCommand = function () { var last = null; var lastTime = null; var timer = null; - return function (obj) { - obj = (0, _extends3.default)({}, obj, { url: window.location.href }); - - (0, _log2.default)('to report', obj); + obj = _objectSpread(_objectSpread({}, obj), {}, { + url: window.location.href + }); + (0, _log["default"])('to report', obj); // Change back to top frame if it was recording inside if (state.recordingFrameStack.length > 0) { state.recordingFrameStack = []; - superCsIpc.ask('CS_RECORD_ADD_COMMAND', { cmd: 'selectFrame', target: 'relative=top', url: window.location.href - }).catch(oops); + })["catch"](oops); } - switch (obj.cmd) { case 'leave': { if (timer) { clearTimeout(timer); } - if (new Date() - lastTime < LEAVE_INTERVAL) { obj = addWaitInCommand(last); } else { return; } - break; } case 'click': @@ -24518,26 +33368,20 @@ var reportCommand = function () { case 'select': { timer = setTimeout(function () { - superCsIpc.ask('CS_RECORD_ADD_COMMAND', obj).catch(oops); + superCsIpc.ask('CS_RECORD_ADD_COMMAND', obj)["catch"](oops); }, LEAVE_INTERVAL); - last = obj; lastTime = new Date(); - return; } - default: break; } - last = obj; lastTime = new Date(); - - superCsIpc.ask('CS_RECORD_ADD_COMMAND', obj).catch(oops); + superCsIpc.ask('CS_RECORD_ADD_COMMAND', obj)["catch"](oops); }; }(); - var isValidClick = function isValidClick(el) { // Note: all elements are allowed to be recorded when clicked return true; @@ -24554,42 +33398,78 @@ var isValidClick = function isValidClick(el) { // // return isValidClick(el.parentNode) }; - var isValidSelect = function isValidSelect(el) { var tag = el.tagName.toLowerCase(); - if (['option', 'select'].indexOf(tag) !== -1) return true; return false; }; - var isValidType = function isValidType(el) { var tag = el.tagName.toLowerCase(); var type = el.getAttribute('type'); - if (tag === 'textarea') return true; if (tag === 'input' && ['radio, checkbox'].indexOf(type) === -1) return true; - return false; }; - +var downloadSaveItem = function downloadSaveItem($dom, cmd) { + if (cmd == "saveItem") { + var cachedImage = $dom; + var url = cachedImage.src; + var filename = url.substring(url.lastIndexOf('/') + 1); + + // Check if the cached image exists + if (cachedImage.complete && cachedImage.naturalWidth !== 0) { + // If the cached image exists, create a temporary URL for the image + var tempUrl = URL.createObjectURL(cachedImage.src); + var link = document.createElement("a"); + link.download = filename; + link.href = tempUrl; + link.click(); + // Release the temporary URL + URL.revokeObjectURL(tempUrl); + } else { + // If the cached image doesn't exist, create a new image object + var image = new Image(); + // Set the image source URL + image.src = url; + // Wait for the image to load + image.onload = function () { + // Store the image in cache for future use + var canvas = document.createElement("canvas"); + canvas.width = image.naturalWidth; + canvas.height = image.naturalHeight; + canvas.getContext("2d").drawImage(image, 0, 0); + var extension = filename.split(".").pop(); + var dataURL = canvas.toDataURL("image/".concat(extension)); + localStorage.setItem("myImage", dataURL); + // Create a temporary URL for the image + var tempUrl = URL.createObjectURL(image.src); + // Create a link element with a download attribute + var link = document.createElement("a"); + link.download = filename; + link.href = tempUrl; + // Click the link to trigger a download of the image + link.click(); + // Release the temporary URL + URL.revokeObjectURL(tempUrl); + }; + } + } +}; var highlightDom = function highlightDom($dom, timeout) { var mask = getMask(); - - _inspector2.default.showMaskOver(mask.maskClick, $dom); - + _inspector["default"].showMaskOver(mask.maskClick, $dom); setTimeout(function () { - _inspector2.default.setStyle(mask.maskClick, { display: 'none' }); + _inspector["default"].setStyle(mask.maskClick, { + display: 'none' + }); }, timeout || MASK_CLICK_FADE_TIMEOUT); }; - var createHighlightRect = function createHighlightRect() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var $mask = document.createElement('div'); var $text = document.createElement('div'); - var timer = void 0; - - _inspector2.default.setStyle($mask, { + var timer; + _inspector["default"].setStyle($mask, { position: 'absolute', zIndex: 110001, border: '1px solid orange', @@ -24597,65 +33477,63 @@ var createHighlightRect = function createHighlightRect() { display: 'none', pointerEvents: 'none' }); - - _inspector2.default.setStyle($text, { + _inspector["default"].setStyle($text, { position: 'absolute', top: 0, left: 0, transform: 'translate(-100%, -100%)', fontSize: '14px' }); - $mask.appendChild($text); - return function (rect, timeout) { clearTimeout(timer); - $text.innerText = rect.text ? rect.text : parseFloat(rect.score).toFixed(2) + (' #' + (rect.index + 1)); - - _inspector2.default.setStyle($mask, (0, _extends3.default)({ + $text.innerText = rect.text ? rect.text : parseFloat(rect.score).toFixed(2) + " #".concat(rect.index + 1); + _inspector["default"].setStyle($mask, _objectSpread({ display: 'block', - top: rect.top + 'px', - left: rect.left + 'px', - width: rect.width + 'px', - height: rect.height + 'px' + top: "".concat(rect.top, "px"), + left: "".concat(rect.left, "px"), + width: "".concat(rect.width, "px"), + height: "".concat(rect.height, "px") }, opts.rectStyle || {})); - - _inspector2.default.setStyle($text, opts.textStyle || {}); - + _inspector["default"].setStyle($text, opts.textStyle || {}); if (!$mask.parentNode) { document.documentElement.appendChild($mask); } - if (opts.scrollIntoView) { - $mask.scrollIntoView({ block: 'center', behavior: 'smooth' }); + $mask.scrollIntoView({ + block: 'center', + behavior: 'smooth' + }); } - if (timeout && timeout > 0) { timer = setTimeout(function () { - _inspector2.default.setStyle($mask, { display: 'none' }); + _inspector["default"].setStyle($mask, { + display: 'none' + }); }, timeout); } - var fn = function fn() { - _inspector2.default.setStyle($mask, { display: 'none' }); + _inspector["default"].setStyle($mask, { + display: 'none' + }); $mask.remove(); }; - - (0, _extends3.default)(fn, { + Object.assign(fn, { hide: function hide() { - return _inspector2.default.setStyle($mask, { display: 'none' }); + return _inspector["default"].setStyle($mask, { + display: 'none' + }); }, show: function show() { - return _inspector2.default.setStyle($mask, { display: 'block' }); + return _inspector["default"].setStyle($mask, { + display: 'block' + }); } }); - return fn; }; }; - var highlightRect = createHighlightRect(); - var highlightRects = function () { var topMatchedOptions = { rectStyle: { @@ -24663,23 +33541,19 @@ var highlightRects = function () { color: '#ff0000' } }; - var destroy = void 0; - + var destroy; var fn = function fn(rects, timeout) { if (destroy) destroy(); - var destroyFns = rects.map(function (rect, i) { rect.index = i; return createHighlightRect(rect.selected ? topMatchedOptions : {})(rect, timeout); }); - destroy = function destroy() { return destroyFns.forEach(function (destroy) { return destroy(); }); }; - - (0, _extends3.default)(destroy, { + Object.assign(destroy, { hide: function hide() { return destroyFns.forEach(function (fn) { return fn.hide && fn.hide(); @@ -24691,11 +33565,9 @@ var highlightRects = function () { }); } }); - return destroy; }; - - (0, _extends3.default)(fn, { + Object.assign(fn, { hide: function hide() { return destroy.hide(); }, @@ -24703,148 +33575,148 @@ var highlightRects = function () { return destroy.show(); } }); - return fn; }(); - var initMultipleSelect = function initMultipleSelect($select) { if ($select && $select.nodeName && $select.nodeName.toLowerCase() === 'select' && $select.multiple) { - (0, _from2.default)($select.options).forEach(function ($option) { + Array.from($select.options).forEach(function ($option) { $option.lastSelected = $option.selected; }); } }; - var onContextMenu = function onContextMenu(e) { state.elementOnContextMenu = e.target; }; - var onClick = function onClick(e) { if (!isValidClick(e.target)) return; - - var targetInfo = _inspector2.default.getLocator(e.target, true); - - (0, _log2.default)('onClick, switch case', state.config.recordClickType); + _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { + var allState, rect; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return (0, _global_state.getState)(); + case 2: + allState = _context.sent; + if (allState['curent_cmd'] == "XClickTextRelative" && allState.status != "NORMAL") { + rect = e.target.getBoundingClientRect(); + (0, _highlighter.getOrcMatchesHighlighter)().highlightRelative(rect); + (0, _global_state.updateState)((0, _utils.setIn)(['curent_cmd'], '')); + //e.target.style.border='2px solid #fe1492'; + } + case 4: + case "end": + return _context.stop(); + } + }, _callee); + }))(); + var targetInfo = _inspector["default"].getLocator(e.target, true); + (0, _log["default"])('onClick, switch case', state.config.recordClickType); switch (state.config.recordClickType) { case 'clickAt': - reportCommand((0, _extends3.default)({}, targetInfo, { + reportCommand(_objectSpread(_objectSpread({}, targetInfo), {}, { cmd: 'clickAt', value: function () { var clientX = e.clientX, - clientY = e.clientY; - + clientY = e.clientY; var _e$target$getBounding = e.target.getBoundingClientRect(), - top = _e$target$getBounding.top, - left = _e$target$getBounding.left; - + top = _e$target$getBounding.top, + left = _e$target$getBounding.left; var x = Math.round(clientX - left); var y = Math.round(clientY - top); - - return x + ',' + y; + return "".concat(x, ",").concat(y); }() })); break; - case 'click': default: - reportCommand((0, _extends3.default)({}, targetInfo, { + reportCommand(_objectSpread(_objectSpread({}, targetInfo), {}, { cmd: 'click' })); break; + case 'saveItem': + console.log('saveItem==> ', targetInfo); + break; } - if (e.target.nodeName.toLowerCase() === 'option') { initMultipleSelect(e.target.parentNode); } }; - var onFocus = function onFocus(e) { if (e.target.nodeName.toLowerCase() === 'select' && e.target.multiple) { initMultipleSelect(e.target); } }; - var onChange = function onChange(e) { if (isValidSelect(e.target)) { var isMultipleSelect = !!e.target.multiple; - if (!isMultipleSelect) { var value = e.target.value; - var $option = (0, _from2.default)(e.target.children).find(function ($op) { + var $option = Array.from(e.target.children).find(function ($op) { return $op.value === value; }); - - reportCommand((0, _extends3.default)({ + reportCommand(_objectSpread({ cmd: 'select', - value: 'label=' + _inspector2.default.domText($option).trim() - }, _inspector2.default.getLocator(e.target, true))); + value: 'label=' + _inspector["default"].domText($option).trim() + }, _inspector["default"].getLocator(e.target, true))); } else { - (0, _from2.default)(e.target.options).forEach(function ($option) { + Array.from(e.target.options).forEach(function ($option) { if ($option.lastSelected !== $option.selected) { - reportCommand((0, _extends3.default)({ + reportCommand(_objectSpread({ cmd: $option.selected ? 'addSelection' : 'removeSelection', - value: 'label=' + _inspector2.default.domText($option).trim() - }, _inspector2.default.getLocator(e.target, true))); + value: 'label=' + _inspector["default"].domText($option).trim() + }, _inspector["default"].getLocator(e.target, true))); } - $option.lastSelected = $option.selected; }); } } else if (isValidType(e.target)) { var _value = (e.target.value || '').replace(/\n/g, '\\n'); - (0, _encrypt.encryptIfNeeded)(_value, e.target).then(function (realValue) { - reportCommand((0, _extends3.default)({ + reportCommand(_objectSpread({ cmd: 'type', value: realValue - }, _inspector2.default.getLocator(e.target, true))); + }, _inspector["default"].getLocator(e.target, true))); }); } }; - var onContentEditableChange = function onContentEditableChange(e) { - reportCommand((0, _extends3.default)({ + reportCommand(_objectSpread({ cmd: 'editContent', value: e.target.innerHTML - }, _inspector2.default.getLocator(e.target, true))); + }, _inspector["default"].getLocator(e.target, true))); }; - var onDragDrop = function () { var dragStart = null; - return function (e) { switch (e.type) { case 'dragstart': { - dragStart = _inspector2.default.getLocator(e.target, true); + dragStart = _inspector["default"].getLocator(e.target, true); break; } case 'drop': { if (!dragStart) return; - var tmp = _inspector2.default.getLocator(e.target, true); + var tmp = _inspector["default"].getLocator(e.target, true); var drop = { value: tmp.target, valueOptions: tmp.targetOptions }; - - reportCommand((0, _extends3.default)({ + reportCommand(_objectSpread(_objectSpread({ cmd: 'dragAndDropToObject' - }, dragStart, drop)); - + }, dragStart), drop)); dragStart = null; } } }; }(); - var onLeave = function onLeave(e) { reportCommand({ cmd: 'leave', target: null, value: null }); - setTimeout(function () { reportCommand({ cmd: 'pullback', @@ -24853,9 +33725,7 @@ var onLeave = function onLeave(e) { }); }, 800); }; - -var unbindContentEditableEvents = void 0; - +var unbindContentEditableEvents; var bindEventsToRecord = function bindEventsToRecord() { document.addEventListener('click', onClick, true); document.addEventListener('focus', onFocus, true); @@ -24864,10 +33734,10 @@ var bindEventsToRecord = function bindEventsToRecord() { document.addEventListener('drop', onDragDrop, true); document.addEventListener('contextmenu', onContextMenu, true); window.addEventListener('beforeunload', onLeave, true); - - unbindContentEditableEvents = (0, _dom_utils.bindContentEditableChange)({ onChange: onContentEditableChange }); + unbindContentEditableEvents = (0, _dom_utils.bindContentEditableChange)({ + onChange: onContentEditableChange + }); }; - var unbindEventsToRecord = function unbindEventsToRecord() { document.removeEventListener('click', onClick, true); document.removeEventListener('focus', onFocus, true); @@ -24876,12 +33746,10 @@ var unbindEventsToRecord = function unbindEventsToRecord() { document.removeEventListener('drop', onDragDrop, true); document.removeEventListener('contextmenu', onContextMenu, true); window.removeEventListener('beforeunload', onLeave, true); - if (unbindContentEditableEvents) { unbindContentEditableEvents(); } }; - var waitForDomReady = function waitForDomReady(accurate) { return (0, _utils.until)('dom ready', function () { return { @@ -24890,11 +33758,9 @@ var waitForDomReady = function waitForDomReady(accurate) { }; }, 1000, 6000 * 10); }; - var broadcastToAllFrames = function broadcastToAllFrames(action, data) { // IMPORTANT: broadcast status change to all frames inside var frames = window.frames; - for (var i = 0, len = frames.length; i < len; i++) { (0, _cs_postmessage.postMessage)(frames[i], window, { action: action, @@ -24902,7 +33768,6 @@ var broadcastToAllFrames = function broadcastToAllFrames(action, data) { }); } }; - var updateStatus = function updateStatus(args) { if (!args.status) { throw new Error('SET_STATUS: missing args.status'); @@ -24910,11 +33775,9 @@ var updateStatus = function updateStatus(args) { if (!C.CONTENT_SCRIPT_STATUS[args.status]) { throw new Error('SET_STATUS: invalid args.status - ' + args.status); } - - (0, _extends3.default)(state, { + Object.assign(state, { status: args.status }); - if (args.status === C.CONTENT_SCRIPT_STATUS.NORMAL || args.status === C.CONTENT_SCRIPT_STATUS.RECORDING) { bindEventsToRecord(); } else { @@ -24937,57 +33800,54 @@ var updateStatus = function updateStatus(args) { // IMPORTANT: broadcast status change to all frames inside broadcastToAllFrames('SET_STATUS', args); }; - var bindIPCListener = function bindIPCListener() { // Note: need to check csIpc in case it's a none-src iframe into which we // inject content_script.js. It has no access to chrome api, thus no csIpc available - if (!_ipc_cs2.default) return; + if (!_ipc_cs["default"]) return; // Note: csIpc instead of superIpc, because only top window is able // to listen to ipc events from bg - _ipc_cs2.default.onAsk(function (cmd, args) { - (0, _log2.default)(cmd, args); - + _ipc_cs["default"].onAsk(function (cmd, args) { + (0, _log["default"])(cmd, args); switch (cmd) { case 'HEART_BEAT': return { - secret: _ipc_cs2.default.secret + secret: _ipc_cs["default"].secret }; - case 'SET_STATUS': { updateStatus(args); return true; } - case 'DOM_READY': return waitForDomReady(false); - case 'STOP_INSPECTING': { getMask(true); - updateStatus({ status: C.CONTENT_SCRIPT_STATUS.NORMAL }); + updateStatus({ + status: C.CONTENT_SCRIPT_STATUS.NORMAL + }); return true; } - case 'RUN_COMMAND': - return runCommand(args.command).catch(function (e) { + return runCommand(args.command)["catch"](function (e) { // Mark that there is already at least one command run window.noCommandsYet = false; - - _log2.default.error(e.stack); + _log["default"].error(e.stack); throw e; }).then(function (data) { // Mark that there is already at least one command run window.noCommandsYet = false; - if (state.playingFrame !== window) { - return { data: data, isIFrame: true }; + return { + data: data, + isIFrame: true + }; } - - return { data: data }; + return { + data: data + }; }); - case 'FIND_DOM': { try { @@ -24997,66 +33857,59 @@ var bindIPCListener = function bindIPCListener() { return false; } } - case 'HIGHLIGHT_DOM': { var _$el = (0, _dom_utils.getElementByLocator)(args.locator); - if (_$el) { - _$el.scrollIntoView({ block: 'center' }); + _$el.scrollIntoView({ + block: 'center' + }); highlightDom(_$el); + downloadSaveItem(_$el, args.cmd); } - return true; } - case 'HIGHLIGHT_RECT': { highlightRect(args.rect, args); return true; } - case 'HIGHLIGHT_RECTS': { highlightRects(args.scoredRects.map(function (rect, i) { - return (0, _extends3.default)({}, rect, { + return _objectSpread(_objectSpread({}, rect), {}, { selected: i === args.selectedIndex }); })); return true; } - case 'CLEAR_VISION_RECTS': { // Note: it will clear previous rects highlightRects([]); return true; } - case 'HIDE_VISION_RECTS': { highlightRects.hide(); return true; } - case 'SHOW_VISION_RECTS': { highlightRects.show(); return true; } - case 'HIGHLIGHT_OCR_MATCHES': { - (0, _highlighter.getOrcMatchesHighlighter)().highlight(args.ocrMatches); + (0, _highlighter.getOrcMatchesHighlighter)().updateStates(args.localStorage); + (0, _highlighter.getOrcMatchesHighlighter)().highlight(args.ocrMatches, args.showOcrOverlay); return true; } - case 'CLEAR_OCR_MATCHES': { (0, _highlighter.getOrcMatchesHighlighter)().clear(); return true; } - case 'HACK_ALERT': { return hackAlertConfirmPrompt().then(function () { @@ -25065,45 +33918,38 @@ var bindIPCListener = function bindIPCListener() { return true; }); } - case 'MARK_NO_COMMANDS_YET': { window.noCommandsYet = true; return true; } - case 'SCREENSHOT_PAGE_INFO': { return _capture_screenshot.captureClientAPI.getPageInfo(); } - case 'START_CAPTURE_FULL_SCREENSHOT': { return _capture_screenshot.captureClientAPI.startCapture(args || {}); } - case 'END_CAPTURE_FULL_SCREENSHOT': { return _capture_screenshot.captureClientAPI.endCapture(args.pageInfo); } - case 'SCROLL_PAGE': { return _capture_screenshot.captureClientAPI.scrollPage(args.offset); } - case 'TAB_ACTIVATED': { loadConfig(); return; } - case 'SELECT_SCREEN_AREA': { return (0, _select_area.selectAreaPromise)({ done: function done(rect, boundingRect) { - (0, _log2.default)('SELECT_SCREEN_AREA - selectArea', rect, boundingRect); - return _ipc_cs2.default.ask('CS_SCREEN_AREA_SELECTED', { + (0, _log["default"])('SELECT_SCREEN_AREA - selectArea', rect, boundingRect); + return _ipc_cs["default"].ask('CS_SCREEN_AREA_SELECTED', { rect: { x: boundingRect.x, y: boundingRect.y, @@ -25115,22 +33961,18 @@ var bindIPCListener = function bindIPCListener() { } }); } - case 'TOGGLE_HIGHLIGHT_VIEWPORT': { var on = args.on; var id = '__kantu_viewport_highlight__'; var _$el2 = document.getElementById(id); - if (_$el2) { _$el2.remove(); } - if (on) { var $dom = document.createElement('div'); $dom.id = id; $dom.innerText = 'Calibrating Computer Vision...'; - (0, _dom_utils.setStyle)($dom, { position: 'fixed', top: 0, @@ -25147,13 +33989,10 @@ var bindIPCListener = function bindIPCListener() { justifyContent: 'center', alignItems: 'center' }); - document.documentElement.appendChild($dom); } - return true; } - case 'CONTEXT_MENU_IN_RECORDING': { switch (args && args.command) { @@ -25162,13 +34001,11 @@ var bindIPCListener = function bindIPCListener() { if (!state.elementOnContextMenu) { break; } - - reportCommand((0, _extends3.default)({}, _inspector2.default.getLocator(state.elementOnContextMenu, true), { + reportCommand(_objectSpread(_objectSpread({}, _inspector["default"].getLocator(state.elementOnContextMenu, true)), {}, { cmd: args.command, value: (0, _dom_utils.domText)(state.elementOnContextMenu) })); break; - case 'verifyTitle': case 'assertTitle': reportCommand({ @@ -25177,30 +34014,25 @@ var bindIPCListener = function bindIPCListener() { }); break; } - return true; } - case 'GET_VIEWPORT_RECT_IN_SCREEN': { var dprService = new _dpr.DevicePixelRatioService({ getZoom: function getZoom() { - return _promise2.default.resolve(args.zoom); + return Promise.resolve(args.zoom); } }); var viewportRectService = new _viewport_rect.ViewportRectService({ devicePixelRatioService: dprService }); - return viewportRectService.getViewportRectInScreen(); } - default: throw new Error('cmd not supported: ' + cmd); } }); }; - var bindEventsToInspect = function bindEventsToInspect() { // Bind click events for inspecting document.addEventListener('click', function (e) { @@ -25209,25 +34041,23 @@ var bindEventsToInspect = function bindEventsToInspect() { { e.preventDefault(); e.stopPropagation(); - var mask = getMask(); - - _inspector2.default.setStyle(mask.maskHover, { display: 'none' }); - _inspector2.default.showMaskOver(mask.maskClick, e.target); - + _inspector["default"].setStyle(mask.maskHover, { + display: 'none' + }); + _inspector["default"].showMaskOver(mask.maskClick, e.target); setTimeout(function () { - _inspector2.default.setStyle(mask.maskClick, { display: 'none' }); + _inspector["default"].setStyle(mask.maskClick, { + display: 'none' + }); }, MASK_CLICK_FADE_TIMEOUT); - - (0, _extends3.default)(state, { + Object.assign(state, { status: C.CONTENT_SCRIPT_STATUS.NORMAL }); - return superCsIpc.ask('CS_DONE_INSPECTING', { - locatorInfo: _inspector2.default.getLocator(e.target, true) - }).catch(oops); + locatorInfo: _inspector["default"].getLocator(e.target, true) + })["catch"](oops); } - default: break; } @@ -25236,33 +34066,28 @@ var bindEventsToInspect = function bindEventsToInspect() { // bind mouse over event for applying for a inspector role document.addEventListener('mouseover', function (e) { if (state.status === C.CONTENT_SCRIPT_STATUS.NORMAL) { - return superCsIpc.ask('CS_ACTIVATE_ME', {}).catch(oops); + return superCsIpc.ask('CS_ACTIVATE_ME', {})["catch"](oops); } }); // bind mouse move event to show hover mask in inspecting document.addEventListener('mousemove', function (e) { if (state.status !== C.CONTENT_SCRIPT_STATUS.INSPECTING) return; - var mask = getMask(); - _inspector2.default.showMaskOver(mask.maskHover, e.target); + _inspector["default"].showMaskOver(mask.maskHover, e.target); }); }; - var bindOnMessage = function bindOnMessage() { - (0, _cs_postmessage.onMessage)(window, function (_ref, _ref2) { - var action = _ref.action, - data = _ref.data; - var source = _ref2.source; - + (0, _cs_postmessage.onMessage)(window, function (_ref2, _ref3) { + var action = _ref2.action, + data = _ref2.data; + var source = _ref3.source; // Should not log source here, because it might cause accessing a cross origin frame error - (0, _log2.default)('onMessage', action, data); - + (0, _log["default"])('onMessage', action, data); switch (action) { case 'SET_STATUS': updateStatus(data); return true; - case 'UPDATE_CONFIG': { state.config = data; @@ -25288,34 +34113,32 @@ var bindOnMessage = function bindOnMessage() { if (state.status === C.CONTENT_SCRIPT_STATUS.PLAYING) { return false; } - data = (0, _utils.updateIn)(['ipcData', 'frameStack'], function () { var stack = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - return [_inspector2.default.getFrameLocator(source, window)].concat((0, _toConsumableArray3.default)(stack)); + return [_inspector["default"].getFrameLocator(source, window)].concat(_toConsumableArray(stack)); }, data); - if (window.top === window) { calcSelectFrameCmds(data.ipcData.frameStack).forEach(function (cmd) { - _ipc_cs2.default.ask('CS_RECORD_ADD_COMMAND', cmd).catch(oops); + _ipc_cs["default"].ask('CS_RECORD_ADD_COMMAND', cmd)["catch"](oops); }); - state.recordingFrameStack = data.ipcData.frameStack; } } - if (window.top === window) { - return _ipc_cs2.default.ask(data.ipcAction, data.ipcData).catch(oops); + return _ipc_cs["default"].ask(data.ipcAction, data.ipcData)["catch"](oops); } else { - return (0, _cs_postmessage.postMessage)(window.parent, window, { action: action, data: data }); + return (0, _cs_postmessage.postMessage)(window.parent, window, { + action: action, + data: data + }); } - case 'RESET_PLAYING_FRAME': { state.playingFrame = window; // pass on RESET_PLAYING_FRAME to parent, all the way till top window if (data === 'TOP' && window.top !== window) { - return (0, _utils.withTimeout)(_config2.default.iframePostMessageTimeout, function () { + return (0, _utils.withTimeout)(_config["default"].iframePostMessageTimeout, function () { return (0, _cs_postmessage.postMessage)(window.parent, window, { action: 'RESET_PLAYING_FRAME', data: 'TOP' @@ -25324,25 +34147,24 @@ var bindOnMessage = function bindOnMessage() { return true; }); } - - return _promise2.default.resolve(true); + return Promise.resolve(true); } - case 'SOURCE_PAGE_OFFSET': { - var $frames = [].concat((0, _toConsumableArray3.default)((0, _from2.default)(document.getElementsByTagName('iframe'))), (0, _toConsumableArray3.default)((0, _from2.default)(document.getElementsByTagName('frame')))); + var $frames = [].concat(_toConsumableArray(Array.from(document.getElementsByTagName('iframe'))), _toConsumableArray(Array.from(document.getElementsByTagName('frame')))); var $frameElement = $frames.find(function ($frame) { return $frame.contentWindow === source; }); - var offset = _inspector2.default.offset($frameElement, true); + var offset = _inspector["default"].offset($frameElement, true); var x = offset.left; var y = offset.top; - (0, _log2.default)('SOURCE_PAGE_OFFSET, iframeDOM', $frameElement); - + (0, _log["default"])('SOURCE_PAGE_OFFSET, iframeDOM', $frameElement); if (window.top === window) { - return { x: x, y: y }; + return { + x: x, + y: y + }; } - return (0, _cs_postmessage.postMessage)(window.parent, window, { action: 'SOURCE_PAGE_OFFSET', data: {} @@ -25353,22 +34175,19 @@ var bindOnMessage = function bindOnMessage() { }; }); } - case 'SOURCE_VIEWPORT_OFFSET': { - var _$frames = [].concat((0, _toConsumableArray3.default)((0, _from2.default)(document.getElementsByTagName('iframe'))), (0, _toConsumableArray3.default)((0, _from2.default)(document.getElementsByTagName('frame')))); + var _$frames = [].concat(_toConsumableArray(Array.from(document.getElementsByTagName('iframe'))), _toConsumableArray(Array.from(document.getElementsByTagName('frame')))); var _$frameElement = _$frames.find(function ($frame) { return $frame.contentWindow === source; }); var rect = _$frameElement.getBoundingClientRect(); - if (window.top === window) { return { x: rect.x, y: rect.y }; } - return (0, _cs_postmessage.postMessage)(window.parent, window, { action: 'SOURCE_VIEWPORT_OFFSET', data: {} @@ -25379,58 +34198,49 @@ var bindOnMessage = function bindOnMessage() { }; }); } - case 'DOM_READY': return waitForDomReady(false); } }); }; - var isUrlInWhiteList = function isUrlInWhiteList(url) { var _state$config$website = state.config.websiteWhiteList, - websiteWhiteList = _state$config$website === undefined ? [] : _state$config$website; - - + websiteWhiteList = _state$config$website === void 0 ? [] : _state$config$website; return websiteWhiteList.reduce(function (prev, cur) { if (prev) return prev; return url.indexOf(cur) === 0; }, false); }; - var bindInvokeEvent = function bindInvokeEvent() { var doesQueriesContainMacroOrTestSuite = function doesQueriesContainMacroOrTestSuite() { var queries = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - return queries['macro'] || queries['testsuite'] || queries['folder']; }; var decorateOptions = function decorateOptions(options, detail) { - return (0, _extends3.default)({ + return _objectSpread(_objectSpread({ loadmacrotree: '0', continueInLastUsedTab: '1' - }, options, detail ? (0, _utils.pick)(['closeKantu', 'closeRPA', 'loadmacrotree'], detail) : {}); + }, options), detail ? (0, _utils.pick)(['closeKantu', 'closeRPA', 'loadmacrotree'], detail) : {}); }; var runCsInvokeFromQueries = function runCsInvokeFromQueries() { var queries = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var userStorageMode = queries.storageMode ? queries.storageMode.toLowerCase() : ''; var isValidStorageMode = ['browser', 'xfile'].indexOf(userStorageMode) !== -1; var storageMode = isValidStorageMode ? userStorageMode : 'browser'; - if (queries['macro']) { - return _ipc_cs2.default.ask('CS_INVOKE', { + return _ipc_cs["default"].ask('CS_INVOKE', { testCase: { storageMode: storageMode, name: queries['macro'], from: 'html' }, options: decorateOptions(queries) - }).catch(function (e) { - return alert('[UI.Vision RPA] ' + e.message); + })["catch"](function (e) { + return alert('[Ui.Vision] ' + e.message); }); } - if (queries['folder']) { - return _ipc_cs2.default.ask('CS_INVOKE', { + return _ipc_cs["default"].ask('CS_INVOKE', { testSuite: { storageMode: storageMode, macroFolder: queries['folder'], @@ -25439,17 +34249,16 @@ var bindInvokeEvent = function bindInvokeEvent() { options: decorateOptions(queries) }); } - if (queries['testsuite']) { - return _ipc_cs2.default.ask('CS_INVOKE', { + return _ipc_cs["default"].ask('CS_INVOKE', { testSuite: { storageMode: storageMode, name: queries['testsuite'], from: 'html' }, options: decorateOptions(queries) - }).catch(function (e) { - return alert('[UI.Vision RPA] ' + e.message); + })["catch"](function (e) { + return alert('[Ui.Vision] ' + e.message); }); } }; @@ -25457,47 +34266,38 @@ var bindInvokeEvent = function bindInvokeEvent() { // Macros (0, _utils.bind)(window, 'kantuRunMacro', function (e) { - (0, _log2.default)('invoke event', e); + (0, _log["default"])('invoke event', e); window.dispatchEvent(new CustomEvent('kantuInvokeSuccess')); - var queries = (0, _utils.parseQuery)(window.location.search); - - _ipc_cs2.default.ask('CS_INVOKE', { + _ipc_cs["default"].ask('CS_INVOKE', { testCase: e.detail, - options: decorateOptions((0, _extends3.default)({ + options: decorateOptions(_objectSpread({ continueInLastUsedTab: '0' }, queries), e.detail) - }).catch(function (e) { - return alert('[UI.Vision RPA] ' + e.message); + })["catch"](function (e) { + return alert('[Ui.Vision] ' + e.message); }); }); - - (isFile ? _utils.bindOnce : _utils.bind)(window, 'kantuSaveAndRunMacro', function (e) { + (isFile ? _utils.bindOnce : _utils.subjectiveBindOnce)(window, 'kantuSaveAndRunMacro', function (e) { var run = function run() { - (0, _log2.default)('save and run macro event', e); + (0, _log["default"])('save and run macro event:>> e:', e); window.dispatchEvent(new CustomEvent('kantuInvokeSuccess')); - if (!e.detail || !e.detail.html && !e.detail.json) { - return alert('[UI.Vision RPA] invalid data format'); + return alert('[Ui.Vision] invalid data format'); } - var queries = (0, _utils.parseQuery)(window.location.search); var direct = !!queries['direct'] || e.detail.json && e.detail.direct; var storageMode = queries['storage'] || e.detail.storageMode || 'browser'; - - var msgDirectParam = 'UI.Vision RPA: Do you want to import and run this macro?\n\nNote: To remove this dialog, add \'?direct=1\' switch to the URL. Example: file:///xx/xx/macro.html?direct=1 For embedded macros, add "direct: true" to the call.'; - var msgWebsiteWhiteList = 'UI.Vision RPA: Do you want to import and run this macro?\n\nNote: To remove this dialog, add this site to whitelist in the UI.Vision RPA settings'; - + var msgDirectParam = 'Ui.Vision: Do you want to import and run this macro?\n\nNote: To remove this dialog, add \'?direct=1\' switch to the URL. Example: file:///xx/xx/macro.html?direct=1 For embedded macros, add "direct: true" to the call.'; + var msgWebsiteWhiteList = 'Ui.Vision: Do you want to import and run this macro?\n\nNote: To remove this dialog, add this site to whitelist in the Ui.Vision settings'; if (isFile && !direct) { var agree = confirm(msgDirectParam); if (!agree) return; } - if (!isFile) { if (!state.config.allowRunFromHttpSchema) { - return alert('[Message from UI.Vision RPA] Error #110: To run an embedded macro from a website, you need to allow it in the RPA settings first'); + return alert('[Message from Ui.Vision] Error #110: To run an embedded macro from a website, you need to allow it in the RPA settings first'); } - if (!isUrlInWhiteList(window.location.href)) { var _agree = confirm(msgWebsiteWhiteList); if (!_agree) return; @@ -25506,74 +34306,67 @@ var bindInvokeEvent = function bindInvokeEvent() { if (!_agree2) return; } } - if (doesQueriesContainMacroOrTestSuite(queries)) { - return runCsInvokeFromQueries((0, _extends3.default)({}, queries, { storageMode: storageMode })); + console.log('doesQueriesContainMacroOrTestSuite:>> queries: ', queries); + return runCsInvokeFromQueries(_objectSpread(_objectSpread({}, queries), {}, { + storageMode: storageMode + })); } else if (e.detail.noImport) { var msg = 'Command line must include one of these params: macro, folder, testsuite'; alert(msg); throw new Error(msg); } - - var extraOptions = !isFile ? { continueInLastUsedTab: '0' } : {}; - - return _ipc_cs2.default.ask('CS_IMPORT_AND_INVOKE', (0, _extends3.default)({}, e.detail, { + var extraOptions = !isFile ? { + continueInLastUsedTab: '0' + } : {}; + return _ipc_cs["default"].ask('CS_IMPORT_AND_INVOKE', _objectSpread(_objectSpread({}, e.detail), {}, { from: 'html', - options: decorateOptions((0, _extends3.default)({}, queries, extraOptions), e.detail) - })).catch(function (e) { - return alert('[UI.Vision RPA] ' + e.message); + options: decorateOptions(_objectSpread(_objectSpread({}, queries), extraOptions), e.detail) + }))["catch"](function (e) { + return alert('[Ui.Vision] ' + e.message); }); }; - - loadConfig().catch(function (e) {}).then(run); + loadConfig()["catch"](function (e) {}).then(run); }); + // we don't need this // Test Suites - (0, _utils.bind)(window, 'kantuRunTestSuite', function (e) { - (0, _log2.default)('invoke event', e); - window.dispatchEvent(new CustomEvent('kantuInvokeSuccess')); - - var queries = (0, _utils.parseQuery)(window.location.search); - var storageMode = queries['storage'] || e.detail.storageMode || 'browser'; - - if (doesQueriesContainMacroOrTestSuite(queries)) { - return runCsInvokeFromQueries((0, _extends3.default)({}, queries, { - storageMode: storageMode - })); - } - - return _ipc_cs2.default.ask('CS_INVOKE', { - testSuite: e.detail, - options: decorateOptions(queries, e.detail) - }).catch(function (e) { - return alert('[UI.Vision RPA] ' + e.message); - }); - }); + // bind(window, 'kantuRunTestSuite', (e) => { + // log('invoke event', e) + // window.dispatchEvent(new CustomEvent('kantuInvokeSuccess')) + + // const queries = parseQuery(window.location.search) + // const storageMode = queries['storage'] || e.detail.storageMode || 'browser' + + // if (doesQueriesContainMacroOrTestSuite(queries)) { + // return runCsInvokeFromQueries({ + // ...queries, + // storageMode + // }) + // } + + // return csIpc.ask('CS_INVOKE', { + // testSuite: e.detail, + // options: decorateOptions(queries, e.detail) + // }) + // .catch(e => alert('[Ui.Vision] ' + e.message)) + // }) }; - var hackAlertConfirmPrompt = function hackAlertConfirmPrompt() { var doc = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document; - - var script = '(function () {\n if (!window.oldAlert) window.oldAlert = window.alert\n if (!window.oldConfirm) window.oldConfirm = window.confirm\n if (!window.oldPrompt) window.oldPrompt = window.prompt\n\n window.alert = function (str) {\n document.body.setAttribute(\'data-alert\', str)\n }\n\n window.confirm = function (str) {\n document.body.setAttribute(\'data-confirm\', str)\n return true\n }\n\n window.prompt = function (str) {\n var answer = document.body.getAttribute(\'data-prompt-answer\')\n document.body.setAttribute(\'data-prompt\', str)\n document.body.setAttribute(\'data-prompt-answer\', \'\')\n return answer\n }\n })();'; - - return (0, _eval.evalViaInject)(script); + var script = "(function () {\n if (!window.oldAlert) window.oldAlert = window.alert\n if (!window.oldConfirm) window.oldConfirm = window.confirm\n if (!window.oldPrompt) window.oldPrompt = window.prompt\n\n window.alert = function (str) {\n document.body.setAttribute('data-alert', str)\n }\n\n window.confirm = function (str) {\n document.body.setAttribute('data-confirm', str)\n return true\n }\n\n window.prompt = function (str) {\n var answer = document.body.getAttribute('data-prompt-answer')\n document.body.setAttribute('data-prompt', str)\n document.body.setAttribute('data-prompt-answer', '')\n return answer\n }\n })();"; + return (0, _eval.hackAlertInject)(script); }; - var restoreAlertConfirmPrompt = function restoreAlertConfirmPrompt() { - var script = '(function () {\n if (window.oldAlert) window.alert = window.oldAlert\n if (window.oldConfirm) window.confirm = window.oldConfirm\n if (window.oldPrompt) window.prompt = window.oldPrompt\n });'; - - return (0, _eval.evalViaInject)(script); + var script = "(function () {\n if (window.oldAlert) window.alert = window.oldAlert\n if (window.oldConfirm) window.confirm = window.oldConfirm\n if (window.oldPrompt) window.prompt = window.oldPrompt\n });"; + return (0, _eval.hackAlertInject)(script); }; - var init = function init() { unbindEventsToRecord(); bindEventsToRecord(); - bindEventsToInspect(); bindOnMessage(); - toggleBodyMark(true); - loadConfig().then(function (config) { return removeBodyMarkIfNecessary(config); }); @@ -25586,21 +34379,17 @@ var init = function init() { onUrlChange(init); } }; - var toggleBodyMark = function toggleBodyMark(shouldMark) { var $root = document.documentElement; - if (!$root) { return; } - if (shouldMark) { $root.setAttribute('data-kantu', 1); } else { $root.removeAttribute('data-kantu'); } }; - var removeBodyMarkIfNecessary = function removeBodyMarkIfNecessary(config) { switch (window.location.protocol) { case 'file:': @@ -25608,24 +34397,20 @@ var removeBodyMarkIfNecessary = function removeBodyMarkIfNecessary(config) { toggleBodyMark(false); } break; - case 'http:': case 'https:': if (!config.allowRunFromHttpSchema) { toggleBodyMark(false); } break; - default: toggleBodyMark(false); } }; - var runCommand = function runCommand(command) { if (!command.cmd) { throw new Error('runCommand: must provide cmd'); } - var pResult = function () { // if it's an 'open' command, it must be executed in the top window if (state.playingFrame === window || command.cmd === 'open') { @@ -25634,21 +34419,19 @@ var runCommand = function runCommand(command) { var ret = (0, _command_runner.run)(command, superCsIpc, { highlightDom: highlightDom, hackAlertConfirmPrompt: hackAlertConfirmPrompt, - xpath: _inspector2.default.xpath + xpath: _inspector["default"].xpath }); // Note: `run` returns the contentWindow of the selected frame if (command.cmd === 'selectFrame') { - return ret.then(function (_ref3) { - var frame = _ref3.frame; - + return ret.then(function (_ref4) { + var frame = _ref4.frame; var p = function () { // let outside window know that playingFrame has been changed, if it's parent or top if (frame !== window && (frame === window.top || frame === window.parent)) { // set playingFrame to own window, get ready for later commands if any state.playingFrame = window; - - return (0, _utils.withTimeout)(_config2.default.iframePostMessageTimeout, function () { + return (0, _utils.withTimeout)(_config["default"].iframePostMessageTimeout, function () { return (0, _cs_postmessage.postMessage)(window.parent, window, { action: 'RESET_PLAYING_FRAME', data: frame === window.top ? 'TOP' : 'PARENT' @@ -25656,11 +34439,9 @@ var runCommand = function runCommand(command) { }); } else { state.playingFrame = frame; - - return _promise2.default.resolve(); + return Promise.resolve(); } }(); - return p.then(function () { return { pageUrl: window.location.href, @@ -25672,23 +34453,23 @@ var runCommand = function runCommand(command) { // Extra info passed on to background, it contains timeout info var wrapResult = function wrapResult(ret) { - return (0, _extends3.default)({}, (typeof ret === 'undefined' ? 'undefined' : (0, _typeof3.default)(ret)) === 'object' ? ret : {}, { + return _objectSpread(_objectSpread({}, _typeof(ret) === 'object' ? ret : {}), {}, { pageUrl: window.location.href, extra: command.extra, // Note: undefined value in an Object will be eliminated during message passing, // Have to transform it into an object first, and convert it back in front end vars: !ret.vars ? undefined : (0, _utils.objMap)(function (val) { - return val !== undefined ? val : { __undefined__: true }; + return val !== undefined ? val : { + __undefined__: true + }; }, ret.vars) }); }; - - return _promise2.default.resolve(ret).then(wrapResult); + return Promise.resolve(ret).then(wrapResult); } else { var isFrameRemoved = function isFrameRemoved(frame) { return !frame.parent; }; - if (isFrameRemoved(state.playingFrame)) { throw new Error('The selected frame has been removed. You may want to use another selectFrame before its removal'); } @@ -25707,14 +34488,12 @@ var runCommand = function runCommand(command) { return pResult.then(function (result) { var secret = result.secret || function () { if (window.top === window) { - return _ipc_cs2.default.secret; + return _ipc_cs["default"].secret; } - window.kantuSecret = window.kantuSecret || '' + Math.floor(Math.random() * 10000); return window.kantuSecret; }(); - - return (0, _extends3.default)({}, result, { + return _objectSpread(_objectSpread({}, result), {}, { secret: secret }); }); @@ -25729,34 +34508,28 @@ var onUrlChange = function () { var lastUrl = window.location.href; var check = function check() { if (window.location.href !== lastUrl) { - (0, _log2.default)('url changed', lastUrl, window.location.href); + (0, _log["default"])('url changed', lastUrl, window.location.href); lastUrl = window.location.href; callback(); } }; - if (window.top === window) { return function () {}; } - setInterval(check, 2000); - return function (fn) { callback = fn; }; }(); - var loadConfig = function loadConfig() { - return _storage2.default.get('config').then(function (config) { + return _storage["default"].get('config').then(function (config) { state.config = config; // IMPORTANT: broadcast status change to all frames inside broadcastToAllFrames('UPDATE_CONFIG', config); - return config; }); }; - init(); })(); diff --git a/dist/csv_editor.html b/dist/csv_editor.html index de6cc51..781ab84 100644 --- a/dist/csv_editor.html +++ b/dist/csv_editor.html @@ -1 +1 @@ -CSV Editor - UI.Vision RPA
\ No newline at end of file +CSV Editor - Ui.Vision
\ No newline at end of file diff --git a/dist/csv_editor.js b/dist/csv_editor.js index 99f39dc..d6809aa 100644 --- a/dist/csv_editor.js +++ b/dist/csv_editor.js @@ -1,187 +1,254 @@ /******/ (() => { // webpackBootstrap +/******/ "use strict"; /******/ var __webpack_modules__ = ({ -/***/ 41471: +/***/ 42860: +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ $e: () => (/* binding */ warning), +/* harmony export */ Em: () => (/* binding */ getSecondaryColor), +/* harmony export */ P3: () => (/* binding */ isIconDefinition), +/* harmony export */ al: () => (/* binding */ normalizeTwoToneColors), +/* harmony export */ cM: () => (/* binding */ generate), +/* harmony export */ lf: () => (/* binding */ useInsertStyles) +/* harmony export */ }); +/* unused harmony exports normalizeAttrs, svgBaseProps, iconStyles */ +/* harmony import */ var _babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(89379); +/* harmony import */ var _babel_runtime_helpers_esm_typeof__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(82284); +/* harmony import */ var _ant_design_colors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(20439); +/* harmony import */ var rc_util_es_Dom_dynamicCSS__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(85089); +/* harmony import */ var rc_util_es_Dom_shadow__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(72633); +/* harmony import */ var rc_util_es_warning__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(68210); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(96540); +/* harmony import */ var _components_Context__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(61053); + + + + + + + + +function camelCase(input) { + return input.replace(/-(.)/g, function (match, g) { + return g.toUpperCase(); + }); +} +function warning(valid, message) { + (0,rc_util_es_warning__WEBPACK_IMPORTED_MODULE_2__/* ["default"] */ .Ay)(valid, "[@ant-design/icons] ".concat(message)); +} +function isIconDefinition(target) { + return (0,_babel_runtime_helpers_esm_typeof__WEBPACK_IMPORTED_MODULE_4__/* ["default"] */ .A)(target) === 'object' && typeof target.name === 'string' && typeof target.theme === 'string' && ((0,_babel_runtime_helpers_esm_typeof__WEBPACK_IMPORTED_MODULE_4__/* ["default"] */ .A)(target.icon) === 'object' || typeof target.icon === 'function'); +} +function normalizeAttrs() { + var attrs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return Object.keys(attrs).reduce(function (acc, key) { + var val = attrs[key]; + switch (key) { + case 'class': + acc.className = val; + delete acc.class; + break; + default: + delete acc[key]; + acc[camelCase(key)] = val; + } + return acc; + }, {}); +} +function generate(node, key, rootProps) { + if (!rootProps) { + return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3__.createElement(node.tag, (0,_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_5__/* ["default"] */ .A)({ + key: key + }, normalizeAttrs(node.attrs)), (node.children || []).map(function (child, index) { + return generate(child, "".concat(key, "-").concat(node.tag, "-").concat(index)); + })); + } + return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3__.createElement(node.tag, (0,_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_5__/* ["default"] */ .A)((0,_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_5__/* ["default"] */ .A)({ + key: key + }, normalizeAttrs(node.attrs)), rootProps), (node.children || []).map(function (child, index) { + return generate(child, "".concat(key, "-").concat(node.tag, "-").concat(index)); + })); +} +function getSecondaryColor(primaryColor) { + // choose the second color + return (0,_ant_design_colors__WEBPACK_IMPORTED_MODULE_0__/* .generate */ .cM)(primaryColor)[0]; +} +function normalizeTwoToneColors(twoToneColor) { + if (!twoToneColor) { + return []; + } + return Array.isArray(twoToneColor) ? twoToneColor : [twoToneColor]; +} + +// These props make sure that the SVG behaviours like general text. +// Reference: https://blog.prototypr.io/align-svg-icons-to-text-and-say-goodbye-to-font-icons-d44b3d7b26b4 +var svgBaseProps = { + width: '1em', + height: '1em', + fill: 'currentColor', + 'aria-hidden': 'true', + focusable: 'false' +}; +var iconStyles = "\n.anticon {\n display: inline-flex;\n align-items: center;\n color: inherit;\n font-style: normal;\n line-height: 0;\n text-align: center;\n text-transform: none;\n vertical-align: -0.125em;\n text-rendering: optimizeLegibility;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n.anticon > * {\n line-height: 1;\n}\n\n.anticon svg {\n display: inline-block;\n}\n\n.anticon::before {\n display: none;\n}\n\n.anticon .anticon-icon {\n display: block;\n}\n\n.anticon[tabindex] {\n cursor: pointer;\n}\n\n.anticon-spin::before,\n.anticon-spin {\n display: inline-block;\n -webkit-animation: loadingCircle 1s infinite linear;\n animation: loadingCircle 1s infinite linear;\n}\n\n@-webkit-keyframes loadingCircle {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n@keyframes loadingCircle {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n"; +var useInsertStyles = function useInsertStyles(eleRef) { + var _useContext = (0,react__WEBPACK_IMPORTED_MODULE_3__.useContext)(_components_Context__WEBPACK_IMPORTED_MODULE_6__/* ["default"] */ .A), + csp = _useContext.csp, + prefixCls = _useContext.prefixCls; + var mergedStyleStr = iconStyles; + if (prefixCls) { + mergedStyleStr = mergedStyleStr.replace(/anticon/g, prefixCls); + } + (0,react__WEBPACK_IMPORTED_MODULE_3__.useEffect)(function () { + var ele = eleRef.current; + var shadowRoot = (0,rc_util_es_Dom_shadow__WEBPACK_IMPORTED_MODULE_7__/* .getShadowRoot */ .j)(ele); + (0,rc_util_es_Dom_dynamicCSS__WEBPACK_IMPORTED_MODULE_1__/* .updateCSS */ .BD)(mergedStyleStr, '@ant-design-icons', { + prepend: true, + csp: csp, + attachTo: shadowRoot + }); + }, []); +}; + +/***/ }), + +/***/ 96571: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); - -var _ipc_bg_cs = __webpack_require__(31745); - +exports["default"] = void 0; +var _ipc_bg_cs = __webpack_require__(59711); var throwNotTop = function throwNotTop() { throw new Error('You are not a top window, not allowed to initialize/use csIpc'); }; +// browser.runtime.id in firefox extension isn't necessarily found in window.location.href +// window.location.href eg. "moz-extension://add2840d-0b3e-41f0-8da1-55d780cc5dd8/sidepanel.html" +var isSidepanelInFirefox = typeof window !== 'undefined' && window.location.href.match(/moz-extension:\/\/[a-z0-9-]+\/sidepanel.html/); +var isSidepanel = false; +if (typeof window !== 'undefined' && (window.location.href.startsWith("chrome-extension://".concat(chrome.runtime.id, "/sidepanel.html")) || isSidepanelInFirefox)) { + isSidepanel = true; +} + // Note: csIpc is only available to top window -var ipc = typeof window !== 'undefined' && window.top === window ? (0, _ipc_bg_cs.csInit)() : { +var ipc = typeof window !== 'undefined' && window.top === window ? isSidepanel ? (0, _ipc_bg_cs.spInit)() : (0, _ipc_bg_cs.csInit)() : { ask: throwNotTop, send: throwNotTop, onAsk: throwNotTop, destroy: throwNotTop +}; - // Note: one ipc singleton per content script -};exports["default"] = ipc; +// Note: one ipc singleton per content script +var _default = exports["default"] = ipc; /***/ }), -/***/ 3146: +/***/ 34391: /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { -"use strict"; - - -var _slicedToArray2 = __webpack_require__(12424); - -var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); - -var _promise = __webpack_require__(46593); - -var _promise2 = _interopRequireDefault(_promise); - -var _extends2 = __webpack_require__(88239); - -var _extends3 = _interopRequireDefault(_extends2); - -var _button = __webpack_require__(65400); - -var _button2 = _interopRequireDefault(_button); - -var _message2 = __webpack_require__(11187); - -var _message3 = _interopRequireDefault(_message2); - -var _getPrototypeOf = __webpack_require__(85105); - -var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); - -var _classCallCheck2 = __webpack_require__(99663); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _createClass2 = __webpack_require__(22600); - -var _createClass3 = _interopRequireDefault(_createClass2); - -var _possibleConstructorReturn2 = __webpack_require__(49135); - -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - -var _inherits2 = __webpack_require__(93196); - -var _inherits3 = _interopRequireDefault(_inherits2); - -var _react = __webpack_require__(67294); - -var _react2 = _interopRequireDefault(_react); - -var _reactDom = __webpack_require__(73935); - -var _reactDom2 = _interopRequireDefault(_reactDom); - -var _antd = __webpack_require__(56318); - -var _reactCodemirror = __webpack_require__(29656); - -__webpack_require__(4631); - -__webpack_require__(96876); - -__webpack_require__(4328); - -__webpack_require__(82801); - -__webpack_require__(47462); - -__webpack_require__(11067); - -__webpack_require__(54956); - -var _storage = __webpack_require__(67585); - -var _storage2 = _interopRequireDefault(_storage); - -var _storage3 = __webpack_require__(16058); - -var _xfile = __webpack_require__(1577); -var _utils = __webpack_require__(63370); - -var _ipc_cs = __webpack_require__(41471); - -var _ipc_cs2 = _interopRequireDefault(_ipc_cs); - -var _cs_timeout = __webpack_require__(28411); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -(0, _cs_timeout.polyfillTimeoutFunctions)(_ipc_cs2.default); +var _react = _interopRequireDefault(__webpack_require__(96540)); +var _reactDom = _interopRequireDefault(__webpack_require__(40961)); +var _antd = __webpack_require__(33061); +var _reactCodemirror = __webpack_require__(82349); +__webpack_require__(15237); +__webpack_require__(16792); +__webpack_require__(97923); +__webpack_require__(55218); +__webpack_require__(9914); +__webpack_require__(62826); +var _storage = _interopRequireDefault(__webpack_require__(88555)); +var _storage2 = __webpack_require__(97467); +var _xfile = __webpack_require__(63109); +var _utils = __webpack_require__(46580); +var _ipc_cs = _interopRequireDefault(__webpack_require__(96571)); +var _cs_timeout = __webpack_require__(41279); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _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; }, _typeof(o); } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +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."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +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; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +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), !0).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; } +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 _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } +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); } // import 'antd/dist/antd.css' +(0, _cs_timeout.polyfillTimeoutFunctions)(_ipc_cs["default"]); var rootEl = document.getElementById('root'); var render = function render() { - return _reactDom2.default.render(_react2.default.createElement(App, null), rootEl); + return _reactDom["default"].render( /*#__PURE__*/_react["default"].createElement(App, null), rootEl); }; - -var App = function (_React$Component) { - (0, _inherits3.default)(App, _React$Component); - +var App = /*#__PURE__*/function (_React$Component) { + _inherits(App, _React$Component); function App() { - var _ref; - - var _temp, _this, _ret; - - (0, _classCallCheck3.default)(this, App); - - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + var _this; + _classCallCheck(this, App); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } - - return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = App.__proto__ || (0, _getPrototypeOf2.default)(App)).call.apply(_ref, [this].concat(args))), _this), _this.state = { + _this = _callSuper(this, App, [].concat(args)); + _defineProperty(_assertThisInitialized(_this), "state", { csvFile: null, ready: false, sourceText: '', sourceTextModified: '' - }, _this.onChangeEditSource = function (editor, data, text) { + }); + _defineProperty(_assertThisInitialized(_this), "onChangeEditSource", function (editor, data, text) { _this.setState({ sourceTextModified: text }); - }, _this.saveCSV = function () { - return (0, _storage3.getStorageManager)().getCSVStorage().overwrite(_this.state.csvFile, new Blob([_this.state.sourceTextModified])).then(function () { - return _message3.default.success('Successfully saved'); + }); + _defineProperty(_assertThisInitialized(_this), "saveCSV", function () { + return (0, _storage2.getStorageManager)().getCSVStorage().overwrite(_this.state.csvFile, new Blob([_this.state.sourceTextModified])).then(function () { + return _antd.message.success('Successfully saved'); }, function (e) { - _message3.default.error('Error: ' + e.message); + _antd.message.error('Error: ' + e.message); throw e; }); - }, _this.onClickSave = function () { + }); + _defineProperty(_assertThisInitialized(_this), "onClickSave", function () { return _this.saveCSV(); - }, _this.onClickSaveClose = function () { + }); + _defineProperty(_assertThisInitialized(_this), "onClickSaveClose", function () { return _this.saveCSV().then(function () { return setTimeout(function () { return window.close(); }, 300); }); - }, _this.onClickCancel = function () { + }); + _defineProperty(_assertThisInitialized(_this), "onClickCancel", function () { window.close(); - }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret); + }); + return _this; } - - (0, _createClass3.default)(App, [{ - key: 'componentDidMount', + _createClass(App, [{ + key: "componentDidMount", value: function componentDidMount() { var _this2 = this; - var queryObj = (0, _utils.parseQuery)(window.location.search); var csvFile = queryObj.csv; - if (!csvFile) return; - document.title = csvFile + ' - RPA CSV Editor'; - - (0, _storage3.getStorageManager)().getCSVStorage().read(csvFile, 'Text').then(function (text) { + (0, _storage2.getStorageManager)().getCSVStorage().read(csvFile, 'Text').then(function (text) { _this2.setState({ csvFile: csvFile, ready: true, @@ -191,110 +258,174 @@ var App = function (_React$Component) { }); } }, { - key: 'render', + key: "render", value: function render() { var _this3 = this; - - if (!this.state.ready) return _react2.default.createElement('div', null); - - return _react2.default.createElement( - 'div', - { className: 'csv-editor' }, - _react2.default.createElement(_reactCodemirror.UnControlled, { - ref: function ref(el) { - _this3.codeMirror = el; - }, - value: this.state.sourceText, - onChange: this.onChangeEditSource, - options: { - lineNumbers: true, - matchBrackets: true, - autoCloseBrackets: true - } - }), - _react2.default.createElement( - 'div', - { className: 'csv-actions' }, - _react2.default.createElement( - _button2.default, - { type: 'primary', onClick: this.onClickSaveClose }, - 'Save & Close' - ), - _react2.default.createElement( - _button2.default, - { onClick: this.onClickSave }, - 'Save' - ), - _react2.default.createElement( - _button2.default, - { onClick: this.onClickCancel }, - 'Cancel' - ) - ) - ); + if (!this.state.ready) return /*#__PURE__*/_react["default"].createElement("div", null); + return /*#__PURE__*/_react["default"].createElement("div", { + className: "csv-editor" + }, /*#__PURE__*/_react["default"].createElement(_reactCodemirror.UnControlled, { + ref: function ref(el) { + _this3.codeMirror = el; + }, + value: this.state.sourceText, + onChange: this.onChangeEditSource, + options: { + lineNumbers: true, + matchBrackets: true, + autoCloseBrackets: true + } + }), /*#__PURE__*/_react["default"].createElement("div", { + className: "csv-actions" + }, /*#__PURE__*/_react["default"].createElement(_antd.Button, { + type: "primary", + onClick: this.onClickSaveClose + }, "Save & Close"), /*#__PURE__*/_react["default"].createElement(_antd.Button, { + onClick: this.onClickSave + }, "Save"), /*#__PURE__*/_react["default"].createElement(_antd.Button, { + onClick: this.onClickCancel + }, "Cancel"))); } }]); return App; -}(_react2.default.Component); - +}(_react["default"].Component); function restoreConfig() { - return _storage2.default.get('config').then(function () { + return _storage["default"].get('config').then(function () { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - return (0, _extends3.default)({ - storageMode: _storage3.StorageStrategyType.Browser + return _objectSpread({ + storageMode: _storage2.StorageStrategyType.Browser }, config); }); } - function init() { - return _promise2.default.all([restoreConfig(), (0, _xfile.getXFile)().getConfig()]).then(function (_ref2) { - var _ref3 = (0, _slicedToArray3.default)(_ref2, 2), - config = _ref3[0], - xFileConfig = _ref3[1]; - - (0, _storage3.getStorageManager)(config.storageMode); + return Promise.all([restoreConfig(), (0, _xfile.getXFile)().getConfig()]).then(function (_ref) { + var _ref2 = _slicedToArray(_ref, 2), + config = _ref2[0], + xFileConfig = _ref2[1]; + (0, _storage2.getStorageManager)(config.storageMode); render(); }, render); } - init(); /***/ }), -/***/ 52395: -/***/ ((module, exports, __webpack_require__) => { +/***/ 53651: +/***/ ((module, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ A: () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(31601); +/* harmony import */ var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(76314); +/* harmony import */ var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__); +// Imports -exports = module.exports = __webpack_require__(9252)(false); -// imports +var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default())); +// Module +___CSS_LOADER_EXPORT___.push([module.id, `.csv-editor{position:absolute;top:0;bottom:0;left:0;right:0;display:flex;flex-direction:column}.csv-editor .react-codemirror2{flex:1;position:relative;border-bottom:1px solid #ccc}.csv-editor .react-codemirror2 .CodeMirror{position:absolute;top:0;bottom:0;left:0;right:0;height:auto;font-size:13px}.csv-editor .csv-actions{height:60px;line-height:60px;text-align:center;background:#f0f0f0}.csv-editor .csv-actions button{margin-right:10px}`, ""]); +// Exports +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___); -// module -exports.push([module.id, ".csv-editor{position:absolute;top:0;bottom:0;left:0;right:0;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column}.csv-editor .react-codemirror2{-webkit-box-flex:1;-ms-flex:1;flex:1;position:relative;border-bottom:1px solid #ccc}.csv-editor .react-codemirror2 .CodeMirror{position:absolute;top:0;bottom:0;left:0;right:0;height:auto;font-size:13px}.csv-editor .csv-actions{height:60px;line-height:60px;text-align:center;background:#f0f0f0}.csv-editor .csv-actions button{margin-right:10px}", ""]); -// exports +/***/ }), + +/***/ 40961: +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + + + +function checkDCE() { + /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ + if ( + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' || + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function' + ) { + return; + } + if (false) {} + try { + // Verify that the code above has been dead code eliminated (DCE'd). + __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE); + } catch (err) { + // DevTools shouldn't crash React, no matter what. + // We should still report in case we break this code. + console.error(err); + } +} + +if (true) { + // DCE check should happen before ReactDOM bundle executes so that + // DevTools can report bad minification during injection. + checkDCE(); + module.exports = __webpack_require__(22551); +} else {} /***/ }), -/***/ 54956: +/***/ 96540: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -// style-loader: Adds some css to the DOM by adding a