{ "version": 3, "sources": ["../../node_modules/@esbuild-plugins/node-globals-polyfill/_virtual-process-polyfill_.js", "../../node_modules/@esbuild-plugins/node-globals-polyfill/Buffer.js", "../../node_modules/@esbuild-plugins/node-globals-polyfill/_buffer.js", "../../../libapi/dist/structs.js", "../../../blackbox/dist/geometry.js", "../../../blackbox/dist/labels.js", "../../../blackbox/dist/layouts.js", "../../../blackbox/dist/sort.js", "../../../blackbox/dist/pallet_config.js", "../../../blackbox/dist/machine.js", "../../../node_modules/uuid/lib/rng-browser.js", "../../../node_modules/uuid/lib/bytesToUuid.js", "../../../node_modules/uuid/v1.js", "../../../node_modules/uuid/v4.js", "../../../node_modules/uuid/index.js", "../../../blackbox/dist/autolayout.js", "../../../blackbox/dist/core_config.js", "../../../blackbox/dist/index.js", "../../../libapi/node_modules/axios/lib/helpers/bind.js", "../../../libapi/node_modules/axios/lib/utils.js", "../../../libapi/node_modules/axios/lib/helpers/buildURL.js", "../../../libapi/node_modules/axios/lib/core/InterceptorManager.js", "../../../libapi/node_modules/axios/lib/helpers/normalizeHeaderName.js", "../../../libapi/node_modules/axios/lib/core/enhanceError.js", "../../../libapi/node_modules/axios/lib/core/createError.js", "../../../libapi/node_modules/axios/lib/core/settle.js", "../../../libapi/node_modules/axios/lib/helpers/cookies.js", "../../../libapi/node_modules/axios/lib/helpers/isAbsoluteURL.js", "../../../libapi/node_modules/axios/lib/helpers/combineURLs.js", "../../../libapi/node_modules/axios/lib/core/buildFullPath.js", "../../../libapi/node_modules/axios/lib/helpers/parseHeaders.js", "../../../libapi/node_modules/axios/lib/helpers/isURLSameOrigin.js", "../../../libapi/node_modules/axios/lib/cancel/Cancel.js", "../../../libapi/node_modules/axios/lib/adapters/xhr.js", "../../../libapi/node_modules/axios/lib/defaults.js", "../../../libapi/node_modules/axios/lib/core/transformData.js", "../../../libapi/node_modules/axios/lib/cancel/isCancel.js", "../../../libapi/node_modules/axios/lib/core/dispatchRequest.js", "../../../libapi/node_modules/axios/lib/core/mergeConfig.js", "../../../libapi/node_modules/axios/lib/env/data.js", "../../../libapi/node_modules/axios/lib/helpers/validator.js", "../../../libapi/node_modules/axios/lib/core/Axios.js", "../../../libapi/node_modules/axios/lib/cancel/CancelToken.js", "../../../libapi/node_modules/axios/lib/helpers/spread.js", "../../../libapi/node_modules/axios/lib/helpers/isAxiosError.js", "../../../libapi/node_modules/axios/lib/axios.js", "../../../libapi/node_modules/axios/index.js", "../../../libapi/dist/api.js", "../../../libapi/dist/utils.js", "node-modules-polyfills:events", "node-modules-polyfills-commonjs:events", "../../../libapi/node_modules/xtend/immutable.js", "../../../libapi/node_modules/readable-stream/lib/internal/streams/stream-browser.js", "node-modules-polyfills:buffer", "node-modules-polyfills-commonjs:buffer", "node-modules-polyfills:process", "../../node_modules/rollup-plugin-node-polyfills/polyfills/inherits.js", "node-modules-polyfills:util", "node-modules-polyfills-commonjs:util", "../../../libapi/node_modules/readable-stream/lib/internal/streams/buffer_list.js", "../../../libapi/node_modules/readable-stream/lib/internal/streams/destroy.js", "../../../libapi/node_modules/readable-stream/errors-browser.js", "../../../libapi/node_modules/readable-stream/lib/internal/streams/state.js", "../../../libapi/node_modules/inherits/inherits_browser.js", "../../../libapi/node_modules/util-deprecate/browser.js", "../../../libapi/node_modules/readable-stream/lib/_stream_writable.js", "../../../libapi/node_modules/readable-stream/lib/_stream_duplex.js", "../../../libapi/node_modules/safe-buffer/index.js", "../../../libapi/node_modules/string_decoder/lib/string_decoder.js", "../../../libapi/node_modules/readable-stream/lib/internal/streams/end-of-stream.js", "../../../libapi/node_modules/readable-stream/lib/internal/streams/async_iterator.js", "../../../libapi/node_modules/readable-stream/lib/internal/streams/from-browser.js", "../../../libapi/node_modules/readable-stream/lib/_stream_readable.js", "../../../libapi/node_modules/readable-stream/lib/_stream_transform.js", "../../../libapi/node_modules/readable-stream/lib/_stream_passthrough.js", "../../../libapi/node_modules/readable-stream/lib/internal/streams/pipeline.js", "../../../libapi/node_modules/readable-stream/readable-browser.js", "../../../libapi/node_modules/mqtt/lib/store.js", "../../../libapi/node_modules/mqtt/lib/topic-alias-recv.js", "../../../libapi/node_modules/yallist/iterator.js", "../../../libapi/node_modules/yallist/yallist.js", "../../../libapi/node_modules/lru-cache/index.js", "../../../libapi/node_modules/js-sdsl/dist/cjs/Vector/Vector.js", "../../../libapi/node_modules/js-sdsl/dist/cjs/Stack/Stack.js", "../../../libapi/node_modules/js-sdsl/dist/cjs/LinkList/LinkList.js", "../../../libapi/node_modules/js-sdsl/dist/cjs/Queue/Queue.js", "../../../libapi/node_modules/js-sdsl/dist/cjs/Deque/Deque.js", "../../../libapi/node_modules/js-sdsl/dist/cjs/PriorityQueue/PriorityQueue.js", "../../../libapi/node_modules/js-sdsl/dist/cjs/Base/TreeNode.js", "../../../libapi/node_modules/js-sdsl/dist/cjs/Set/Set.js", "../../../libapi/node_modules/js-sdsl/dist/cjs/Map/Map.js", "../../../libapi/node_modules/js-sdsl/dist/cjs/HashSet/HashSet.js", "../../../libapi/node_modules/js-sdsl/dist/cjs/HashMap/HashMap.js", "../../../libapi/node_modules/js-sdsl/dist/cjs/index.js", "../../../libapi/node_modules/ms/index.js", "../../../libapi/node_modules/debug/src/common.js", "../../../libapi/node_modules/debug/src/browser.js", "../../../libapi/node_modules/number-allocator/lib/number-allocator.js", "../../../libapi/node_modules/number-allocator/index.js", "../../../libapi/node_modules/mqtt/lib/topic-alias-send.js", "../../../libapi/node_modules/bl/BufferList.js", "../../../libapi/node_modules/bl/bl.js", "../../../libapi/node_modules/mqtt-packet/packet.js", "../../../libapi/node_modules/mqtt-packet/constants.js", "../../../libapi/node_modules/mqtt-packet/parser.js", "../../../libapi/node_modules/mqtt-packet/numbers.js", "../../../libapi/node_modules/process-nextick-args/index.js", "../../../libapi/node_modules/mqtt-packet/writeToStream.js", "../../../libapi/node_modules/mqtt-packet/generate.js", "../../../libapi/node_modules/mqtt-packet/mqtt.js", "../../../libapi/node_modules/mqtt/lib/default-message-id-provider.js", "../../../libapi/node_modules/reinterval/index.js", "../../../libapi/node_modules/rfdc/index.js", "../../../libapi/node_modules/rfdc/default.js", "../../../libapi/node_modules/mqtt/lib/validations.js", "../../../libapi/node_modules/mqtt/lib/client.js", "node-modules-polyfills:punycode", "node-modules-polyfills:querystring", "node-modules-polyfills:url", "node-modules-polyfills-commonjs:url", "node-modules-polyfills:net", "node-modules-polyfills-commonjs:net", "../../../libapi/node_modules/mqtt/lib/connect/tcp.js", "node-modules-polyfills:tls", "node-modules-polyfills-commonjs:tls", "../../../libapi/node_modules/mqtt/lib/connect/tls.js", "../../../libapi/node_modules/wrappy/wrappy.js", "../../../libapi/node_modules/once/once.js", "../../../libapi/node_modules/end-of-stream/index.js", "../../../libapi/node_modules/stream-shift/index.js", "../../../libapi/node_modules/duplexify/index.js", "../../../libapi/node_modules/mqtt/lib/connect/wx.js", "../../../libapi/node_modules/mqtt/lib/connect/ali.js", "../../../libapi/node_modules/ws/browser.js", "../../../libapi/node_modules/mqtt/lib/connect/ws.js", "../../../libapi/node_modules/mqtt/lib/connect/index.js", "../../../libapi/node_modules/uuid/dist/esm-browser/rng.js", "../../../libapi/node_modules/uuid/dist/esm-browser/regex.js", "../../../libapi/node_modules/uuid/dist/esm-browser/validate.js", "../../../libapi/node_modules/uuid/dist/esm-browser/stringify.js", "../../../libapi/node_modules/uuid/dist/esm-browser/v1.js", "../../../libapi/node_modules/uuid/dist/esm-browser/parse.js", "../../../libapi/node_modules/uuid/dist/esm-browser/v35.js", "../../../libapi/node_modules/uuid/dist/esm-browser/md5.js", "../../../libapi/node_modules/uuid/dist/esm-browser/v3.js", "../../../libapi/node_modules/uuid/dist/esm-browser/v4.js", "../../../libapi/node_modules/uuid/dist/esm-browser/sha1.js", "../../../libapi/node_modules/uuid/dist/esm-browser/v5.js", "../../../libapi/node_modules/uuid/dist/esm-browser/nil.js", "../../../libapi/node_modules/uuid/dist/esm-browser/version.js", "../../../libapi/node_modules/uuid/dist/esm-browser/index.js", "../../../libapi/dist/app.js", "../../../libapi/dist/index.js", "../../node_modules/object-assign/index.js", "../../node_modules/react/cjs/react.production.min.js", "../../node_modules/react/index.js", "../../node_modules/react/cjs/react-jsx-runtime.production.min.js", "../../node_modules/react/jsx-runtime.js", "../../node_modules/react-simple-keyboard/build/index.js", "../../node_modules/prop-types/lib/ReactPropTypesSecret.js", "../../node_modules/prop-types/factoryWithThrowingShims.js", "../../node_modules/prop-types/index.js", "../../node_modules/isarray/index.js", "../../node_modules/path-to-regexp/index.js", "../../node_modules/react-router/node_modules/react-is/cjs/react-is.production.min.js", "../../node_modules/react-router/node_modules/react-is/index.js", "../../node_modules/hoist-non-react-statics/node_modules/react-is/cjs/react-is.production.min.js", "../../node_modules/hoist-non-react-statics/node_modules/react-is/index.js", "../../node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js", "../../node_modules/jszip/dist/jszip.min.js", "../../node_modules/file-saver/src/FileSaver.js", "../../node_modules/scheduler/cjs/scheduler.production.min.js", "../../node_modules/scheduler/index.js", "../../node_modules/react-dom/cjs/react-dom.production.min.js", "../../node_modules/react-dom/index.js", "../../src/index.tsx", "../../src/App.tsx", "../../src/context/PalletizerContext.tsx", "../../src/parts/Calibration.tsx", "../../src/parts/General.tsx", "../../src/parts/Layout.tsx", "../../src/parts/PendantButton.tsx", "../../src/parts/shared/shared.ts", "../../node_modules/react-simple-keyboard/build/css/index.css", "../../src/parts/images/bell.svg", "../../src/parts/images/exclamation-circle.svg", "../../src/parts/images/info-circle.svg", "../../src/parts/Modal.tsx", "../../src/parts/PalletizerPage.tsx", "../../src/parts/Visualizer.tsx", "../../src/parts/pallet_config/3D/ObjAcc.ts", "../../src/parts/viz_utils.ts", "../../node_modules/three/build/three.module.js", "../../node_modules/three/examples/jsm/controls/OrbitControls.js", "../../src/parts/common/Checkbox.tsx", "../../src/parts/common/Dropdown.tsx", "../../src/parts/common/IOUtils.tsx", "../../src/parts/common/ProgressRing.tsx", "../../src/parts/pallet_config/Layouts.tsx", "../../node_modules/uuid/dist/esm-browser/index.js", "../../node_modules/uuid/dist/esm-browser/rng.js", "../../node_modules/uuid/dist/esm-browser/stringify.js", "../../node_modules/uuid/dist/esm-browser/validate.js", "../../node_modules/uuid/dist/esm-browser/regex.js", "../../node_modules/uuid/dist/esm-browser/v4.js", "../../src/parts/pallet_config/ContentItem.tsx", "../../src/parts/pallet_config/Shared.tsx", "../../src/parts/pallet_config/images/plus.svg", "../../src/parts/pallet_config/layout_utils.ts", "../../src/parts/shared/dates.ts", "../../src/parts/pallet_config/3D/BoxRender.tsx", "../../src/parts/pallet_config/Pallets.tsx", "../../src/parts/Settings.tsx", "../../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js", "../../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js", "../../node_modules/history/esm/history.js", "../../node_modules/@babel/runtime/helpers/esm/extends.js", "../../node_modules/resolve-pathname/esm/resolve-pathname.js", "../../node_modules/value-equal/esm/value-equal.js", "../../node_modules/tiny-invariant/dist/tiny-invariant.esm.js", "../../node_modules/mini-create-react-context/dist/esm/index.js", "../../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js", "../../node_modules/react-router/modules/createNameContext.js", "../../node_modules/react-router/modules/HistoryContext.js", "../../node_modules/react-router/modules/RouterContext.js", "../../node_modules/react-router/modules/Router.js", "../../node_modules/react-router/modules/MemoryRouter.js", "../../node_modules/react-router/modules/Lifecycle.js", "../../node_modules/react-router/modules/Prompt.js", "../../node_modules/react-router/modules/generatePath.js", "../../node_modules/react-router/modules/Redirect.js", "../../node_modules/react-router/modules/matchPath.js", "../../node_modules/react-router/modules/Route.js", "../../node_modules/react-router/modules/StaticRouter.js", "../../node_modules/react-router/modules/Switch.js", "../../node_modules/react-router/modules/withRouter.js", "../../node_modules/react-router/modules/hooks.js", "../../node_modules/react-router/modules/index.js", "../../node_modules/react-router-dom/modules/BrowserRouter.js", "../../node_modules/react-router-dom/modules/HashRouter.js", "../../node_modules/react-router-dom/modules/utils/locationUtils.js", "../../node_modules/react-router-dom/modules/Link.js", "../../node_modules/react-router-dom/modules/NavLink.js", "../../src/parts/Preferences.tsx", "../../src/parts/CollectionsPage.tsx", "../../src/parts/Configuration.tsx", "../../src/parts/pallet_config/Boxes.tsx", "../../src/parts/common/Slider.tsx", "../../src/parts/pallet_config/Stacks.tsx", "../../src/parts/pallet_config/Summary.tsx", "../../src/parts/pallet_config/SlipSheets.tsx", "../../src/parts/Sidebar.tsx", "../../src/parts/common/PalletizerRunStatusDisplay.tsx", "../../src/parts/images/remote_support.svg", "../../src/scss/App.scss", "../../src/scss/Fonts.scss", "../../src/index.css", "../../src/scss/Global.scss", "../../src/serviceWorker.ts"], "sourcesContent": ["// shim for using process in browser\n// based off https://github.com/defunctzombie/node-process/blob/master/browser.js\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined')\n}\nfunction defaultClearTimeout() {\n throw new Error('clearTimeout has not been defined')\n}\nvar cachedSetTimeout = defaultSetTimout\nvar cachedClearTimeout = defaultClearTimeout\nif (typeof global.setTimeout === 'function') {\n cachedSetTimeout = setTimeout\n}\nif (typeof global.clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout\n}\n\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0)\n }\n // if setTimeout wasn't available but was latter defined\n if (\n (cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) &&\n setTimeout\n ) {\n cachedSetTimeout = setTimeout\n return setTimeout(fun, 0)\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0)\n } catch (e) {\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0)\n } catch (e) {\n // 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\n return cachedSetTimeout.call(this, fun, 0)\n }\n }\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker)\n }\n // if clearTimeout wasn't available but was latter defined\n if (\n (cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) &&\n clearTimeout\n ) {\n cachedClearTimeout = clearTimeout\n return clearTimeout(marker)\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker)\n } catch (e) {\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker)\n } catch (e) {\n // 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.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker)\n }\n }\n}\nvar queue = []\nvar draining = false\nvar currentQueue\nvar queueIndex = -1\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return\n }\n draining = false\n if (currentQueue.length) {\n queue = currentQueue.concat(queue)\n } else {\n queueIndex = -1\n }\n if (queue.length) {\n drainQueue()\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return\n }\n var timeout = runTimeout(cleanUpNextTick)\n draining = true\n\n var len = queue.length\n while (len) {\n currentQueue = queue\n queue = []\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run()\n }\n }\n queueIndex = -1\n len = queue.length\n }\n currentQueue = null\n draining = false\n runClearTimeout(timeout)\n}\nfunction nextTick(fun) {\n var args = new Array(arguments.length - 1)\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i]\n }\n }\n queue.push(new Item(fun, args))\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue)\n }\n}\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun\n this.array = array\n}\nItem.prototype.run = function() {\n this.fun.apply(null, this.array)\n}\nvar title = 'browser'\nvar platform = 'browser'\nvar browser = true\nvar env = {}\nvar argv = []\nvar version = '' // empty string to avoid regexp issues\nvar versions = {}\nvar release = {}\nvar config = {}\n\nfunction noop() {}\n\nvar on = noop\nvar addListener = noop\nvar once = noop\nvar off = noop\nvar removeListener = noop\nvar removeAllListeners = noop\nvar emit = noop\n\nfunction binding(name) {\n throw new Error('process.binding is not supported')\n}\n\nfunction cwd() {\n return '/'\n}\nfunction chdir(dir) {\n throw new Error('process.chdir is not supported')\n}\nfunction umask() {\n return 0\n}\n\n// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js\nvar performance = global.performance || {}\nvar performanceNow =\n performance.now ||\n performance.mozNow ||\n performance.msNow ||\n performance.oNow ||\n performance.webkitNow ||\n function() {\n return new Date().getTime()\n }\n\n// generate timestamp or delta\n// see http://nodejs.org/api/process.html#process_process_hrtime\nfunction hrtime(previousTimestamp) {\n var clocktime = performanceNow.call(performance) * 1e-3\n var seconds = Math.floor(clocktime)\n var nanoseconds = Math.floor((clocktime % 1) * 1e9)\n if (previousTimestamp) {\n seconds = seconds - previousTimestamp[0]\n nanoseconds = nanoseconds - previousTimestamp[1]\n if (nanoseconds < 0) {\n seconds--\n nanoseconds += 1e9\n }\n }\n return [seconds, nanoseconds]\n}\n\nvar startTime = new Date()\nfunction uptime() {\n var currentTime = new Date()\n var dif = currentTime - startTime\n return dif / 1000\n}\n\nexport var process = {\n nextTick: nextTick,\n title: title,\n browser: browser,\n env: env,\n argv: argv,\n version: version,\n versions: versions,\n on: on,\n addListener: addListener,\n once: once,\n off: off,\n removeListener: removeListener,\n removeAllListeners: removeAllListeners,\n emit: emit,\n binding: binding,\n cwd: cwd,\n chdir: chdir,\n umask: umask,\n hrtime: hrtime,\n platform: platform,\n release: release,\n config: config,\n uptime: uptime,\n}\n\n// replace process.env.VAR with define\n\nconst defines = {\n\n}\nObject.keys(defines).forEach((key) => {\n const segs = key.split('.')\n let target = process\n for (let i = 0; i < segs.length; i++) {\n const seg = segs[i]\n if (i === segs.length - 1) {\n target[seg] = defines[key]\n } else {\n target = target[seg] || (target[seg] = {})\n }\n }\n})\n", "// taken from https://github.com/calvinmetcalf/buffer-es6\n\n/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\nvar inited = false\nfunction init() {\n inited = true\n var code =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n for (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n }\n\n revLookup['-'.charCodeAt(0)] = 62\n revLookup['_'.charCodeAt(0)] = 63\n}\n\nfunction base64toByteArray(b64) {\n if (!inited) {\n init()\n }\n var i, j, l, tmp, placeHolders, arr\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // the number of equal signs (place holders)\n // if there are two placeholders, than the two characters before it\n // represent one byte\n // if there is only one, then the three characters before it represent 2 bytes\n // this is just a cheap hack to not do indexOf twice\n placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0\n\n // base64 is 4/3 + up to two characters of the original data\n arr = new Arr((len * 3) / 4 - placeHolders)\n\n // if there are placeholders, only get up to the last complete 4 chars\n l = placeHolders > 0 ? len - 4 : len\n\n var L = 0\n\n for (i = 0, j = 0; i < l; i += 4, j += 3) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[L++] = (tmp >> 16) & 0xff\n arr[L++] = (tmp >> 8) & 0xff\n arr[L++] = tmp & 0xff\n }\n\n if (placeHolders === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[L++] = tmp & 0xff\n } else if (placeHolders === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[L++] = (tmp >> 8) & 0xff\n arr[L++] = tmp & 0xff\n }\n\n return arr\n}\n\nfunction tripletToBase64(num) {\n return (\n lookup[(num >> 18) & 0x3f] +\n lookup[(num >> 12) & 0x3f] +\n lookup[(num >> 6) & 0x3f] +\n lookup[num & 0x3f]\n )\n}\n\nfunction encodeChunk(uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction base64fromByteArray(uint8) {\n if (!inited) {\n init()\n }\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var output = ''\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(\n encodeChunk(\n uint8,\n i,\n i + maxChunkLength > len2 ? len2 : i + maxChunkLength,\n ),\n )\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n output += lookup[tmp >> 2]\n output += lookup[(tmp << 4) & 0x3f]\n output += '=='\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n output += lookup[tmp >> 10]\n output += lookup[(tmp >> 4) & 0x3f]\n output += lookup[(tmp << 2) & 0x3f]\n output += '='\n }\n\n parts.push(output)\n\n return parts.join('')\n}\n\nvar INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT =\n global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : true\n\nfunction kMaxLength() {\n return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff\n}\n\nfunction createBuffer(that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nexport function Buffer(arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string',\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function(arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from(that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function(value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nBuffer.kMaxLength = kMaxLength()\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (\n typeof Symbol !== 'undefined' &&\n Symbol.species &&\n Buffer[Symbol.species] === Buffer\n ) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n // Object.defineProperty(Buffer, Symbol.species, {\n // value: null,\n // configurable: true\n // })\n }\n}\n\nfunction assertSize(size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc(that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function(size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe(that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function(size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function(size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString(that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike(that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer(that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError(\"'offset' is out of bounds\")\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError(\"'length' is out of bounds\")\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject(that, obj) {\n if (internalIsBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if (\n (typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) ||\n 'length' in obj\n ) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError(\n 'First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.',\n )\n}\n\nfunction checked(length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError(\n 'Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' +\n kMaxLength().toString(16) +\n ' bytes',\n )\n }\n return length | 0\n}\n\nexport function SlowBuffer(length) {\n if (+length != length) {\n // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\nBuffer.isBuffer = isBuffer\nfunction internalIsBuffer(b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare(a, b) {\n if (!internalIsBuffer(a) || !internalIsBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding(encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat(list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!internalIsBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength(string, encoding) {\n if (internalIsBuffer(string)) {\n return string.length\n }\n if (\n typeof ArrayBuffer !== 'undefined' &&\n typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)\n ) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString(encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase)\n throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap(b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16() {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32() {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64() {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString() {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals(b) {\n if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\n\nBuffer.prototype.compare = function compare(\n target,\n start,\n end,\n thisStart,\n thisEnd,\n) {\n if (!internalIsBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (\n start < 0 ||\n end > target.length ||\n thisStart < 0 ||\n thisEnd > this.length\n ) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : buffer.length - 1\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (internalIsBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xff // Search for a byte value [0-255]\n if (\n Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function'\n ) {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(\n buffer,\n val,\n byteOffset,\n )\n } else {\n return Uint8Array.prototype.lastIndexOf.call(\n buffer,\n val,\n byteOffset,\n )\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf(arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (\n encoding === 'ucs2' ||\n encoding === 'ucs-2' ||\n encoding === 'utf16le' ||\n encoding === 'utf-16le'\n ) {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read(buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (\n read(arr, i) ===\n read(val, foundIndex === -1 ? 0 : i - foundIndex)\n ) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength)\n return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength)\n byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes(val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite(buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write(buf, string, offset, length) {\n return blitBuffer(\n utf8ToBytes(string, buf.length - offset),\n buf,\n offset,\n length,\n )\n}\n\nfunction asciiWrite(buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write(buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write(buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write(buf, string, offset, length) {\n return blitBuffer(\n utf16leToBytes(string, buf.length - offset),\n buf,\n offset,\n length,\n )\n}\n\nBuffer.prototype.write = function write(string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported',\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if (\n (string.length > 0 && (length < 0 || offset < 0)) ||\n offset > this.length\n ) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase)\n throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON() {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0),\n }\n}\n\nfunction base64Slice(buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64fromByteArray(buf)\n } else {\n return base64fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice(buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence =\n firstByte > 0xef\n ? 4\n : firstByte > 0xdf\n ? 3\n : firstByte > 0xbf\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xc0) === 0x80) {\n tempCodePoint =\n ((firstByte & 0x1f) << 0x6) | (secondByte & 0x3f)\n if (tempCodePoint > 0x7f) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if (\n (secondByte & 0xc0) === 0x80 &&\n (thirdByte & 0xc0) === 0x80\n ) {\n tempCodePoint =\n ((firstByte & 0xf) << 0xc) |\n ((secondByte & 0x3f) << 0x6) |\n (thirdByte & 0x3f)\n if (\n tempCodePoint > 0x7ff &&\n (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)\n ) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if (\n (secondByte & 0xc0) === 0x80 &&\n (thirdByte & 0xc0) === 0x80 &&\n (fourthByte & 0xc0) === 0x80\n ) {\n tempCodePoint =\n ((firstByte & 0xf) << 0x12) |\n ((secondByte & 0x3f) << 0xc) |\n ((thirdByte & 0x3f) << 0x6) |\n (fourthByte & 0x3f)\n if (\n tempCodePoint > 0xffff &&\n tempCodePoint < 0x110000\n ) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xfffd\n bytesPerSequence = 1\n } else if (codePoint > 0xffff) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(((codePoint >>> 10) & 0x3ff) | 0xd800)\n codePoint = 0xdc00 | (codePoint & 0x3ff)\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray(codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, (i += MAX_ARGUMENTS_LENGTH)),\n )\n }\n return res\n}\n\nfunction asciiSlice(buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7f)\n }\n return ret\n}\n\nfunction latin1Slice(buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice(buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice(buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice(start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset(offset, ext, length) {\n if (offset % 1 !== 0 || offset < 0)\n throw new RangeError('offset is not uint')\n if (offset + ext > length)\n throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE(\n offset,\n byteLength,\n noAssert,\n) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE(\n offset,\n byteLength,\n noAssert,\n) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (\n (this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16)) +\n this[offset + 3] * 0x1000000\n )\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (\n this[offset] * 0x1000000 +\n ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3])\n )\n}\n\nBuffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return this[offset]\n return (0xff - this[offset] + 1) * -1\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return val & 0x8000 ? val | 0xffff0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return val & 0x8000 ? val | 0xffff0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (\n this[offset] |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n )\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (\n (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3]\n )\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754read(this, offset, false, 52, 8)\n}\n\nfunction checkInt(buf, value, offset, ext, max, min) {\n if (!internalIsBuffer(buf))\n throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min)\n throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE(\n value,\n offset,\n byteLength,\n noAssert,\n) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xff\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xff\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE(\n value,\n offset,\n byteLength,\n noAssert,\n) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xff\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xff\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = value & 0xff\n return offset + 1\n}\n\nfunction objectWriteUInt16(buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] =\n (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n ((littleEndian ? i : 1 - i) * 8)\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE(\n value,\n offset,\n noAssert,\n) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = value & 0xff\n this[offset + 1] = value >>> 8\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE(\n value,\n offset,\n noAssert,\n) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = value >>> 8\n this[offset + 1] = value & 0xff\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32(buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> ((littleEndian ? i : 3 - i) * 8)) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE(\n value,\n offset,\n noAssert,\n) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = value >>> 24\n this[offset + 2] = value >>> 16\n this[offset + 1] = value >>> 8\n this[offset] = value & 0xff\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE(\n value,\n offset,\n noAssert,\n) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = value >>> 24\n this[offset + 1] = value >>> 16\n this[offset + 2] = value >>> 8\n this[offset + 3] = value & 0xff\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE(\n value,\n offset,\n byteLength,\n noAssert,\n) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xff\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = (((value / mul) >> 0) - sub) & 0xff\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE(\n value,\n offset,\n byteLength,\n noAssert,\n) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xff\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = (((value / mul) >> 0) - sub) & 0xff\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = value & 0xff\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = value & 0xff\n this[offset + 1] = value >>> 8\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = value >>> 8\n this[offset + 1] = value & 0xff\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = value & 0xff\n this[offset + 1] = value >>> 8\n this[offset + 2] = value >>> 16\n this[offset + 3] = value >>> 24\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = value >>> 24\n this[offset + 1] = value >>> 16\n this[offset + 2] = value >>> 8\n this[offset + 3] = value & 0xff\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754(buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat(buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(\n buf,\n value,\n offset,\n 4,\n 3.4028234663852886e38,\n -3.4028234663852886e38,\n )\n }\n ieee754write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble(buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(\n buf,\n value,\n offset,\n 8,\n 1.7976931348623157e308,\n -1.7976931348623157e308,\n )\n }\n ieee754write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE(\n value,\n offset,\n noAssert,\n) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE(\n value,\n offset,\n noAssert,\n) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy(target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length)\n throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart,\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill(val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = internalIsBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean(str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim(str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex(n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes(string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xd7ff && codePoint < 0xe000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xdbff) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xdc00) {\n if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint =\n (((leadSurrogate - 0xd800) << 10) | (codePoint - 0xdc00)) +\n 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push((codePoint >> 0x6) | 0xc0, (codePoint & 0x3f) | 0x80)\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n (codePoint >> 0xc) | 0xe0,\n ((codePoint >> 0x6) & 0x3f) | 0x80,\n (codePoint & 0x3f) | 0x80,\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n (codePoint >> 0x12) | 0xf0,\n ((codePoint >> 0xc) & 0x3f) | 0x80,\n ((codePoint >> 0x6) & 0x3f) | 0x80,\n (codePoint & 0x3f) | 0x80,\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes(str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xff)\n }\n return byteArray\n}\n\nfunction utf16leToBytes(str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes(str) {\n return base64toByteArray(base64clean(str))\n}\n\nfunction blitBuffer(src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if (i + offset >= dst.length || i >= src.length) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan(val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n\n// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nfunction isBuffer(obj) {\n return (\n obj != null &&\n (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))\n )\n}\n\nfunction isFastBuffer(obj) {\n return (\n !!obj.constructor &&\n typeof obj.constructor.isBuffer === 'function' &&\n obj.constructor.isBuffer(obj)\n )\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer(obj) {\n return (\n typeof obj.readFloatLE === 'function' &&\n typeof obj.slice === 'function' &&\n isFastBuffer(obj.slice(0, 0))\n )\n}\n\nfunction ieee754read(buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = nBytes * 8 - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? nBytes - 1 : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << -nBits) - 1)\n s >>= -nBits\n nBits += eLen\n for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << -nBits) - 1)\n e >>= -nBits\n nBits += mLen\n for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : (s ? -1 : 1) * Infinity\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nfunction ieee754write(buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = nBytes * 8 - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0\n var i = isLE ? 0 : nBytes - 1\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = (value * c - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (\n ;\n mLen >= 8;\n buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8\n ) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (\n ;\n eLen > 0;\n buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8\n ) {}\n\n buffer[offset + i - d] |= s * 128\n}\n", "export { Buffer } from '_node-buffer-polyfill_.js'\n", "\"use strict\";\n/*\n structs.ts\n various type, interface and enumeration defintions used in libapi\n*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ARStatus = exports.default_op_state = exports.UnitsSystem = exports.formaInfoTimeStamp = exports.getInfoTimeStamp = exports.PickType = exports.StackQueueStatus = exports.SafetyStatus = exports.CALIB_TCP_INDEX = exports.PalletizerStatus = exports.Side = exports.RobotState = exports.InformationType = exports.IOLEVEL = exports.ControlType = void 0;\nvar ControlType;\n(function (ControlType) {\n ControlType[ControlType[\"Start\"] = 0] = \"Start\";\n ControlType[ControlType[\"Stop\"] = 1] = \"Stop\";\n ControlType[ControlType[\"Pause\"] = 2] = \"Pause\";\n ControlType[ControlType[\"Home\"] = 3] = \"Home\";\n ControlType[ControlType[\"Recover\"] = 4] = \"Recover\";\n ControlType[ControlType[\"ManualMode\"] = 5] = \"ManualMode\";\n ControlType[ControlType[\"GetPosition\"] = 6] = \"GetPosition\";\n ControlType[ControlType[\"StartScanning\"] = 7] = \"StartScanning\";\n ControlType[ControlType[\"OpenClampGripper\"] = 8] = \"OpenClampGripper\";\n})(ControlType = exports.ControlType || (exports.ControlType = {}));\nvar IOLEVEL;\n(function (IOLEVEL) {\n IOLEVEL[IOLEVEL[\"GOOD\"] = 0] = \"GOOD\";\n IOLEVEL[IOLEVEL[\"WARN\"] = 1] = \"WARN\";\n IOLEVEL[IOLEVEL[\"BAD\"] = 2] = \"BAD\";\n IOLEVEL[IOLEVEL[\"OFF\"] = 3] = \"OFF\";\n})(IOLEVEL = exports.IOLEVEL || (exports.IOLEVEL = {}));\nvar InformationType;\n(function (InformationType) {\n InformationType[\"Status\"] = \"Status\";\n InformationType[\"Error\"] = \"Error\";\n InformationType[\"Warning\"] = \"Warning\";\n})(InformationType = exports.InformationType || (exports.InformationType = {}));\nvar RobotState;\n(function (RobotState) {\n RobotState[\"Running\"] = \"Running\";\n RobotState[\"Stopped\"] = \"Stopped\";\n RobotState[\"Paused\"] = \"Paused\";\n RobotState[\"Offline\"] = \"Offline\";\n RobotState[\"Homing\"] = \"Homing\";\n})(RobotState = exports.RobotState || (exports.RobotState = {}));\nvar Side;\n(function (Side) {\n Side[Side[\"Left\"] = 0] = \"Left\";\n Side[Side[\"Right\"] = 1] = \"Right\";\n})(Side = exports.Side || (exports.Side = {}));\n(function (IOLEVEL) {\n})(IOLEVEL = exports.IOLEVEL || (exports.IOLEVEL = {}));\nvar PalletizerStatus;\n(function (PalletizerStatus) {\n PalletizerStatus[\"Offline\"] = \"Offline\";\n PalletizerStatus[\"Ready\"] = \"Ready\";\n PalletizerStatus[\"Running\"] = \"Running\"; /* or busy */\n PalletizerStatus[\"Homing\"] = \"Homing\";\n PalletizerStatus[\"Fault\"] = \"Fault\";\n PalletizerStatus[\"Scanning\"] = \"Scanning\";\n})(PalletizerStatus = exports.PalletizerStatus || (exports.PalletizerStatus = {}));\nvar CALIB_TCP_INDEX;\n(function (CALIB_TCP_INDEX) {\n CALIB_TCP_INDEX[CALIB_TCP_INDEX[\"SlipSheet\"] = 0] = \"SlipSheet\";\n CALIB_TCP_INDEX[CALIB_TCP_INDEX[\"Box\"] = 1] = \"Box\";\n})(CALIB_TCP_INDEX = exports.CALIB_TCP_INDEX || (exports.CALIB_TCP_INDEX = {}));\nvar SafetyStatus;\n(function (SafetyStatus) {\n SafetyStatus[SafetyStatus[\"Triggered\"] = 0] = \"Triggered\"; /* Estop */\n SafetyStatus[SafetyStatus[\"Resetting\"] = 1] = \"Resetting\";\n SafetyStatus[SafetyStatus[\"Ready\"] = 2] = \"Ready\";\n SafetyStatus[SafetyStatus[\"Offline\"] = 3] = \"Offline\";\n})(SafetyStatus = exports.SafetyStatus || (exports.SafetyStatus = {}));\nvar StackQueueStatus;\n(function (StackQueueStatus) {\n StackQueueStatus[StackQueueStatus[\"Waiting\"] = 0] = \"Waiting\"; /* Blue Dot */\n StackQueueStatus[StackQueueStatus[\"Running\"] = 1] = \"Running\"; /* Green Dot */\n StackQueueStatus[StackQueueStatus[\"Complete\"] = 2] = \"Complete\"; /* Gray Dot (TODO: Checkmark) */\n})(StackQueueStatus = exports.StackQueueStatus || (exports.StackQueueStatus = {}));\nvar PickType;\n(function (PickType) {\n PickType[PickType[\"Box\"] = 0] = \"Box\";\n PickType[PickType[\"SlipSheet\"] = 1] = \"SlipSheet\";\n PickType[PickType[\"TopSlipSheet\"] = 2] = \"TopSlipSheet\";\n})(PickType = exports.PickType || (exports.PickType = {}));\nfunction getInfoTimeStamp(start, last_log, now) {\n return {\n delta_log: now.getTime() - last_log.getTime(),\n delta_start: now.getTime() - start.getTime(),\n };\n}\nexports.getInfoTimeStamp = getInfoTimeStamp;\nfunction addZeroPrefix(n) {\n if (n < 10)\n return `0${n}`;\n return `${n}`;\n}\nfunction toDateString(seconds) {\n let h, m, s;\n h = Math.floor(seconds / (60 * 60 * 1000));\n seconds -= h * 60 * 60 * 1000;\n m = Math.floor(seconds / (60 * 1000));\n seconds -= m * 60 * 1000;\n s = seconds / 1000;\n return `${addZeroPrefix(h)}:${addZeroPrefix(m)}:${addZeroPrefix(s)}`;\n}\nfunction formaInfoTimeStamp(ts) {\n return [`+${ts.delta_log / 1000}s`, toDateString(ts.delta_start)];\n}\nexports.formaInfoTimeStamp = formaInfoTimeStamp;\nvar UnitsSystem;\n(function (UnitsSystem) {\n UnitsSystem[\"METRIC\"] = \"Metric\";\n UnitsSystem[\"IMPERIAL\"] = \"Imperial\";\n})(UnitsSystem = exports.UnitsSystem || (exports.UnitsSystem = {}));\nfunction default_op_state() {\n return {\n status: PalletizerStatus.Offline,\n auxiliary_text: '...',\n };\n}\nexports.default_op_state = default_op_state;\nvar ARStatus;\n(function (ARStatus) {\n ARStatus[ARStatus[\"LOCKED\"] = 0] = \"LOCKED\";\n ARStatus[ARStatus[\"UNLOCKED\"] = 1] = \"UNLOCKED\";\n})(ARStatus = exports.ARStatus || (exports.ARStatus = {}));\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MultiPickType = exports.getCenterOfPallet = exports.getPalletCorners = exports.getXAxisAngle = exports.getPalletDimensions = exports.hasSlipSheet = exports.getSlipSheet = exports.SlipSheetOption = exports.LabelNames = exports.LabelSide = exports.Add3D = exports.Norm = exports.MultiplyScalar = exports.Subtract3D = exports.compareDimensions = exports.to_coord = void 0;\nconst to_coord = (x) => {\n return {\n x: x[0],\n y: x[1],\n z: x[2],\n \u03B8: x[3],\n };\n};\nexports.to_coord = to_coord;\nfunction compareDimensions(bd1, bd2) {\n return (bd1.length === bd2.length &&\n bd1.width === bd2.width &&\n bd1.height === bd2.height);\n}\nexports.compareDimensions = compareDimensions;\nfunction Subtract3D(c1, c2) {\n return { x: c1.x - c2.x, y: c1.y - c2.y, z: c1.z - c2.z };\n}\nexports.Subtract3D = Subtract3D;\nfunction MultiplyScalar(c1, alpha) {\n return { x: c1.x * alpha, y: c1.y * alpha, z: c1.z * alpha };\n}\nexports.MultiplyScalar = MultiplyScalar;\nfunction Norm(c) {\n return Math.sqrt(c.x ** 2 + c.y ** 2 + c.z ** 2);\n}\nexports.Norm = Norm;\nfunction Add3D(c1, c2) {\n return Subtract3D(c1, MultiplyScalar(c2, -1));\n}\nexports.Add3D = Add3D;\nvar LabelSide;\n(function (LabelSide) {\n LabelSide[LabelSide[\"None\"] = 0] = \"None\";\n LabelSide[LabelSide[\"Left\"] = 1] = \"Left\";\n LabelSide[LabelSide[\"Front\"] = 2] = \"Front\"; /* ie: bottom edge of box in 2d overhead view/layouts editor */\n LabelSide[LabelSide[\"Right\"] = 3] = \"Right\";\n LabelSide[LabelSide[\"Back\"] = 4] = \"Back\"; /* ie: top edge of box in 2d overhead view/layouts editor */\n})(LabelSide = exports.LabelSide || (exports.LabelSide = {}));\nexports.LabelNames = [\n 'No Labels',\n 'Label Side 1',\n 'Label Side 2',\n 'Label Side 3',\n 'Label Side 4',\n];\nvar SlipSheetOption;\n(function (SlipSheetOption) {\n SlipSheetOption[SlipSheetOption[\"None\"] = 0] = \"None\";\n SlipSheetOption[SlipSheetOption[\"YesExceptTopBottom\"] = 1] = \"YesExceptTopBottom\";\n SlipSheetOption[SlipSheetOption[\"YesExceptBottom\"] = 2] = \"YesExceptBottom\";\n SlipSheetOption[SlipSheetOption[\"YesExceptTop\"] = 3] = \"YesExceptTop\";\n SlipSheetOption[SlipSheetOption[\"Yes\"] = 4] = \"Yes\";\n SlipSheetOption[SlipSheetOption[\"Custom\"] = 5] = \"Custom\";\n})(SlipSheetOption = exports.SlipSheetOption || (exports.SlipSheetOption = {}));\nfunction getSlipSheet(pLayerIndex, pStackLength, allSlipSheets, pConfig) {\n if (!hasSlipSheet(pLayerIndex, pStackLength, pConfig) || !allSlipSheets)\n return undefined;\n // This data structure should be better...\n const ids = pConfig === null || pConfig === void 0 ? void 0 : pConfig.ids;\n if (!!ids && pLayerIndex in ids) {\n const id = ids[pLayerIndex];\n const idx = allSlipSheets.findIndex(ss => ss.id === id);\n if (idx >= 0) {\n return allSlipSheets[idx];\n }\n }\n return undefined;\n}\nexports.getSlipSheet = getSlipSheet;\nfunction hasSlipSheet(pLayerIndex, pStackLength, pConfig) {\n if (!pConfig)\n return false;\n if (pConfig.exclude && pConfig.exclude[pLayerIndex] !== void 0) {\n return !pConfig.exclude[pLayerIndex];\n }\n switch (pConfig.config) {\n case SlipSheetOption.None:\n case SlipSheetOption.Custom:\n return false;\n case SlipSheetOption.Yes:\n return true;\n case SlipSheetOption.YesExceptTopBottom:\n return pLayerIndex !== 0 && pLayerIndex !== pStackLength;\n case SlipSheetOption.YesExceptBottom:\n return pLayerIndex !== 0;\n case SlipSheetOption.YesExceptTop:\n return pLayerIndex !== pStackLength;\n default:\n return false;\n }\n}\nexports.hasSlipSheet = hasSlipSheet;\nfunction getPalletDimensions(pallet) {\n return pallet.Dimensions;\n}\nexports.getPalletDimensions = getPalletDimensions;\nfunction getXAxisAngle(v) {\n return (Math.atan(v.y / v.x) * 180) / Math.PI; // to degrees\n}\nexports.getXAxisAngle = getXAxisAngle;\nfunction getPalletCorners(pallet, gripper) {\n const angle = (pallet.point.\u03B8 * Math.PI) / 180;\n let bl = { ...pallet.point };\n bl.x -= Math.cos(angle) * gripper.x_low + Math.sin(angle) * gripper.y_low;\n bl.y -= Math.sin(angle) * gripper.x_low + Math.cos(angle) * gripper.y_low;\n // ignore angles temporarily.\n let tl = { ...bl };\n tl.y += pallet.Dimensions.length;\n // tl.x += Math.sin(angle) * pallet.Dimensions.length;\n // tl.y += Math.cos(angle) * pallet.Dimensions.length;\n let br = { ...bl };\n br.x += pallet.Dimensions.width;\n // br.x += Math.cos(angle) * pallet.Dimensions.width;\n // br.y += Math.sin(angle) * pallet.Dimensions.width;\n return [tl, bl, br];\n}\nexports.getPalletCorners = getPalletCorners;\nfunction getCenterOfPallet(p, gripper) {\n let [corner1, corner2, corner3] = getPalletCorners(p, gripper);\n let v1 = Subtract3D(corner1, corner2);\n let v2 = Subtract3D(corner3, corner2);\n return Add3D(Add3D(MultiplyScalar(v1, 0.5), MultiplyScalar(v2, 0.5)), corner2);\n}\nexports.getCenterOfPallet = getCenterOfPallet;\nvar MultiPickType;\n(function (MultiPickType) {\n MultiPickType[MultiPickType[\"None\"] = 0] = \"None\";\n MultiPickType[MultiPickType[\"Double\"] = 1] = \"Double\";\n MultiPickType[MultiPickType[\"Triple\"] = 2] = \"Triple\";\n // Quadruple = 3,\n // Quintuple = 4,\n // Sextuple = 5,\n // Septuple = 6,\n})(MultiPickType = exports.MultiPickType || (exports.MultiPickType = {}));\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.applyLabelSpins = void 0;\n/*\n labels.ts\n to handle the layer orientation feature.\n*/\nconst geometry_1 = require(\"./geometry\");\nconst gOverlapTolerance = 1 / 100; // ~0 (for floating point)\nfunction segmentOverlap(pMin1, pMax1, pMin2, pMax2) {\n let lOverlap = Math.max(0, Math.min(pMax1, pMax2) - Math.max(pMin1, pMin2));\n return lOverlap;\n}\nclass Lane {\n constructor(boxes, bpo, pPallet) {\n this.bpo = bpo;\n this.box = boxes[bpo.index];\n const { x, y } = this.position;\n let { width, length, height } = this.box.dimensions;\n const mp = bpo.multipick || 0;\n if (bpo.multipickAlongWidth) {\n width *= mp + 1;\n }\n else {\n length *= mp + 1;\n }\n if (bpo.rotated) {\n const tmp = width;\n width = length;\n length = tmp;\n }\n width /= pPallet.Dimensions.width;\n length /= pPallet.Dimensions.length;\n // x, y position is top left coordinate.\n this.minX = x;\n this.maxX = x + width;\n this.minY = y;\n this.maxY = y + length;\n this.scaledDimensions = { width, length, height };\n this.intersection = {\n left: false,\n right: false,\n top: false,\n bottom: false,\n };\n }\n get labelSide() {\n if ('labelSide' in this.box)\n return this.box.labelSide;\n return geometry_1.LabelSide.None;\n }\n get labelSideAlt() {\n return this.box.labelSideAlt || geometry_1.LabelSide.None;\n }\n get position() {\n return this.bpo.position;\n }\n printBounds() {\n console.log(`X: [${this.minX}, ${this.maxX}], Y [${this.minY}, ${this.maxY}]`);\n }\n inYLane(pLane) {\n let lOverlap = segmentOverlap(this.minY, this.maxY, pLane.minY, pLane.maxY);\n // console.log('Y overlap', lOverlap);\n return lOverlap > gOverlapTolerance;\n }\n inXLane(pLane) {\n let lOverlap = segmentOverlap(this.minX, this.maxX, pLane.minX, pLane.maxX);\n // console.log('X overlap', lOverlap);\n return lOverlap > gOverlapTolerance;\n }\n intersect(pLane) {\n let [in_x_lane, in_y_lane] = [this.inXLane(pLane), this.inYLane(pLane)];\n // this.printBounds();\n // pLane.printBounds();\n // console.log(in_x_lane, in_y_lane);\n if (in_y_lane) {\n if (this.maxX > pLane.maxX) {\n this.intersection.left = true;\n pLane.intersection.right = true;\n }\n else {\n this.intersection.right = true;\n pLane.intersection.left = true;\n }\n }\n if (in_x_lane) {\n if (this.maxY > pLane.maxY) {\n // (higher Y values in svg coordinates are closer to the bottom)\n this.intersection.top = true;\n pLane.intersection.bottom = true;\n }\n else {\n this.intersection.bottom = true;\n pLane.intersection.top = true;\n }\n }\n // console.log(this.intersection);\n }\n // assumes clockwise rotation. (left side -> top, top -> right, right -> bottom, bottom -> left)\n getBoxPosition() {\n this.bpo.spin = false;\n let lLabelSide = this.labelSide;\n const lAltSide = this.labelSideAlt;\n switch (lLabelSide) {\n case geometry_1.LabelSide.None:\n this.bpo.spin = false;\n break;\n case geometry_1.LabelSide.Left:\n if (lAltSide !== geometry_1.LabelSide.Right) {\n /* if opposide side labels, ignore */\n if (this.bpo.rotated) {\n /* label on top */\n if (this.intersection.top) {\n if (!this.intersection.bottom ||\n (lAltSide === geometry_1.LabelSide.Back &&\n this.intersection.right &&\n !this.intersection.left) ||\n (lAltSide === geometry_1.LabelSide.Front &&\n this.intersection.left &&\n !this.intersection.right)) {\n this.bpo.spin = true;\n }\n }\n }\n else {\n if (this.intersection.left) {\n if (!this.intersection.right ||\n (lAltSide === geometry_1.LabelSide.Back &&\n this.intersection.top &&\n !this.intersection.bottom) ||\n (lAltSide === geometry_1.LabelSide.Front &&\n this.intersection.bottom &&\n !this.intersection.top)) {\n this.bpo.spin = true;\n }\n }\n }\n }\n break;\n case geometry_1.LabelSide.Right:\n if (lAltSide !== geometry_1.LabelSide.Left) {\n /* if opposite side labels, ignore */\n if (this.bpo.rotated) {\n /* label on bottom */\n if (this.intersection.bottom) {\n if (!this.intersection.top ||\n (lAltSide === geometry_1.LabelSide.Back &&\n this.intersection.right &&\n !this.intersection.left) ||\n (lAltSide === geometry_1.LabelSide.Front &&\n this.intersection.left &&\n !this.intersection.right)) {\n this.bpo.spin = true;\n }\n }\n }\n else {\n if (this.intersection.right) {\n if (!this.intersection.left ||\n (lAltSide === geometry_1.LabelSide.Back &&\n this.intersection.top &&\n !this.intersection.top) ||\n (lAltSide == geometry_1.LabelSide.Front &&\n this.intersection.bottom &&\n !this.intersection.top)) {\n this.bpo.spin = true;\n }\n }\n }\n }\n break;\n case geometry_1.LabelSide.Back /* ie: top of box in overhead view 2D view */:\n if (lAltSide !== geometry_1.LabelSide.Front) {\n /* if opposite side labels, ignore */\n if (this.bpo.rotated) {\n /* label on right */\n if (this.intersection.right) {\n if (!this.intersection.left ||\n (lAltSide === geometry_1.LabelSide.Left &&\n this.intersection.top &&\n !this.intersection.bottom) ||\n (lAltSide === geometry_1.LabelSide.Right &&\n this.intersection.bottom &&\n !this.intersection.top)) {\n this.bpo.spin = true;\n }\n }\n }\n else {\n if (this.intersection.top) {\n if (!this.intersection.bottom ||\n (lAltSide === geometry_1.LabelSide.Left &&\n this.intersection.left &&\n !this.intersection.top) ||\n (lAltSide === geometry_1.LabelSide.Right &&\n this.intersection.right &&\n !this.intersection.left)) {\n this.bpo.spin = true;\n }\n }\n }\n }\n break;\n case geometry_1.LabelSide.Front /* ie: bottom of box in overhead 2D view */:\n if (lAltSide !== geometry_1.LabelSide.Back) {\n /* if opposite side labels, ignore */\n if (this.bpo.rotated) {\n /* label on left */\n if (this.intersection.left) {\n if (!this.intersection.right ||\n (lAltSide === geometry_1.LabelSide.Left &&\n this.intersection.top &&\n !this.intersection.bottom) ||\n (lAltSide === geometry_1.LabelSide.Right &&\n this.intersection.bottom &&\n !this.intersection.top)) {\n this.bpo.spin = true;\n }\n }\n }\n else {\n if (this.intersection.bottom) {\n if (!this.intersection.top ||\n (lAltSide === geometry_1.LabelSide.Left &&\n this.intersection.left &&\n !this.intersection.right) ||\n (lAltSide === geometry_1.LabelSide.Right &&\n this.intersection.right &&\n !this.intersection.left)) {\n this.bpo.spin = true;\n }\n }\n }\n }\n break;\n }\n return this.bpo;\n }\n}\nfunction applyLabelSpins(boxes, layout, pPallet) {\n const lanes = layout.boxPositions.map((bpo) => new Lane(boxes, bpo, pPallet));\n for (let i = 0; i < lanes.length; i++) {\n let l1 = lanes[i];\n for (let j = i + 1; j < lanes.length; j++) {\n let l2 = lanes[j];\n l1.intersect(l2);\n }\n }\n // lanes.forEach(function (pLane, pIndex) {\n // console.log(pIndex, pLane.intersection);\n // });\n layout.boxPositions = lanes.map(l => l.getBoxPosition());\n}\nexports.applyLabelSpins = applyLabelSpins;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LayoutTransform = exports.rotateBoxPositions = exports.getBoxPositionCOM = exports.getBoxPositionsBoundingBoxCenter = exports.getBoxPositionsBounds = exports.getEffectiveDimensions = void 0;\nconst labels_1 = require(\"./labels\");\nfunction getEffectiveDimensions(bpo, boxes) {\n const box = boxes[bpo.index];\n let { width, length } = box.dimensions;\n const mp = bpo.multipick || 0;\n if (bpo.multipickAlongWidth) {\n width *= mp + 1;\n }\n else {\n length *= mp + 1;\n }\n if (bpo.rotated) {\n const tmp = width;\n width = length;\n length = tmp;\n }\n return { width, length };\n}\nexports.getEffectiveDimensions = getEffectiveDimensions;\nfunction _getCenterBPO(boxes, bpo, scale_factor, pallet_dims) {\n let { width, length } = getEffectiveDimensions(bpo, boxes);\n width *= scale_factor / pallet_dims.width;\n length *= scale_factor / pallet_dims.length;\n let p = {\n x: bpo.position.x + width / 2,\n y: bpo.position.y + length / 2,\n };\n return p;\n}\nfunction getBoxPositionsBounds(boxes, bpos, scale_factor, pallet_dims) {\n if (bpos.length === 0)\n return { xLow: 0, yLow: 0, yHigh: 0, xHigh: 0 };\n let x_low = 1, x_high = 0, y_low = 1, y_high = 0;\n bpos.forEach((bpo) => {\n const { x: bx, y: by } = _getCenterBPO(boxes, bpo, scale_factor, pallet_dims);\n let { width, length } = getEffectiveDimensions(bpo, boxes);\n width *= scale_factor / pallet_dims.width;\n length *= scale_factor / pallet_dims.length;\n const bXlow = bx - width / 2;\n if (bXlow < x_low)\n x_low = bXlow;\n const bXhigh = bx + width / 2;\n if (bXhigh > x_high)\n x_high = bXhigh;\n const bYlow = by - length / 2;\n if (bYlow < y_low)\n y_low = bYlow;\n const bYhigh = by + length / 2;\n if (bYhigh > y_high)\n y_high = bYhigh;\n });\n return {\n xLow: x_low,\n xHigh: x_high,\n yLow: y_low,\n yHigh: y_high,\n };\n}\nexports.getBoxPositionsBounds = getBoxPositionsBounds;\nfunction getBoxPositionsBoundingBoxCenter(boxes, bpos, scale_factor, pallet_dims) {\n const lBounds = getBoxPositionsBounds(boxes, bpos, scale_factor, pallet_dims);\n let x = (lBounds.xHigh - lBounds.xLow) / 2 + lBounds.xLow, y = (lBounds.yHigh - lBounds.yLow) / 2 + lBounds.yLow;\n return { x, y };\n}\nexports.getBoxPositionsBoundingBoxCenter = getBoxPositionsBoundingBoxCenter;\nfunction getBoxPositionCOM(boxes, bpos, scale_factor, pallet_dims) {\n // Determine COM using com = (m1*y1 + m2*y2 + ...) / (m1 + m2 + ...)\n // Where mi is the weight (size of box, e.g. double_length = 2 * y => m = 2)\n // and yi is the center y coord of the box\n let x = 0, y = 0, xWeights = bpos.length, // = 1 for each to start (all even).\n yWeights = bpos.length;\n if (bpos.length === 0)\n return { x, y };\n bpos.forEach((bpo) => {\n let { x: bx, y: by } = _getCenterBPO(boxes, bpo, scale_factor, pallet_dims);\n //Weight factor in COM equation numerator\n const mp = bpo.multipick || 0;\n if ((!bpo.multipickAlongWidth && !bpo.rotated) ||\n (bpo.multipickAlongWidth && bpo.rotated)) {\n by *= mp + 1;\n yWeights += mp;\n }\n else {\n bx *= mp + 1;\n xWeights += mp;\n }\n x += bx;\n y += by;\n });\n // unrotated x the same\n x /= xWeights;\n y /= yWeights;\n return { x, y };\n}\nexports.getBoxPositionCOM = getBoxPositionCOM;\n// convert to norm space x -> x * pallet.width / norm, y -> y * pallet.length / norm;\nfunction _rotateBoxPosition_t(boxes, bpo, about, scale_factor, pallet_dims) {\n const s = Math.sin(Math.PI / 2);\n const c = Math.cos(Math.PI / 2);\n let { x, y } = _getCenterBPO(boxes, bpo, scale_factor, pallet_dims);\n // translate to origin.\n x -= about.x;\n y -= about.y;\n // copy\n let ptx = x, pty = y;\n // rotate\n let lratio = pallet_dims.length / pallet_dims.width;\n let wratio = 1 / lratio;\n x = ptx * c - pty * lratio * s;\n y = ptx * wratio * s + pty * c;\n // translate\n x += about.x;\n y += about.y;\n bpo.rotated = !bpo.rotated; // flip rotation.\n let { width, length } = boxes[bpo.index].dimensions;\n const mp = bpo.multipick || 0;\n if (bpo.multipickAlongWidth) {\n width *= mp + 1;\n }\n else {\n length *= mp + 1;\n }\n if (bpo.rotated) {\n let tmp = width;\n width = length;\n length = tmp;\n }\n width *= scale_factor / pallet_dims.width;\n length *= scale_factor / pallet_dims.length;\n x -= width / 2;\n y -= length / 2;\n bpo.position = { x, y };\n}\nfunction rotateBoxPositions(boxes, bpos, scale_factor, pallet_dims) {\n const com = getBoxPositionCOM(boxes, bpos, scale_factor, pallet_dims);\n bpos.forEach(function (bpo) {\n _rotateBoxPosition_t(boxes, bpo, com, scale_factor, pallet_dims);\n });\n}\nexports.rotateBoxPositions = rotateBoxPositions;\n// Layout Transformations For Use In AutoStack.\n// 1. Rotate 180deg\n// 2. Reflect Y\n// 3. Reflect X\nvar LayoutTransform;\n(function (LayoutTransform) {\n // utils.\n function cloneLayout(pLayout) {\n const lNewLayout = { ...pLayout, boxPositions: [...pLayout.boxPositions] };\n lNewLayout.boxPositions = lNewLayout.boxPositions.map(function (lBoxPosition) {\n const lNewPosition = { ...lBoxPosition };\n lNewPosition.position = { ...lBoxPosition.position };\n return lNewPosition;\n });\n return lNewLayout;\n }\n let TransformType;\n (function (TransformType) {\n TransformType[TransformType[\"Identity\"] = 0] = \"Identity\";\n TransformType[TransformType[\"Spin\"] = 1] = \"Spin\";\n TransformType[TransformType[\"ReflectX\"] = 2] = \"ReflectX\";\n TransformType[TransformType[\"ReflectY\"] = 3] = \"ReflectY\";\n TransformType[TransformType[\"ReflectGlobalX\"] = 4] = \"ReflectGlobalX\";\n TransformType[TransformType[\"ReflectGlobalY\"] = 5] = \"ReflectGlobalY\";\n })(TransformType = LayoutTransform.TransformType || (LayoutTransform.TransformType = {}));\n LayoutTransform.TransformTypeNames = [\n 'None',\n 'Rotate 180',\n 'Mirror Vertical',\n 'Mirror Horizontal',\n ];\n function Transform(pType, pPallet, pBoxes, pLayoutIndex) {\n let lTransformer = Identity;\n switch (pType) {\n case TransformType.Identity:\n lTransformer = Identity;\n break;\n case TransformType.Spin:\n lTransformer = Spin;\n break;\n case TransformType.ReflectX:\n lTransformer = ReflectX;\n break;\n case TransformType.ReflectY:\n lTransformer = ReflectY;\n break;\n case TransformType.ReflectGlobalX:\n lTransformer = ReflectGlobalX;\n break;\n case TransformType.ReflectGlobalY:\n lTransformer = ReflectGlobalY;\n break;\n }\n return lTransformer(pPallet, pBoxes, pLayoutIndex);\n }\n LayoutTransform.Transform = Transform;\n function Identity(pPallet, pBoxes, pLayoutIndex) {\n const lNewLayout = cloneLayout(pPallet.Layouts[pLayoutIndex]);\n (0, labels_1.applyLabelSpins)(pBoxes, lNewLayout, pPallet);\n return lNewLayout;\n }\n LayoutTransform.Identity = Identity;\n // Spin: rotate 180deg\n function Spin(pPallet, pBoxes, pLayoutIndex) {\n const lNewLayout = cloneLayout(pPallet.Layouts[pLayoutIndex]);\n for (let i = 0; i < Math.floor(180 / 90); // ie. 2 x 90 deg rotation.\n i++)\n rotateBoxPositions(pBoxes, lNewLayout.boxPositions, 1, pPallet.Dimensions);\n (0, labels_1.applyLabelSpins)(pBoxes, lNewLayout, pPallet);\n return lNewLayout;\n }\n LayoutTransform.Spin = Spin;\n function ReflectXHelper(pPallet, pBoxes, pLayoutIndex, pReflectAboutBoundingBoxCenter) {\n const lNewLayout = cloneLayout(pPallet.Layouts[pLayoutIndex]);\n let lLayoutCenter;\n if (pReflectAboutBoundingBoxCenter) {\n lLayoutCenter = getBoxPositionsBoundingBoxCenter(pBoxes, lNewLayout.boxPositions, 1, pPallet.Dimensions);\n }\n lNewLayout.boxPositions.forEach(function (pBoxPosition) {\n let lBox = pBoxes[pBoxPosition.index];\n let bl = lBox.dimensions.length;\n let bw = lBox.dimensions.width;\n const mp = pBoxPosition.multipick || 0;\n if (pBoxPosition.multipickAlongWidth) {\n bw *= mp + 1;\n }\n else {\n bl *= mp + 1;\n }\n let lBoxLength = (pBoxPosition.rotated ? bw : bl) / pPallet.Dimensions.length;\n let lNewY;\n if (pReflectAboutBoundingBoxCenter) {\n lNewY = lLayoutCenter.y * 2 - pBoxPosition.position.y - lBoxLength;\n }\n else {\n lNewY = 1 - pBoxPosition.position.y - lBoxLength;\n }\n pBoxPosition.position.y = lNewY;\n });\n (0, labels_1.applyLabelSpins)(pBoxes, lNewLayout, pPallet);\n return lNewLayout;\n }\n LayoutTransform.ReflectXHelper = ReflectXHelper;\n function ReflectX(pPallet, pBoxes, pLayoutIndex) {\n return ReflectXHelper(pPallet, pBoxes, pLayoutIndex, true);\n }\n LayoutTransform.ReflectX = ReflectX;\n function ReflectGlobalX(pPallet, pBoxes, pLayoutIndex) {\n return ReflectXHelper(pPallet, pBoxes, pLayoutIndex, false);\n }\n LayoutTransform.ReflectGlobalX = ReflectGlobalX;\n function ReflectYHelper(pPallet, pBoxes, pLayoutIndex, pReflectAboutBoundingBoxCenter) {\n const lNewLayout = cloneLayout(pPallet.Layouts[pLayoutIndex]);\n let lLayoutCenter;\n if (pReflectAboutBoundingBoxCenter) {\n lLayoutCenter = getBoxPositionsBoundingBoxCenter(pBoxes, lNewLayout.boxPositions, 1, pPallet.Dimensions);\n }\n lNewLayout.boxPositions.forEach(function (pBoxPosition) {\n let lBox = pBoxes[pBoxPosition.index];\n let bl = lBox.dimensions.length;\n let bw = lBox.dimensions.width;\n const mp = pBoxPosition.multipick || 0;\n if (pBoxPosition.multipickAlongWidth) {\n bw *= mp + 1;\n }\n else {\n bl *= mp + 1;\n }\n let lBoxWidth = (pBoxPosition.rotated ? bl : bw) / pPallet.Dimensions.width;\n let lNewX;\n if (pReflectAboutBoundingBoxCenter) {\n lNewX = 2 * lLayoutCenter.x - pBoxPosition.position.x - lBoxWidth;\n }\n else {\n lNewX = 1 - pBoxPosition.position.x - lBoxWidth;\n }\n pBoxPosition.position.x = lNewX;\n });\n (0, labels_1.applyLabelSpins)(pBoxes, lNewLayout, pPallet);\n return lNewLayout;\n }\n function ReflectY(pPallet, pBoxes, pLayoutIndex) {\n return ReflectYHelper(pPallet, pBoxes, pLayoutIndex, true);\n }\n LayoutTransform.ReflectY = ReflectY;\n function ReflectGlobalY(pPallet, pBoxes, pLayoutIndex) {\n return ReflectYHelper(pPallet, pBoxes, pLayoutIndex, false);\n }\n LayoutTransform.ReflectGlobalY = ReflectGlobalY;\n})(LayoutTransform = exports.LayoutTransform || (exports.LayoutTransform = {}));\n", "\"use strict\";\n/*\n sort.ts\n Marc-Antoine Deragon's box sorting implementation for the doosan\n cobot palletizer.\n*/\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.marcSort = exports.BoxSort = void 0;\nfunction FirstCondition(x1, x2, y1, y2, side) {\n if (x1 < x2 &&\n y1 < y2 &&\n Math.abs(x1 - x2) > 1 &&\n Math.abs(y1 - y2) > 1 &&\n side == 'left') {\n return true;\n }\n if (x1 > x2 &&\n y1 < y2 &&\n Math.abs(x1 - x2) > 1 &&\n Math.abs(y1 - y2) > 1 &&\n side == 'right') {\n return true;\n }\n return false;\n}\nfunction SecondCondition(x1, x2, x3, x4, y1, y2) {\n if (Math.abs(x1 - x3) < 1 && Math.abs(x2 - x4) < 1 && y1 < y2) {\n return true;\n }\n return false;\n}\nfunction ThirdCondition(y1, y2, y3, y4, x1, x2, side) {\n if (Math.abs(y1 - y3) < 1 &&\n Math.abs(y2 - y4) < 1 &&\n x1 < x2 &&\n side == 'left') {\n return true;\n }\n if (Math.abs(y1 - y3) < 1 &&\n Math.abs(y2 - y4) < 1 &&\n x1 > x2 &&\n side == 'right') {\n return true;\n }\n return false;\n}\nfunction FourthCondition(x1, x2, x3, side) {\n if (x1 <= x2 && x1 <= x3 && side == 'left') {\n return true;\n }\n if (x1 >= x2 && x1 >= x3 && side == 'right') {\n return true;\n }\n return false;\n}\nfunction BoolIndex(arr) {\n let indicesFalse = [];\n let indicesTrue = [];\n //Finding index of !rotated\n let idx = arr.indexOf(false);\n while (idx != -1) {\n indicesFalse.push(idx);\n idx = arr.indexOf(false, idx + 1);\n }\n //Finding index of rotated\n idx = arr.indexOf(true);\n while (idx != -1) {\n indicesTrue.push(idx);\n idx = arr.indexOf(true, idx + 1);\n }\n return [indicesTrue, indicesFalse];\n}\nfunction BoxSort(x, y, r, s, multiPick, multipickAlongWidth, boxWidth, boxLength, palletWidth, palletLength, side) {\n // Changing frame for bottom left\n y = y.map(function (item) {\n return Math.floor((1 - item) * palletLength);\n });\n if (side == 'right') {\n x = x.map(function (item) {\n return item - 1;\n });\n }\n x = x.map(function (item) {\n return Math.floor(item * palletWidth);\n });\n //Finding rotated and !rotated pos index\n let [indicesTrue, indicesFalse] = BoolIndex(r);\n let minX = x.slice();\n let maxX = x.slice();\n let minY = y.slice();\n let maxY = y.slice();\n if (side == 'left') {\n //Finding each boxes max X and max Y\n indicesFalse.forEach(function (val) {\n if (multipickAlongWidth[val]) {\n maxX[val] += (multiPick[val] + 1) * boxWidth;\n minY[val] -= boxLength;\n }\n else {\n maxX[val] += boxWidth;\n minY[val] -= (multiPick[val] + 1) * boxLength;\n }\n });\n indicesTrue.forEach(function (val) {\n if (multipickAlongWidth[val]) {\n maxX[val] += boxLength;\n minY[val] -= (multiPick[val] + 1) * boxWidth;\n }\n else {\n maxX[val] += (multiPick[val] + 1) * boxLength;\n minY[val] -= boxWidth;\n }\n });\n }\n if (side == 'right') {\n indicesFalse.forEach(function (val) {\n if (multipickAlongWidth[val]) {\n minX[val] += (multiPick[val] + 1) * boxWidth;\n minY[val] -= boxLength;\n }\n else {\n minX[val] += boxWidth;\n minY[val] -= (multiPick[val] + 1) * boxLength;\n }\n });\n indicesTrue.forEach(function (val) {\n if (multipickAlongWidth[val]) {\n minX[val] += boxLength;\n minY[val] -= (multiPick[val] + 1) * boxWidth;\n }\n else {\n minX[val] += (multiPick[val] + 1) * boxLength;\n minY[val] -= boxWidth;\n }\n });\n }\n let swapped = true;\n let loopCount = 0;\n let maxLoop = 10000;\n let nextPoint;\n do {\n swapped = false;\n loopCount++;\n for (let i = 0; i < x.length; i++) {\n for (let j = i; j < x.length; j++) {\n if (i < x.length - 1) {\n nextPoint = minX[i + 1];\n }\n else {\n if (side == 'right') {\n nextPoint = 2;\n }\n else {\n nextPoint = -1;\n }\n }\n if ((FirstCondition(minX[i], maxX[j], minY[i], maxY[j], side) ||\n SecondCondition(maxX[i], minX[i], maxX[j], minX[j], y[i], y[j]) ||\n ThirdCondition(maxY[i], minY[i], maxY[j], minY[j], x[i], x[j], side) ||\n FourthCondition(maxX[i], minX[j], nextPoint, side)) &&\n i != j) {\n let temp = [\n x[j],\n minX[j],\n maxX[j],\n y[j],\n minY[j],\n maxY[j],\n multiPick[j],\n multipickAlongWidth[j],\n ];\n let tempBool = [r[j], s[j]];\n [\n x[j],\n minX[j],\n maxX[j],\n y[j],\n minY[j],\n maxY[j],\n multiPick[j],\n multipickAlongWidth[j],\n ] = [\n x[i],\n minX[i],\n maxX[i],\n y[i],\n minY[i],\n maxY[i],\n multiPick[i],\n multipickAlongWidth[i],\n ];\n [r[j], s[j]] = [r[i], s[i]];\n [\n x[i],\n minX[i],\n maxX[i],\n y[i],\n minY[i],\n maxY[i],\n multiPick[i],\n multipickAlongWidth[i],\n ] = temp;\n [r[i], s[i]] = tempBool;\n swapped = true;\n }\n }\n }\n } while (swapped && loopCount <= maxLoop);\n // Check if we could find a solution within a reasonable amount of tries\n if (loopCount > maxLoop) {\n throw new Error('Could not find solution in reasonable amount of time.');\n }\n // Changing frame for top left\n y = y.map(function (item) {\n return 1 - item / palletLength;\n });\n x = x.map(function (item) {\n return item / palletWidth;\n });\n if (side == 'right') {\n x = x.map(function (item) {\n return item + 1;\n });\n }\n return [x, y, r, s, multiPick, multipickAlongWidth];\n}\nexports.BoxSort = BoxSort;\nvar Side;\n(function (Side) {\n Side[Side[\"Left\"] = 0] = \"Left\";\n Side[Side[\"Right\"] = 1] = \"Right\";\n})(Side || (Side = {}));\nfunction marcSort(pConfig, pSide) {\n const lPallet = pConfig.config.pallets[0];\n const lAllBoxes = pConfig.config.boxes;\n const lStack = lPallet.Stack;\n const lLayouts = lPallet.Layouts;\n if (lStack.length === 0 || lLayouts.length === 0)\n return true;\n let xS = [], yS = [];\n let rS = [], sS = [];\n let lMultipick = [];\n let lMultipickAlongWidth = [];\n let lSuccess = true;\n lStack.forEach(function (lLayoutId) {\n const lLayout = lLayouts[lLayoutId];\n if (lLayout.boxPositions.length === 0)\n return;\n const lFirstBoxId = lLayout.boxPositions[0].index;\n const lFirstBox = lAllBoxes[lFirstBoxId];\n const lBoxWidth = lFirstBox.dimensions.width;\n const lBoxLength = lFirstBox.dimensions.length;\n // Clear old coordinates.\n lLayout.boxPositions.forEach(function (lBoxPosition) {\n xS.push(lBoxPosition.position.x);\n yS.push(lBoxPosition.position.y);\n rS.push(lBoxPosition.rotated);\n sS.push(lBoxPosition.spin);\n lMultipick.push(lBoxPosition.multipick || 0);\n lMultipickAlongWidth.push(lBoxPosition.multipickAlongWidth);\n });\n try {\n const [lNewX, lNewY, lNewR, lNewS, lNewMultipick, lNewMultipickAlongWidth,] = BoxSort(xS, yS, rS, sS, lMultipick, lMultipickAlongWidth, lBoxWidth, lBoxLength, lPallet.Dimensions.width, lPallet.Dimensions.length, pSide == Side.Left ? 'left' : 'right');\n // update coordinates in place.\n lLayout.boxPositions.forEach(function (lBoxPosition, lIndex) {\n lBoxPosition.position.x = lNewX[lIndex];\n lBoxPosition.position.y = lNewY[lIndex];\n lBoxPosition.rotated = lNewR[lIndex];\n lBoxPosition.spin = lNewS[lIndex];\n lBoxPosition.multipick = lNewMultipick[lIndex];\n lBoxPosition.multipickAlongWidth = (lNewMultipickAlongWidth[lIndex]);\n });\n }\n catch (_pError) {\n return false;\n }\n });\n return lSuccess;\n}\nexports.marcSort = marcSort;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GenerateFinalConfig = exports.PalletConfigObj = exports.newPalletConfiguration = exports.getDefaultPallets = exports.getLayoutHeight = void 0;\nconst geometry_1 = require(\"./geometry\");\nconst layouts_1 = require(\"./layouts\");\nconst sort_1 = require(\"./sort\");\nfunction getLayoutHeight(pLayout, pBoxes) {\n if (pLayout.boxPositions.length === 0)\n return 0;\n let lBox = pBoxes[pLayout.boxPositions[0].index];\n return lBox.dimensions.height;\n}\nexports.getLayoutHeight = getLayoutHeight;\n/*\n * {Name: \"Standard GMA Pallet\"; Dimensions: \"1016 x 1219mm\"} and {Name: \"EUR-pallet\"; Dimensions: \"800 x 1200mm\"}\n */\nfunction getDefaultPallets() {\n return [\n {\n name: '40 x 48 in.',\n id: 'eca7450b-bb55-4b98-82a0-bdf72e6609e9',\n Dimensions: { width: 1016, length: 1219, height: 165 },\n point: { x: 0, y: 0, z: 0, \u03B8: 0 },\n Stack: [],\n Layouts: [],\n Detection: {\n TopEnabled: false,\n Top: 0,\n BottomEnabled: false,\n Bottom: 0,\n },\n },\n {\n name: 'EUR',\n id: '0450d23e-0804-4500-ac3f-0acdec598f74',\n Dimensions: { width: 800, length: 1200, height: 144 },\n point: { x: 0, y: 0, z: 0, \u03B8: 0 },\n Stack: [],\n Layouts: [],\n Detection: {\n TopEnabled: false,\n Top: 0,\n BottomEnabled: false,\n Bottom: 0,\n },\n },\n ];\n}\nexports.getDefaultPallets = getDefaultPallets;\nfunction newPalletConfiguration(name) {\n return {\n name,\n boxes: [],\n slipsheets: [],\n pallets: getDefaultPallets(),\n };\n}\nexports.newPalletConfiguration = newPalletConfiguration;\nclass PalletConfigObj {\n constructor() {\n this.complete = true;\n this.boxCoordinates = [];\n this.config = {\n name: 'null configuration',\n boxes: [],\n slipsheets: [],\n pallets: [],\n };\n }\n // use to absorb data into class.\n static from(spc) {\n const c = new PalletConfigObj();\n Object.assign(c, spc);\n // validate + fix configurations\n c.config.pallets.forEach(function (p) {\n if (!p.Layouts || p.Layouts === null)\n p.Layouts = [];\n if (!p.Stack || p.Stack === null)\n p.Stack = [];\n });\n return c;\n }\n hasBox() {\n return this.config.boxes.length > 0;\n }\n hasSlipSheet() {\n return this.config.slipsheets.length > 0;\n }\n hasPallet() {\n return this.config.pallets.length > 0;\n }\n hasLayout() {\n return (this.config.pallets.map(p => p.Layouts.length).filter(x => x > 0).length >\n 0);\n }\n hasStack() {\n return (this.config.pallets.map(p => p.Stack.length).filter(x => x > 0).length > 0);\n }\n getBox(box_index) {\n return this.config.boxes[box_index];\n }\n getPallet(pallet_index) {\n return this.config.pallets[pallet_index];\n }\n getStack(pallet_index, stack_index) {\n return this.getPallet(pallet_index).Stack[stack_index];\n }\n getLayer(pallet_index, stack_index, layer_index) {\n return this.getStack(pallet_index, stack_index).layers[layer_index];\n }\n findPalletIDAndStackIDFromSKUID(skuID) {\n var _a;\n const ps = this.config.pallets;\n for (let p = 0; p < ps.length; p++) {\n const pallet = ps[p];\n for (let s = 0; s < pallet.Stack.length; s++) {\n const stack = pallet.Stack[s];\n const layers = stack.layers;\n if (layers.length > 0) {\n const layout_index = layers[0].index;\n if (pallet.Layouts.length > layout_index) {\n const layout = pallet.Layouts[layout_index];\n const boxPos = layout.boxPositions;\n const boxIndex = boxPos[0].index;\n const box = this.getBox(boxIndex);\n const lMatches = ((_a = box.skuId) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === (skuID === null || skuID === void 0 ? void 0 : skuID.toLowerCase());\n if (lMatches)\n return { PalletID: p, StackID: s };\n }\n }\n }\n }\n return void 0;\n }\n getLayout(pallet_index, layout_index) {\n return this.getPallet(pallet_index).Layouts[layout_index];\n }\n getLayoutHeight(pPalletIndex, pLayoutIndex) {\n return getLayoutHeight(this.getLayout(pPalletIndex, pLayoutIndex), this.config.boxes);\n }\n getStackHeight(pPalletIndex, pStackIndex) {\n let lHeight = 0;\n const lStack = this.getPallet(pPalletIndex).Stack[pStackIndex];\n lStack.layers.forEach(lLayer => {\n lHeight += this.getLayoutHeight(pPalletIndex, lLayer.index);\n });\n return lHeight;\n }\n getStackLayout(pPalletIndex, pStackIndex, pLayerIndex) {\n const lPallet = this.getPallet(pPalletIndex), lStack = this.getStack(pPalletIndex, pStackIndex);\n const lStackLayout = lStack.layers[pLayerIndex];\n return layouts_1.LayoutTransform.Transform(lStackLayout.transform, lPallet, this.config.boxes, lStackLayout.index);\n }\n getSortedStackLayout(pPalletIndex, pStackIndex, pLayerIndex, pSide) {\n let lTargetLayout = this.getStackLayout(pPalletIndex, pStackIndex, pLayerIndex);\n const lConfigCp = JSON.parse(JSON.stringify(this));\n lConfigCp.config.pallets = [lConfigCp.config.pallets[pPalletIndex]];\n const lPalletCp = lConfigCp.config.pallets[0];\n lPalletCp.Layouts = [lTargetLayout];\n lPalletCp.Stack = [0];\n // Transform to robot space\n lTargetLayout = layouts_1.LayoutTransform.Transform(layouts_1.LayoutTransform.TransformType.ReflectGlobalY, lPalletCp, lConfigCp.config.boxes, 0);\n lPalletCp.Layouts = [lTargetLayout];\n lTargetLayout = layouts_1.LayoutTransform.Transform(layouts_1.LayoutTransform.TransformType.ReflectGlobalX, lPalletCp, lConfigCp.config.boxes, 0);\n lPalletCp.Layouts = [lTargetLayout];\n let lSuccess = (0, sort_1.marcSort)(lConfigCp, pSide); /* sort rifled configuration */\n if (!lSuccess) {\n return this.getStackLayout(pPalletIndex, pStackIndex, pLayerIndex);\n }\n else {\n lPalletCp.sorted = true;\n return lTargetLayout;\n }\n }\n getBoxCountOffset(pPalletIndex, pStackIndex, pStartLayer, pStartBox) {\n const lStack = this.getStack(pPalletIndex, pStackIndex);\n let lBoxCount = 0;\n for (let lLayerIndex = 0; lLayerIndex < lStack.layers.length; lLayerIndex++) {\n const lLayer = lStack.layers[lLayerIndex], lLayout = this.getLayout(pPalletIndex, lLayer.index), lIsLastLayer = lLayerIndex === pStartLayer;\n for (let lBoxIndex = 0; lBoxIndex < lLayout.boxPositions.length; lBoxIndex++) {\n if (lIsLastLayer && lBoxIndex === pStartBox)\n break;\n lBoxCount++;\n }\n if (lIsLastLayer)\n break;\n }\n return lBoxCount;\n }\n getPickCountLayout(pallet_index, layout_index) {\n return this.getLayout(pallet_index, layout_index).boxPositions.length;\n }\n getBoxCountLayout(pallet_index, layout_index) {\n const bPos = this.getLayout(pallet_index, layout_index).boxPositions;\n let count = 0;\n for (let b = 0; b < bPos.length; b++) {\n count += (bPos[b].multipick || 0) + 1;\n }\n return count;\n }\n getLayoutCountStack(pallet_index, stack_index) {\n return this.getStack(pallet_index, stack_index).layers.length;\n }\n /* returns [layerIndex, boxIndexInLayer] */\n getLayoutAndRelativeIndexForBox(pPalletIndex, pStackIndex, pBoxIndex) {\n const lStack = this.getStack(pPalletIndex, pStackIndex);\n let lTotalBoxes = 0;\n for (let lLayerIndex = 0; lLayerIndex < lStack.layers.length; lLayerIndex++) {\n const lBoxesInLayer = this.getBoxCountLayout(pPalletIndex, lStack.layers[lLayerIndex].index);\n lTotalBoxes += lBoxesInLayer;\n if (lTotalBoxes > pBoxIndex)\n return [lLayerIndex, lBoxesInLayer - (lTotalBoxes - pBoxIndex)];\n }\n return [0, 0];\n }\n getAbsoluteCount(pPalletIndex, pStackIndex, pLayerIndex, pRelativeBoxIndex) {\n let lCount = 0;\n const _lMy = this;\n _lMy\n .getStack(pPalletIndex, pStackIndex)\n .layers.forEach(function (pLayer, pIndex) {\n if (pIndex > pLayerIndex)\n return;\n if (pIndex === pLayerIndex)\n lCount += pRelativeBoxIndex;\n else\n lCount += _lMy.getBoxCountLayout(pPalletIndex, pLayer.index);\n });\n return lCount;\n }\n getPickCountStack(pallet_index, stack_index) {\n let count = 0;\n const my = this;\n my.getStack(pallet_index, stack_index).layers.forEach((pLayer_t) => {\n count += my.getPickCountLayout(pallet_index, pLayer_t.index);\n });\n return count;\n }\n getBoxCountStack(pallet_index, stack_index) {\n let count = 0;\n const my = this;\n my.getStack(pallet_index, stack_index).layers.forEach((pLayer_t) => {\n count += my.getBoxCountLayout(pallet_index, pLayer_t.index);\n });\n return count;\n }\n getSSCountStack(pallet_index, stack_index) {\n let count = 0;\n const my = this;\n const s = my.getStack(pallet_index, stack_index);\n if (!s.slipSheet)\n return 0;\n const layers = s.layers;\n for (let l = 0; l <= layers.length; l++) {\n count += (0, geometry_1.hasSlipSheet)(l, layers.length, s.slipSheet) ? 1 : 0;\n }\n return count;\n }\n}\nexports.PalletConfigObj = PalletConfigObj;\nfunction GenerateFinalConfig(startingConfig, gripper) {\n const config = { ...startingConfig };\n const { pallets } = config;\n let boxCoordinates = [];\n let g_x_shift = (gripper.x_high - gripper.x_low) / 2;\n let g_y_shift = (gripper.y_high - gripper.y_low) / 2;\n const stackShifts = new Array(config.boxes.length).fill(0);\n pallets.forEach((p, palletIndex) => {\n const { Layouts, Stack } = p;\n const [corner1, corner2, corner3] = (0, geometry_1.getPalletCorners)(p, gripper);\n /* console.log('picked pallet corner', p.point.x, p.point.y, p.point.\u03B8);\n console.log('pallet corner', corner2, p.point.x - corner2.x); */\n const palletHeight = (corner1.z + corner2.z + corner3.z) / 3;\n const Ydirection = (0, geometry_1.Subtract3D)(corner1, corner2);\n const Xdirection = (0, geometry_1.Subtract3D)(corner3, corner2);\n const \u03C6_pallet = (0, geometry_1.getXAxisAngle)(Xdirection);\n let currentHeightIncrement = palletHeight;\n Stack[0].layers.forEach((pLayer_t, stackIndex) => {\n const n = pLayer_t.index;\n const { boxPositions } = Layouts[n];\n let lLayerHeight = 0;\n boxPositions.forEach((b, i) => {\n let { position, rotated } = b;\n const box = config.boxes[b.index];\n lLayerHeight = box.dimensions.height;\n const pickLocation = (0, geometry_1.to_coord)(box.pickLocation);\n const { x, y } = position;\n let boxWidth = box.dimensions.width;\n let boxLength = box.dimensions.length;\n let temp = boxWidth;\n boxWidth = rotated ? boxLength : boxWidth;\n boxLength = rotated ? temp : boxLength;\n const \u03B8_drop = (rotated ? 90 : 0) + \u03C6_pallet;\n const \u03B8_drop_rad = (\u03B8_drop * Math.PI) / 180;\n let boxXmid = boxWidth / 2;\n let boxYmid = boxLength / 2;\n let x_shift = g_y_shift * Math.sin(\u03B8_drop_rad) - g_x_shift * Math.cos(\u03B8_drop_rad);\n let y_shift = -g_x_shift * Math.sin(\u03B8_drop_rad) - g_y_shift * Math.cos(\u03B8_drop_rad);\n let x_pos = (0, geometry_1.MultiplyScalar)(Xdirection, x);\n let y_pos = (0, geometry_1.MultiplyScalar)(Ydirection, 1 - y);\n let Xunit = (0, geometry_1.MultiplyScalar)(Xdirection, 1 / (0, geometry_1.Norm)(Xdirection));\n let Yunit = (0, geometry_1.MultiplyScalar)(Ydirection, 1 / (0, geometry_1.Norm)(Ydirection));\n x_pos = (0, geometry_1.Add3D)(x_pos, (0, geometry_1.MultiplyScalar)(Xunit, boxXmid));\n y_pos = (0, geometry_1.Add3D)(y_pos, (0, geometry_1.MultiplyScalar)(Yunit, -boxYmid));\n let averagePosition = (0, geometry_1.Add3D)(x_pos, y_pos);\n averagePosition = (0, geometry_1.Add3D)(averagePosition, corner2);\n let z_add = currentHeightIncrement;\n if (stackIndex > 0) {\n z_add -= box.dimensions.height;\n }\n averagePosition.z = z_add;\n let dropLocation = { ...averagePosition, \u03B8: \u03B8_drop };\n dropLocation.x += x_shift;\n dropLocation.y += y_shift;\n let linearPathDistance = (0, geometry_1.Norm)((0, geometry_1.Subtract3D)(pickLocation, dropLocation));\n if (box.pickFromStack) {\n pickLocation.z += box.dimensions.height * stackShifts[b.index];\n stackShifts[b.index]++;\n }\n boxCoordinates.push({\n pickLocation: { ...pickLocation },\n dropLocation,\n dimensions: box.dimensions,\n boxIndex: b.index,\n palletIndex,\n stackIndex,\n linearPathDistance,\n boxDetection: box.boxDetection,\n detectionEnabled: box.detectionEnabled,\n });\n });\n if (stackIndex > 0)\n currentHeightIncrement -= lLayerHeight;\n });\n });\n return {\n config: startingConfig,\n boxCoordinates,\n complete: true,\n };\n}\nexports.GenerateFinalConfig = GenerateFinalConfig;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default_gripper = exports.axes_to_arr = void 0;\nconst axes_to_arr = (ax) => {\n return [ax.X, ax.Y, ax.Z, ax.Rotation];\n};\nexports.axes_to_arr = axes_to_arr;\nconst default_gripper = () => {\n return {\n x_low: 200,\n x_high: 200,\n y_low: 100,\n y_high: 100,\n SuctionOutput: -1,\n PressureInput: -1,\n };\n};\nexports.default_gripper = default_gripper;\n", "// Unique ID creation requires a high quality random # generator. In the\n// browser this is a little complicated due to unknown quality of Math.random()\n// and inconsistent support for the `crypto` API. We do the best we can via\n// feature-detection\n\n// getRandomValues needs to be invoked in a context where \"this\" is a Crypto\n// implementation. Also, find the complete implementation of crypto on IE11.\nvar getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||\n (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));\n\nif (getRandomValues) {\n // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n\n module.exports = function whatwgRNG() {\n getRandomValues(rnds8);\n return rnds8;\n };\n} else {\n // Math.random()-based (RNG)\n //\n // If all else fails, use Math.random(). It's fast, but is of unspecified\n // quality.\n var rnds = new Array(16);\n\n module.exports = function mathRNG() {\n for (var i = 0, r; i < 16; i++) {\n if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n }\n\n return rnds;\n };\n}\n", "/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex[i] = (i + 0x100).toString(16).substr(1);\n}\n\nfunction bytesToUuid(buf, offset) {\n var i = offset || 0;\n var bth = byteToHex;\n // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4\n return ([\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]]\n ]).join('');\n}\n\nmodule.exports = bytesToUuid;\n", "var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nvar _nodeId;\nvar _clockseq;\n\n// Previous uuid creation time\nvar _lastMSecs = 0;\nvar _lastNSecs = 0;\n\n// See https://github.com/uuidjs/uuid for API details\nfunction v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || [];\n\n options = options || {};\n var node = options.node || _nodeId;\n var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;\n\n // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n if (node == null || clockseq == null) {\n var seedBytes = rng();\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [\n seedBytes[0] | 0x01,\n seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]\n ];\n }\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n }\n\n // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n for (var n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf ? buf : bytesToUuid(b);\n}\n\nmodule.exports = v1;\n", "var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\nfunction v4(options, buf, offset) {\n var i = buf && offset || 0;\n\n if (typeof(options) == 'string') {\n buf = options === 'binary' ? new Array(16) : null;\n options = null;\n }\n options = options || {};\n\n var rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n for (var ii = 0; ii < 16; ++ii) {\n buf[i + ii] = rnds[ii];\n }\n }\n\n return buf || bytesToUuid(rnds);\n}\n\nmodule.exports = v4;\n", "var v1 = require('./v1');\nvar v4 = require('./v4');\n\nvar uuid = v4;\nuuid.v1 = v1;\nuuid.v4 = v4;\n\nmodule.exports = uuid;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.auto_all_forward = exports.auto_all_rotated = void 0;\nconst uuid_1 = require(\"uuid\");\nfunction auto_all_rotated(params, gapDistance) {\n const rotated = true;\n return auto_all_forward(params, gapDistance, rotated);\n}\nexports.auto_all_rotated = auto_all_rotated;\nfunction auto_all_forward({ all_boxes, all_pallets, box_index, pallet_index }, gapDistance, rotated = false) {\n const { width: pwidth, length: plength } = all_pallets[pallet_index].Dimensions;\n let { width: bwidth, length: blength } = all_boxes[box_index].dimensions;\n if (rotated) {\n let tmp = bwidth;\n bwidth = blength;\n blength = tmp;\n }\n let layout = {\n name: rotated ? 'All Rotated' : 'All Forward',\n id: String((0, uuid_1.v4)()),\n box_id: '',\n boxPositions: [],\n gapDistance,\n };\n let x;\n let y;\n // center of mass\n let com_x = 0;\n let com_y = 0;\n let i = 0;\n let j = 0;\n for (i = 0; (i + 1) * bwidth < pwidth; i++) {\n for (j = 0; (j + 1) * blength < plength; j++) {\n x = (i * bwidth) / pwidth;\n y = (j * blength) / plength;\n com_x += x + bwidth / (2 * pwidth);\n com_y += y + blength / (2 * plength);\n layout.boxPositions.push({\n rotated,\n index: box_index,\n position: { x, y },\n });\n }\n }\n com_x /= layout.boxPositions.length;\n com_y /= layout.boxPositions.length;\n // align to center of pallet (0.5, 0.5).\n let d_x = com_x - 1 / 2;\n let d_y = com_y - 1 / 2;\n layout.boxPositions.forEach((bp) => {\n bp.position.x -= d_x;\n bp.position.y -= d_y;\n });\n return layout;\n}\nexports.auto_all_forward = auto_all_forward;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.RobotModel = void 0;\nvar RobotModel;\n(function (RobotModel) {\n RobotModel[\"CRX_10IA\"] = \"crx10ia\";\n RobotModel[\"CRX_25IA\"] = \"crx25ia\";\n RobotModel[\"M710_IC45M\"] = \"m710ic45m\";\n RobotModel[\"M20_ID35\"] = \"m20id35\";\n RobotModel[\"DOOSAN_H2017\"] = \"doosan_h2017\";\n RobotModel[\"UR3_E\"] = \"ur3_e\";\n RobotModel[\"UR10_E\"] = \"ur10_e\";\n RobotModel[\"UR20\"] = \"ur20\";\n RobotModel[\"M410_IB140H\"] = \"m410ib140h\";\n})(RobotModel = exports.RobotModel || (exports.RobotModel = {}));\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./pallet_config\"), exports);\n__exportStar(require(\"./geometry\"), exports);\n__exportStar(require(\"./machine\"), exports);\n__exportStar(require(\"./autolayout\"), exports);\n__exportStar(require(\"./sort\"), exports);\n__exportStar(require(\"./labels\"), exports);\n__exportStar(require(\"./layouts\"), exports);\n__exportStar(require(\"./core_config\"), exports);\n", "'use strict';\n\nmodule.exports = function bind(fn, thisArg) {\n return function wrap() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.apply(thisArg, args);\n };\n};\n", "'use strict';\n\nvar bind = require('./helpers/bind');\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return toString.call(val) === '[object Array]';\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nfunction isArrayBuffer(val) {\n return toString.call(val) === '[object ArrayBuffer]';\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(val) {\n return (typeof FormData !== 'undefined') && (val instanceof FormData);\n}\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {Object} val The value to test\n * @return {boolean} True if value is a plain Object, otherwise false\n */\nfunction isPlainObject(val) {\n if (toString.call(val) !== '[object Object]') {\n return false;\n }\n\n var prototype = Object.getPrototypeOf(val);\n return prototype === null || prototype === Object.prototype;\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nfunction isDate(val) {\n return toString.call(val) === '[object Date]';\n}\n\n/**\n * Determine if a value is a File\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nfunction isFile(val) {\n return toString.call(val) === '[object File]';\n}\n\n/**\n * Determine if a value is a Blob\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nfunction isBlob(val) {\n return toString.call(val) === '[object Blob]';\n}\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nfunction isURLSearchParams(val) {\n return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;\n}\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (isPlainObject(result[key]) && isPlainObject(val)) {\n result[key] = merge(result[key], val);\n } else if (isPlainObject(val)) {\n result[key] = merge({}, val);\n } else if (isArray(val)) {\n result[key] = val.slice();\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n * @return {string} content value without BOM\n */\nfunction stripBOM(content) {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isPlainObject: isPlainObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n extend: extend,\n trim: trim,\n stripBOM: stripBOM\n};\n", "'use strict';\n\nvar utils = require('./../utils');\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n } else {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n var hashmarkIndex = url.indexOf('#');\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n", "'use strict';\n\nvar utils = require('./../utils');\n\nfunction InterceptorManager() {\n this.handlers = [];\n}\n\n/**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\nInterceptorManager.prototype.use = function use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled: fulfilled,\n rejected: rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n};\n\n/**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n */\nInterceptorManager.prototype.eject = function eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n};\n\n/**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n */\nInterceptorManager.prototype.forEach = function forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n};\n\nmodule.exports = InterceptorManager;\n", "'use strict';\n\nvar utils = require('../utils');\n\nmodule.exports = function normalizeHeaderName(headers, normalizedName) {\n utils.forEach(headers, function processHeader(value, name) {\n if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {\n headers[normalizedName] = value;\n delete headers[name];\n }\n });\n};\n", "'use strict';\n\n/**\n * Update an Error with the specified config, error code, and response.\n *\n * @param {Error} error The error to update.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The error.\n */\nmodule.exports = function enhanceError(error, config, code, request, response) {\n error.config = config;\n if (code) {\n error.code = code;\n }\n\n error.request = request;\n error.response = response;\n error.isAxiosError = true;\n\n error.toJSON = function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: this.config,\n code: this.code,\n status: this.response && this.response.status ? this.response.status : null\n };\n };\n return error;\n};\n", "'use strict';\n\nvar enhanceError = require('./enhanceError');\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The created error.\n */\nmodule.exports = function createError(message, config, code, request, response) {\n var error = new Error(message);\n return enhanceError(error, config, code, request, response);\n};\n", "'use strict';\n\nvar createError = require('./createError');\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n */\nmodule.exports = function settle(resolve, reject, response) {\n var validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(createError(\n 'Request failed with status code ' + response.status,\n response.config,\n null,\n response.request,\n response\n ));\n }\n};\n", "'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs support document.cookie\n (function standardBrowserEnv() {\n return {\n write: function write(name, value, expires, path, domain, secure) {\n var cookie = [];\n cookie.push(name + '=' + encodeURIComponent(value));\n\n if (utils.isNumber(expires)) {\n cookie.push('expires=' + new Date(expires).toGMTString());\n }\n\n if (utils.isString(path)) {\n cookie.push('path=' + path);\n }\n\n if (utils.isString(domain)) {\n cookie.push('domain=' + domain);\n }\n\n if (secure === true) {\n cookie.push('secure');\n }\n\n document.cookie = cookie.join('; ');\n },\n\n read: function read(name) {\n var match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove: function remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n };\n })() :\n\n // Non standard browser env (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return {\n write: function write() {},\n read: function read() { return null; },\n remove: function remove() {}\n };\n })()\n);\n", "'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nmodule.exports = function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d\\+\\-\\.]*:)?\\/\\//i.test(url);\n};\n", "'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n * @returns {string} The combined URL\n */\nmodule.exports = function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n", "'use strict';\n\nvar isAbsoluteURL = require('../helpers/isAbsoluteURL');\nvar combineURLs = require('../helpers/combineURLs');\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n * @returns {string} The combined full path\n */\nmodule.exports = function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n};\n", "'use strict';\n\nvar utils = require('./../utils');\n\n// Headers whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nvar ignoreDuplicateOf = [\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n];\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} headers Headers needing to be parsed\n * @returns {Object} Headers parsed into an object\n */\nmodule.exports = function parseHeaders(headers) {\n var parsed = {};\n var key;\n var val;\n var i;\n\n if (!headers) { return parsed; }\n\n utils.forEach(headers.split('\\n'), function parser(line) {\n i = line.indexOf(':');\n key = utils.trim(line.substr(0, i)).toLowerCase();\n val = utils.trim(line.substr(i + 1));\n\n if (key) {\n if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {\n return;\n }\n if (key === 'set-cookie') {\n parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n });\n\n return parsed;\n};\n", "'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs have full support of the APIs needed to test\n // whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n var msie = /(msie|trident)/i.test(navigator.userAgent);\n var urlParsingNode = document.createElement('a');\n var originURL;\n\n /**\n * Parse a URL to discover it's components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n var href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })()\n);\n", "'use strict';\n\n/**\n * A `Cancel` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction Cancel(message) {\n this.message = message;\n}\n\nCancel.prototype.toString = function toString() {\n return 'Cancel' + (this.message ? ': ' + this.message : '');\n};\n\nCancel.prototype.__CANCEL__ = true;\n\nmodule.exports = Cancel;\n", "'use strict';\n\nvar utils = require('./../utils');\nvar settle = require('./../core/settle');\nvar cookies = require('./../helpers/cookies');\nvar buildURL = require('./../helpers/buildURL');\nvar buildFullPath = require('../core/buildFullPath');\nvar parseHeaders = require('./../helpers/parseHeaders');\nvar isURLSameOrigin = require('./../helpers/isURLSameOrigin');\nvar createError = require('../core/createError');\nvar defaults = require('../defaults');\nvar Cancel = require('../cancel/Cancel');\n\nmodule.exports = function xhrAdapter(config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n var requestData = config.data;\n var requestHeaders = config.headers;\n var responseType = config.responseType;\n var onCanceled;\n function done() {\n if (config.cancelToken) {\n config.cancelToken.unsubscribe(onCanceled);\n }\n\n if (config.signal) {\n config.signal.removeEventListener('abort', onCanceled);\n }\n }\n\n if (utils.isFormData(requestData)) {\n delete requestHeaders['Content-Type']; // Let the browser set it\n }\n\n var request = new XMLHttpRequest();\n\n // HTTP basic authentication\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';\n requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);\n }\n\n var fullPath = buildFullPath(config.baseURL, config.url);\n request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);\n\n // Set the request timeout in MS\n request.timeout = config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;\n var responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n var response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config: config,\n request: request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(createError('Request aborted', config, 'ECONNABORTED', request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(createError('Network Error', config, null, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';\n var transitional = config.transitional || defaults.transitional;\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(createError(\n timeoutErrorMessage,\n config,\n transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',\n request));\n\n // Clean up request\n request = null;\n };\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n if (utils.isStandardBrowserEnv()) {\n // Add xsrf header\n var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?\n cookies.read(config.xsrfCookieName) :\n undefined;\n\n if (xsrfValue) {\n requestHeaders[config.xsrfHeaderName] = xsrfValue;\n }\n }\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders, function setRequestHeader(val, key) {\n if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {\n // Remove Content-Type if data is undefined\n delete requestHeaders[key];\n } else {\n // Otherwise add header to the request\n request.setRequestHeader(key, val);\n }\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(config.withCredentials)) {\n request.withCredentials = !!config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = config.responseType;\n }\n\n // Handle progress if needed\n if (typeof config.onDownloadProgress === 'function') {\n request.addEventListener('progress', config.onDownloadProgress);\n }\n\n // Not all browsers support upload events\n if (typeof config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', config.onUploadProgress);\n }\n\n if (config.cancelToken || config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = function(cancel) {\n if (!request) {\n return;\n }\n reject(!cancel || (cancel && cancel.type) ? new Cancel('canceled') : cancel);\n request.abort();\n request = null;\n };\n\n config.cancelToken && config.cancelToken.subscribe(onCanceled);\n if (config.signal) {\n config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n if (!requestData) {\n requestData = null;\n }\n\n // Send the request\n request.send(requestData);\n });\n};\n", "'use strict';\n\nvar utils = require('./utils');\nvar normalizeHeaderName = require('./helpers/normalizeHeaderName');\nvar enhanceError = require('./core/enhanceError');\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = require('./adapters/xhr');\n } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {\n // For node use HTTP adapter\n adapter = require('./adapters/http');\n }\n return adapter;\n}\n\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nvar defaults = {\n\n transitional: {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n },\n\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Accept');\n normalizeHeaderName(headers, 'Content-Type');\n\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {\n setContentTypeIfUnset(headers, 'application/json');\n return stringifySafely(data);\n }\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n var transitional = this.transitional || defaults.transitional;\n var silentJSONParsing = transitional && transitional.silentJSONParsing;\n var forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';\n\n if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw enhanceError(e, this, 'E_JSON_PARSE');\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n", "'use strict';\n\nvar utils = require('./../utils');\nvar defaults = require('./../defaults');\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Object|String} data The data to be transformed\n * @param {Array} headers The headers for the request or response\n * @param {Array|Function} fns A single function or Array of functions\n * @returns {*} The resulting transformed data\n */\nmodule.exports = function transformData(data, headers, fns) {\n var context = this || defaults;\n /*eslint no-param-reassign:0*/\n utils.forEach(fns, function transform(fn) {\n data = fn.call(context, data, headers);\n });\n\n return data;\n};\n", "'use strict';\n\nmodule.exports = function isCancel(value) {\n return !!(value && value.__CANCEL__);\n};\n", "'use strict';\n\nvar utils = require('./../utils');\nvar transformData = require('./transformData');\nvar isCancel = require('../cancel/isCancel');\nvar defaults = require('../defaults');\nvar Cancel = require('../cancel/Cancel');\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new Cancel('canceled');\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n * @returns {Promise} The Promise to be fulfilled\n */\nmodule.exports = function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n // Ensure headers exist\n config.headers = config.headers || {};\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.data,\n config.headers,\n config.transformRequest\n );\n\n // Flatten headers\n config.headers = utils.merge(\n config.headers.common || {},\n config.headers[config.method] || {},\n config.headers\n );\n\n utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n function cleanHeaderConfig(method) {\n delete config.headers[method];\n }\n );\n\n var adapter = config.adapter || defaults.adapter;\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n response.data,\n response.headers,\n config.transformResponse\n );\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n reason.response.data,\n reason.response.headers,\n config.transformResponse\n );\n }\n }\n\n return Promise.reject(reason);\n });\n};\n", "'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n * @returns {Object} New object resulting from merging config2 to config1\n */\nmodule.exports = function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n var config = {};\n\n function getMergedValue(target, source) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge(target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(config1[prop], config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(undefined, config2[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(undefined, config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(prop) {\n if (prop in config2) {\n return getMergedValue(config1[prop], config2[prop]);\n } else if (prop in config1) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n var mergeMap = {\n 'url': valueFromConfig2,\n 'method': valueFromConfig2,\n 'data': valueFromConfig2,\n 'baseURL': defaultToConfig2,\n 'transformRequest': defaultToConfig2,\n 'transformResponse': defaultToConfig2,\n 'paramsSerializer': defaultToConfig2,\n 'timeout': defaultToConfig2,\n 'timeoutMessage': defaultToConfig2,\n 'withCredentials': defaultToConfig2,\n 'adapter': defaultToConfig2,\n 'responseType': defaultToConfig2,\n 'xsrfCookieName': defaultToConfig2,\n 'xsrfHeaderName': defaultToConfig2,\n 'onUploadProgress': defaultToConfig2,\n 'onDownloadProgress': defaultToConfig2,\n 'decompress': defaultToConfig2,\n 'maxContentLength': defaultToConfig2,\n 'maxBodyLength': defaultToConfig2,\n 'transport': defaultToConfig2,\n 'httpAgent': defaultToConfig2,\n 'httpsAgent': defaultToConfig2,\n 'cancelToken': defaultToConfig2,\n 'socketPath': defaultToConfig2,\n 'responseEncoding': defaultToConfig2,\n 'validateStatus': mergeDirectKeys\n };\n\n utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {\n var merge = mergeMap[prop] || mergeDeepProperties;\n var configValue = merge(prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n};\n", "module.exports = {\n \"version\": \"0.24.0\"\n};", "'use strict';\n\nvar VERSION = require('../env/data').version;\n\nvar validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nvar deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return function(value, opt, opts) {\n if (validator === false) {\n throw new Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')));\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\n/**\n * Assert object's properties type\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n var keys = Object.keys(options);\n var i = keys.length;\n while (i-- > 0) {\n var opt = keys[i];\n var validator = schema[opt];\n if (validator) {\n var value = options[opt];\n var result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new TypeError('option ' + opt + ' must be ' + result);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw Error('Unknown option ' + opt);\n }\n }\n}\n\nmodule.exports = {\n assertOptions: assertOptions,\n validators: validators\n};\n", "'use strict';\n\nvar utils = require('./../utils');\nvar buildURL = require('../helpers/buildURL');\nvar InterceptorManager = require('./InterceptorManager');\nvar dispatchRequest = require('./dispatchRequest');\nvar mergeConfig = require('./mergeConfig');\nvar validator = require('../helpers/validator');\n\nvar validators = validator.validators;\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n */\nfunction Axios(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n}\n\n/**\n * Dispatch a request\n *\n * @param {Object} config The config specific for this request (merged with this.defaults)\n */\nAxios.prototype.request = function request(config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof config === 'string') {\n config = arguments[1] || {};\n config.url = arguments[0];\n } else {\n config = config || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n // Set config.method\n if (config.method) {\n config.method = config.method.toLowerCase();\n } else if (this.defaults.method) {\n config.method = this.defaults.method.toLowerCase();\n } else {\n config.method = 'get';\n }\n\n var transitional = config.transitional;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n // filter out skipped interceptors\n var requestInterceptorChain = [];\n var synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n var responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n var promise;\n\n if (!synchronousRequestInterceptors) {\n var chain = [dispatchRequest, undefined];\n\n Array.prototype.unshift.apply(chain, requestInterceptorChain);\n chain = chain.concat(responseInterceptorChain);\n\n promise = Promise.resolve(config);\n while (chain.length) {\n promise = promise.then(chain.shift(), chain.shift());\n }\n\n return promise;\n }\n\n\n var newConfig = config;\n while (requestInterceptorChain.length) {\n var onFulfilled = requestInterceptorChain.shift();\n var onRejected = requestInterceptorChain.shift();\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected(error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest(newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n while (responseInterceptorChain.length) {\n promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());\n }\n\n return promise;\n};\n\nAxios.prototype.getUri = function getUri(config) {\n config = mergeConfig(this.defaults, config);\n return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\\?/, '');\n};\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: data\n }));\n };\n});\n\nmodule.exports = Axios;\n", "'use strict';\n\nvar Cancel = require('./Cancel');\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @class\n * @param {Function} executor The executor function.\n */\nfunction CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(function(cancel) {\n if (!token._listeners) return;\n\n var i;\n var l = token._listeners.length;\n\n for (i = 0; i < l; i++) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = function(onfulfilled) {\n var _resolve;\n // eslint-disable-next-line func-names\n var promise = new Promise(function(resolve) {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new Cancel(message);\n resolvePromise(token.reason);\n });\n}\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nCancelToken.prototype.throwIfRequested = function throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n};\n\n/**\n * Subscribe to the cancel signal\n */\n\nCancelToken.prototype.subscribe = function subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n};\n\n/**\n * Unsubscribe from the cancel signal\n */\n\nCancelToken.prototype.unsubscribe = function unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n var index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n};\n\n/**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\nCancelToken.source = function source() {\n var cancel;\n var token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token: token,\n cancel: cancel\n };\n};\n\nmodule.exports = CancelToken;\n", "'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n * @returns {Function}\n */\nmodule.exports = function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n};\n", "'use strict';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nmodule.exports = function isAxiosError(payload) {\n return (typeof payload === 'object') && (payload.isAxiosError === true);\n};\n", "'use strict';\n\nvar utils = require('./utils');\nvar bind = require('./helpers/bind');\nvar Axios = require('./core/Axios');\nvar mergeConfig = require('./core/mergeConfig');\nvar defaults = require('./defaults');\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n * @return {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nvar axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.Cancel = require('./cancel/Cancel');\naxios.CancelToken = require('./cancel/CancelToken');\naxios.isCancel = require('./cancel/isCancel');\naxios.VERSION = require('./env/data').version;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\naxios.spread = require('./helpers/spread');\n\n// Expose isAxiosError\naxios.isAxiosError = require('./helpers/isAxiosError');\n\nmodule.exports = axios;\n\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = axios;\n", "module.exports = require('./lib/axios');", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.API = exports.APIPath = void 0;\n/*\n http.ts\n handles http interactions with the engine's configuration server.\n*/\nconst blackbox_1 = require(\"../../blackbox\");\nconst axios_1 = __importDefault(require(\"axios\"));\nvar APIPath;\n(function (APIPath) {\n APIPath[\"StatusItems\"] = \"/api/status-items\";\n APIPath[\"InfoLogs\"] = \"/api/info-logs/\";\n APIPath[\"Pallet\"] = \"/api/pallet/\";\n APIPath[\"Machine\"] = \"/api/machine/\";\n APIPath[\"CoreAppConfig\"] = \"/api/app-config\";\n APIPath[\"VRDFConfig\"] = \"/api/vrdf\";\n APIPath[\"CoreIOConfig\"] = \"/api/io-config\";\n APIPath[\"GripperConfig\"] = \"/api/gripper-config\";\n APIPath[\"SKUSpecific\"] = \"/api/sku-specific\";\n APIPath[\"CoreLogs\"] = \"/api/core-logs\";\n APIPath[\"SAPIConfig\"] = \"/api/sapi/config.js/\";\n APIPath[\"Generic\"] = \"/api/json/\";\n APIPath[\"Pack\"] = \"/api/pack/\";\n APIPath[\"Queue\"] = \"/api/queue/\";\n APIPath[\"Command\"] = \"/api/command/\";\n APIPath[\"Collections\"] = \"/api/collections/\";\n})(APIPath = exports.APIPath || (exports.APIPath = {}));\nclass _Queue {\n constructor(base) {\n this.base = base;\n }\n delete(pID) {\n return axios_1.default.delete(this.base + APIPath.Queue + String(void 0 !== pID ? pID : ''));\n }\n async get(pID) {\n return axios_1.default\n .get(this.base + APIPath.Queue + String(void 0 !== pID ? pID : ''))\n .then(function (pResponse) {\n if (void 0 === pID)\n return pResponse.data;\n return pResponse.data;\n });\n }\n async patch(pID, pPartialItem) {\n return axios_1.default.patch(this.base + APIPath.Queue + String(pID), pPartialItem);\n }\n async put(pStackQueueItem, pID) {\n const lIdStr = String(void 0 !== pID ? pID : -1);\n return axios_1.default.put(this.base + APIPath.Queue + lIdStr, pStackQueueItem);\n }\n async post(pStackQueue) {\n return axios_1.default.post(this.base + APIPath.Queue, pStackQueue);\n }\n}\nclass _Collections {\n constructor(base) {\n this.base = base;\n }\n async post(pCollection) {\n return axios_1.default.post(this.base + APIPath.Collections, { config: pCollection });\n }\n async deploy(pCollectionId, pSystemIps) {\n return axios_1.default.post(this.base + APIPath.Collections + pCollectionId, pSystemIps);\n }\n async edit(pCollection, id) {\n return axios_1.default.put(this.base + APIPath.Collections + id, {\n config: pCollection,\n });\n }\n async get() {\n return axios_1.default\n .get(this.base + APIPath.Collections)\n .then((pRes) => {\n return pRes.data;\n });\n }\n async getCollection(id) {\n return axios_1.default\n .get(this.base + APIPath.Collections + id)\n .then((pRes) => {\n return pRes.data;\n });\n }\n async delete(id) {\n return axios_1.default\n .delete(this.base + APIPath.Collections + id)\n .then((pRes) => {\n return pRes.data;\n });\n }\n}\nclass _Generic {\n constructor(base) {\n this.base = base;\n }\n async get(...pArgs) {\n const lFlattenedArgs = pArgs.flat();\n return axios_1.default\n .get(this.base + APIPath.Generic, {\n params: { keys: lFlattenedArgs },\n })\n .then((pRes) => {\n return pRes.data;\n });\n }\n async getRobotConfig() {\n return this.get('preferences').then(function (pData) {\n if (pData['robot_configurations'])\n return JSON.parse(pData['robot_configurations']);\n return void 0;\n });\n }\n set(pKeys = [], pData) {\n return axios_1.default.put(this.base + APIPath.Generic, pData, {\n params: { keys: pKeys },\n });\n }\n}\nclass _Pack {\n constructor(base) {\n this.base = base;\n }\n async pack(PL, PW, BL, BW) {\n PL = Math.round(PL);\n PW = Math.round(PW);\n BL = Math.round(BL);\n BW = Math.round(BW);\n return axios_1.default\n .get(this.base + APIPath.Pack, { params: { PL, PW, BL, BW } })\n .then((res) => {\n return res.data;\n });\n }\n}\nclass _Pallet {\n constructor(base) {\n this.base = base;\n }\n _gen_cf(config) {\n let cf = config;\n // let [acts, _] = generateStandardPath(config, machine_config);\n // cf.Actions = acts;\n cf.Actions = [];\n delete cf.name;\n return cf;\n }\n update(config) {\n const cf = this._gen_cf(config);\n return axios_1.default.put(this.base + APIPath.Pallet, cf);\n }\n delete() {\n return axios_1.default.delete(this.base + APIPath.Pallet);\n }\n async get() {\n return axios_1.default.get(this.base + APIPath.Pallet).then((res) => {\n return blackbox_1.PalletConfigObj.from(res.data);\n });\n }\n}\nclass _CoreAppConfig {\n constructor(base) {\n this.base = base;\n }\n async get() {\n return axios_1.default\n .get(this.base + APIPath.CoreAppConfig)\n .then((r) => {\n return r.data;\n });\n }\n async update(config) {\n return axios_1.default.put(this.base + APIPath.CoreAppConfig, config);\n }\n}\nclass _VRDFConfig {\n constructor(base) {\n this.base = base;\n }\n async get() {\n return axios_1.default\n .get(this.base + APIPath.VRDFConfig)\n .then((r) => {\n return r.data;\n });\n }\n async update(config) {\n return axios_1.default.put(this.base + APIPath.VRDFConfig, config);\n }\n}\nclass _CoreIOConfig {\n constructor(base) {\n this.base = base;\n }\n async get() {\n return axios_1.default\n .get(this.base + APIPath.CoreIOConfig)\n .then((r) => {\n return r.data;\n });\n }\n async update(config) {\n return axios_1.default.put(this.base + APIPath.CoreIOConfig, config);\n }\n}\nclass _GripperConfig {\n constructor(base) {\n this.base = base;\n }\n async get() {\n return axios_1.default\n .get(this.base + APIPath.GripperConfig)\n .then((r) => {\n return r.data;\n });\n }\n async update(config) {\n return axios_1.default.put(this.base + APIPath.GripperConfig, config);\n }\n}\nclass _Machine {\n constructor(base) {\n this.base = base;\n }\n async get() {\n return axios_1.default.get(this.base + APIPath.Machine).then((r) => {\n return r.data;\n });\n }\n update(config) {\n return axios_1.default.put(this.base + APIPath.Machine, config);\n }\n}\nclass _SKUSpecific {\n constructor(base) {\n this.base = base;\n }\n async get() {\n return axios_1.default\n .get(this.base + APIPath.SKUSpecific)\n .then((r) => {\n return r.data;\n });\n }\n async update(config) {\n return axios_1.default.put(this.base + APIPath.SKUSpecific, config);\n }\n async delete(id) {\n return axios_1.default.delete(this.base + APIPath.SKUSpecific + '/' + id);\n }\n}\nclass _CoreLogs {\n constructor(base) {\n this.base = base;\n }\n async get() {\n return axios_1.default.get(this.base + APIPath.CoreLogs).then((r) => {\n return r.data;\n });\n }\n}\nclass _InfoLogs {\n constructor(base) {\n this.base = base;\n }\n async get() {\n return axios_1.default.get(this.base + APIPath.InfoLogs).then((r) => {\n return r.data;\n });\n }\n push(item) {\n return axios_1.default.post(this.base + APIPath.InfoLogs, item);\n }\n}\nclass _StatusItems {\n constructor(base) {\n this.base = base;\n }\n async get() {\n return axios_1.default\n .get(this.base + APIPath.StatusItems)\n .then((r) => {\n return r.data;\n });\n }\n push(items) {\n return axios_1.default.post(this.base + APIPath.StatusItems, items);\n }\n}\nclass _Commands {\n constructor(base) {\n this.base = base;\n }\n async send(data) {\n return axios_1.default.post(this.base + APIPath.Command, data);\n }\n}\nclass API {\n constructor(host, port = 8001) {\n this.webDeployment = undefined != host.match(/palletizer.vention.io/);\n if (port === 0)\n this.webDeployment = true;\n const base = this.webDeployment\n ? `https://${host}`\n : `http://${host}:${port}`;\n this.Pallet = new _Pallet(base);\n this.Machine = new _Machine(base);\n this.CoreAppConfig = new _CoreAppConfig(base);\n this.VRDFConfig = new _VRDFConfig(base);\n this.GripperConfig = new _GripperConfig(base);\n this.SKUSpecific = new _SKUSpecific(base);\n this.CoreLogs = new _CoreLogs(base);\n this.CoreIOConfig = new _CoreIOConfig(base);\n this.Pack = new _Pack(base);\n this.Generic = new _Generic(base);\n this.Queue = new _Queue(base);\n this.Collections = new _Collections(base);\n this.InfoLogs = new _InfoLogs(base);\n this.StatusItems = new _StatusItems(base);\n this.Commands = new _Commands(base);\n }\n isWebDeployment() {\n return this.webDeployment;\n }\n}\nexports.API = API;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.join_args = void 0;\nfunction join_args(...args) {\n const str = args\n .map(x => {\n // Avoid adding extra \\\" chars if we're just dealing with strings\n if (typeof x == 'string') {\n return x;\n }\n try {\n return JSON.stringify(x);\n }\n catch {\n return x.toString();\n }\n })\n .join(' ');\n return str;\n}\nexports.join_args = join_args;\n", "'use strict';\n\nvar domain;\n\n// This constructor is used to store event handlers. Instantiating this is\n// faster than explicitly calling `Object.create(null)` to get a \"clean\" empty\n// object (tested with v8 v4.9).\nfunction EventHandlers() {}\nEventHandlers.prototype = Object.create(null);\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nexport default EventEmitter;\nexport {EventEmitter};\n\n// nodejs oddity\n// require('events') === require('events').EventEmitter\nEventEmitter.EventEmitter = EventEmitter\n\nEventEmitter.usingDomains = false;\n\nEventEmitter.prototype.domain = undefined;\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\nEventEmitter.init = function() {\n this.domain = null;\n if (EventEmitter.usingDomains) {\n // if there is an active domain, then attach to it.\n if (domain.active && !(this instanceof domain.Domain)) {\n this.domain = domain.active;\n }\n }\n\n if (!this._events || this._events === Object.getPrototypeOf(this)._events) {\n this._events = new EventHandlers();\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || isNaN(n))\n throw new TypeError('\"n\" argument must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nfunction $getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return $getMaxListeners(this);\n};\n\n// These standalone emit* functions are used to optimize calling of event\n// handlers for fast cases because emit() itself often has a variable number of\n// arguments and can be deoptimized because of that. These functions always have\n// the same number of arguments and thus do not get deoptimized, so the code\n// inside them can execute faster.\nfunction emitNone(handler, isFn, self) {\n if (isFn)\n handler.call(self);\n else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n listeners[i].call(self);\n }\n}\nfunction emitOne(handler, isFn, self, arg1) {\n if (isFn)\n handler.call(self, arg1);\n else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n listeners[i].call(self, arg1);\n }\n}\nfunction emitTwo(handler, isFn, self, arg1, arg2) {\n if (isFn)\n handler.call(self, arg1, arg2);\n else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n listeners[i].call(self, arg1, arg2);\n }\n}\nfunction emitThree(handler, isFn, self, arg1, arg2, arg3) {\n if (isFn)\n handler.call(self, arg1, arg2, arg3);\n else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n listeners[i].call(self, arg1, arg2, arg3);\n }\n}\n\nfunction emitMany(handler, isFn, self, args) {\n if (isFn)\n handler.apply(self, args);\n else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n listeners[i].apply(self, args);\n }\n}\n\nEventEmitter.prototype.emit = function emit(type) {\n var er, handler, len, args, i, events, domain;\n var needDomainExit = false;\n var doError = (type === 'error');\n\n events = this._events;\n if (events)\n doError = (doError && events.error == null);\n else if (!doError)\n return false;\n\n domain = this.domain;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n er = arguments[1];\n if (domain) {\n if (!er)\n er = new Error('Uncaught, unspecified \"error\" event');\n er.domainEmitter = this;\n er.domain = domain;\n er.domainThrown = false;\n domain.emit('error', er);\n } else if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n return false;\n }\n\n handler = events[type];\n\n if (!handler)\n return false;\n\n var isFn = typeof handler === 'function';\n len = arguments.length;\n switch (len) {\n // fast cases\n case 1:\n emitNone(handler, isFn, this);\n break;\n case 2:\n emitOne(handler, isFn, this, arguments[1]);\n break;\n case 3:\n emitTwo(handler, isFn, this, arguments[1], arguments[2]);\n break;\n case 4:\n emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);\n break;\n // slower\n default:\n args = new Array(len - 1);\n for (i = 1; i < len; i++)\n args[i - 1] = arguments[i];\n emitMany(handler, isFn, this, args);\n }\n\n if (needDomainExit)\n domain.exit();\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n if (typeof listener !== 'function')\n throw new TypeError('\"listener\" argument must be a function');\n\n events = target._events;\n if (!events) {\n events = target._events = new EventHandlers();\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (!existing) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] = prepend ? [listener, existing] :\n [existing, listener];\n } else {\n // If we've already got an array, just append.\n if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n }\n\n // Check for listener leak\n if (!existing.warned) {\n m = $getMaxListeners(target);\n if (m && m > 0 && existing.length > m) {\n existing.warned = true;\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + type + ' listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n emitWarning(w);\n }\n }\n }\n\n return target;\n}\nfunction emitWarning(e) {\n typeof console.warn === 'function' ? console.warn(e) : console.log(e);\n}\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction _onceWrap(target, type, listener) {\n var fired = false;\n function g() {\n target.removeListener(type, g);\n if (!fired) {\n fired = true;\n listener.apply(target, arguments);\n }\n }\n g.listener = listener;\n return g;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n if (typeof listener !== 'function')\n throw new TypeError('\"listener\" argument must be a function');\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n if (typeof listener !== 'function')\n throw new TypeError('\"listener\" argument must be a function');\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n if (typeof listener !== 'function')\n throw new TypeError('\"listener\" argument must be a function');\n\n events = this._events;\n if (!events)\n return this;\n\n list = events[type];\n if (!list)\n return this;\n\n if (list === listener || (list.listener && list.listener === listener)) {\n if (--this._eventsCount === 0)\n this._events = new EventHandlers();\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list[0] = undefined;\n if (--this._eventsCount === 0) {\n this._events = new EventHandlers();\n return this;\n } else {\n delete events[type];\n }\n } else {\n spliceOne(list, position);\n }\n\n if (events.removeListener)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events;\n\n events = this._events;\n if (!events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!events.removeListener) {\n if (arguments.length === 0) {\n this._events = new EventHandlers();\n this._eventsCount = 0;\n } else if (events[type]) {\n if (--this._eventsCount === 0)\n this._events = new EventHandlers();\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n for (var i = 0, key; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = new EventHandlers();\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n do {\n this.removeListener(type, listeners[listeners.length - 1]);\n } while (listeners[0]);\n }\n\n return this;\n };\n\nEventEmitter.prototype.listeners = function listeners(type) {\n var evlistener;\n var ret;\n var events = this._events;\n\n if (!events)\n ret = [];\n else {\n evlistener = events[type];\n if (!evlistener)\n ret = [];\n else if (typeof evlistener === 'function')\n ret = [evlistener.listener || evlistener];\n else\n ret = unwrapListeners(evlistener);\n }\n\n return ret;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];\n};\n\n// About 1.5x faster than the two-arg version of Array#splice().\nfunction spliceOne(list, index) {\n for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)\n list[i] = list[k];\n list.pop();\n}\n\nfunction arrayClone(arr, i) {\n var copy = new Array(i);\n while (i--)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n", "\nconst polyfill = require('events')\n\nif (polyfill && polyfill.default) {\n module.exports = polyfill.default\n for (let k in polyfill) {\n module.exports[k] = polyfill[k]\n }\n} else if (polyfill) {\n module.exports = polyfill\n}\n\n\n", "module.exports = extend\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nfunction extend() {\n var target = {}\n\n for (var i = 0; i < arguments.length; i++) {\n var source = arguments[i]\n\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n target[key] = source[key]\n }\n }\n }\n\n return target\n}\n", "module.exports = require('events').EventEmitter;\n", "var lookup = [];\nvar revLookup = [];\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;\nvar inited = false;\nfunction init () {\n inited = true;\n var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n for (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i];\n revLookup[code.charCodeAt(i)] = i;\n }\n\n revLookup['-'.charCodeAt(0)] = 62;\n revLookup['_'.charCodeAt(0)] = 63;\n}\n\nfunction toByteArray (b64) {\n if (!inited) {\n init();\n }\n var i, j, l, tmp, placeHolders, arr;\n var len = b64.length;\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // the number of equal signs (place holders)\n // if there are two placeholders, than the two characters before it\n // represent one byte\n // if there is only one, then the three characters before it represent 2 bytes\n // this is just a cheap hack to not do indexOf twice\n placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;\n\n // base64 is 4/3 + up to two characters of the original data\n arr = new Arr(len * 3 / 4 - placeHolders);\n\n // if there are placeholders, only get up to the last complete 4 chars\n l = placeHolders > 0 ? len - 4 : len;\n\n var L = 0;\n\n for (i = 0, j = 0; i < l; i += 4, j += 3) {\n tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];\n arr[L++] = (tmp >> 16) & 0xFF;\n arr[L++] = (tmp >> 8) & 0xFF;\n arr[L++] = tmp & 0xFF;\n }\n\n if (placeHolders === 2) {\n tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);\n arr[L++] = tmp & 0xFF;\n } else if (placeHolders === 1) {\n tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);\n arr[L++] = (tmp >> 8) & 0xFF;\n arr[L++] = tmp & 0xFF;\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp;\n var output = [];\n for (var i = start; i < end; i += 3) {\n tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);\n output.push(tripletToBase64(tmp));\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n if (!inited) {\n init();\n }\n var tmp;\n var len = uint8.length;\n var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes\n var output = '';\n var parts = [];\n var maxChunkLength = 16383; // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1];\n output += lookup[tmp >> 2];\n output += lookup[(tmp << 4) & 0x3F];\n output += '==';\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);\n output += lookup[tmp >> 10];\n output += lookup[(tmp >> 4) & 0x3F];\n output += lookup[(tmp << 2) & 0x3F];\n output += '=';\n }\n\n parts.push(output);\n\n return parts.join('')\n}\n\nfunction read (buffer, offset, isLE, mLen, nBytes) {\n var e, m;\n var eLen = nBytes * 8 - mLen - 1;\n var eMax = (1 << eLen) - 1;\n var eBias = eMax >> 1;\n var nBits = -7;\n var i = isLE ? (nBytes - 1) : 0;\n var d = isLE ? -1 : 1;\n var s = buffer[offset + i];\n\n i += d;\n\n e = s & ((1 << (-nBits)) - 1);\n s >>= (-nBits);\n nBits += eLen;\n for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1);\n e >>= (-nBits);\n nBits += mLen;\n for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias;\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen);\n e = e - eBias;\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nfunction write (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c;\n var eLen = nBytes * 8 - mLen - 1;\n var eMax = (1 << eLen) - 1;\n var eBias = eMax >> 1;\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);\n var i = isLE ? 0 : (nBytes - 1);\n var d = isLE ? 1 : -1;\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;\n\n value = Math.abs(value);\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0;\n e = eMax;\n } else {\n e = Math.floor(Math.log(value) / Math.LN2);\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--;\n c *= 2;\n }\n if (e + eBias >= 1) {\n value += rt / c;\n } else {\n value += rt * Math.pow(2, 1 - eBias);\n }\n if (value * c >= 2) {\n e++;\n c /= 2;\n }\n\n if (e + eBias >= eMax) {\n m = 0;\n e = eMax;\n } else if (e + eBias >= 1) {\n m = (value * c - 1) * Math.pow(2, mLen);\n e = e + eBias;\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);\n e = 0;\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m;\n eLen += mLen;\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128;\n}\n\nvar toString = {}.toString;\n\nvar isArray = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n\n/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\nvar INSPECT_MAX_BYTES = 50;\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : true;\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nvar _kMaxLength = kMaxLength();\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length);\n that.__proto__ = Buffer.prototype;\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length);\n }\n that.length = length;\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192; // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype;\n return arr\n};\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n};\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype;\n Buffer.__proto__ = Uint8Array;\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size);\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n};\n\nfunction allocUnsafe (that, size) {\n assertSize(size);\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0;\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n};\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n};\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8';\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0;\n that = createBuffer(that, length);\n\n var actual = that.write(string, encoding);\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual);\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0;\n that = createBuffer(that, length);\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255;\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength; // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array);\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset);\n } else {\n array = new Uint8Array(array, byteOffset, length);\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array;\n that.__proto__ = Buffer.prototype;\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array);\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (internalIsBuffer(obj)) {\n var len = checked(obj.length) | 0;\n that = createBuffer(that, len);\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len);\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0;\n }\n return Buffer.alloc(+length)\n}\nBuffer.isBuffer = isBuffer;\nfunction internalIsBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!internalIsBuffer(a) || !internalIsBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length;\n var y = b.length;\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i];\n y = b[i];\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n};\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n};\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i;\n if (length === undefined) {\n length = 0;\n for (i = 0; i < list.length; ++i) {\n length += list[i].length;\n }\n }\n\n var buffer = Buffer.allocUnsafe(length);\n var pos = 0;\n for (i = 0; i < list.length; ++i) {\n var buf = list[i];\n if (!internalIsBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos);\n pos += buf.length;\n }\n return buffer\n};\n\nfunction byteLength (string, encoding) {\n if (internalIsBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string;\n }\n\n var len = string.length;\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false;\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase();\n loweredCase = true;\n }\n }\n}\nBuffer.byteLength = byteLength;\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false;\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0;\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length;\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0;\n start >>>= 0;\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8';\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase();\n loweredCase = true;\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true;\n\nfunction swap (b, n, m) {\n var i = b[n];\n b[n] = b[m];\n b[m] = i;\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length;\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1);\n }\n return this\n};\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length;\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3);\n swap(this, i + 1, i + 2);\n }\n return this\n};\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length;\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7);\n swap(this, i + 1, i + 6);\n swap(this, i + 2, i + 5);\n swap(this, i + 3, i + 4);\n }\n return this\n};\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0;\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n};\n\nBuffer.prototype.equals = function equals (b) {\n if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n};\n\nBuffer.prototype.inspect = function inspect () {\n var str = '';\n var max = INSPECT_MAX_BYTES;\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');\n if (this.length > max) str += ' ... ';\n }\n return ''\n};\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!internalIsBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0;\n }\n if (end === undefined) {\n end = target ? target.length : 0;\n }\n if (thisStart === undefined) {\n thisStart = 0;\n }\n if (thisEnd === undefined) {\n thisEnd = this.length;\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0;\n end >>>= 0;\n thisStart >>>= 0;\n thisEnd >>>= 0;\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart;\n var y = end - start;\n var len = Math.min(x, y);\n\n var thisCopy = this.slice(thisStart, thisEnd);\n var targetCopy = target.slice(start, end);\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i];\n y = targetCopy[i];\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n};\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset;\n byteOffset = 0;\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff;\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000;\n }\n byteOffset = +byteOffset; // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1);\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset;\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1;\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0;\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding);\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (internalIsBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF; // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1;\n var arrLength = arr.length;\n var valLength = val.length;\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase();\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2;\n arrLength /= 2;\n valLength /= 2;\n byteOffset /= 2;\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i;\n if (dir) {\n var foundIndex = -1;\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i;\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex;\n foundIndex = -1;\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;\n for (i = byteOffset; i >= 0; i--) {\n var found = true;\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false;\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n};\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n};\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n};\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0;\n var remaining = buf.length - offset;\n if (!length) {\n length = remaining;\n } else {\n length = Number(length);\n if (length > remaining) {\n length = remaining;\n }\n }\n\n // must be an even number of digits\n var strLen = string.length;\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2;\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16);\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed;\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8';\n length = this.length;\n offset = 0;\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset;\n length = this.length;\n offset = 0;\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0;\n if (isFinite(length)) {\n length = length | 0;\n if (encoding === undefined) encoding = 'utf8';\n } else {\n encoding = length;\n length = undefined;\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset;\n if (length === undefined || length > remaining) length = remaining;\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8';\n\n var loweredCase = false;\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase();\n loweredCase = true;\n }\n }\n};\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n};\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return fromByteArray(buf)\n } else {\n return fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end);\n var res = [];\n\n var i = start;\n while (i < end) {\n var firstByte = buf[i];\n var codePoint = null;\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1;\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint;\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte;\n }\n break\n case 2:\n secondByte = buf[i + 1];\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint;\n }\n }\n break\n case 3:\n secondByte = buf[i + 1];\n thirdByte = buf[i + 2];\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint;\n }\n }\n break\n case 4:\n secondByte = buf[i + 1];\n thirdByte = buf[i + 2];\n fourthByte = buf[i + 3];\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint;\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD;\n bytesPerSequence = 1;\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000;\n res.push(codePoint >>> 10 & 0x3FF | 0xD800);\n codePoint = 0xDC00 | codePoint & 0x3FF;\n }\n\n res.push(codePoint);\n i += bytesPerSequence;\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000;\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length;\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = '';\n var i = 0;\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n );\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = '';\n end = Math.min(buf.length, end);\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F);\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = '';\n end = Math.min(buf.length, end);\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i]);\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length;\n\n if (!start || start < 0) start = 0;\n if (!end || end < 0 || end > len) end = len;\n\n var out = '';\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i]);\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end);\n var res = '';\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length;\n start = ~~start;\n end = end === undefined ? len : ~~end;\n\n if (start < 0) {\n start += len;\n if (start < 0) start = 0;\n } else if (start > len) {\n start = len;\n }\n\n if (end < 0) {\n end += len;\n if (end < 0) end = 0;\n } else if (end > len) {\n end = len;\n }\n\n if (end < start) end = start;\n\n var newBuf;\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end);\n newBuf.__proto__ = Buffer.prototype;\n } else {\n var sliceLen = end - start;\n newBuf = new Buffer(sliceLen, undefined);\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start];\n }\n }\n\n return newBuf\n};\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0;\n byteLength = byteLength | 0;\n if (!noAssert) checkOffset(offset, byteLength, this.length);\n\n var val = this[offset];\n var mul = 1;\n var i = 0;\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul;\n }\n\n return val\n};\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0;\n byteLength = byteLength | 0;\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length);\n }\n\n var val = this[offset + --byteLength];\n var mul = 1;\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul;\n }\n\n return val\n};\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length);\n return this[offset]\n};\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length);\n return this[offset] | (this[offset + 1] << 8)\n};\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length);\n return (this[offset] << 8) | this[offset + 1]\n};\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length);\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n};\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length);\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n};\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0;\n byteLength = byteLength | 0;\n if (!noAssert) checkOffset(offset, byteLength, this.length);\n\n var val = this[offset];\n var mul = 1;\n var i = 0;\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul;\n }\n mul *= 0x80;\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength);\n\n return val\n};\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0;\n byteLength = byteLength | 0;\n if (!noAssert) checkOffset(offset, byteLength, this.length);\n\n var i = byteLength;\n var mul = 1;\n var val = this[offset + --i];\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul;\n }\n mul *= 0x80;\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength);\n\n return val\n};\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length);\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n};\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length);\n var val = this[offset] | (this[offset + 1] << 8);\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n};\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length);\n var val = this[offset + 1] | (this[offset] << 8);\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n};\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length);\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n};\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length);\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n};\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length);\n return read(this, offset, true, 23, 4)\n};\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length);\n return read(this, offset, false, 23, 4)\n};\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length);\n return read(this, offset, true, 52, 8)\n};\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length);\n return read(this, offset, false, 52, 8)\n};\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!internalIsBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value;\n offset = offset | 0;\n byteLength = byteLength | 0;\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1;\n checkInt(this, value, offset, byteLength, maxBytes, 0);\n }\n\n var mul = 1;\n var i = 0;\n this[offset] = value & 0xFF;\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF;\n }\n\n return offset + byteLength\n};\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value;\n offset = offset | 0;\n byteLength = byteLength | 0;\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1;\n checkInt(this, value, offset, byteLength, maxBytes, 0);\n }\n\n var i = byteLength - 1;\n var mul = 1;\n this[offset + i] = value & 0xFF;\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF;\n }\n\n return offset + byteLength\n};\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);\n this[offset] = (value & 0xff);\n return offset + 1\n};\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1;\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8;\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff);\n this[offset + 1] = (value >>> 8);\n } else {\n objectWriteUInt16(this, value, offset, true);\n }\n return offset + 2\n};\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8);\n this[offset + 1] = (value & 0xff);\n } else {\n objectWriteUInt16(this, value, offset, false);\n }\n return offset + 2\n};\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1;\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24);\n this[offset + 2] = (value >>> 16);\n this[offset + 1] = (value >>> 8);\n this[offset] = (value & 0xff);\n } else {\n objectWriteUInt32(this, value, offset, true);\n }\n return offset + 4\n};\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24);\n this[offset + 1] = (value >>> 16);\n this[offset + 2] = (value >>> 8);\n this[offset + 3] = (value & 0xff);\n } else {\n objectWriteUInt32(this, value, offset, false);\n }\n return offset + 4\n};\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1);\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit);\n }\n\n var i = 0;\n var mul = 1;\n var sub = 0;\n this[offset] = value & 0xFF;\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1;\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;\n }\n\n return offset + byteLength\n};\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1);\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit);\n }\n\n var i = byteLength - 1;\n var mul = 1;\n var sub = 0;\n this[offset + i] = value & 0xFF;\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1;\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;\n }\n\n return offset + byteLength\n};\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);\n if (value < 0) value = 0xff + value + 1;\n this[offset] = (value & 0xff);\n return offset + 1\n};\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff);\n this[offset + 1] = (value >>> 8);\n } else {\n objectWriteUInt16(this, value, offset, true);\n }\n return offset + 2\n};\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8);\n this[offset + 1] = (value & 0xff);\n } else {\n objectWriteUInt16(this, value, offset, false);\n }\n return offset + 2\n};\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff);\n this[offset + 1] = (value >>> 8);\n this[offset + 2] = (value >>> 16);\n this[offset + 3] = (value >>> 24);\n } else {\n objectWriteUInt32(this, value, offset, true);\n }\n return offset + 4\n};\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);\n if (value < 0) value = 0xffffffff + value + 1;\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24);\n this[offset + 1] = (value >>> 16);\n this[offset + 2] = (value >>> 8);\n this[offset + 3] = (value & 0xff);\n } else {\n objectWriteUInt32(this, value, offset, false);\n }\n return offset + 4\n};\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4);\n }\n write(buf, value, offset, littleEndian, 23, 4);\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n};\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n};\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8);\n }\n write(buf, value, offset, littleEndian, 52, 8);\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n};\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n};\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0;\n if (!end && end !== 0) end = this.length;\n if (targetStart >= target.length) targetStart = target.length;\n if (!targetStart) targetStart = 0;\n if (end > 0 && end < start) end = start;\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length;\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start;\n }\n\n var len = end - start;\n var i;\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start];\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start];\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n );\n }\n\n return len\n};\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start;\n start = 0;\n end = this.length;\n } else if (typeof end === 'string') {\n encoding = end;\n end = this.length;\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0);\n if (code < 256) {\n val = code;\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255;\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0;\n end = end === undefined ? this.length : end >>> 0;\n\n if (!val) val = 0;\n\n var i;\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val;\n }\n } else {\n var bytes = internalIsBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString());\n var len = bytes.length;\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len];\n }\n }\n\n return this\n};\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g;\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '');\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '=';\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity;\n var codePoint;\n var length = string.length;\n var leadSurrogate = null;\n var bytes = [];\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i);\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint;\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n leadSurrogate = codePoint;\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n }\n\n leadSurrogate = null;\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint);\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n );\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n );\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n );\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = [];\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF);\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo;\n var byteArray = [];\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i);\n hi = c >> 8;\n lo = c % 256;\n byteArray.push(lo);\n byteArray.push(hi);\n }\n\n return byteArray\n}\n\n\nfunction base64ToBytes (str) {\n return toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i];\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n\n\n// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nfunction isBuffer(obj) {\n return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))\n}\n\nfunction isFastBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))\n}\n\nexport { Buffer, INSPECT_MAX_BYTES, SlowBuffer, isBuffer, _kMaxLength as kMaxLength };\n", "\nconst polyfill = require('buffer')\n\nif (polyfill && polyfill.default) {\n module.exports = polyfill.default\n for (let k in polyfill) {\n module.exports[k] = polyfill[k]\n }\n} else if (polyfill) {\n module.exports = polyfill\n}\n\n\n", "// shim for using process in browser\n// based off https://github.com/defunctzombie/node-process/blob/master/browser.js\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\nvar cachedSetTimeout = defaultSetTimout;\nvar cachedClearTimeout = defaultClearTimeout;\nif (typeof global.setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n}\nif (typeof global.clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n}\n\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // 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\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // 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.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\nfunction nextTick(fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n}\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nvar title = 'browser';\nvar platform = 'browser';\nvar browser = true;\nvar env = {};\nvar argv = [];\nvar version = ''; // empty string to avoid regexp issues\nvar versions = {};\nvar release = {};\nvar config = {};\n\nfunction noop() {}\n\nvar on = noop;\nvar addListener = noop;\nvar once = noop;\nvar off = noop;\nvar removeListener = noop;\nvar removeAllListeners = noop;\nvar emit = noop;\n\nfunction binding(name) {\n throw new Error('process.binding is not supported');\n}\n\nfunction cwd () { return '/' }\nfunction chdir (dir) {\n throw new Error('process.chdir is not supported');\n}function umask() { return 0; }\n\n// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js\nvar performance = global.performance || {};\nvar performanceNow =\n performance.now ||\n performance.mozNow ||\n performance.msNow ||\n performance.oNow ||\n performance.webkitNow ||\n function(){ return (new Date()).getTime() };\n\n// generate timestamp or delta\n// see http://nodejs.org/api/process.html#process_process_hrtime\nfunction hrtime(previousTimestamp){\n var clocktime = performanceNow.call(performance)*1e-3;\n var seconds = Math.floor(clocktime);\n var nanoseconds = Math.floor((clocktime%1)*1e9);\n if (previousTimestamp) {\n seconds = seconds - previousTimestamp[0];\n nanoseconds = nanoseconds - previousTimestamp[1];\n if (nanoseconds<0) {\n seconds--;\n nanoseconds += 1e9;\n }\n }\n return [seconds,nanoseconds]\n}\n\nvar startTime = new Date();\nfunction uptime() {\n var currentTime = new Date();\n var dif = currentTime - startTime;\n return dif / 1000;\n}\n\nvar browser$1 = {\n nextTick: nextTick,\n title: title,\n browser: browser,\n env: env,\n argv: argv,\n version: version,\n versions: versions,\n on: on,\n addListener: addListener,\n once: once,\n off: off,\n removeListener: removeListener,\n removeAllListeners: removeAllListeners,\n emit: emit,\n binding: binding,\n cwd: cwd,\n chdir: chdir,\n umask: umask,\n hrtime: hrtime,\n platform: platform,\n release: release,\n config: config,\n uptime: uptime\n};\n\nexport default browser$1;\nexport { addListener, argv, binding, browser, chdir, config, cwd, emit, env, hrtime, nextTick, off, on, once, platform, release, removeAllListeners, removeListener, title, umask, uptime, version, versions };\n", "\nvar inherits;\nif (typeof Object.create === 'function'){\n inherits = function inherits(ctor, superCtor) {\n // implementation from standard node.js 'util' module\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n inherits = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\nexport default inherits;\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\nimport process from 'process';\nvar formatRegExp = /%[sdj%]/g;\nexport function format(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexport function deprecate(fn, msg) {\n // Allow for deprecating things in the process of starting up.\n if (isUndefined(global.process)) {\n return function() {\n return deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n if (process.noDeprecation === true) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnviron;\nexport function debuglog(set) {\n if (isUndefined(debugEnviron))\n debugEnviron = process.env.NODE_DEBUG || '';\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (new RegExp('\\\\b' + set + '\\\\b', 'i').test(debugEnviron)) {\n var pid = 0;\n debugs[set] = function() {\n var msg = format.apply(null, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nexport function inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n _extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nexport function isArray(ar) {\n return Array.isArray(ar);\n}\n\nexport function isBoolean(arg) {\n return typeof arg === 'boolean';\n}\n\nexport function isNull(arg) {\n return arg === null;\n}\n\nexport function isNullOrUndefined(arg) {\n return arg == null;\n}\n\nexport function isNumber(arg) {\n return typeof arg === 'number';\n}\n\nexport function isString(arg) {\n return typeof arg === 'string';\n}\n\nexport function isSymbol(arg) {\n return typeof arg === 'symbol';\n}\n\nexport function isUndefined(arg) {\n return arg === void 0;\n}\n\nexport function isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\n\nexport function isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nexport function isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\n\nexport function isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\n\nexport function isFunction(arg) {\n return typeof arg === 'function';\n}\n\nexport function isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\n\nexport function isBuffer(maybeBuf) {\n return Buffer.isBuffer(maybeBuf);\n}\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexport function log() {\n console.log('%s - %s', timestamp(), format.apply(null, arguments));\n}\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nimport inherits from './inherits';\nexport {inherits}\n\nexport function _extend(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nexport default {\n inherits: inherits,\n _extend: _extend,\n log: log,\n isBuffer: isBuffer,\n isPrimitive: isPrimitive,\n isFunction: isFunction,\n isError: isError,\n isDate: isDate,\n isObject: isObject,\n isRegExp: isRegExp,\n isUndefined: isUndefined,\n isSymbol: isSymbol,\n isString: isString,\n isNumber: isNumber,\n isNullOrUndefined: isNullOrUndefined,\n isNull: isNull,\n isBoolean: isBoolean,\n isArray: isArray,\n inspect: inspect,\n deprecate: deprecate,\n format: format,\n debuglog: debuglog\n}\n", "\nconst polyfill = require('util')\n\nif (polyfill && polyfill.default) {\n module.exports = polyfill.default\n for (let k in polyfill) {\n module.exports[k] = polyfill[k]\n }\n} else if (polyfill) {\n module.exports = polyfill\n}\n\n\n", "'use strict';\n\nfunction 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; }\n\nfunction _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; }\n\nfunction _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; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('buffer'),\n Buffer = _require.Buffer;\n\nvar _require2 = require('util'),\n inspect = _require2.inspect;\n\nvar custom = inspect && inspect.custom || 'inspect';\n\nfunction copyBuffer(src, target, offset) {\n Buffer.prototype.copy.call(src, target, offset);\n}\n\nmodule.exports =\n/*#__PURE__*/\nfunction () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n _createClass(BufferList, [{\n key: \"push\",\n value: function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n }\n }, {\n key: \"unshift\",\n value: function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n }\n }, {\n key: \"shift\",\n value: function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this.head = this.tail = null;\n this.length = 0;\n }\n }, {\n key: \"join\",\n value: function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n\n while (p = p.next) {\n ret += s + p.data;\n }\n\n return ret;\n }\n }, {\n key: \"concat\",\n value: function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n\n return ret;\n } // Consumes a specified amount of bytes or characters from the buffered data.\n\n }, {\n key: \"consume\",\n value: function consume(n, hasStrings) {\n var ret;\n\n if (n < this.head.data.length) {\n // `slice` is the same for buffers and strings.\n ret = this.head.data.slice(0, n);\n this.head.data = this.head.data.slice(n);\n } else if (n === this.head.data.length) {\n // First chunk is a perfect match.\n ret = this.shift();\n } else {\n // Result spans more than one buffer.\n ret = hasStrings ? this._getString(n) : this._getBuffer(n);\n }\n\n return ret;\n }\n }, {\n key: \"first\",\n value: function first() {\n return this.head.data;\n } // Consumes a specified amount of characters from the buffered data.\n\n }, {\n key: \"_getString\",\n value: function _getString(n) {\n var p = this.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = str.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Consumes a specified amount of bytes from the buffered data.\n\n }, {\n key: \"_getBuffer\",\n value: function _getBuffer(n) {\n var ret = Buffer.allocUnsafe(n);\n var p = this.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = buf.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Make sure the linked list only shows the minimal necessary information.\n\n }, {\n key: custom,\n value: function value(_, options) {\n return inspect(this, _objectSpread({}, options, {\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n }));\n }\n }]);\n\n return BufferList;\n}();", "'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};", "'use strict';\n\nfunction _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }\n\nvar codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error;\n }\n\n function getMessage(arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message;\n } else {\n return message(arg1, arg2, arg3);\n }\n }\n\n var NodeError =\n /*#__PURE__*/\n function (_Base) {\n _inheritsLoose(NodeError, _Base);\n\n function NodeError(arg1, arg2, arg3) {\n return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;\n }\n\n return NodeError;\n }(Base);\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n codes[code] = NodeError;\n} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\n\n\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n var len = expected.length;\n expected = expected.map(function (i) {\n return String(i);\n });\n\n if (len > 2) {\n return \"one of \".concat(thing, \" \").concat(expected.slice(0, len - 1).join(', '), \", or \") + expected[len - 1];\n } else if (len === 2) {\n return \"one of \".concat(thing, \" \").concat(expected[0], \" or \").concat(expected[1]);\n } else {\n return \"of \".concat(thing, \" \").concat(expected[0]);\n }\n } else {\n return \"of \".concat(thing, \" \").concat(String(expected));\n }\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\n\n\nfunction startsWith(str, search, pos) {\n return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\n\n\nfunction endsWith(str, search, this_len) {\n if (this_len === undefined || this_len > str.length) {\n this_len = str.length;\n }\n\n return str.substring(this_len - search.length, this_len) === search;\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\n\n\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"';\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n var determiner;\n\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n var msg;\n\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = \"The \".concat(name, \" \").concat(determiner, \" \").concat(oneOf(expected, 'type'));\n } else {\n var type = includes(name, '.') ? 'property' : 'argument';\n msg = \"The \\\"\".concat(name, \"\\\" \").concat(type, \" \").concat(determiner, \" \").concat(oneOf(expected, 'type'));\n }\n\n msg += \". Received type \".concat(typeof actual);\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented';\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\nmodule.exports.codes = codes;\n", "'use strict';\n\nvar ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;\n\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;\n}\n\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);\n\n if (hwm != null) {\n if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {\n var name = isDuplex ? duplexKey : 'highWaterMark';\n throw new ERR_INVALID_OPT_VALUE(name, hwm);\n }\n\n return Math.floor(hwm);\n } // Default value\n\n\n return state.objectMode ? 16 : 16 * 1024;\n}\n\nmodule.exports = {\n getHighWaterMark: getHighWaterMark\n};", "if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n", "\n/**\n * Module exports.\n */\n\nmodule.exports = deprecate;\n\n/**\n * Mark that a method should not be used.\n * Returns a modified function which warns once by default.\n *\n * If `localStorage.noDeprecation = true` is set, then it is a no-op.\n *\n * If `localStorage.throwDeprecation = true` is set, then deprecated functions\n * will throw an Error when invoked.\n *\n * If `localStorage.traceDeprecation = true` is set, then deprecated functions\n * will invoke `console.trace()` instead of `console.error()`.\n *\n * @param {Function} fn - the function to deprecate\n * @param {String} msg - the string to print to the console when `fn` is invoked\n * @returns {Function} a new \"deprecated\" version of `fn`\n * @api public\n */\n\nfunction deprecate (fn, msg) {\n if (config('noDeprecation')) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (config('throwDeprecation')) {\n throw new Error(msg);\n } else if (config('traceDeprecation')) {\n console.trace(msg);\n } else {\n console.warn(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n}\n\n/**\n * Checks `localStorage` for boolean values for the given `name`.\n *\n * @param {String} name\n * @returns {Boolean}\n * @api private\n */\n\nfunction config (name) {\n // accessing global.localStorage can trigger a DOMException in sandboxed iframes\n try {\n if (!global.localStorage) return false;\n } catch (_) {\n return false;\n }\n var val = global.localStorage[name];\n if (null == val) return false;\n return String(val).toLowerCase() === 'true';\n}\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\n\n\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n/**/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n 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);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n 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);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/**/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/**/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});", "/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n 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':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n 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;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}", "// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n callback.apply(this, args);\n };\n}\n\nfunction noop() {}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction eos(stream, opts, callback) {\n if (typeof opts === 'function') return eos(stream, null, opts);\n if (!opts) opts = {};\n callback = once(callback || noop);\n var readable = opts.readable || opts.readable !== false && stream.readable;\n var writable = opts.writable || opts.writable !== false && stream.writable;\n\n var onlegacyfinish = function onlegacyfinish() {\n if (!stream.writable) onfinish();\n };\n\n var writableEnded = stream._writableState && stream._writableState.finished;\n\n var onfinish = function onfinish() {\n writable = false;\n writableEnded = true;\n if (!readable) callback.call(stream);\n };\n\n var readableEnded = stream._readableState && stream._readableState.endEmitted;\n\n var onend = function onend() {\n readable = false;\n readableEnded = true;\n if (!writable) callback.call(stream);\n };\n\n var onerror = function onerror(err) {\n callback.call(stream, err);\n };\n\n var onclose = function onclose() {\n var err;\n\n if (readable && !readableEnded) {\n if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n\n if (writable && !writableEnded) {\n if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n };\n\n var onrequest = function onrequest() {\n stream.req.on('finish', onfinish);\n };\n\n if (isRequest(stream)) {\n stream.on('complete', onfinish);\n stream.on('abort', onclose);\n if (stream.req) onrequest();else stream.on('request', onrequest);\n } else if (writable && !stream._writableState) {\n // legacy streams\n stream.on('end', onlegacyfinish);\n stream.on('close', onlegacyfinish);\n }\n\n stream.on('end', onend);\n stream.on('finish', onfinish);\n if (opts.error !== false) stream.on('error', onerror);\n stream.on('close', onclose);\n return function () {\n stream.removeListener('complete', onfinish);\n stream.removeListener('abort', onclose);\n stream.removeListener('request', onrequest);\n if (stream.req) stream.req.removeListener('finish', onfinish);\n stream.removeListener('end', onlegacyfinish);\n stream.removeListener('close', onlegacyfinish);\n stream.removeListener('finish', onfinish);\n stream.removeListener('end', onend);\n stream.removeListener('error', onerror);\n stream.removeListener('close', onclose);\n };\n}\n\nmodule.exports = eos;", "'use strict';\n\nvar _Object$setPrototypeO;\n\nfunction _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; }\n\nvar finished = require('./end-of-stream');\n\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\n\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\n\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n\n if (resolve !== null) {\n var data = iter[kStream].read(); // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\n\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\n\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\n\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n\n next: function next() {\n var _this = this;\n\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n\n if (error !== null) {\n return Promise.reject(error);\n }\n\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n } // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n\n\n var lastPromise = this[kLastPromise];\n var promise;\n\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n\n promise = new Promise(this[kHandlePromise]);\n }\n\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\n\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n\n iterator[kError] = err;\n return;\n }\n\n var resolve = iterator[kLastResolve];\n\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\n\nmodule.exports = createReadableStreamAsyncIterator;", "module.exports = function () {\n throw new Error('Readable.from is not available in the browser')\n};\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/**/\n\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n/**/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\n\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/**/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/**/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n 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\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n 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]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n'use strict';\n\nmodule.exports = Transform;\n\nvar _require$codes = require('../errors').codes,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\n\nvar Duplex = require('./_stream_duplex');\n\nrequire('inherits')(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n }; // start out asking for a readable event once data is transformed.\n\n this._readableState.needReadable = true; // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n } // When the writable side finishes, then flush out anything remaining.\n\n\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n}; // This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\n\n\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n}; // Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\n\n\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data); // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\nrequire('inherits')(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};", "// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar eos;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n callback.apply(void 0, arguments);\n };\n}\n\nvar _require$codes = require('../../../errors').codes,\n ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;\n\nfunction noop(err) {\n // Rethrow the error if it exists to avoid swallowing it\n if (err) throw err;\n}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction destroyer(stream, reading, writing, callback) {\n callback = once(callback);\n var closed = false;\n stream.on('close', function () {\n closed = true;\n });\n if (eos === undefined) eos = require('./end-of-stream');\n eos(stream, {\n readable: reading,\n writable: writing\n }, function (err) {\n if (err) return callback(err);\n closed = true;\n callback();\n });\n var destroyed = false;\n return function (err) {\n if (closed) return;\n if (destroyed) return;\n destroyed = true; // request.destroy just do .end - .abort is what we want\n\n if (isRequest(stream)) return stream.abort();\n if (typeof stream.destroy === 'function') return stream.destroy();\n callback(err || new ERR_STREAM_DESTROYED('pipe'));\n };\n}\n\nfunction call(fn) {\n fn();\n}\n\nfunction pipe(from, to) {\n return from.pipe(to);\n}\n\nfunction popCallback(streams) {\n if (!streams.length) return noop;\n if (typeof streams[streams.length - 1] !== 'function') return noop;\n return streams.pop();\n}\n\nfunction pipeline() {\n for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {\n streams[_key] = arguments[_key];\n }\n\n var callback = popCallback(streams);\n if (Array.isArray(streams[0])) streams = streams[0];\n\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams');\n }\n\n var error;\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1;\n var writing = i > 0;\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err;\n if (err) destroys.forEach(call);\n if (reading) return;\n destroys.forEach(call);\n callback(error);\n });\n });\n return streams.reduce(pipe);\n}\n\nmodule.exports = pipeline;", "exports = module.exports = require('./lib/_stream_readable.js');\nexports.Stream = exports;\nexports.Readable = exports;\nexports.Writable = require('./lib/_stream_writable.js');\nexports.Duplex = require('./lib/_stream_duplex.js');\nexports.Transform = require('./lib/_stream_transform.js');\nexports.PassThrough = require('./lib/_stream_passthrough.js');\nexports.finished = require('./lib/internal/streams/end-of-stream.js');\nexports.pipeline = require('./lib/internal/streams/pipeline.js');\n", "'use strict'\n\n/**\n * Module dependencies\n */\nconst xtend = require('xtend')\n\nconst Readable = require('readable-stream').Readable\nconst streamsOpts = { objectMode: true }\nconst defaultStoreOptions = {\n clean: true\n}\n\n/**\n * In-memory implementation of the message store\n * This can actually be saved into files.\n *\n * @param {Object} [options] - store options\n */\nfunction Store (options) {\n if (!(this instanceof Store)) {\n return new Store(options)\n }\n\n this.options = options || {}\n\n // Defaults\n this.options = xtend(defaultStoreOptions, options)\n\n this._inflights = new Map()\n}\n\n/**\n * Adds a packet to the store, a packet is\n * anything that has a messageId property.\n *\n */\nStore.prototype.put = function (packet, cb) {\n this._inflights.set(packet.messageId, packet)\n\n if (cb) {\n cb()\n }\n\n return this\n}\n\n/**\n * Creates a stream with all the packets in the store\n *\n */\nStore.prototype.createStream = function () {\n const stream = new Readable(streamsOpts)\n const values = []\n let destroyed = false\n let i = 0\n\n this._inflights.forEach(function (value, key) {\n values.push(value)\n })\n\n stream._read = function () {\n if (!destroyed && i < values.length) {\n this.push(values[i++])\n } else {\n this.push(null)\n }\n }\n\n stream.destroy = function () {\n if (destroyed) {\n return\n }\n\n const self = this\n\n destroyed = true\n\n setTimeout(function () {\n self.emit('close')\n }, 0)\n }\n\n return stream\n}\n\n/**\n * deletes a packet from the store.\n */\nStore.prototype.del = function (packet, cb) {\n packet = this._inflights.get(packet.messageId)\n if (packet) {\n this._inflights.delete(packet.messageId)\n cb(null, packet)\n } else if (cb) {\n cb(new Error('missing packet'))\n }\n\n return this\n}\n\n/**\n * get a packet from the store.\n */\nStore.prototype.get = function (packet, cb) {\n packet = this._inflights.get(packet.messageId)\n if (packet) {\n cb(null, packet)\n } else if (cb) {\n cb(new Error('missing packet'))\n }\n\n return this\n}\n\n/**\n * Close the store\n */\nStore.prototype.close = function (cb) {\n if (this.options.clean) {\n this._inflights = null\n }\n if (cb) {\n cb()\n }\n}\n\nmodule.exports = Store\n", "'use strict'\n\n/**\n * Topic Alias receiving manager\n * This holds alias to topic map\n * @param {Number} [max] - topic alias maximum entries\n */\nfunction TopicAliasRecv (max) {\n if (!(this instanceof TopicAliasRecv)) {\n return new TopicAliasRecv(max)\n }\n this.aliasToTopic = {}\n this.max = max\n}\n\n/**\n * Insert or update topic - alias entry.\n * @param {String} [topic] - topic\n * @param {Number} [alias] - topic alias\n * @returns {Boolean} - if success return true otherwise false\n */\nTopicAliasRecv.prototype.put = function (topic, alias) {\n if (alias === 0 || alias > this.max) {\n return false\n }\n this.aliasToTopic[alias] = topic\n this.length = Object.keys(this.aliasToTopic).length\n return true\n}\n\n/**\n * Get topic by alias\n * @param {String} [topic] - topic\n * @returns {Number} - if mapped topic exists return topic alias, otherwise return undefined\n */\nTopicAliasRecv.prototype.getTopicByAlias = function (alias) {\n return this.aliasToTopic[alias]\n}\n\n/**\n * Clear all entries\n */\nTopicAliasRecv.prototype.clear = function () {\n this.aliasToTopic = {}\n}\n\nmodule.exports = TopicAliasRecv\n", "'use strict'\nmodule.exports = function (Yallist) {\n Yallist.prototype[Symbol.iterator] = function* () {\n for (let walker = this.head; walker; walker = walker.next) {\n yield walker.value\n }\n }\n}\n", "'use strict'\nmodule.exports = Yallist\n\nYallist.Node = Node\nYallist.create = Yallist\n\nfunction Yallist (list) {\n var self = this\n if (!(self instanceof Yallist)) {\n self = new Yallist()\n }\n\n self.tail = null\n self.head = null\n self.length = 0\n\n if (list && typeof list.forEach === 'function') {\n list.forEach(function (item) {\n self.push(item)\n })\n } else if (arguments.length > 0) {\n for (var i = 0, l = arguments.length; i < l; i++) {\n self.push(arguments[i])\n }\n }\n\n return self\n}\n\nYallist.prototype.removeNode = function (node) {\n if (node.list !== this) {\n throw new Error('removing node which does not belong to this list')\n }\n\n var next = node.next\n var prev = node.prev\n\n if (next) {\n next.prev = prev\n }\n\n if (prev) {\n prev.next = next\n }\n\n if (node === this.head) {\n this.head = next\n }\n if (node === this.tail) {\n this.tail = prev\n }\n\n node.list.length--\n node.next = null\n node.prev = null\n node.list = null\n\n return next\n}\n\nYallist.prototype.unshiftNode = function (node) {\n if (node === this.head) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n var head = this.head\n node.list = this\n node.next = head\n if (head) {\n head.prev = node\n }\n\n this.head = node\n if (!this.tail) {\n this.tail = node\n }\n this.length++\n}\n\nYallist.prototype.pushNode = function (node) {\n if (node === this.tail) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n var tail = this.tail\n node.list = this\n node.prev = tail\n if (tail) {\n tail.next = node\n }\n\n this.tail = node\n if (!this.head) {\n this.head = node\n }\n this.length++\n}\n\nYallist.prototype.push = function () {\n for (var i = 0, l = arguments.length; i < l; i++) {\n push(this, arguments[i])\n }\n return this.length\n}\n\nYallist.prototype.unshift = function () {\n for (var i = 0, l = arguments.length; i < l; i++) {\n unshift(this, arguments[i])\n }\n return this.length\n}\n\nYallist.prototype.pop = function () {\n if (!this.tail) {\n return undefined\n }\n\n var res = this.tail.value\n this.tail = this.tail.prev\n if (this.tail) {\n this.tail.next = null\n } else {\n this.head = null\n }\n this.length--\n return res\n}\n\nYallist.prototype.shift = function () {\n if (!this.head) {\n return undefined\n }\n\n var res = this.head.value\n this.head = this.head.next\n if (this.head) {\n this.head.prev = null\n } else {\n this.tail = null\n }\n this.length--\n return res\n}\n\nYallist.prototype.forEach = function (fn, thisp) {\n thisp = thisp || this\n for (var walker = this.head, i = 0; walker !== null; i++) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.next\n }\n}\n\nYallist.prototype.forEachReverse = function (fn, thisp) {\n thisp = thisp || this\n for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.prev\n }\n}\n\nYallist.prototype.get = function (n) {\n for (var i = 0, walker = this.head; walker !== null && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.next\n }\n if (i === n && walker !== null) {\n return walker.value\n }\n}\n\nYallist.prototype.getReverse = function (n) {\n for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.prev\n }\n if (i === n && walker !== null) {\n return walker.value\n }\n}\n\nYallist.prototype.map = function (fn, thisp) {\n thisp = thisp || this\n var res = new Yallist()\n for (var walker = this.head; walker !== null;) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.next\n }\n return res\n}\n\nYallist.prototype.mapReverse = function (fn, thisp) {\n thisp = thisp || this\n var res = new Yallist()\n for (var walker = this.tail; walker !== null;) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.prev\n }\n return res\n}\n\nYallist.prototype.reduce = function (fn, initial) {\n var acc\n var walker = this.head\n if (arguments.length > 1) {\n acc = initial\n } else if (this.head) {\n walker = this.head.next\n acc = this.head.value\n } else {\n throw new TypeError('Reduce of empty list with no initial value')\n }\n\n for (var i = 0; walker !== null; i++) {\n acc = fn(acc, walker.value, i)\n walker = walker.next\n }\n\n return acc\n}\n\nYallist.prototype.reduceReverse = function (fn, initial) {\n var acc\n var walker = this.tail\n if (arguments.length > 1) {\n acc = initial\n } else if (this.tail) {\n walker = this.tail.prev\n acc = this.tail.value\n } else {\n throw new TypeError('Reduce of empty list with no initial value')\n }\n\n for (var i = this.length - 1; walker !== null; i--) {\n acc = fn(acc, walker.value, i)\n walker = walker.prev\n }\n\n return acc\n}\n\nYallist.prototype.toArray = function () {\n var arr = new Array(this.length)\n for (var i = 0, walker = this.head; walker !== null; i++) {\n arr[i] = walker.value\n walker = walker.next\n }\n return arr\n}\n\nYallist.prototype.toArrayReverse = function () {\n var arr = new Array(this.length)\n for (var i = 0, walker = this.tail; walker !== null; i++) {\n arr[i] = walker.value\n walker = walker.prev\n }\n return arr\n}\n\nYallist.prototype.slice = function (from, to) {\n to = to || this.length\n if (to < 0) {\n to += this.length\n }\n from = from || 0\n if (from < 0) {\n from += this.length\n }\n var ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n for (var i = 0, walker = this.head; walker !== null && i < from; i++) {\n walker = walker.next\n }\n for (; walker !== null && i < to; i++, walker = walker.next) {\n ret.push(walker.value)\n }\n return ret\n}\n\nYallist.prototype.sliceReverse = function (from, to) {\n to = to || this.length\n if (to < 0) {\n to += this.length\n }\n from = from || 0\n if (from < 0) {\n from += this.length\n }\n var ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {\n walker = walker.prev\n }\n for (; walker !== null && i > from; i--, walker = walker.prev) {\n ret.push(walker.value)\n }\n return ret\n}\n\nYallist.prototype.splice = function (start, deleteCount, ...nodes) {\n if (start > this.length) {\n start = this.length - 1\n }\n if (start < 0) {\n start = this.length + start;\n }\n\n for (var i = 0, walker = this.head; walker !== null && i < start; i++) {\n walker = walker.next\n }\n\n var ret = []\n for (var i = 0; walker && i < deleteCount; i++) {\n ret.push(walker.value)\n walker = this.removeNode(walker)\n }\n if (walker === null) {\n walker = this.tail\n }\n\n if (walker !== this.head && walker !== this.tail) {\n walker = walker.prev\n }\n\n for (var i = 0; i < nodes.length; i++) {\n walker = insert(this, walker, nodes[i])\n }\n return ret;\n}\n\nYallist.prototype.reverse = function () {\n var head = this.head\n var tail = this.tail\n for (var walker = head; walker !== null; walker = walker.prev) {\n var p = walker.prev\n walker.prev = walker.next\n walker.next = p\n }\n this.head = tail\n this.tail = head\n return this\n}\n\nfunction insert (self, node, value) {\n var inserted = node === self.head ?\n new Node(value, null, node, self) :\n new Node(value, node, node.next, self)\n\n if (inserted.next === null) {\n self.tail = inserted\n }\n if (inserted.prev === null) {\n self.head = inserted\n }\n\n self.length++\n\n return inserted\n}\n\nfunction push (self, item) {\n self.tail = new Node(item, self.tail, null, self)\n if (!self.head) {\n self.head = self.tail\n }\n self.length++\n}\n\nfunction unshift (self, item) {\n self.head = new Node(item, null, self.head, self)\n if (!self.tail) {\n self.tail = self.head\n }\n self.length++\n}\n\nfunction Node (value, prev, next, list) {\n if (!(this instanceof Node)) {\n return new Node(value, prev, next, list)\n }\n\n this.list = list\n this.value = value\n\n if (prev) {\n prev.next = this\n this.prev = prev\n } else {\n this.prev = null\n }\n\n if (next) {\n next.prev = this\n this.next = next\n } else {\n this.next = null\n }\n}\n\ntry {\n // add if support for Symbol.iterator is present\n require('./iterator.js')(Yallist)\n} catch (er) {}\n", "'use strict'\n\n// A linked list to keep track of recently-used-ness\nconst Yallist = require('yallist')\n\nconst MAX = Symbol('max')\nconst LENGTH = Symbol('length')\nconst LENGTH_CALCULATOR = Symbol('lengthCalculator')\nconst ALLOW_STALE = Symbol('allowStale')\nconst MAX_AGE = Symbol('maxAge')\nconst DISPOSE = Symbol('dispose')\nconst NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')\nconst LRU_LIST = Symbol('lruList')\nconst CACHE = Symbol('cache')\nconst UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')\n\nconst naiveLength = () => 1\n\n// lruList is a yallist where the head is the youngest\n// item, and the tail is the oldest. the list contains the Hit\n// objects as the entries.\n// Each Hit object has a reference to its Yallist.Node. This\n// never changes.\n//\n// cache is a Map (or PseudoMap) that matches the keys to\n// the Yallist.Node object.\nclass LRUCache {\n constructor (options) {\n if (typeof options === 'number')\n options = { max: options }\n\n if (!options)\n options = {}\n\n if (options.max && (typeof options.max !== 'number' || options.max < 0))\n throw new TypeError('max must be a non-negative number')\n // Kind of weird to have a default max of Infinity, but oh well.\n const max = this[MAX] = options.max || Infinity\n\n const lc = options.length || naiveLength\n this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc\n this[ALLOW_STALE] = options.stale || false\n if (options.maxAge && typeof options.maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n this[MAX_AGE] = options.maxAge || 0\n this[DISPOSE] = options.dispose\n this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false\n this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false\n this.reset()\n }\n\n // resize the cache when the max changes.\n set max (mL) {\n if (typeof mL !== 'number' || mL < 0)\n throw new TypeError('max must be a non-negative number')\n\n this[MAX] = mL || Infinity\n trim(this)\n }\n get max () {\n return this[MAX]\n }\n\n set allowStale (allowStale) {\n this[ALLOW_STALE] = !!allowStale\n }\n get allowStale () {\n return this[ALLOW_STALE]\n }\n\n set maxAge (mA) {\n if (typeof mA !== 'number')\n throw new TypeError('maxAge must be a non-negative number')\n\n this[MAX_AGE] = mA\n trim(this)\n }\n get maxAge () {\n return this[MAX_AGE]\n }\n\n // resize the cache when the lengthCalculator changes.\n set lengthCalculator (lC) {\n if (typeof lC !== 'function')\n lC = naiveLength\n\n if (lC !== this[LENGTH_CALCULATOR]) {\n this[LENGTH_CALCULATOR] = lC\n this[LENGTH] = 0\n this[LRU_LIST].forEach(hit => {\n hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)\n this[LENGTH] += hit.length\n })\n }\n trim(this)\n }\n get lengthCalculator () { return this[LENGTH_CALCULATOR] }\n\n get length () { return this[LENGTH] }\n get itemCount () { return this[LRU_LIST].length }\n\n rforEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].tail; walker !== null;) {\n const prev = walker.prev\n forEachStep(this, fn, walker, thisp)\n walker = prev\n }\n }\n\n forEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].head; walker !== null;) {\n const next = walker.next\n forEachStep(this, fn, walker, thisp)\n walker = next\n }\n }\n\n keys () {\n return this[LRU_LIST].toArray().map(k => k.key)\n }\n\n values () {\n return this[LRU_LIST].toArray().map(k => k.value)\n }\n\n reset () {\n if (this[DISPOSE] &&\n this[LRU_LIST] &&\n this[LRU_LIST].length) {\n this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))\n }\n\n this[CACHE] = new Map() // hash of items by key\n this[LRU_LIST] = new Yallist() // list of items in order of use recency\n this[LENGTH] = 0 // length of items in the list\n }\n\n dump () {\n return this[LRU_LIST].map(hit =>\n isStale(this, hit) ? false : {\n k: hit.key,\n v: hit.value,\n e: hit.now + (hit.maxAge || 0)\n }).toArray().filter(h => h)\n }\n\n dumpLru () {\n return this[LRU_LIST]\n }\n\n set (key, value, maxAge) {\n maxAge = maxAge || this[MAX_AGE]\n\n if (maxAge && typeof maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n\n const now = maxAge ? Date.now() : 0\n const len = this[LENGTH_CALCULATOR](value, key)\n\n if (this[CACHE].has(key)) {\n if (len > this[MAX]) {\n del(this, this[CACHE].get(key))\n return false\n }\n\n const node = this[CACHE].get(key)\n const item = node.value\n\n // dispose of the old one before overwriting\n // split out into 2 ifs for better coverage tracking\n if (this[DISPOSE]) {\n if (!this[NO_DISPOSE_ON_SET])\n this[DISPOSE](key, item.value)\n }\n\n item.now = now\n item.maxAge = maxAge\n item.value = value\n this[LENGTH] += len - item.length\n item.length = len\n this.get(key)\n trim(this)\n return true\n }\n\n const hit = new Entry(key, value, len, now, maxAge)\n\n // oversized objects fall out of cache automatically.\n if (hit.length > this[MAX]) {\n if (this[DISPOSE])\n this[DISPOSE](key, value)\n\n return false\n }\n\n this[LENGTH] += hit.length\n this[LRU_LIST].unshift(hit)\n this[CACHE].set(key, this[LRU_LIST].head)\n trim(this)\n return true\n }\n\n has (key) {\n if (!this[CACHE].has(key)) return false\n const hit = this[CACHE].get(key).value\n return !isStale(this, hit)\n }\n\n get (key) {\n return get(this, key, true)\n }\n\n peek (key) {\n return get(this, key, false)\n }\n\n pop () {\n const node = this[LRU_LIST].tail\n if (!node)\n return null\n\n del(this, node)\n return node.value\n }\n\n del (key) {\n del(this, this[CACHE].get(key))\n }\n\n load (arr) {\n // reset the cache\n this.reset()\n\n const now = Date.now()\n // A previous serialized cache has the most recent items first\n for (let l = arr.length - 1; l >= 0; l--) {\n const hit = arr[l]\n const expiresAt = hit.e || 0\n if (expiresAt === 0)\n // the item was created without expiration in a non aged cache\n this.set(hit.k, hit.v)\n else {\n const maxAge = expiresAt - now\n // dont add already expired items\n if (maxAge > 0) {\n this.set(hit.k, hit.v, maxAge)\n }\n }\n }\n }\n\n prune () {\n this[CACHE].forEach((value, key) => get(this, key, false))\n }\n}\n\nconst get = (self, key, doUse) => {\n const node = self[CACHE].get(key)\n if (node) {\n const hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n return undefined\n } else {\n if (doUse) {\n if (self[UPDATE_AGE_ON_GET])\n node.value.now = Date.now()\n self[LRU_LIST].unshiftNode(node)\n }\n }\n return hit.value\n }\n}\n\nconst isStale = (self, hit) => {\n if (!hit || (!hit.maxAge && !self[MAX_AGE]))\n return false\n\n const diff = Date.now() - hit.now\n return hit.maxAge ? diff > hit.maxAge\n : self[MAX_AGE] && (diff > self[MAX_AGE])\n}\n\nconst trim = self => {\n if (self[LENGTH] > self[MAX]) {\n for (let walker = self[LRU_LIST].tail;\n self[LENGTH] > self[MAX] && walker !== null;) {\n // We know that we're about to delete this one, and also\n // what the next least recently used key will be, so just\n // go ahead and set it now.\n const prev = walker.prev\n del(self, walker)\n walker = prev\n }\n }\n}\n\nconst del = (self, node) => {\n if (node) {\n const hit = node.value\n if (self[DISPOSE])\n self[DISPOSE](hit.key, hit.value)\n\n self[LENGTH] -= hit.length\n self[CACHE].delete(hit.key)\n self[LRU_LIST].removeNode(node)\n }\n}\n\nclass Entry {\n constructor (key, value, length, now, maxAge) {\n this.key = key\n this.value = value\n this.length = length\n this.now = now\n this.maxAge = maxAge || 0\n }\n}\n\nconst forEachStep = (self, fn, node, thisp) => {\n let hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n hit = undefined\n }\n if (hit)\n fn.call(thisp, hit.value, hit.key, self)\n}\n\nmodule.exports = LRUCache\n", "\"use strict\";\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction Vector(container) {\n var _this = this;\n if (container === void 0) { container = []; }\n var len = 0;\n var vector = [];\n this.size = function () {\n return len;\n };\n this.empty = function () {\n return len === 0;\n };\n this.clear = function () {\n len = 0;\n vector.length = 0;\n };\n this.front = function () {\n if (this.empty())\n return undefined;\n return vector[0];\n };\n this.back = function () {\n if (this.empty())\n return undefined;\n return vector[len - 1];\n };\n this.forEach = function (callback) {\n vector.forEach(callback);\n };\n this.getElementByPos = function (pos) {\n if (pos < 0 || pos >= len)\n throw new Error(\"pos must more than 0 and less than vector's size\");\n return vector[pos];\n };\n this.eraseElementByPos = function (pos) {\n if (pos < 0 || pos >= len)\n throw new Error(\"pos must more than 0 and less than vector's size\");\n for (var i = pos; i < len - 1; ++i)\n vector[i] = vector[i + 1];\n this.popBack();\n };\n this.eraseElementByValue = function (value) {\n var newArr = [];\n this.forEach(function (element) {\n if (element !== value)\n newArr.push(element);\n });\n newArr.forEach(function (element, index) {\n vector[index] = element;\n });\n var newLen = newArr.length;\n while (len > newLen)\n this.popBack();\n };\n this.pushBack = function (element) {\n vector.push(element);\n ++len;\n };\n this.popBack = function () {\n vector.pop();\n if (len > 0)\n --len;\n };\n this.setElementByPos = function (pos, element) {\n if (pos < 0 || pos >= len)\n throw new Error(\"pos must more than 0 and less than vector's size\");\n vector[pos] = element;\n };\n this.insert = function (pos, element, num) {\n if (num === void 0) { num = 1; }\n if (pos < 0 || pos > len)\n throw new Error(\"pos must more than 0 and less than or equal to vector's size\");\n vector.splice.apply(vector, __spreadArray([pos, 0], __read(new Array(num).fill(element)), false));\n len += num;\n };\n this.find = function (element) {\n return vector.includes(element);\n };\n this.reverse = function () {\n vector.reverse();\n };\n this.unique = function () {\n var pre;\n var newArr = [];\n this.forEach(function (element, index) {\n if (index === 0 || element !== pre) {\n newArr.push(element);\n pre = element;\n }\n });\n newArr.forEach(function (element, index) {\n vector[index] = element;\n });\n var newLen = newArr.length;\n while (len > newLen)\n this.popBack();\n };\n this.sort = function (cmp) {\n vector.sort(cmp);\n };\n this[Symbol.iterator] = function () {\n return (function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [5 /*yield**/, __values(vector)];\n case 1: return [2 /*return*/, _a.sent()];\n }\n });\n })();\n };\n container.forEach(function (element) { return _this.pushBack(element); });\n Object.freeze(this);\n}\nObject.freeze(Vector);\nexports.default = Vector;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction Stack(container) {\n var _this = this;\n if (container === void 0) { container = []; }\n var len = 0;\n var stack = [];\n this.size = function () {\n return len;\n };\n this.empty = function () {\n return len === 0;\n };\n this.clear = function () {\n len = 0;\n stack.length = 0;\n };\n this.push = function (element) {\n stack.push(element);\n ++len;\n };\n this.pop = function () {\n stack.pop();\n if (len > 0)\n --len;\n };\n this.top = function () {\n return stack[len - 1];\n };\n container.forEach(function (element) { return _this.push(element); });\n Object.freeze(this);\n}\nObject.freeze(Stack);\nexports.default = Stack;\n", "\"use strict\";\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar LinkNode = /** @class */ (function () {\n function LinkNode(element) {\n this.value = undefined;\n this.pre = undefined;\n this.next = undefined;\n this.value = element;\n }\n return LinkNode;\n}());\nfunction LinkList(container) {\n var _this = this;\n if (container === void 0) { container = []; }\n var len = 0;\n var head = undefined;\n var tail = undefined;\n this.size = function () {\n return len;\n };\n this.empty = function () {\n return len === 0;\n };\n this.clear = function () {\n head = tail = undefined;\n len = 0;\n };\n this.front = function () {\n return head === null || head === void 0 ? void 0 : head.value;\n };\n this.back = function () {\n return tail === null || tail === void 0 ? void 0 : tail.value;\n };\n this.forEach = function (callback) {\n var curNode = head;\n var index = 0;\n while (curNode) {\n if (curNode.value === undefined)\n throw new Error(\"unknown error\");\n callback(curNode.value, index++);\n curNode = curNode.next;\n }\n };\n this.getElementByPos = function (pos) {\n if (pos < 0 || pos >= len)\n throw new Error(\"pos must more then 0 and less then the list length\");\n var curNode = head;\n while (pos--) {\n if (!curNode)\n break;\n curNode = curNode.next;\n }\n if (!curNode || curNode.value === undefined)\n throw new Error(\"unknown error\");\n return curNode.value;\n };\n this.eraseElementByPos = function (pos) {\n if (pos < 0 || pos >= len)\n throw new Error(\"erase pos must more then 0 and less then the list length\");\n if (pos === 0)\n this.popFront();\n else if (pos === len - 1)\n this.popBack();\n else {\n var curNode = head;\n while (pos--) {\n if (!(curNode === null || curNode === void 0 ? void 0 : curNode.next))\n throw new Error(\"unknown error\");\n curNode = curNode.next;\n }\n if (!curNode || !curNode.pre || !curNode.next) {\n throw new Error(\"unknown error\");\n }\n var pre = curNode.pre;\n var next = curNode.next;\n next.pre = pre;\n pre.next = next;\n if (len > 0)\n --len;\n }\n };\n this.eraseElementByValue = function (value) {\n while (head && head.value === value)\n this.popFront();\n while (tail && tail.value === value)\n this.popBack();\n if (!head)\n return;\n var curNode = head;\n while (curNode) {\n if (curNode.value === value) {\n var pre = curNode.pre;\n var next = curNode.next;\n if (next)\n next.pre = pre;\n if (pre)\n pre.next = next;\n if (len > 0)\n --len;\n }\n curNode = curNode.next;\n }\n };\n this.pushBack = function (element) {\n if (element === null || element === undefined) {\n throw new Error(\"you can't push null or undefined here\");\n }\n ++len;\n var newTail = new LinkNode(element);\n if (!tail) {\n head = tail = newTail;\n }\n else {\n tail.next = newTail;\n newTail.pre = tail;\n tail = newTail;\n }\n };\n this.popBack = function () {\n if (!tail)\n return;\n if (len > 0)\n --len;\n if (!tail)\n return;\n if (head === tail) {\n head = tail = undefined;\n }\n else {\n tail = tail.pre;\n if (tail)\n tail.next = undefined;\n }\n };\n this.setElementByPos = function (pos, element) {\n if (element === null || element === undefined) {\n throw new Error(\"you can't set null or undefined here\");\n }\n if (pos < 0 || pos >= len)\n throw new Error(\"pos must more then 0 and less then the list length\");\n var curNode = head;\n while (pos--) {\n if (!curNode)\n throw new Error(\"unknown error\");\n curNode = curNode.next;\n }\n if (curNode)\n curNode.value = element;\n };\n /**\n * @param {number} pos insert element before pos, should in [0, list.size]\n * @param {any} element the element you want to insert\n * @param {number} [num = 1] the nums you want to insert\n */\n this.insert = function (pos, element, num) {\n if (num === void 0) { num = 1; }\n if (element === null || element === undefined) {\n throw new Error(\"you can't insert null or undefined here\");\n }\n if (pos < 0 || pos > len)\n throw new Error(\"insert pos must more then 0 and less then or equal to the list length\");\n if (num < 0)\n throw new Error(\"insert size must more than 0\");\n if (pos === 0) {\n while (num--)\n this.pushFront(element);\n }\n else if (pos === len) {\n while (num--)\n this.pushBack(element);\n }\n else {\n var curNode = head;\n for (var i = 1; i < pos; ++i) {\n if (!(curNode === null || curNode === void 0 ? void 0 : curNode.next))\n throw new Error(\"unknown error\");\n curNode = curNode === null || curNode === void 0 ? void 0 : curNode.next;\n }\n if (!curNode) {\n throw new Error(\"unknown error\");\n }\n var next = curNode.next;\n len += num;\n while (num--) {\n curNode.next = new LinkNode(element);\n curNode.next.pre = curNode;\n curNode = curNode.next;\n }\n curNode.next = next;\n if (next)\n next.pre = curNode;\n }\n };\n this.find = function (element) {\n var curNode = head;\n while (curNode) {\n if (curNode.value === element)\n return true;\n curNode = curNode.next;\n }\n return false;\n };\n this.reverse = function () {\n var pHead = head;\n var pTail = tail;\n var cnt = 0;\n while (pHead && pTail && cnt * 2 < len) {\n var tmp = pHead.value;\n pHead.value = pTail.value;\n pTail.value = tmp;\n pHead = pHead.next;\n pTail = pTail.pre;\n ++cnt;\n }\n };\n this.unique = function () {\n var curNode = head;\n while (curNode) {\n var tmpNode = curNode;\n while (tmpNode && tmpNode.next && tmpNode.value === tmpNode.next.value) {\n tmpNode = tmpNode.next;\n if (len > 0)\n --len;\n }\n curNode.next = tmpNode.next;\n if (curNode.next)\n curNode.next.pre = curNode;\n curNode = curNode.next;\n }\n };\n this.sort = function (cmp) {\n var arr = [];\n this.forEach(function (element) {\n arr.push(element);\n });\n arr.sort(cmp);\n var curNode = head;\n arr.forEach(function (element) {\n if (curNode) {\n curNode.value = element;\n curNode = curNode.next;\n }\n });\n };\n this.pushFront = function (element) {\n if (element === null || element === undefined) {\n throw new Error(\"you can't push null or undefined here\");\n }\n ++len;\n var newHead = new LinkNode(element);\n if (!head) {\n head = tail = newHead;\n }\n else {\n newHead.next = head;\n head.pre = newHead;\n head = newHead;\n }\n };\n this.popFront = function () {\n if (!head)\n return;\n if (len > 0)\n --len;\n if (!head)\n return;\n if (head === tail) {\n head = tail = undefined;\n }\n else {\n head = head.next;\n if (head)\n head.pre = undefined;\n }\n };\n /**\n * merge two sorted lists\n * @param list other list\n */\n this.merge = function (list) {\n var _this = this;\n var curNode = head;\n list.forEach(function (element) {\n while (curNode && curNode.value !== undefined && curNode.value <= element) {\n curNode = curNode.next;\n }\n if (curNode === undefined) {\n _this.pushBack(element);\n curNode = tail;\n }\n else if (curNode === head) {\n _this.pushFront(element);\n curNode = head;\n }\n else {\n ++len;\n var pre = curNode.pre;\n if (pre) {\n pre.next = new LinkNode(element);\n pre.next.pre = pre;\n pre.next.next = curNode;\n if (curNode)\n curNode.pre = pre.next;\n }\n }\n });\n };\n this[Symbol.iterator] = function () {\n return (function () {\n var curNode;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n curNode = head;\n _a.label = 1;\n case 1:\n if (!(curNode !== undefined)) return [3 /*break*/, 3];\n if (!curNode.value)\n throw new Error(\"unknown error\");\n return [4 /*yield*/, curNode.value];\n case 2:\n _a.sent();\n curNode = curNode.next;\n return [3 /*break*/, 1];\n case 3: return [2 /*return*/];\n }\n });\n })();\n };\n container.forEach(function (element) { return _this.pushBack(element); });\n Object.freeze(this);\n}\nObject.freeze(LinkList);\nexports.default = LinkList;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar LinkList_1 = require(\"../LinkList/LinkList\");\nfunction Queue(container) {\n if (container === void 0) { container = []; }\n var queue = new LinkList_1.default(container);\n this.size = function () {\n return queue.size();\n };\n this.empty = function () {\n return queue.empty();\n };\n this.clear = function () {\n queue.clear();\n };\n this.push = function (element) {\n queue.pushBack(element);\n };\n this.pop = function () {\n queue.popFront();\n };\n this.front = function () {\n return queue.front();\n };\n Object.freeze(this);\n}\nObject.freeze(Queue);\nexports.default = Queue;\n", "\"use strict\";\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nDeque.sigma = 3; // growth factor\nDeque.bucketSize = 5000;\nfunction Deque(container) {\n var _this = this;\n if (container === void 0) { container = []; }\n var map = [];\n var first = 0;\n var curFirst = 0;\n var last = 0;\n var curLast = 0;\n var bucketNum = 0;\n var len = 0;\n this.size = function () {\n return len;\n };\n this.empty = function () {\n return len === 0;\n };\n this.clear = function () {\n first = last = curFirst = curLast = bucketNum = len = 0;\n reAllocate.call(this, Deque.bucketSize);\n len = 0;\n };\n this.front = function () {\n return map[first][curFirst];\n };\n this.back = function () {\n return map[last][curLast];\n };\n this.forEach = function (callback) {\n if (this.empty())\n return;\n var index = 0;\n if (first === last) {\n for (var i = curFirst; i <= curLast; ++i) {\n callback(map[first][i], index++);\n }\n return;\n }\n for (var i = curFirst; i < Deque.bucketSize; ++i) {\n callback(map[first][i], index++);\n }\n for (var i = first + 1; i < last; ++i) {\n for (var j = 0; j < Deque.bucketSize; ++j) {\n callback(map[i][j], index++);\n }\n }\n for (var i = 0; i <= curLast; ++i) {\n callback(map[last][i], index++);\n }\n };\n var getElementIndex = function (pos) {\n var curFirstIndex = first * Deque.bucketSize + curFirst;\n var curNodeIndex = curFirstIndex + pos;\n var curLastIndex = last * Deque.bucketSize + curLast;\n if (curNodeIndex < curFirstIndex || curNodeIndex > curLastIndex)\n throw new Error(\"pos should more than 0 and less than queue's size\");\n var curNodeBucketIndex = Math.floor(curNodeIndex / Deque.bucketSize);\n var curNodePointerIndex = curNodeIndex % Deque.bucketSize;\n return { curNodeBucketIndex: curNodeBucketIndex, curNodePointerIndex: curNodePointerIndex };\n };\n /**\n * @param pos index from 0 to size - 1\n */\n this.getElementByPos = function (pos) {\n var _a = getElementIndex(pos), curNodeBucketIndex = _a.curNodeBucketIndex, curNodePointerIndex = _a.curNodePointerIndex;\n return map[curNodeBucketIndex][curNodePointerIndex];\n };\n this.eraseElementByPos = function (pos) {\n var _this = this;\n if (pos < 0 || pos > len)\n throw new Error(\"pos should more than 0 and less than queue's size\");\n if (pos === 0)\n this.popFront();\n else if (pos === this.size())\n this.popBack();\n else {\n var arr = [];\n for (var i = pos + 1; i < len; ++i) {\n arr.push(this.getElementByPos(i));\n }\n this.cut(pos);\n this.popBack();\n arr.forEach(function (element) { return _this.pushBack(element); });\n }\n };\n this.eraseElementByValue = function (value) {\n if (this.empty())\n return;\n var arr = [];\n this.forEach(function (element) {\n if (element !== value) {\n arr.push(element);\n }\n });\n var _len = arr.length;\n for (var i = 0; i < _len; ++i)\n this.setElementByPos(i, arr[i]);\n this.cut(_len - 1);\n };\n var reAllocate = function (originalSize) {\n var newMap = [];\n var needSize = originalSize * Deque.sigma;\n var newBucketNum = Math.max(Math.ceil(needSize / Deque.bucketSize), 2);\n for (var i = 0; i < newBucketNum; ++i) {\n newMap.push(new Array(Deque.bucketSize));\n }\n var needBucketNum = Math.ceil(originalSize / Deque.bucketSize);\n var newFirst = Math.floor(newBucketNum / 2) - Math.floor(needBucketNum / 2);\n var newLast = newFirst, newCurLast = 0;\n if (this.size()) {\n for (var i = 0; i < needBucketNum; ++i) {\n for (var j = 0; j < Deque.bucketSize; ++j) {\n newMap[newFirst + i][j] = this.front();\n this.popFront();\n if (this.empty()) {\n newLast = newFirst + i;\n newCurLast = j;\n break;\n }\n }\n if (this.empty())\n break;\n }\n }\n map = newMap;\n first = newFirst;\n curFirst = 0;\n last = newLast;\n curLast = newCurLast;\n bucketNum = newBucketNum;\n len = originalSize;\n };\n this.pushBack = function (element) {\n if (!this.empty()) {\n if (last === bucketNum - 1 && curLast === Deque.bucketSize - 1) {\n reAllocate.call(this, this.size());\n }\n if (curLast < Deque.bucketSize - 1) {\n ++curLast;\n }\n else if (last < bucketNum - 1) {\n ++last;\n curLast = 0;\n }\n }\n ++len;\n map[last][curLast] = element;\n };\n this.popBack = function () {\n if (this.empty())\n return;\n if (this.size() !== 1) {\n if (curLast > 0) {\n --curLast;\n }\n else if (first < last) {\n --last;\n curLast = Deque.bucketSize - 1;\n }\n }\n if (len > 0)\n --len;\n };\n this.setElementByPos = function (pos, element) {\n var _a = getElementIndex(pos), curNodeBucketIndex = _a.curNodeBucketIndex, curNodePointerIndex = _a.curNodePointerIndex;\n map[curNodeBucketIndex][curNodePointerIndex] = element;\n };\n /**\n * @param {number} pos insert element before pos, should in [0, queue.size]\n * @param {any} element the element you want to insert\n * @param {number} [num = 1] the nums you want to insert\n */\n this.insert = function (pos, element, num) {\n var _this = this;\n if (num === void 0) { num = 1; }\n if (pos === 0) {\n while (num--)\n this.pushFront(element);\n }\n else if (pos === this.size()) {\n while (num--)\n this.pushBack(element);\n }\n else {\n var arr = [];\n for (var i = pos; i < len; ++i) {\n arr.push(this.getElementByPos(i));\n }\n this.cut(pos - 1);\n for (var i = 0; i < num; ++i)\n this.pushBack(element);\n arr.forEach(function (element) { return _this.pushBack(element); });\n }\n };\n this.find = function (element) {\n if (first === last) {\n for (var i = curFirst; i <= curLast; ++i) {\n if (map[first][i] === element)\n return true;\n }\n return false;\n }\n for (var i = curFirst; i < Deque.bucketSize; ++i) {\n if (map[first][i] === element)\n return true;\n }\n for (var i = first + 1; i < last; ++i) {\n for (var j = 0; j < Deque.bucketSize; ++j) {\n if (map[i][j] === element)\n return true;\n }\n }\n for (var i = 0; i <= curLast; ++i) {\n if (map[last][i] === element)\n return true;\n }\n return false;\n };\n this.reverse = function () {\n var l = 0, r = len - 1;\n while (l < r) {\n var tmp = this.getElementByPos(l);\n this.setElementByPos(l, this.getElementByPos(r));\n this.setElementByPos(r, tmp);\n ++l;\n --r;\n }\n };\n this.unique = function () {\n if (this.empty())\n return;\n var arr = [];\n var pre = this.front();\n this.forEach(function (element, index) {\n if (index === 0 || element !== pre) {\n arr.push(element);\n pre = element;\n }\n });\n for (var i = 0; i < len; ++i) {\n this.setElementByPos(i, arr[i]);\n }\n this.cut(arr.length - 1);\n };\n this.sort = function (cmp) {\n var arr = [];\n this.forEach(function (element) {\n arr.push(element);\n });\n arr.sort(cmp);\n for (var i = 0; i < len; ++i)\n this.setElementByPos(i, arr[i]);\n };\n this.pushFront = function (element) {\n if (!this.empty()) {\n if (first === 0 && curFirst === 0) {\n reAllocate.call(this, this.size());\n }\n if (curFirst > 0) {\n --curFirst;\n }\n else if (first > 0) {\n --first;\n curFirst = Deque.bucketSize - 1;\n }\n }\n ++len;\n map[first][curFirst] = element;\n };\n this.popFront = function () {\n if (this.empty())\n return;\n if (this.size() !== 1) {\n if (curFirst < Deque.bucketSize - 1) {\n ++curFirst;\n }\n else if (first < last) {\n ++first;\n curFirst = 0;\n }\n }\n if (len > 0)\n --len;\n };\n /**\n * reduces memory usage by freeing unused memory\n */\n this.shrinkToFit = function () {\n var _this = this;\n var arr = [];\n this.forEach(function (element) {\n arr.push(element);\n });\n var _len = arr.length;\n map = [];\n var bucketNum = Math.ceil(_len / Deque.bucketSize);\n for (var i = 0; i < bucketNum; ++i) {\n map.push(new Array(Deque.bucketSize));\n }\n this.clear();\n arr.forEach(function (element) { return _this.pushBack(element); });\n };\n /**\n * @param pos cut elements after pos\n */\n this.cut = function (pos) {\n if (pos < 0) {\n this.clear();\n return;\n }\n var _a = getElementIndex(pos), curNodeBucketIndex = _a.curNodeBucketIndex, curNodePointerIndex = _a.curNodePointerIndex;\n last = curNodeBucketIndex;\n curLast = curNodePointerIndex;\n len = pos + 1;\n };\n this[Symbol.iterator] = function () {\n return (function () {\n var i, i, i, j, i;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (len === 0)\n return [2 /*return*/];\n if (!(first === last)) return [3 /*break*/, 5];\n i = curFirst;\n _a.label = 1;\n case 1:\n if (!(i <= curLast)) return [3 /*break*/, 4];\n return [4 /*yield*/, map[first][i]];\n case 2:\n _a.sent();\n _a.label = 3;\n case 3:\n ++i;\n return [3 /*break*/, 1];\n case 4: return [2 /*return*/];\n case 5:\n i = curFirst;\n _a.label = 6;\n case 6:\n if (!(i < Deque.bucketSize)) return [3 /*break*/, 9];\n return [4 /*yield*/, map[first][i]];\n case 7:\n _a.sent();\n _a.label = 8;\n case 8:\n ++i;\n return [3 /*break*/, 6];\n case 9:\n i = first + 1;\n _a.label = 10;\n case 10:\n if (!(i < last)) return [3 /*break*/, 15];\n j = 0;\n _a.label = 11;\n case 11:\n if (!(j < Deque.bucketSize)) return [3 /*break*/, 14];\n return [4 /*yield*/, map[i][j]];\n case 12:\n _a.sent();\n _a.label = 13;\n case 13:\n ++j;\n return [3 /*break*/, 11];\n case 14:\n ++i;\n return [3 /*break*/, 10];\n case 15:\n i = 0;\n _a.label = 16;\n case 16:\n if (!(i <= curLast)) return [3 /*break*/, 19];\n return [4 /*yield*/, map[last][i]];\n case 17:\n _a.sent();\n _a.label = 18;\n case 18:\n ++i;\n return [3 /*break*/, 16];\n case 19: return [2 /*return*/];\n }\n });\n })();\n };\n (function () {\n var _len = Deque.bucketSize;\n if (container.size) {\n _len = container.size();\n }\n else if (container.length) {\n _len = container.length;\n }\n var needSize = _len * Deque.sigma;\n bucketNum = Math.ceil(needSize / Deque.bucketSize);\n bucketNum = Math.max(bucketNum, 3);\n for (var i = 0; i < bucketNum; ++i) {\n map.push(new Array(Deque.bucketSize));\n }\n var needBucketNum = Math.ceil(_len / Deque.bucketSize);\n first = Math.floor(bucketNum / 2) - Math.floor(needBucketNum / 2);\n last = first;\n container.forEach(function (element) { return _this.pushBack(element); });\n })();\n Object.freeze(this);\n}\nObject.freeze(Deque);\nexports.default = Deque;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @param container\n * @param cmp default cmp will generate a max heap\n * @constructor\n */\nfunction PriorityQueue(container, cmp) {\n if (container === void 0) { container = []; }\n cmp = cmp || (function (x, y) {\n if (x > y)\n return -1;\n if (x < y)\n return 1;\n return 0;\n });\n var priorityQueue = [];\n container.forEach(function (element) { return priorityQueue.push(element); });\n var len = priorityQueue.length;\n var swap = function (x, y) {\n if (x < 0 || x >= len)\n throw new Error(\"unknown error\");\n if (y < 0 || y >= len)\n throw new Error(\"unknown error\");\n var tmp = priorityQueue[x];\n priorityQueue[x] = priorityQueue[y];\n priorityQueue[y] = tmp;\n };\n var adjust = function (parent) {\n if (parent < 0 || parent >= len)\n throw new Error(\"unknown error\");\n var leftChild = parent * 2 + 1;\n var rightChild = parent * 2 + 2;\n if (leftChild < len && cmp(priorityQueue[parent], priorityQueue[leftChild]) > 0)\n swap(parent, leftChild);\n if (rightChild < len && cmp(priorityQueue[parent], priorityQueue[rightChild]) > 0)\n swap(parent, rightChild);\n };\n (function () {\n for (var parent_1 = Math.floor((len - 1) / 2); parent_1 >= 0; --parent_1) {\n var curParent = parent_1;\n var curChild = curParent * 2 + 1;\n while (curChild < len) {\n var leftChild = curChild;\n var rightChild = leftChild + 1;\n var minChild = leftChild;\n if (rightChild < len && cmp(priorityQueue[leftChild], priorityQueue[rightChild]) > 0)\n minChild = rightChild;\n if (cmp(priorityQueue[curParent], priorityQueue[minChild]) <= 0)\n break;\n swap(curParent, minChild);\n curParent = minChild;\n curChild = curParent * 2 + 1;\n }\n }\n })();\n this.size = function () {\n return len;\n };\n this.empty = function () {\n return len === 0;\n };\n this.clear = function () {\n len = 0;\n priorityQueue.length = 0;\n };\n this.push = function (element) {\n priorityQueue.push(element);\n ++len;\n if (len === 1)\n return;\n var curNode = len - 1;\n while (curNode > 0) {\n var parent_2 = Math.floor((curNode - 1) / 2);\n if (cmp(priorityQueue[parent_2], element) <= 0)\n break;\n adjust(parent_2);\n curNode = parent_2;\n }\n };\n this.pop = function () {\n if (this.empty())\n return;\n if (this.size() === 1) {\n --len;\n return;\n }\n var last = priorityQueue[len - 1];\n --len;\n var parent = 0;\n while (parent < this.size()) {\n var leftChild = parent * 2 + 1;\n var rightChild = parent * 2 + 2;\n if (leftChild >= this.size())\n break;\n var minChild = leftChild;\n if (rightChild < this.size() && cmp(priorityQueue[leftChild], priorityQueue[rightChild]) > 0)\n minChild = rightChild;\n if (cmp(priorityQueue[minChild], last) >= 0)\n break;\n priorityQueue[parent] = priorityQueue[minChild];\n parent = minChild;\n }\n priorityQueue[parent] = last;\n };\n this.top = function () {\n return priorityQueue[0];\n };\n Object.freeze(this);\n}\nObject.freeze(PriorityQueue);\nexports.default = PriorityQueue;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar TreeNode = /** @class */ (function () {\n function TreeNode(key, value) {\n this.color = true;\n this.key = undefined;\n this.value = undefined;\n this.parent = undefined;\n this.brother = undefined;\n this.leftChild = undefined;\n this.rightChild = undefined;\n this.key = key;\n this.value = value;\n }\n TreeNode.prototype.rotateLeft = function () {\n var PP = this.parent;\n var PB = this.brother;\n var F = this.leftChild;\n var V = this.rightChild;\n if (!V)\n throw new Error(\"unknown error\");\n var R = V.leftChild;\n var X = V.rightChild;\n if (PP) {\n if (PP.leftChild === this)\n PP.leftChild = V;\n else if (PP.rightChild === this)\n PP.rightChild = V;\n }\n V.parent = PP;\n V.brother = PB;\n V.leftChild = this;\n V.rightChild = X;\n if (PB)\n PB.brother = V;\n this.parent = V;\n this.brother = X;\n this.leftChild = F;\n this.rightChild = R;\n if (X) {\n X.parent = V;\n X.brother = this;\n }\n if (F) {\n F.parent = this;\n F.brother = R;\n }\n if (R) {\n R.parent = this;\n R.brother = F;\n }\n return V;\n };\n TreeNode.prototype.rotateRight = function () {\n var PP = this.parent;\n var PB = this.brother;\n var F = this.leftChild;\n if (!F)\n throw new Error(\"unknown error\");\n var V = this.rightChild;\n var D = F.leftChild;\n var K = F.rightChild;\n if (PP) {\n if (PP.leftChild === this)\n PP.leftChild = F;\n else if (PP.rightChild === this)\n PP.rightChild = F;\n }\n F.parent = PP;\n F.brother = PB;\n F.leftChild = D;\n F.rightChild = this;\n if (PB)\n PB.brother = F;\n if (D) {\n D.parent = F;\n D.brother = this;\n }\n this.parent = F;\n this.brother = D;\n this.leftChild = K;\n this.rightChild = V;\n if (K) {\n K.parent = this;\n K.brother = V;\n }\n if (V) {\n V.parent = this;\n V.brother = K;\n }\n return F;\n };\n TreeNode.prototype.remove = function () {\n if (this.leftChild || this.rightChild)\n throw new Error(\"can only remove leaf node\");\n if (this.parent) {\n if (this === this.parent.leftChild)\n this.parent.leftChild = undefined;\n else if (this === this.parent.rightChild)\n this.parent.rightChild = undefined;\n }\n if (this.brother)\n this.brother.brother = undefined;\n this.key = undefined;\n this.value = undefined;\n this.parent = undefined;\n this.brother = undefined;\n };\n TreeNode.TreeNodeColorType = {\n red: true,\n black: false\n };\n return TreeNode;\n}());\nObject.freeze(TreeNode);\nexports.default = TreeNode;\n", "\"use strict\";\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar TreeNode_1 = require(\"../Base/TreeNode\");\nfunction Set(container, cmp) {\n var _this = this;\n if (container === void 0) { container = []; }\n cmp = cmp || (function (x, y) {\n if (x < y)\n return -1;\n if (x > y)\n return 1;\n return 0;\n });\n var len = 0;\n var root = new TreeNode_1.default();\n root.color = TreeNode_1.default.TreeNodeColorType.black;\n this.size = function () {\n return len;\n };\n this.empty = function () {\n return len === 0;\n };\n this.clear = function () {\n len = 0;\n root.key = undefined;\n root.leftChild = root.rightChild = root.brother = root.parent = undefined;\n root.color = TreeNode_1.default.TreeNodeColorType.black;\n };\n var findSubTreeMinNode = function (curNode) {\n if (!curNode || curNode.key === undefined)\n throw new Error(\"unknown error\");\n return curNode.leftChild ? findSubTreeMinNode(curNode.leftChild) : curNode;\n };\n var findSubTreeMaxNode = function (curNode) {\n if (!curNode || curNode.key === undefined)\n throw new Error(\"unknown error\");\n return curNode.rightChild ? findSubTreeMaxNode(curNode.rightChild) : curNode;\n };\n this.front = function () {\n if (this.empty())\n return undefined;\n var minNode = findSubTreeMinNode(root);\n return minNode.key;\n };\n this.back = function () {\n if (this.empty())\n return undefined;\n var maxNode = findSubTreeMaxNode(root);\n return maxNode.key;\n };\n this.forEach = function (callback) {\n var e_1, _a;\n var index = 0;\n try {\n for (var _b = __values(this), _c = _b.next(); !_c.done; _c = _b.next()) {\n var element = _c.value;\n callback(element, index++);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n };\n this.getElementByPos = function (pos) {\n var e_2, _a;\n if (pos < 0 || pos >= this.size())\n throw new Error(\"pos must more than 0 and less than set's size\");\n var index = 0;\n try {\n for (var _b = __values(this), _c = _b.next(); !_c.done; _c = _b.next()) {\n var element = _c.value;\n if (index === pos)\n return element;\n ++index;\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_2) throw e_2.error; }\n }\n throw new Error(\"unknown error\");\n };\n var eraseNodeSelfBalance = function (curNode) {\n var parentNode = curNode.parent;\n if (!parentNode) {\n if (curNode === root)\n return;\n throw new Error(\"unknown error\");\n }\n if (curNode.color === TreeNode_1.default.TreeNodeColorType.red) {\n curNode.color = TreeNode_1.default.TreeNodeColorType.black;\n return;\n }\n var brotherNode = curNode.brother;\n if (!brotherNode)\n throw new Error(\"unknown error\");\n if (curNode === parentNode.leftChild) {\n if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.red) {\n brotherNode.color = TreeNode_1.default.TreeNodeColorType.black;\n parentNode.color = TreeNode_1.default.TreeNodeColorType.red;\n var newRoot = parentNode.rotateLeft();\n if (root === parentNode)\n root = newRoot;\n eraseNodeSelfBalance(curNode);\n }\n else if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.black) {\n if (brotherNode.rightChild && brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.red) {\n brotherNode.color = parentNode.color;\n parentNode.color = TreeNode_1.default.TreeNodeColorType.black;\n if (brotherNode.rightChild)\n brotherNode.rightChild.color = TreeNode_1.default.TreeNodeColorType.black;\n var newRoot = parentNode.rotateLeft();\n if (root === parentNode)\n root = newRoot;\n curNode.color = TreeNode_1.default.TreeNodeColorType.black;\n }\n else if ((!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black) && brotherNode.leftChild && brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.red) {\n brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;\n if (brotherNode.leftChild)\n brotherNode.leftChild.color = TreeNode_1.default.TreeNodeColorType.black;\n var newRoot = brotherNode.rotateRight();\n if (root === brotherNode)\n root = newRoot;\n eraseNodeSelfBalance(curNode);\n }\n else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black)) {\n brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;\n eraseNodeSelfBalance(parentNode);\n }\n }\n }\n else if (curNode === parentNode.rightChild) {\n if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.red) {\n brotherNode.color = TreeNode_1.default.TreeNodeColorType.black;\n parentNode.color = TreeNode_1.default.TreeNodeColorType.red;\n var newRoot = parentNode.rotateRight();\n if (root === parentNode)\n root = newRoot;\n eraseNodeSelfBalance(curNode);\n }\n else if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.black) {\n if (brotherNode.leftChild && brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.red) {\n brotherNode.color = parentNode.color;\n parentNode.color = TreeNode_1.default.TreeNodeColorType.black;\n if (brotherNode.leftChild)\n brotherNode.leftChild.color = TreeNode_1.default.TreeNodeColorType.black;\n var newRoot = parentNode.rotateRight();\n if (root === parentNode)\n root = newRoot;\n curNode.color = TreeNode_1.default.TreeNodeColorType.black;\n }\n else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && brotherNode.rightChild && brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.red) {\n brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;\n if (brotherNode.rightChild)\n brotherNode.rightChild.color = TreeNode_1.default.TreeNodeColorType.black;\n var newRoot = brotherNode.rotateLeft();\n if (root === brotherNode)\n root = newRoot;\n eraseNodeSelfBalance(curNode);\n }\n else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black)) {\n brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;\n eraseNodeSelfBalance(parentNode);\n }\n }\n }\n };\n var eraseNode = function (curNode) {\n var swapNode = curNode;\n while (swapNode.leftChild || swapNode.rightChild) {\n if (swapNode.rightChild) {\n swapNode = findSubTreeMinNode(swapNode.rightChild);\n var tmpKey = curNode.key;\n curNode.key = swapNode.key;\n swapNode.key = tmpKey;\n curNode = swapNode;\n }\n if (swapNode.leftChild) {\n swapNode = findSubTreeMaxNode(swapNode.leftChild);\n var tmpKey = curNode.key;\n curNode.key = swapNode.key;\n swapNode.key = tmpKey;\n curNode = swapNode;\n }\n }\n eraseNodeSelfBalance(swapNode);\n if (swapNode)\n swapNode.remove();\n --len;\n root.color = TreeNode_1.default.TreeNodeColorType.black;\n };\n var inOrderTraversal = function (curNode, callback) {\n if (!curNode || curNode.key === undefined)\n return false;\n var ifReturn = inOrderTraversal(curNode.leftChild, callback);\n if (ifReturn)\n return true;\n if (callback(curNode))\n return true;\n return inOrderTraversal(curNode.rightChild, callback);\n };\n this.eraseElementByPos = function (pos) {\n if (pos < 0 || pos >= len)\n throw new Error(\"pos must more than 0 and less than set's size\");\n var index = 0;\n inOrderTraversal(root, function (curNode) {\n if (pos === index) {\n eraseNode(curNode);\n return true;\n }\n ++index;\n return false;\n });\n };\n this.eraseElementByValue = function (value) {\n if (this.empty())\n return;\n var curNode = findElementPos(root, value);\n if (curNode === undefined || curNode.key === undefined || cmp(curNode.key, value) !== 0)\n return;\n eraseNode(curNode);\n };\n var findInsertPos = function (curNode, element) {\n if (!curNode || curNode.key === undefined)\n throw new Error(\"unknown error\");\n var cmpResult = cmp(element, curNode.key);\n if (cmpResult < 0) {\n if (!curNode.leftChild) {\n curNode.leftChild = new TreeNode_1.default();\n curNode.leftChild.parent = curNode;\n curNode.leftChild.brother = curNode.rightChild;\n if (curNode.rightChild)\n curNode.rightChild.brother = curNode.leftChild;\n return curNode.leftChild;\n }\n return findInsertPos(curNode.leftChild, element);\n }\n else if (cmpResult > 0) {\n if (!curNode.rightChild) {\n curNode.rightChild = new TreeNode_1.default();\n curNode.rightChild.parent = curNode;\n curNode.rightChild.brother = curNode.leftChild;\n if (curNode.leftChild)\n curNode.leftChild.brother = curNode.rightChild;\n return curNode.rightChild;\n }\n return findInsertPos(curNode.rightChild, element);\n }\n return curNode;\n };\n var insertNodeSelfBalance = function (curNode) {\n var parentNode = curNode.parent;\n if (!parentNode) {\n if (curNode === root)\n return;\n throw new Error(\"unknown error\");\n }\n if (parentNode.color === TreeNode_1.default.TreeNodeColorType.black)\n return;\n if (parentNode.color === TreeNode_1.default.TreeNodeColorType.red) {\n var uncleNode = parentNode.brother;\n var grandParent = parentNode.parent;\n if (!grandParent)\n throw new Error(\"unknown error\");\n if (uncleNode && uncleNode.color === TreeNode_1.default.TreeNodeColorType.red) {\n uncleNode.color = parentNode.color = TreeNode_1.default.TreeNodeColorType.black;\n grandParent.color = TreeNode_1.default.TreeNodeColorType.red;\n insertNodeSelfBalance(grandParent);\n }\n else if (!uncleNode || uncleNode.color === TreeNode_1.default.TreeNodeColorType.black) {\n if (parentNode === grandParent.leftChild) {\n if (curNode === parentNode.leftChild) {\n parentNode.color = TreeNode_1.default.TreeNodeColorType.black;\n grandParent.color = TreeNode_1.default.TreeNodeColorType.red;\n var newRoot = grandParent.rotateRight();\n if (grandParent === root)\n root = newRoot;\n }\n else if (curNode === parentNode.rightChild) {\n var newRoot = parentNode.rotateLeft();\n if (grandParent === root)\n root = newRoot;\n insertNodeSelfBalance(parentNode);\n }\n }\n else if (parentNode === grandParent.rightChild) {\n if (curNode === parentNode.leftChild) {\n var newRoot = parentNode.rotateRight();\n if (grandParent === root)\n root = newRoot;\n insertNodeSelfBalance(parentNode);\n }\n else if (curNode === parentNode.rightChild) {\n parentNode.color = TreeNode_1.default.TreeNodeColorType.black;\n grandParent.color = TreeNode_1.default.TreeNodeColorType.red;\n var newRoot = grandParent.rotateLeft();\n if (grandParent === root)\n root = newRoot;\n }\n }\n }\n }\n };\n this.insert = function (element) {\n if (element === null || element === undefined) {\n throw new Error(\"to avoid some unnecessary errors, we don't suggest you insert null or undefined here\");\n }\n if (this.empty()) {\n ++len;\n root.key = element;\n root.color = TreeNode_1.default.TreeNodeColorType.black;\n return;\n }\n var curNode = findInsertPos(root, element);\n if (curNode.key !== undefined && cmp(curNode.key, element) === 0)\n return;\n ++len;\n curNode.key = element;\n insertNodeSelfBalance(curNode);\n root.color = TreeNode_1.default.TreeNodeColorType.black;\n };\n var findElementPos = function (curNode, element) {\n if (!curNode || curNode.key === undefined)\n return undefined;\n var cmpResult = cmp(element, curNode.key);\n if (cmpResult < 0)\n return findElementPos(curNode.leftChild, element);\n else if (cmpResult > 0)\n return findElementPos(curNode.rightChild, element);\n return curNode;\n };\n this.find = function (element) {\n var curNode = findElementPos(root, element);\n return curNode !== undefined && curNode.key !== undefined && cmp(curNode.key, element) === 0;\n };\n var _lowerBound = function (curNode, key) {\n if (!curNode || curNode.key === undefined)\n return undefined;\n var cmpResult = cmp(curNode.key, key);\n if (cmpResult === 0)\n return curNode.key;\n if (cmpResult < 0)\n return _lowerBound(curNode.rightChild, key);\n var res = _lowerBound(curNode.leftChild, key);\n if (res !== undefined)\n return res;\n return curNode.key;\n };\n this.lowerBound = function (key) {\n return _lowerBound(root, key);\n };\n var _upperBound = function (curNode, key) {\n if (!curNode || curNode.key === undefined)\n return undefined;\n var cmpResult = cmp(curNode.key, key);\n if (cmpResult <= 0)\n return _upperBound(curNode.rightChild, key);\n var res = _upperBound(curNode.leftChild, key);\n if (res !== undefined)\n return res;\n return curNode.key;\n };\n this.upperBound = function (key) {\n return _upperBound(root, key);\n };\n var _reverseLowerBound = function (curNode, key) {\n if (!curNode || curNode.key === undefined)\n return undefined;\n var cmpResult = cmp(curNode.key, key);\n if (cmpResult === 0)\n return curNode.key;\n if (cmpResult > 0)\n return _reverseLowerBound(curNode.leftChild, key);\n var res = _reverseLowerBound(curNode.rightChild, key);\n if (res !== undefined)\n return res;\n return curNode.key;\n };\n this.reverseLowerBound = function (key) {\n return _reverseLowerBound(root, key);\n };\n var _reverseUpperBound = function (curNode, key) {\n if (!curNode || curNode.key === undefined)\n return undefined;\n var cmpResult = cmp(curNode.key, key);\n if (cmpResult >= 0)\n return _reverseUpperBound(curNode.leftChild, key);\n var res = _reverseUpperBound(curNode.rightChild, key);\n if (res !== undefined)\n return res;\n return curNode.key;\n };\n this.reverseUpperBound = function (key) {\n return _reverseUpperBound(root, key);\n };\n // waiting for optimization, this is O(mlog(n+m)) algorithm now, but we expect it to be O(mlog(n/m+1)).\n // (https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Set_operations_and_bulk_operations)\n this.union = function (other) {\n var _this = this;\n other.forEach(function (element) { return _this.insert(element); });\n };\n this.getHeight = function () {\n if (this.empty())\n return 0;\n var traversal = function (curNode) {\n if (!curNode)\n return 1;\n return Math.max(traversal(curNode.leftChild), traversal(curNode.rightChild)) + 1;\n };\n return traversal(root);\n };\n var iterationFunc = function (curNode) {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!curNode || curNode.key === undefined)\n return [2 /*return*/];\n return [5 /*yield**/, __values(iterationFunc(curNode.leftChild))];\n case 1:\n _a.sent();\n return [4 /*yield*/, curNode.key];\n case 2:\n _a.sent();\n return [5 /*yield**/, __values(iterationFunc(curNode.rightChild))];\n case 3:\n _a.sent();\n return [2 /*return*/];\n }\n });\n };\n this[Symbol.iterator] = function () {\n return iterationFunc(root);\n };\n container.forEach(function (element) { return _this.insert(element); });\n Object.freeze(this);\n}\nObject.freeze(Set);\nexports.default = Set;\n", "\"use strict\";\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar TreeNode_1 = require(\"../Base/TreeNode\");\nfunction Map(container, cmp) {\n var _this = this;\n if (container === void 0) { container = []; }\n cmp = cmp || (function (x, y) {\n if (x < y)\n return -1;\n if (x > y)\n return 1;\n return 0;\n });\n var len = 0;\n var root = new TreeNode_1.default();\n root.color = TreeNode_1.default.TreeNodeColorType.black;\n this.size = function () {\n return len;\n };\n this.empty = function () {\n return len === 0;\n };\n this.clear = function () {\n len = 0;\n root.key = root.value = undefined;\n root.leftChild = root.rightChild = root.brother = undefined;\n };\n var findSubTreeMinNode = function (curNode) {\n if (!curNode || curNode.key === undefined)\n throw new Error(\"unknown error\");\n return curNode.leftChild ? findSubTreeMinNode(curNode.leftChild) : curNode;\n };\n var findSubTreeMaxNode = function (curNode) {\n if (!curNode || curNode.key === undefined)\n throw new Error(\"unknown error\");\n return curNode.rightChild ? findSubTreeMaxNode(curNode.rightChild) : curNode;\n };\n this.front = function () {\n if (this.empty())\n return undefined;\n var minNode = findSubTreeMinNode(root);\n if (minNode.key === undefined || minNode.value === undefined)\n throw new Error(\"unknown error\");\n return {\n key: minNode.key,\n value: minNode.value\n };\n };\n this.back = function () {\n if (this.empty())\n return undefined;\n var maxNode = findSubTreeMaxNode(root);\n if (maxNode.key === undefined || maxNode.value === undefined)\n throw new Error(\"unknown error\");\n return {\n key: maxNode.key,\n value: maxNode.value\n };\n };\n this.forEach = function (callback) {\n var e_1, _a;\n var index = 0;\n try {\n for (var _b = __values(this), _c = _b.next(); !_c.done; _c = _b.next()) {\n var pair = _c.value;\n callback(pair, index++);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n };\n this.getElementByPos = function (pos) {\n var e_2, _a;\n if (pos < 0 || pos >= this.size())\n throw new Error(\"pos must more than 0 and less than set's size\");\n var index = 0;\n try {\n for (var _b = __values(this), _c = _b.next(); !_c.done; _c = _b.next()) {\n var pair = _c.value;\n if (index === pos)\n return pair;\n ++index;\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_2) throw e_2.error; }\n }\n throw new Error(\"unknown Error\");\n };\n var _lowerBound = function (curNode, key) {\n if (!curNode || curNode.key === undefined || curNode.value === undefined)\n return undefined;\n var cmpResult = cmp(curNode.key, key);\n if (cmpResult === 0)\n return { key: curNode.key, value: curNode.value };\n if (cmpResult < 0)\n return _lowerBound(curNode.rightChild, key);\n return _lowerBound(curNode.leftChild, key) || {\n key: curNode.key,\n value: curNode.value\n };\n };\n this.lowerBound = function (key) {\n return _lowerBound(root, key);\n };\n var _upperBound = function (curNode, key) {\n if (!curNode || curNode.key === undefined || curNode.value === undefined)\n return undefined;\n var cmpResult = cmp(curNode.key, key);\n if (cmpResult <= 0)\n return _upperBound(curNode.rightChild, key);\n return _upperBound(curNode.leftChild, key) || {\n key: curNode.key,\n value: curNode.value\n };\n };\n this.upperBound = function (key) {\n return _upperBound(root, key);\n };\n var _reverseLowerBound = function (curNode, key) {\n if (!curNode || curNode.key === undefined || curNode.value === undefined)\n return undefined;\n var cmpResult = cmp(curNode.key, key);\n if (cmpResult === 0)\n return { key: curNode.key, value: curNode.value };\n if (cmpResult > 0)\n return _reverseLowerBound(curNode.leftChild, key);\n return _reverseLowerBound(curNode.rightChild, key) || {\n key: curNode.key,\n value: curNode.value\n };\n };\n this.reverseLowerBound = function (key) {\n return _reverseLowerBound(root, key);\n };\n var _reverseUpperBound = function (curNode, key) {\n if (!curNode || curNode.key === undefined || curNode.value === undefined)\n return undefined;\n var cmpResult = cmp(curNode.key, key);\n if (cmpResult >= 0)\n return _reverseUpperBound(curNode.leftChild, key);\n return _reverseUpperBound(curNode.rightChild, key) || {\n key: curNode.key,\n value: curNode.value\n };\n };\n this.reverseUpperBound = function (key) {\n return _reverseUpperBound(root, key);\n };\n var eraseNodeSelfBalance = function (curNode) {\n var parentNode = curNode.parent;\n if (!parentNode) {\n if (curNode === root)\n return;\n throw new Error(\"unknown error\");\n }\n if (curNode.color === TreeNode_1.default.TreeNodeColorType.red) {\n curNode.color = TreeNode_1.default.TreeNodeColorType.black;\n return;\n }\n var brotherNode = curNode.brother;\n if (!brotherNode)\n throw new Error(\"unknown error\");\n if (curNode === parentNode.leftChild) {\n if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.red) {\n brotherNode.color = TreeNode_1.default.TreeNodeColorType.black;\n parentNode.color = TreeNode_1.default.TreeNodeColorType.red;\n var newRoot = parentNode.rotateLeft();\n if (root === parentNode)\n root = newRoot;\n eraseNodeSelfBalance(curNode);\n }\n else if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.black) {\n if (brotherNode.rightChild && brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.red) {\n brotherNode.color = parentNode.color;\n parentNode.color = TreeNode_1.default.TreeNodeColorType.black;\n if (brotherNode.rightChild)\n brotherNode.rightChild.color = TreeNode_1.default.TreeNodeColorType.black;\n var newRoot = parentNode.rotateLeft();\n if (root === parentNode)\n root = newRoot;\n curNode.color = TreeNode_1.default.TreeNodeColorType.black;\n }\n else if ((!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black) && brotherNode.leftChild && brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.red) {\n brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;\n if (brotherNode.leftChild)\n brotherNode.leftChild.color = TreeNode_1.default.TreeNodeColorType.black;\n var newRoot = brotherNode.rotateRight();\n if (root === brotherNode)\n root = newRoot;\n eraseNodeSelfBalance(curNode);\n }\n else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black)) {\n brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;\n eraseNodeSelfBalance(parentNode);\n }\n }\n }\n else if (curNode === parentNode.rightChild) {\n if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.red) {\n brotherNode.color = TreeNode_1.default.TreeNodeColorType.black;\n parentNode.color = TreeNode_1.default.TreeNodeColorType.red;\n var newRoot = parentNode.rotateRight();\n if (root === parentNode)\n root = newRoot;\n eraseNodeSelfBalance(curNode);\n }\n else if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.black) {\n if (brotherNode.leftChild && brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.red) {\n brotherNode.color = parentNode.color;\n parentNode.color = TreeNode_1.default.TreeNodeColorType.black;\n if (brotherNode.leftChild)\n brotherNode.leftChild.color = TreeNode_1.default.TreeNodeColorType.black;\n var newRoot = parentNode.rotateRight();\n if (root === parentNode)\n root = newRoot;\n curNode.color = TreeNode_1.default.TreeNodeColorType.black;\n }\n else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && brotherNode.rightChild && brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.red) {\n brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;\n if (brotherNode.rightChild)\n brotherNode.rightChild.color = TreeNode_1.default.TreeNodeColorType.black;\n var newRoot = brotherNode.rotateLeft();\n if (root === brotherNode)\n root = newRoot;\n eraseNodeSelfBalance(curNode);\n }\n else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black)) {\n brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;\n eraseNodeSelfBalance(parentNode);\n }\n }\n }\n };\n var eraseNode = function (curNode) {\n var swapNode = curNode;\n while (swapNode.leftChild || swapNode.rightChild) {\n if (swapNode.rightChild) {\n swapNode = findSubTreeMinNode(swapNode.rightChild);\n var tmpKey = curNode.key;\n curNode.key = swapNode.key;\n swapNode.key = tmpKey;\n var tmpValue = curNode.value;\n curNode.value = swapNode.value;\n swapNode.value = tmpValue;\n curNode = swapNode;\n }\n if (swapNode.leftChild) {\n swapNode = findSubTreeMaxNode(swapNode.leftChild);\n var tmpKey = curNode.key;\n curNode.key = swapNode.key;\n swapNode.key = tmpKey;\n var tmpValue = curNode.value;\n curNode.value = swapNode.value;\n swapNode.value = tmpValue;\n curNode = swapNode;\n }\n }\n eraseNodeSelfBalance(swapNode);\n if (swapNode)\n swapNode.remove();\n --len;\n root.color = TreeNode_1.default.TreeNodeColorType.black;\n };\n var inOrderTraversal = function (curNode, callback) {\n if (!curNode || curNode.key === undefined)\n return false;\n var ifReturn = inOrderTraversal(curNode.leftChild, callback);\n if (ifReturn)\n return true;\n if (callback(curNode))\n return true;\n return inOrderTraversal(curNode.rightChild, callback);\n };\n this.eraseElementByPos = function (pos) {\n if (pos < 0 || pos >= len)\n throw new Error(\"pos must more than 0 and less than set's size\");\n var index = 0;\n inOrderTraversal(root, function (curNode) {\n if (pos === index) {\n eraseNode(curNode);\n return true;\n }\n ++index;\n return false;\n });\n };\n this.eraseElementByKey = function (key) {\n if (this.empty())\n return;\n var curNode = findElementPos(root, key);\n if (curNode === undefined || curNode.key === undefined || cmp(curNode.key, key) !== 0)\n return;\n eraseNode(curNode);\n };\n var findInsertPos = function (curNode, element) {\n if (!curNode || curNode.key === undefined)\n throw new Error(\"unknown error\");\n var cmpResult = cmp(element, curNode.key);\n if (cmpResult < 0) {\n if (!curNode.leftChild) {\n curNode.leftChild = new TreeNode_1.default();\n curNode.leftChild.parent = curNode;\n curNode.leftChild.brother = curNode.rightChild;\n if (curNode.rightChild)\n curNode.rightChild.brother = curNode.leftChild;\n return curNode.leftChild;\n }\n return findInsertPos(curNode.leftChild, element);\n }\n else if (cmpResult > 0) {\n if (!curNode.rightChild) {\n curNode.rightChild = new TreeNode_1.default();\n curNode.rightChild.parent = curNode;\n curNode.rightChild.brother = curNode.leftChild;\n if (curNode.leftChild)\n curNode.leftChild.brother = curNode.rightChild;\n return curNode.rightChild;\n }\n return findInsertPos(curNode.rightChild, element);\n }\n return curNode;\n };\n var insertNodeSelfBalance = function (curNode) {\n var parentNode = curNode.parent;\n if (!parentNode) {\n if (curNode === root)\n return;\n throw new Error(\"unknown error\");\n }\n if (parentNode.color === TreeNode_1.default.TreeNodeColorType.black)\n return;\n if (parentNode.color === TreeNode_1.default.TreeNodeColorType.red) {\n var uncleNode = parentNode.brother;\n var grandParent = parentNode.parent;\n if (!grandParent)\n throw new Error(\"unknown error\");\n if (uncleNode && uncleNode.color === TreeNode_1.default.TreeNodeColorType.red) {\n uncleNode.color = parentNode.color = TreeNode_1.default.TreeNodeColorType.black;\n grandParent.color = TreeNode_1.default.TreeNodeColorType.red;\n insertNodeSelfBalance(grandParent);\n }\n else if (!uncleNode || uncleNode.color === TreeNode_1.default.TreeNodeColorType.black) {\n if (parentNode === grandParent.leftChild) {\n if (curNode === parentNode.leftChild) {\n parentNode.color = TreeNode_1.default.TreeNodeColorType.black;\n grandParent.color = TreeNode_1.default.TreeNodeColorType.red;\n var newRoot = grandParent.rotateRight();\n if (grandParent === root)\n root = newRoot;\n }\n else if (curNode === parentNode.rightChild) {\n var newRoot = parentNode.rotateLeft();\n if (grandParent === root)\n root = newRoot;\n insertNodeSelfBalance(parentNode);\n }\n }\n else if (parentNode === grandParent.rightChild) {\n if (curNode === parentNode.leftChild) {\n var newRoot = parentNode.rotateRight();\n if (grandParent === root)\n root = newRoot;\n insertNodeSelfBalance(parentNode);\n }\n else if (curNode === parentNode.rightChild) {\n parentNode.color = TreeNode_1.default.TreeNodeColorType.black;\n grandParent.color = TreeNode_1.default.TreeNodeColorType.red;\n var newRoot = grandParent.rotateLeft();\n if (grandParent === root)\n root = newRoot;\n }\n }\n }\n }\n };\n this.setElement = function (key, value) {\n if (key === null || key === undefined) {\n throw new Error(\"to avoid some unnecessary errors, we don't suggest you insert null or undefined here\");\n }\n if (value === null || value === undefined) {\n this.eraseElementByKey(key);\n return;\n }\n if (this.empty()) {\n ++len;\n root.key = key;\n root.value = value;\n root.color = TreeNode_1.default.TreeNodeColorType.black;\n return;\n }\n var curNode = findInsertPos(root, key);\n if (curNode.key !== undefined && cmp(curNode.key, key) === 0) {\n curNode.value = value;\n return;\n }\n ++len;\n curNode.key = key;\n curNode.value = value;\n insertNodeSelfBalance(curNode);\n root.color = TreeNode_1.default.TreeNodeColorType.black;\n };\n var findElementPos = function (curNode, element) {\n if (!curNode || curNode.key === undefined)\n return undefined;\n var cmpResult = cmp(element, curNode.key);\n if (cmpResult < 0)\n return findElementPos(curNode.leftChild, element);\n else if (cmpResult > 0)\n return findElementPos(curNode.rightChild, element);\n return curNode;\n };\n this.find = function (element) {\n return !!findElementPos(root, element);\n };\n this.getElementByKey = function (element) {\n var curNode = findElementPos(root, element);\n if ((curNode === null || curNode === void 0 ? void 0 : curNode.key) === undefined || (curNode === null || curNode === void 0 ? void 0 : curNode.value) === undefined)\n throw new Error(\"unknown error\");\n return curNode.value;\n };\n // waiting for optimization, this is O(mlog(n+m)) algorithm now, but we expect it to be O(mlog(n/m+1)).\n // (https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Set_operations_and_bulk_operations)\n this.union = function (other) {\n var _this = this;\n other.forEach(function (_a) {\n var key = _a.key, value = _a.value;\n return _this.setElement(key, value);\n });\n };\n this.getHeight = function () {\n if (this.empty())\n return 0;\n var traversal = function (curNode) {\n if (!curNode)\n return 1;\n return Math.max(traversal(curNode.leftChild), traversal(curNode.rightChild)) + 1;\n };\n return traversal(root);\n };\n var iterationFunc = function (curNode) {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!curNode || curNode.key === undefined || curNode.value === undefined)\n return [2 /*return*/];\n return [5 /*yield**/, __values(iterationFunc(curNode.leftChild))];\n case 1:\n _a.sent();\n return [4 /*yield*/, { key: curNode.key, value: curNode.value }];\n case 2:\n _a.sent();\n return [5 /*yield**/, __values(iterationFunc(curNode.rightChild))];\n case 3:\n _a.sent();\n return [2 /*return*/];\n }\n });\n };\n this[Symbol.iterator] = function () {\n return iterationFunc(root);\n };\n container.forEach(function (_a) {\n var key = _a.key, value = _a.value;\n return _this.setElement(key, value);\n });\n Object.freeze(this);\n}\nObject.freeze(Map);\nexports.default = Map;\n", "\"use strict\";\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Set_1 = require(\"../Set/Set\");\nvar LinkList_1 = require(\"../LinkList/LinkList\");\nHashSet.initSize = (1 << 4);\nHashSet.maxSize = (1 << 30);\nHashSet.sigma = 0.75; // default load factor\nHashSet.treeifyThreshold = 8;\nHashSet.untreeifyThreshold = 6;\nHashSet.minTreeifySize = 64;\n/**\n * Note that resize is a time-consuming operation, please try to determine the number of buckets before use.\n * @param container Initialize the container\n * @param initBucketNum Initialize the bucket num\n * @param hashFunc Function to map elements to numbers\n * @constructor\n */\nfunction HashSet(container, initBucketNum, hashFunc) {\n var _this = this;\n if (container === void 0) { container = []; }\n if (initBucketNum === void 0) { initBucketNum = HashSet.initSize; }\n hashFunc = hashFunc || (function (x) {\n var hashCode = 0;\n var str = '';\n if (typeof x === \"number\") {\n hashCode = Math.floor(x);\n hashCode = ((hashCode << 5) - hashCode);\n hashCode = hashCode & hashCode;\n }\n else {\n if (typeof x !== \"string\") {\n str = JSON.stringify(x);\n }\n else\n str = x;\n for (var i = 0; i < str.length; i++) {\n var character = str.charCodeAt(i);\n hashCode = ((hashCode << 5) - hashCode) + character;\n hashCode = hashCode & hashCode;\n }\n }\n hashCode ^= (hashCode >>> 16);\n return hashCode;\n });\n if ((initBucketNum & (initBucketNum - 1)) !== 0) {\n throw new Error(\"initBucketNum must be 2 to the power of n\");\n }\n var len = 0;\n var hashTable = [];\n var bucketNum = Math.max(HashSet.initSize, Math.min(HashSet.maxSize, initBucketNum));\n this.size = function () {\n return len;\n };\n this.empty = function () {\n return len === 0;\n };\n this.clear = function () {\n len = 0;\n bucketNum = initBucketNum;\n hashTable = [];\n };\n this.forEach = function (callback) {\n var index = 0;\n hashTable.forEach(function (container) {\n container.forEach(function (element) {\n callback(element, index++);\n });\n });\n };\n var reAllocate = function (originalBucketNum) {\n if (originalBucketNum >= HashSet.maxSize)\n return;\n bucketNum = originalBucketNum * 2;\n var newHashTable = [];\n hashTable.forEach(function (container, index) {\n if (container.empty())\n return;\n if (container instanceof LinkList_1.default && container.size() === 1) {\n var element = container.front();\n if (element === undefined)\n throw new Error(\"unknown error\");\n newHashTable[hashFunc(element) & (bucketNum - 1)] = new LinkList_1.default([element]);\n }\n else if (container instanceof Set_1.default) {\n var lowList_1 = new LinkList_1.default();\n var highList_1 = new LinkList_1.default();\n container.forEach(function (element) {\n var hashCode = hashFunc(element);\n if ((hashCode & originalBucketNum) === 0) {\n lowList_1.pushBack(element);\n }\n else\n highList_1.pushBack(element);\n });\n if (lowList_1.size() > HashSet.untreeifyThreshold)\n newHashTable[index] = new Set_1.default(lowList_1);\n else if (lowList_1.size())\n newHashTable[index] = lowList_1;\n if (highList_1.size() > HashSet.untreeifyThreshold)\n newHashTable[index + originalBucketNum] = new Set_1.default(highList_1);\n else if (highList_1.size())\n newHashTable[index + originalBucketNum] = highList_1;\n }\n else {\n var lowList_2 = new LinkList_1.default();\n var highList_2 = new LinkList_1.default();\n container.forEach(function (element) {\n var hashCode = hashFunc(element);\n if ((hashCode & originalBucketNum) === 0) {\n lowList_2.pushBack(element);\n }\n else\n highList_2.pushBack(element);\n });\n if (lowList_2.size())\n newHashTable[index] = lowList_2;\n if (highList_2.size())\n newHashTable[index + originalBucketNum] = highList_2;\n }\n hashTable[index].clear();\n });\n hashTable = newHashTable;\n };\n this.insert = function (element) {\n if (element === null || element === undefined) {\n throw new Error(\"to avoid some unnecessary errors, we don't suggest you insert null or undefined here\");\n }\n var index = hashFunc(element) & (bucketNum - 1);\n if (!hashTable[index]) {\n hashTable[index] = new LinkList_1.default([element]);\n ++len;\n }\n else {\n var preSize = hashTable[index].size();\n if (hashTable[index] instanceof LinkList_1.default) {\n if (hashTable[index].find(element))\n return;\n hashTable[index].pushBack(element);\n if (hashTable[index].size() >= HashSet.treeifyThreshold) {\n hashTable[index] = new Set_1.default(hashTable[index]);\n }\n }\n else\n hashTable[index].insert(element);\n var curSize = hashTable[index].size();\n len += curSize - preSize;\n }\n if (len > bucketNum * HashSet.sigma) {\n reAllocate.call(this, bucketNum);\n }\n };\n this.eraseElementByValue = function (element) {\n var index = hashFunc(element) & (bucketNum - 1);\n if (!hashTable[index])\n return;\n var preSize = hashTable[index].size();\n hashTable[index].eraseElementByValue(element);\n if (hashTable[index] instanceof Set_1.default) {\n if (hashTable[index].size() <= HashSet.untreeifyThreshold) {\n hashTable[index] = new LinkList_1.default(hashTable[index]);\n }\n }\n var curSize = hashTable[index].size();\n len += curSize - preSize;\n };\n this.find = function (element) {\n var index = hashFunc(element) & (bucketNum - 1);\n if (!hashTable[index])\n return false;\n return hashTable[index].find(element);\n };\n this[Symbol.iterator] = function () {\n return (function () {\n var index, _a, _b, element, e_1_1;\n var e_1, _c;\n return __generator(this, function (_d) {\n switch (_d.label) {\n case 0:\n index = 0;\n _d.label = 1;\n case 1:\n if (!(index < bucketNum)) return [3 /*break*/, 10];\n while (index < bucketNum && !hashTable[index])\n ++index;\n if (index >= bucketNum)\n return [3 /*break*/, 10];\n _d.label = 2;\n case 2:\n _d.trys.push([2, 7, 8, 9]);\n _a = (e_1 = void 0, __values(hashTable[index])), _b = _a.next();\n _d.label = 3;\n case 3:\n if (!!_b.done) return [3 /*break*/, 6];\n element = _b.value;\n return [4 /*yield*/, element];\n case 4:\n _d.sent();\n _d.label = 5;\n case 5:\n _b = _a.next();\n return [3 /*break*/, 3];\n case 6: return [3 /*break*/, 9];\n case 7:\n e_1_1 = _d.sent();\n e_1 = { error: e_1_1 };\n return [3 /*break*/, 9];\n case 8:\n try {\n if (_b && !_b.done && (_c = _a.return)) _c.call(_a);\n }\n finally { if (e_1) throw e_1.error; }\n return [7 /*endfinally*/];\n case 9:\n ++index;\n return [3 /*break*/, 1];\n case 10: return [2 /*return*/];\n }\n });\n })();\n };\n container.forEach(function (element) { return _this.insert(element); });\n Object.freeze(this);\n}\nObject.freeze(HashSet);\nexports.default = HashSet;\n", "\"use strict\";\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar LinkList_1 = require(\"../LinkList/LinkList\");\nvar Map_1 = require(\"../Map/Map\");\nHashMap.initSize = (1 << 4);\nHashMap.maxSize = (1 << 30);\nHashMap.sigma = 0.75; // default load factor\nHashMap.treeifyThreshold = 8;\nHashMap.untreeifyThreshold = 6;\nHashMap.minTreeifySize = 64;\n/**\n * Note that resize is a time-consuming operation, please try to determine the number of buckets before use.\n * @param container Initialize the container\n * @param initBucketNum Initialize the bucket num, must be 2 to the power of n\n * @param hashFunc Function to map elements to numbers\n * @constructor\n */\nfunction HashMap(container, initBucketNum, hashFunc) {\n var _this = this;\n if (container === void 0) { container = []; }\n if (initBucketNum === void 0) { initBucketNum = HashMap.initSize; }\n hashFunc = hashFunc || (function (x) {\n var e_1, _a;\n var hashCode = 0;\n var str = '';\n if (typeof x === \"number\") {\n hashCode = Math.floor(x);\n hashCode = ((hashCode << 5) - hashCode);\n hashCode = hashCode & hashCode;\n }\n else {\n if (typeof x !== \"string\") {\n str = JSON.stringify(x);\n }\n else\n str = x;\n try {\n for (var str_1 = __values(str), str_1_1 = str_1.next(); !str_1_1.done; str_1_1 = str_1.next()) {\n var ch = str_1_1.value;\n var character = ch.charCodeAt(0);\n hashCode = ((hashCode << 5) - hashCode) + character;\n hashCode = hashCode & hashCode;\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (str_1_1 && !str_1_1.done && (_a = str_1.return)) _a.call(str_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n hashCode ^= (hashCode >>> 16);\n return hashCode;\n });\n if ((initBucketNum & (initBucketNum - 1)) !== 0) {\n throw new Error(\"initBucketNum must be 2 to the power of n\");\n }\n var len = 0;\n var hashTable = [];\n var bucketNum = Math.max(HashMap.initSize, Math.min(HashMap.maxSize, initBucketNum));\n this.size = function () {\n return len;\n };\n this.empty = function () {\n return len === 0;\n };\n this.clear = function () {\n len = 0;\n bucketNum = initBucketNum;\n hashTable = [];\n };\n this.forEach = function (callback) {\n var index = 0;\n hashTable.forEach(function (container) {\n container.forEach(function (element) {\n callback(element, index++);\n });\n });\n };\n var reAllocate = function (originalBucketNum) {\n if (originalBucketNum >= HashMap.maxSize)\n return;\n bucketNum = originalBucketNum * 2;\n var newHashTable = [];\n hashTable.forEach(function (container, index) {\n if (container.empty())\n return;\n if (container instanceof LinkList_1.default && container.size() === 1) {\n var _a = container.front(), key = _a.key, value = _a.value;\n newHashTable[hashFunc(key) & (bucketNum - 1)] = new LinkList_1.default([{\n key: key,\n value: value\n }]);\n }\n else if (container instanceof Map_1.default) {\n var lowList_1 = new LinkList_1.default();\n var highList_1 = new LinkList_1.default();\n container.forEach(function (pair) {\n var hashCode = hashFunc(pair.key);\n if ((hashCode & originalBucketNum) === 0) {\n lowList_1.pushBack(pair);\n }\n else\n highList_1.pushBack(pair);\n });\n if (lowList_1.size() > HashMap.untreeifyThreshold)\n newHashTable[index] = new Map_1.default(lowList_1);\n else if (lowList_1.size())\n newHashTable[index] = lowList_1;\n if (highList_1.size() > HashMap.untreeifyThreshold)\n newHashTable[index + originalBucketNum] = new Map_1.default(highList_1);\n else if (highList_1.size())\n newHashTable[index + originalBucketNum] = highList_1;\n }\n else {\n var lowList_2 = new LinkList_1.default();\n var highList_2 = new LinkList_1.default();\n container.forEach(function (pair) {\n var hashCode = hashFunc(pair.key);\n if ((hashCode & originalBucketNum) === 0) {\n lowList_2.pushBack(pair);\n }\n else\n highList_2.pushBack(pair);\n });\n if (lowList_2.size())\n newHashTable[index] = lowList_2;\n if (highList_2.size())\n newHashTable[index + originalBucketNum] = highList_2;\n }\n hashTable[index].clear();\n });\n hashTable = newHashTable;\n };\n this.setElement = function (key, value) {\n var e_2, _a;\n if (key === null || key === undefined) {\n throw new Error(\"to avoid some unnecessary errors, we don't suggest you insert null or undefined here\");\n }\n if (value === null || value === undefined) {\n this.eraseElementByKey(key);\n return;\n }\n var index = hashFunc(key) & (bucketNum - 1);\n if (!hashTable[index]) {\n ++len;\n hashTable[index] = new LinkList_1.default([{ key: key, value: value }]);\n }\n else {\n var preSize = hashTable[index].size();\n if (hashTable[index] instanceof LinkList_1.default) {\n try {\n for (var _b = __values(hashTable[index]), _c = _b.next(); !_c.done; _c = _b.next()) {\n var pair = _c.value;\n if (pair.key === key) {\n pair.value = value;\n return;\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_2) throw e_2.error; }\n }\n hashTable[index].pushBack({\n key: key,\n value: value,\n });\n if (hashTable[index].size() >= HashMap.treeifyThreshold) {\n hashTable[index] = new Map_1.default(hashTable[index]);\n }\n }\n else\n hashTable[index].setElement(key, value);\n var curSize = hashTable[index].size();\n len += curSize - preSize;\n }\n if (len > bucketNum * HashMap.sigma) {\n reAllocate.call(this, bucketNum);\n }\n };\n this.getElementByKey = function (key) {\n var e_3, _a;\n var index = hashFunc(key) & (bucketNum - 1);\n if (!hashTable[index])\n return undefined;\n if (hashTable[index] instanceof Map_1.default)\n return hashTable[index].getElementByKey(key);\n else {\n try {\n for (var _b = __values(hashTable[index]), _c = _b.next(); !_c.done; _c = _b.next()) {\n var pair = _c.value;\n if (pair.key === key)\n return pair.value;\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_3) throw e_3.error; }\n }\n return undefined;\n }\n };\n this.eraseElementByKey = function (key) {\n var e_4, _a;\n var index = hashFunc(key) & (bucketNum - 1);\n if (!hashTable[index])\n return;\n var preSize = hashTable[index].size();\n if (hashTable[index] instanceof Map_1.default) {\n hashTable[index].eraseElementByKey(key);\n if (hashTable[index].size() <= HashMap.untreeifyThreshold) {\n hashTable[index] = new LinkList_1.default(hashTable[index]);\n }\n }\n else {\n var pos = -1;\n try {\n for (var _b = __values(hashTable[index]), _c = _b.next(); !_c.done; _c = _b.next()) {\n var pair = _c.value;\n ++pos;\n if (pair.key === key) {\n hashTable[index].eraseElementByPos(pos);\n break;\n }\n }\n }\n catch (e_4_1) { e_4 = { error: e_4_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_4) throw e_4.error; }\n }\n }\n var curSize = hashTable[index].size();\n len += curSize - preSize;\n };\n this.find = function (key) {\n var e_5, _a;\n var index = hashFunc(key) & (bucketNum - 1);\n if (!hashTable[index])\n return false;\n if (hashTable[index] instanceof Map_1.default)\n return hashTable[index].find(key);\n try {\n for (var _b = __values(hashTable[index]), _c = _b.next(); !_c.done; _c = _b.next()) {\n var pair = _c.value;\n if (pair.key === key)\n return true;\n }\n }\n catch (e_5_1) { e_5 = { error: e_5_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_5) throw e_5.error; }\n }\n return false;\n };\n this[Symbol.iterator] = function () {\n return (function () {\n var index, _a, _b, pair, e_6_1;\n var e_6, _c;\n return __generator(this, function (_d) {\n switch (_d.label) {\n case 0:\n index = 0;\n _d.label = 1;\n case 1:\n if (!(index < bucketNum)) return [3 /*break*/, 10];\n while (index < bucketNum && !hashTable[index])\n ++index;\n if (index >= bucketNum)\n return [3 /*break*/, 10];\n _d.label = 2;\n case 2:\n _d.trys.push([2, 7, 8, 9]);\n _a = (e_6 = void 0, __values(hashTable[index])), _b = _a.next();\n _d.label = 3;\n case 3:\n if (!!_b.done) return [3 /*break*/, 6];\n pair = _b.value;\n return [4 /*yield*/, pair];\n case 4:\n _d.sent();\n _d.label = 5;\n case 5:\n _b = _a.next();\n return [3 /*break*/, 3];\n case 6: return [3 /*break*/, 9];\n case 7:\n e_6_1 = _d.sent();\n e_6 = { error: e_6_1 };\n return [3 /*break*/, 9];\n case 8:\n try {\n if (_b && !_b.done && (_c = _a.return)) _c.call(_a);\n }\n finally { if (e_6) throw e_6.error; }\n return [7 /*endfinally*/];\n case 9:\n ++index;\n return [3 /*break*/, 1];\n case 10: return [2 /*return*/];\n }\n });\n })();\n };\n container.forEach(function (_a) {\n var key = _a.key, value = _a.value;\n return _this.setElement(key, value);\n });\n Object.freeze(this);\n}\nObject.freeze(HashMap);\nexports.default = HashMap;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.HashMap = exports.HashSet = exports.Map = exports.Set = exports.PriorityQueue = exports.Deque = exports.LinkList = exports.Queue = exports.Stack = exports.Vector = void 0;\nvar Vector_1 = require(\"./Vector/Vector\");\nexports.Vector = Vector_1.default;\nvar Stack_1 = require(\"./Stack/Stack\");\nexports.Stack = Stack_1.default;\nvar Queue_1 = require(\"./Queue/Queue\");\nexports.Queue = Queue_1.default;\nvar LinkList_1 = require(\"./LinkList/LinkList\");\nexports.LinkList = LinkList_1.default;\nvar Deque_1 = require(\"./Deque/Deque\");\nexports.Deque = Deque_1.default;\nvar PriorityQueue_1 = require(\"./PriorityQueue/PriorityQueue\");\nexports.PriorityQueue = PriorityQueue_1.default;\nvar Set_1 = require(\"./Set/Set\");\nexports.Set = Set_1.default;\nvar Map_1 = require(\"./Map/Map\");\nexports.Map = Map_1.default;\nvar HashSet_1 = require(\"./HashSet/HashSet\");\nexports.HashSet = HashSet_1.default;\nvar HashMap_1 = require(\"./HashMap/HashMap\");\nexports.HashMap = HashMap_1.default;\n", "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "// Copyright Takatoshi Kondo 2021\n//\n// Distributed under the MIT License\n\n'use strict'\n\nconst SortedSet = require('js-sdsl').Set\nconst debugTrace = require('debug')('number-allocator:trace')\nconst debugError = require('debug')('number-allocator:error')\n/**\n * Interval constructor\n * @constructor\n * @param {Number} low - The lowest value of the interval\n * @param {Number} high - The highest value of the interval\n */\nfunction Interval (low, high) {\n this.low = low\n this.high = high\n}\n\nInterval.prototype.equals = function (other) {\n return this.low === other.low && this.high === other.high\n}\n\nInterval.prototype.compare = function (other) {\n if (this.low < other.low && this.high < other.low) return -1\n if (other.low < this.low && other.high < this.low) return 1\n return 0\n}\n\n/**\n * NumberAllocator constructor.\n * The all numbers are set to vacant status.\n * Time Complexity O(1)\n * @constructor\n * @param {Number} min - The maximum number of allocatable. The number must be integer.\n * @param {Number} maxh - The minimum number of allocatable. The number must be integer.\n */\nfunction NumberAllocator (min, max) {\n if (!(this instanceof NumberAllocator)) {\n return new NumberAllocator(min, max)\n }\n\n this.min = min\n this.max = max\n\n this.ss = new SortedSet(\n [],\n (lhs, rhs) => {\n return lhs.compare(rhs)\n }\n )\n debugTrace('Create')\n this.clear()\n}\n\n/**\n * Get the first vacant number. The status of the number is not updated.\n * Time Complexity O(1)\n * @return {Number} - The first vacant number. If all numbers are occupied, return null.\n * When alloc() is called then the same value will be allocated.\n */\nNumberAllocator.prototype.firstVacant = function () {\n if (this.ss.size() === 0) return null\n return this.ss.front().low\n}\n\n/**\n * Allocate the first vacant number. The number become occupied status.\n * Time Complexity O(1)\n * @return {Number} - The first vacant number. If all numbers are occupied, return null.\n */\nNumberAllocator.prototype.alloc = function () {\n if (this.ss.size() === 0) {\n debugTrace('alloc():empty')\n return null\n }\n const it = this.ss.front()\n const num = it.low\n if (num + 1 <= it.high) {\n // Overwrite the interval in the ss but it is safe,\n // because no order violation is happened.\n // x|----|\n ++it.low\n } else {\n this.ss.eraseElementByPos(0)\n }\n debugTrace('alloc():' + num)\n return num\n}\n\n/**\n * Use the number. The number become occupied status.\n * If the number has already been occupied, then return false.\n * Time Complexity O(logN) : N is the number of intervals (not numbers)\n * @param {Number} num - The number to request use.\n * @return {Boolean} - If `num` was not occupied, then return true, otherwise return false.\n */\nNumberAllocator.prototype.use = function (num) {\n const key = new Interval(num, num)\n const it = this.ss.lowerBound(key)\n if (it) {\n if (it.equals(key)) {\n // |x|\n this.ss.eraseElementByValue(it)\n debugTrace('use():' + num)\n return true\n }\n\n // x |-----|\n if (it.low > num) return false\n\n // |x----|\n if (it.low === num) {\n // Overwrite the interval in the ss but it is safe,\n // because no order violation is happened.\n // x|----|\n ++it.low\n debugTrace('use():' + num)\n return true\n }\n\n // |----x|\n if (it.high === num) {\n // Overwrite the interval in the ss but it is safe,\n // because no order violation is happened.\n // |----|x\n --it.high\n debugTrace('use():' + num)\n return true\n }\n\n const low = it.low\n\n // |--x--|\n // Overwrite the interval in the ss but it is safe,\n // because no order violation is happened.\n // x|--|\n it.low = num + 1\n\n // |--|x|--|\n this.ss.insert(new Interval(low, num - 1))\n debugTrace('use():' + num)\n return true\n }\n\n debugTrace('use():failed')\n return false\n}\n\n/**\n * Deallocate the number. The number become vacant status.\n * Time Complexity O(logN) : N is the number of intervals (not numbers)\n * @param {Number} num - The number to deallocate. The number must be occupied status.\n * In other words, the number must be allocated by alloc() or occupied be use().\n */\nNumberAllocator.prototype.free = function (num) {\n if (num < this.min || num > this.max) {\n debugError('free():' + num + ' is out of range')\n return\n }\n const key = new Interval(num, num)\n const it = this.ss.lowerBound(key)\n if (it) {\n if (it.low <= num && num <= it.high) {\n debugError('free():' + num + ' has already been vacant')\n return\n }\n if (it === this.ss.front()) {\n // v....\n if (num + 1 === it.low) {\n // Concat to right\n // Overwrite the interval in the ss but it is safe,\n // because no order violation is happened.\n --it.low\n } else {\n // Insert new interval\n this.ss.insert(key)\n }\n } else {\n // ..v..\n const itl = this.ss.reverseLowerBound(key)\n if (itl.high + 1 === num) {\n if (num + 1 === it.low) {\n // Concat to left and right\n this.ss.eraseElementByValue(itl)\n // Overwrite the interval in the ss but it is safe,\n // because no order violation is happened.\n it.low = itl.low\n } else {\n // Concat to left\n // Overwrite the interval in the ss but it is safe,\n // because no order violation is happened.\n itl.high = num\n }\n } else {\n if (num + 1 === it.low) {\n // Concat to right\n // Overwrite the interval in the ss but it is safe,\n // because no order violation is happened.\n it.low = num\n } else {\n // Insert new interval\n this.ss.insert(key)\n }\n }\n }\n } else {\n // ....v\n if (it === this.ss.front()) {\n // Insert new interval\n this.ss.insert(key)\n return\n }\n const itl = this.ss.reverseLowerBound(key)\n if (itl.high + 1 === num) {\n // Concat to left\n // Overwrite the interval in the ss but it is safe,\n // because no order violation is happened.\n itl.high = num\n } else {\n // Insert new interval\n this.ss.insert(key)\n }\n }\n debugTrace('free():' + num)\n}\n\n/**\n * Clear all occupied numbers.\n * The all numbers are set to vacant status.\n * Time Complexity O(1)\n */\nNumberAllocator.prototype.clear = function () {\n debugTrace('clear()')\n this.ss.clear()\n this.ss.insert(new Interval(this.min, this.max))\n}\n\n/**\n * Get the number of intervals. Interval is internal structure of this library.\n * This function is for debugging.\n * Time Complexity O(1)\n * @return {Number} - The number of intervals.\n */\nNumberAllocator.prototype.intervalCount = function () {\n return this.ss.size()\n}\n\n/**\n * Dump the internal structor of the library.\n * This function is for debugging.\n * Time Complexity O(N) : N is the number of intervals (not numbers)\n */\nNumberAllocator.prototype.dump = function () {\n console.log('length:' + this.ss.size())\n for (const element of this.ss) {\n console.log(element)\n }\n}\n\nmodule.exports = NumberAllocator\n", "// Copyright Takatoshi Kondo 2021\n//\n// Distributed under the MIT License\n\nconst NumberAllocator = require('./lib/number-allocator.js')\n\nmodule.exports.NumberAllocator = NumberAllocator\n", "'use strict'\n\n/**\n * Module dependencies\n */\nconst LruMap = require('lru-cache')\nconst NumberAllocator = require('number-allocator').NumberAllocator\n\n/**\n * Topic Alias sending manager\n * This holds both topic to alias and alias to topic map\n * @param {Number} [max] - topic alias maximum entries\n */\nfunction TopicAliasSend (max) {\n if (!(this instanceof TopicAliasSend)) {\n return new TopicAliasSend(max)\n }\n\n if (max > 0) {\n this.aliasToTopic = new LruMap({ max: max })\n this.topicToAlias = {}\n this.numberAllocator = new NumberAllocator(1, max)\n this.max = max\n this.length = 0\n }\n}\n\n/**\n * Insert or update topic - alias entry.\n * @param {String} [topic] - topic\n * @param {Number} [alias] - topic alias\n * @returns {Boolean} - if success return true otherwise false\n */\nTopicAliasSend.prototype.put = function (topic, alias) {\n if (alias === 0 || alias > this.max) {\n return false\n }\n const entry = this.aliasToTopic.get(alias)\n if (entry) {\n delete this.topicToAlias[entry]\n }\n this.aliasToTopic.set(alias, topic)\n this.topicToAlias[topic] = alias\n this.numberAllocator.use(alias)\n this.length = this.aliasToTopic.length\n return true\n}\n\n/**\n * Get topic by alias\n * @param {Number} [alias] - topic alias\n * @returns {String} - if mapped topic exists return topic, otherwise return undefined\n */\nTopicAliasSend.prototype.getTopicByAlias = function (alias) {\n return this.aliasToTopic.get(alias)\n}\n\n/**\n * Get topic by alias\n * @param {String} [topic] - topic\n * @returns {Number} - if mapped topic exists return topic alias, otherwise return undefined\n */\nTopicAliasSend.prototype.getAliasByTopic = function (topic) {\n const alias = this.topicToAlias[topic]\n if (typeof alias !== 'undefined') {\n this.aliasToTopic.get(alias) // LRU update\n }\n return alias\n}\n\n/**\n * Clear all entries\n */\nTopicAliasSend.prototype.clear = function () {\n this.aliasToTopic.reset()\n this.topicToAlias = {}\n this.numberAllocator.clear()\n this.length = 0\n}\n\n/**\n * Get Least Recently Used (LRU) topic alias\n * @returns {Number} - if vacant alias exists then return it, otherwise then return LRU alias\n */\nTopicAliasSend.prototype.getLruAlias = function () {\n const alias = this.numberAllocator.firstVacant()\n if (alias) return alias\n return this.aliasToTopic.keys()[this.aliasToTopic.length - 1]\n}\n\nmodule.exports = TopicAliasSend\n", "'use strict'\n\nconst { Buffer } = require('buffer')\nconst symbol = Symbol.for('BufferList')\n\nfunction BufferList (buf) {\n if (!(this instanceof BufferList)) {\n return new BufferList(buf)\n }\n\n BufferList._init.call(this, buf)\n}\n\nBufferList._init = function _init (buf) {\n Object.defineProperty(this, symbol, { value: true })\n\n this._bufs = []\n this.length = 0\n\n if (buf) {\n this.append(buf)\n }\n}\n\nBufferList.prototype._new = function _new (buf) {\n return new BufferList(buf)\n}\n\nBufferList.prototype._offset = function _offset (offset) {\n if (offset === 0) {\n return [0, 0]\n }\n\n let tot = 0\n\n for (let i = 0; i < this._bufs.length; i++) {\n const _t = tot + this._bufs[i].length\n if (offset < _t || i === this._bufs.length - 1) {\n return [i, offset - tot]\n }\n tot = _t\n }\n}\n\nBufferList.prototype._reverseOffset = function (blOffset) {\n const bufferId = blOffset[0]\n let offset = blOffset[1]\n\n for (let i = 0; i < bufferId; i++) {\n offset += this._bufs[i].length\n }\n\n return offset\n}\n\nBufferList.prototype.get = function get (index) {\n if (index > this.length || index < 0) {\n return undefined\n }\n\n const offset = this._offset(index)\n\n return this._bufs[offset[0]][offset[1]]\n}\n\nBufferList.prototype.slice = function slice (start, end) {\n if (typeof start === 'number' && start < 0) {\n start += this.length\n }\n\n if (typeof end === 'number' && end < 0) {\n end += this.length\n }\n\n return this.copy(null, 0, start, end)\n}\n\nBufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {\n if (typeof srcStart !== 'number' || srcStart < 0) {\n srcStart = 0\n }\n\n if (typeof srcEnd !== 'number' || srcEnd > this.length) {\n srcEnd = this.length\n }\n\n if (srcStart >= this.length) {\n return dst || Buffer.alloc(0)\n }\n\n if (srcEnd <= 0) {\n return dst || Buffer.alloc(0)\n }\n\n const copy = !!dst\n const off = this._offset(srcStart)\n const len = srcEnd - srcStart\n let bytes = len\n let bufoff = (copy && dstStart) || 0\n let start = off[1]\n\n // copy/slice everything\n if (srcStart === 0 && srcEnd === this.length) {\n if (!copy) {\n // slice, but full concat if multiple buffers\n return this._bufs.length === 1\n ? this._bufs[0]\n : Buffer.concat(this._bufs, this.length)\n }\n\n // copy, need to copy individual buffers\n for (let i = 0; i < this._bufs.length; i++) {\n this._bufs[i].copy(dst, bufoff)\n bufoff += this._bufs[i].length\n }\n\n return dst\n }\n\n // easy, cheap case where it's a subset of one of the buffers\n if (bytes <= this._bufs[off[0]].length - start) {\n return copy\n ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)\n : this._bufs[off[0]].slice(start, start + bytes)\n }\n\n if (!copy) {\n // a slice, we need something to copy in to\n dst = Buffer.allocUnsafe(len)\n }\n\n for (let i = off[0]; i < this._bufs.length; i++) {\n const l = this._bufs[i].length - start\n\n if (bytes > l) {\n this._bufs[i].copy(dst, bufoff, start)\n bufoff += l\n } else {\n this._bufs[i].copy(dst, bufoff, start, start + bytes)\n bufoff += l\n break\n }\n\n bytes -= l\n\n if (start) {\n start = 0\n }\n }\n\n // safeguard so that we don't return uninitialized memory\n if (dst.length > bufoff) return dst.slice(0, bufoff)\n\n return dst\n}\n\nBufferList.prototype.shallowSlice = function shallowSlice (start, end) {\n start = start || 0\n end = typeof end !== 'number' ? this.length : end\n\n if (start < 0) {\n start += this.length\n }\n\n if (end < 0) {\n end += this.length\n }\n\n if (start === end) {\n return this._new()\n }\n\n const startOffset = this._offset(start)\n const endOffset = this._offset(end)\n const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)\n\n if (endOffset[1] === 0) {\n buffers.pop()\n } else {\n buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1])\n }\n\n if (startOffset[1] !== 0) {\n buffers[0] = buffers[0].slice(startOffset[1])\n }\n\n return this._new(buffers)\n}\n\nBufferList.prototype.toString = function toString (encoding, start, end) {\n return this.slice(start, end).toString(encoding)\n}\n\nBufferList.prototype.consume = function consume (bytes) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) return this\n\n while (this._bufs.length) {\n if (bytes >= this._bufs[0].length) {\n bytes -= this._bufs[0].length\n this.length -= this._bufs[0].length\n this._bufs.shift()\n } else {\n this._bufs[0] = this._bufs[0].slice(bytes)\n this.length -= bytes\n break\n }\n }\n\n return this\n}\n\nBufferList.prototype.duplicate = function duplicate () {\n const copy = this._new()\n\n for (let i = 0; i < this._bufs.length; i++) {\n copy.append(this._bufs[i])\n }\n\n return copy\n}\n\nBufferList.prototype.append = function append (buf) {\n if (buf == null) {\n return this\n }\n\n if (buf.buffer) {\n // append a view of the underlying ArrayBuffer\n this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength))\n } else if (Array.isArray(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.append(buf[i])\n }\n } else if (this._isBufferList(buf)) {\n // unwrap argument into individual BufferLists\n for (let i = 0; i < buf._bufs.length; i++) {\n this.append(buf._bufs[i])\n }\n } else {\n // coerce number arguments to strings, since Buffer(number) does\n // uninitialized memory allocation\n if (typeof buf === 'number') {\n buf = buf.toString()\n }\n\n this._appendBuffer(Buffer.from(buf))\n }\n\n return this\n}\n\nBufferList.prototype._appendBuffer = function appendBuffer (buf) {\n this._bufs.push(buf)\n this.length += buf.length\n}\n\nBufferList.prototype.indexOf = function (search, offset, encoding) {\n if (encoding === undefined && typeof offset === 'string') {\n encoding = offset\n offset = undefined\n }\n\n if (typeof search === 'function' || Array.isArray(search)) {\n throw new TypeError('The \"value\" argument must be one of type string, Buffer, BufferList, or Uint8Array.')\n } else if (typeof search === 'number') {\n search = Buffer.from([search])\n } else if (typeof search === 'string') {\n search = Buffer.from(search, encoding)\n } else if (this._isBufferList(search)) {\n search = search.slice()\n } else if (Array.isArray(search.buffer)) {\n search = Buffer.from(search.buffer, search.byteOffset, search.byteLength)\n } else if (!Buffer.isBuffer(search)) {\n search = Buffer.from(search)\n }\n\n offset = Number(offset || 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n const blOffset = this._offset(offset)\n let blIndex = blOffset[0] // index of which internal buffer we're working on\n let buffOffset = blOffset[1] // offset of the internal buffer we're working on\n\n // scan over each buffer\n for (; blIndex < this._bufs.length; blIndex++) {\n const buff = this._bufs[blIndex]\n\n while (buffOffset < buff.length) {\n const availableWindow = buff.length - buffOffset\n\n if (availableWindow >= search.length) {\n const nativeSearchResult = buff.indexOf(search, buffOffset)\n\n if (nativeSearchResult !== -1) {\n return this._reverseOffset([blIndex, nativeSearchResult])\n }\n\n buffOffset = buff.length - search.length + 1 // end of native search window\n } else {\n const revOffset = this._reverseOffset([blIndex, buffOffset])\n\n if (this._match(revOffset, search)) {\n return revOffset\n }\n\n buffOffset++\n }\n }\n\n buffOffset = 0\n }\n\n return -1\n}\n\nBufferList.prototype._match = function (offset, search) {\n if (this.length - offset < search.length) {\n return false\n }\n\n for (let searchOffset = 0; searchOffset < search.length; searchOffset++) {\n if (this.get(offset + searchOffset) !== search[searchOffset]) {\n return false\n }\n }\n return true\n}\n\n;(function () {\n const methods = {\n readDoubleBE: 8,\n readDoubleLE: 8,\n readFloatBE: 4,\n readFloatLE: 4,\n readInt32BE: 4,\n readInt32LE: 4,\n readUInt32BE: 4,\n readUInt32LE: 4,\n readInt16BE: 2,\n readInt16LE: 2,\n readUInt16BE: 2,\n readUInt16LE: 2,\n readInt8: 1,\n readUInt8: 1,\n readIntBE: null,\n readIntLE: null,\n readUIntBE: null,\n readUIntLE: null\n }\n\n for (const m in methods) {\n (function (m) {\n if (methods[m] === null) {\n BufferList.prototype[m] = function (offset, byteLength) {\n return this.slice(offset, offset + byteLength)[m](0, byteLength)\n }\n } else {\n BufferList.prototype[m] = function (offset = 0) {\n return this.slice(offset, offset + methods[m])[m](0)\n }\n }\n }(m))\n }\n}())\n\n// Used internally by the class and also as an indicator of this object being\n// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser\n// environment because there could be multiple different copies of the\n// BufferList class and some `BufferList`s might be `BufferList`s.\nBufferList.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferList || BufferList.isBufferList(b)\n}\n\nBufferList.isBufferList = function isBufferList (b) {\n return b != null && b[symbol]\n}\n\nmodule.exports = BufferList\n", "'use strict'\n\nconst DuplexStream = require('readable-stream').Duplex\nconst inherits = require('inherits')\nconst BufferList = require('./BufferList')\n\nfunction BufferListStream (callback) {\n if (!(this instanceof BufferListStream)) {\n return new BufferListStream(callback)\n }\n\n if (typeof callback === 'function') {\n this._callback = callback\n\n const piper = function piper (err) {\n if (this._callback) {\n this._callback(err)\n this._callback = null\n }\n }.bind(this)\n\n this.on('pipe', function onPipe (src) {\n src.on('error', piper)\n })\n this.on('unpipe', function onUnpipe (src) {\n src.removeListener('error', piper)\n })\n\n callback = null\n }\n\n BufferList._init.call(this, callback)\n DuplexStream.call(this)\n}\n\ninherits(BufferListStream, DuplexStream)\nObject.assign(BufferListStream.prototype, BufferList.prototype)\n\nBufferListStream.prototype._new = function _new (callback) {\n return new BufferListStream(callback)\n}\n\nBufferListStream.prototype._write = function _write (buf, encoding, callback) {\n this._appendBuffer(buf)\n\n if (typeof callback === 'function') {\n callback()\n }\n}\n\nBufferListStream.prototype._read = function _read (size) {\n if (!this.length) {\n return this.push(null)\n }\n\n size = Math.min(size, this.length)\n this.push(this.slice(0, size))\n this.consume(size)\n}\n\nBufferListStream.prototype.end = function end (chunk) {\n DuplexStream.prototype.end.call(this, chunk)\n\n if (this._callback) {\n this._callback(null, this.slice())\n this._callback = null\n }\n}\n\nBufferListStream.prototype._destroy = function _destroy (err, cb) {\n this._bufs.length = 0\n this.length = 0\n cb(err)\n}\n\nBufferListStream.prototype._isBufferList = function _isBufferList (b) {\n return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b)\n}\n\nBufferListStream.isBufferList = BufferList.isBufferList\n\nmodule.exports = BufferListStream\nmodule.exports.BufferListStream = BufferListStream\nmodule.exports.BufferList = BufferList\n", "class Packet {\n constructor () {\n this.cmd = null\n this.retain = false\n this.qos = 0\n this.dup = false\n this.length = -1\n this.topic = null\n this.payload = null\n }\n}\n\nmodule.exports = Packet\n", "/* Protocol - protocol constants */\nconst protocol = module.exports\n\n/* Command code => mnemonic */\nprotocol.types = {\n 0: 'reserved',\n 1: 'connect',\n 2: 'connack',\n 3: 'publish',\n 4: 'puback',\n 5: 'pubrec',\n 6: 'pubrel',\n 7: 'pubcomp',\n 8: 'subscribe',\n 9: 'suback',\n 10: 'unsubscribe',\n 11: 'unsuback',\n 12: 'pingreq',\n 13: 'pingresp',\n 14: 'disconnect',\n 15: 'auth'\n}\n\n/* Mnemonic => Command code */\nprotocol.codes = {}\nfor (const k in protocol.types) {\n const v = protocol.types[k]\n protocol.codes[v] = k\n}\n\n/* Header */\nprotocol.CMD_SHIFT = 4\nprotocol.CMD_MASK = 0xF0\nprotocol.DUP_MASK = 0x08\nprotocol.QOS_MASK = 0x03\nprotocol.QOS_SHIFT = 1\nprotocol.RETAIN_MASK = 0x01\n\n/* Length */\nprotocol.VARBYTEINT_MASK = 0x7F\nprotocol.VARBYTEINT_FIN_MASK = 0x80\nprotocol.VARBYTEINT_MAX = 268435455\n\n/* Connack */\nprotocol.SESSIONPRESENT_MASK = 0x01\nprotocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK])\nprotocol.CONNACK_HEADER = Buffer.from([protocol.codes.connack << protocol.CMD_SHIFT])\n\n/* Connect */\nprotocol.USERNAME_MASK = 0x80\nprotocol.PASSWORD_MASK = 0x40\nprotocol.WILL_RETAIN_MASK = 0x20\nprotocol.WILL_QOS_MASK = 0x18\nprotocol.WILL_QOS_SHIFT = 3\nprotocol.WILL_FLAG_MASK = 0x04\nprotocol.CLEAN_SESSION_MASK = 0x02\nprotocol.CONNECT_HEADER = Buffer.from([protocol.codes.connect << protocol.CMD_SHIFT])\n\n/* Properties */\nprotocol.properties = {\n sessionExpiryInterval: 17,\n willDelayInterval: 24,\n receiveMaximum: 33,\n maximumPacketSize: 39,\n topicAliasMaximum: 34,\n requestResponseInformation: 25,\n requestProblemInformation: 23,\n userProperties: 38,\n authenticationMethod: 21,\n authenticationData: 22,\n payloadFormatIndicator: 1,\n messageExpiryInterval: 2,\n contentType: 3,\n responseTopic: 8,\n correlationData: 9,\n maximumQoS: 36,\n retainAvailable: 37,\n assignedClientIdentifier: 18,\n reasonString: 31,\n wildcardSubscriptionAvailable: 40,\n subscriptionIdentifiersAvailable: 41,\n sharedSubscriptionAvailable: 42,\n serverKeepAlive: 19,\n responseInformation: 26,\n serverReference: 28,\n topicAlias: 35,\n subscriptionIdentifier: 11\n}\nprotocol.propertiesCodes = {}\nfor (const prop in protocol.properties) {\n const id = protocol.properties[prop]\n protocol.propertiesCodes[id] = prop\n}\nprotocol.propertiesTypes = {\n sessionExpiryInterval: 'int32',\n willDelayInterval: 'int32',\n receiveMaximum: 'int16',\n maximumPacketSize: 'int32',\n topicAliasMaximum: 'int16',\n requestResponseInformation: 'byte',\n requestProblemInformation: 'byte',\n userProperties: 'pair',\n authenticationMethod: 'string',\n authenticationData: 'binary',\n payloadFormatIndicator: 'byte',\n messageExpiryInterval: 'int32',\n contentType: 'string',\n responseTopic: 'string',\n correlationData: 'binary',\n maximumQoS: 'int8',\n retainAvailable: 'byte',\n assignedClientIdentifier: 'string',\n reasonString: 'string',\n wildcardSubscriptionAvailable: 'byte',\n subscriptionIdentifiersAvailable: 'byte',\n sharedSubscriptionAvailable: 'byte',\n serverKeepAlive: 'int16',\n responseInformation: 'string',\n serverReference: 'string',\n topicAlias: 'int16',\n subscriptionIdentifier: 'var'\n}\n\nfunction genHeader (type) {\n return [0, 1, 2].map(qos => {\n return [0, 1].map(dup => {\n return [0, 1].map(retain => {\n const buf = Buffer.alloc(1)\n buf.writeUInt8(\n protocol.codes[type] << protocol.CMD_SHIFT |\n (dup ? protocol.DUP_MASK : 0) |\n qos << protocol.QOS_SHIFT | retain, 0, true)\n return buf\n })\n })\n })\n}\n\n/* Publish */\nprotocol.PUBLISH_HEADER = genHeader('publish')\n\n/* Subscribe */\nprotocol.SUBSCRIBE_HEADER = genHeader('subscribe')\nprotocol.SUBSCRIBE_OPTIONS_QOS_MASK = 0x03\nprotocol.SUBSCRIBE_OPTIONS_NL_MASK = 0x01\nprotocol.SUBSCRIBE_OPTIONS_NL_SHIFT = 2\nprotocol.SUBSCRIBE_OPTIONS_RAP_MASK = 0x01\nprotocol.SUBSCRIBE_OPTIONS_RAP_SHIFT = 3\nprotocol.SUBSCRIBE_OPTIONS_RH_MASK = 0x03\nprotocol.SUBSCRIBE_OPTIONS_RH_SHIFT = 4\nprotocol.SUBSCRIBE_OPTIONS_RH = [0x00, 0x10, 0x20]\nprotocol.SUBSCRIBE_OPTIONS_NL = 0x04\nprotocol.SUBSCRIBE_OPTIONS_RAP = 0x08\nprotocol.SUBSCRIBE_OPTIONS_QOS = [0x00, 0x01, 0x02]\n\n/* Unsubscribe */\nprotocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe')\n\n/* Confirmations */\nprotocol.ACKS = {\n unsuback: genHeader('unsuback'),\n puback: genHeader('puback'),\n pubcomp: genHeader('pubcomp'),\n pubrel: genHeader('pubrel'),\n pubrec: genHeader('pubrec')\n}\n\nprotocol.SUBACK_HEADER = Buffer.from([protocol.codes.suback << protocol.CMD_SHIFT])\n\n/* Protocol versions */\nprotocol.VERSION3 = Buffer.from([3])\nprotocol.VERSION4 = Buffer.from([4])\nprotocol.VERSION5 = Buffer.from([5])\nprotocol.VERSION131 = Buffer.from([131])\nprotocol.VERSION132 = Buffer.from([132])\n\n/* QoS */\nprotocol.QOS = [0, 1, 2].map(qos => {\n return Buffer.from([qos])\n})\n\n/* Empty packets */\nprotocol.EMPTY = {\n pingreq: Buffer.from([protocol.codes.pingreq << 4, 0]),\n pingresp: Buffer.from([protocol.codes.pingresp << 4, 0]),\n disconnect: Buffer.from([protocol.codes.disconnect << 4, 0])\n}\n", "const bl = require('bl')\nconst EventEmitter = require('events')\nconst Packet = require('./packet')\nconst constants = require('./constants')\nconst debug = require('debug')('mqtt-packet:parser')\n\nclass Parser extends EventEmitter {\n constructor () {\n super()\n this.parser = this.constructor.parser\n }\n\n static parser (opt) {\n if (!(this instanceof Parser)) return (new Parser()).parser(opt)\n\n this.settings = opt || {}\n\n this._states = [\n '_parseHeader',\n '_parseLength',\n '_parsePayload',\n '_newPacket'\n ]\n\n this._resetState()\n return this\n }\n\n _resetState () {\n debug('_resetState: resetting packet, error, _list, and _stateCounter')\n this.packet = new Packet()\n this.error = null\n this._list = bl()\n this._stateCounter = 0\n }\n\n parse (buf) {\n if (this.error) this._resetState()\n\n this._list.append(buf)\n debug('parse: current state: %s', this._states[this._stateCounter])\n while ((this.packet.length !== -1 || this._list.length > 0) &&\n this[this._states[this._stateCounter]]() &&\n !this.error) {\n this._stateCounter++\n debug('parse: state complete. _stateCounter is now: %d', this._stateCounter)\n debug('parse: packet.length: %d, buffer list length: %d', this.packet.length, this._list.length)\n if (this._stateCounter >= this._states.length) this._stateCounter = 0\n }\n debug('parse: exited while loop. packet: %d, buffer list length: %d', this.packet.length, this._list.length)\n return this._list.length\n }\n\n _parseHeader () {\n // There is at least one byte in the buffer\n const zero = this._list.readUInt8(0)\n this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT]\n this.packet.retain = (zero & constants.RETAIN_MASK) !== 0\n this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK\n this.packet.dup = (zero & constants.DUP_MASK) !== 0\n debug('_parseHeader: packet: %o', this.packet)\n\n this._list.consume(1)\n\n return true\n }\n\n _parseLength () {\n // There is at least one byte in the list\n const result = this._parseVarByteNum(true)\n\n if (result) {\n this.packet.length = result.value\n this._list.consume(result.bytes)\n }\n debug('_parseLength %d', result.value)\n return !!result\n }\n\n _parsePayload () {\n debug('_parsePayload: payload %O', this._list)\n let result = false\n\n // Do we have a payload? Do we have enough data to complete the payload?\n // PINGs have no payload\n if (this.packet.length === 0 || this._list.length >= this.packet.length) {\n this._pos = 0\n\n switch (this.packet.cmd) {\n case 'connect':\n this._parseConnect()\n break\n case 'connack':\n this._parseConnack()\n break\n case 'publish':\n this._parsePublish()\n break\n case 'puback':\n case 'pubrec':\n case 'pubrel':\n case 'pubcomp':\n this._parseConfirmation()\n break\n case 'subscribe':\n this._parseSubscribe()\n break\n case 'suback':\n this._parseSuback()\n break\n case 'unsubscribe':\n this._parseUnsubscribe()\n break\n case 'unsuback':\n this._parseUnsuback()\n break\n case 'pingreq':\n case 'pingresp':\n // These are empty, nothing to do\n break\n case 'disconnect':\n this._parseDisconnect()\n break\n case 'auth':\n this._parseAuth()\n break\n default:\n this._emitError(new Error('Not supported'))\n }\n\n result = true\n }\n debug('_parsePayload complete result: %s', result)\n return result\n }\n\n _parseConnect () {\n debug('_parseConnect')\n let topic // Will topic\n let payload // Will payload\n let password // Password\n let username // Username\n const flags = {}\n const packet = this.packet\n\n // Parse protocolId\n const protocolId = this._parseString()\n\n if (protocolId === null) return this._emitError(new Error('Cannot parse protocolId'))\n if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') {\n return this._emitError(new Error('Invalid protocolId'))\n }\n\n packet.protocolId = protocolId\n\n // Parse constants version number\n if (this._pos >= this._list.length) return this._emitError(new Error('Packet too short'))\n\n packet.protocolVersion = this._list.readUInt8(this._pos)\n\n if (packet.protocolVersion >= 128) {\n packet.bridgeMode = true\n packet.protocolVersion = packet.protocolVersion - 128\n }\n\n if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4 && packet.protocolVersion !== 5) {\n return this._emitError(new Error('Invalid protocol version'))\n }\n\n this._pos++\n\n if (this._pos >= this._list.length) {\n return this._emitError(new Error('Packet too short'))\n }\n\n // Parse connect flags\n flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK)\n flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK)\n flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK)\n\n if (flags.will) {\n packet.will = {}\n packet.will.retain = (this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) !== 0\n packet.will.qos = (this._list.readUInt8(this._pos) &\n constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT\n }\n\n packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0\n this._pos++\n\n // Parse keepalive\n packet.keepalive = this._parseNum()\n if (packet.keepalive === -1) return this._emitError(new Error('Packet too short'))\n\n // parse properties\n if (packet.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n // Parse clientId\n const clientId = this._parseString()\n if (clientId === null) return this._emitError(new Error('Packet too short'))\n packet.clientId = clientId\n debug('_parseConnect: packet.clientId: %s', packet.clientId)\n\n if (flags.will) {\n if (packet.protocolVersion === 5) {\n const willProperties = this._parseProperties()\n if (Object.getOwnPropertyNames(willProperties).length) {\n packet.will.properties = willProperties\n }\n }\n // Parse will topic\n topic = this._parseString()\n if (topic === null) return this._emitError(new Error('Cannot parse will topic'))\n packet.will.topic = topic\n debug('_parseConnect: packet.will.topic: %s', packet.will.topic)\n\n // Parse will payload\n payload = this._parseBuffer()\n if (payload === null) return this._emitError(new Error('Cannot parse will payload'))\n packet.will.payload = payload\n debug('_parseConnect: packet.will.paylaod: %s', packet.will.payload)\n }\n\n // Parse username\n if (flags.username) {\n username = this._parseString()\n if (username === null) return this._emitError(new Error('Cannot parse username'))\n packet.username = username\n debug('_parseConnect: packet.username: %s', packet.username)\n }\n\n // Parse password\n if (flags.password) {\n password = this._parseBuffer()\n if (password === null) return this._emitError(new Error('Cannot parse password'))\n packet.password = password\n }\n // need for right parse auth packet and self set up\n this.settings = packet\n debug('_parseConnect: complete')\n return packet\n }\n\n _parseConnack () {\n debug('_parseConnack')\n const packet = this.packet\n\n if (this._list.length < 1) return null\n packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants.SESSIONPRESENT_MASK)\n\n if (this.settings.protocolVersion === 5) {\n if (this._list.length >= 2) {\n packet.reasonCode = this._list.readUInt8(this._pos++)\n } else {\n packet.reasonCode = 0\n }\n } else {\n if (this._list.length < 2) return null\n packet.returnCode = this._list.readUInt8(this._pos++)\n }\n\n if (packet.returnCode === -1 || packet.reasonCode === -1) return this._emitError(new Error('Cannot parse return code'))\n // mqtt 5 properties\n if (this.settings.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n debug('_parseConnack: complete')\n }\n\n _parsePublish () {\n debug('_parsePublish')\n const packet = this.packet\n packet.topic = this._parseString()\n\n if (packet.topic === null) return this._emitError(new Error('Cannot parse topic'))\n\n // Parse messageId\n if (packet.qos > 0) if (!this._parseMessageId()) { return }\n\n // Properties mqtt 5\n if (this.settings.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n\n packet.payload = this._list.slice(this._pos, packet.length)\n debug('_parsePublish: payload from buffer list: %o', packet.payload)\n }\n\n _parseSubscribe () {\n debug('_parseSubscribe')\n const packet = this.packet\n let topic\n let options\n let qos\n let rh\n let rap\n let nl\n let subscription\n\n if (packet.qos !== 1) {\n return this._emitError(new Error('Wrong subscribe header'))\n }\n\n packet.subscriptions = []\n\n if (!this._parseMessageId()) { return }\n\n // Properties mqtt 5\n if (this.settings.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n\n while (this._pos < packet.length) {\n // Parse topic\n topic = this._parseString()\n if (topic === null) return this._emitError(new Error('Cannot parse topic'))\n if (this._pos >= packet.length) return this._emitError(new Error('Malformed Subscribe Payload'))\n\n options = this._parseByte()\n qos = options & constants.SUBSCRIBE_OPTIONS_QOS_MASK\n nl = ((options >> constants.SUBSCRIBE_OPTIONS_NL_SHIFT) & constants.SUBSCRIBE_OPTIONS_NL_MASK) !== 0\n rap = ((options >> constants.SUBSCRIBE_OPTIONS_RAP_SHIFT) & constants.SUBSCRIBE_OPTIONS_RAP_MASK) !== 0\n rh = (options >> constants.SUBSCRIBE_OPTIONS_RH_SHIFT) & constants.SUBSCRIBE_OPTIONS_RH_MASK\n\n subscription = { topic, qos }\n\n // mqtt 5 options\n if (this.settings.protocolVersion === 5) {\n subscription.nl = nl\n subscription.rap = rap\n subscription.rh = rh\n } else if (this.settings.bridgeMode) {\n subscription.rh = 0\n subscription.rap = true\n subscription.nl = true\n }\n\n // Push pair to subscriptions\n debug('_parseSubscribe: push subscription `%s` to subscription', subscription)\n packet.subscriptions.push(subscription)\n }\n }\n\n _parseSuback () {\n debug('_parseSuback')\n const packet = this.packet\n this.packet.granted = []\n\n if (!this._parseMessageId()) { return }\n\n // Properties mqtt 5\n if (this.settings.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n\n // Parse granted QoSes\n while (this._pos < this.packet.length) {\n this.packet.granted.push(this._list.readUInt8(this._pos++))\n }\n }\n\n _parseUnsubscribe () {\n debug('_parseUnsubscribe')\n const packet = this.packet\n\n packet.unsubscriptions = []\n\n // Parse messageId\n if (!this._parseMessageId()) { return }\n\n // Properties mqtt 5\n if (this.settings.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n\n while (this._pos < packet.length) {\n // Parse topic\n const topic = this._parseString()\n if (topic === null) return this._emitError(new Error('Cannot parse topic'))\n\n // Push topic to unsubscriptions\n debug('_parseUnsubscribe: push topic `%s` to unsubscriptions', topic)\n packet.unsubscriptions.push(topic)\n }\n }\n\n _parseUnsuback () {\n debug('_parseUnsuback')\n const packet = this.packet\n if (!this._parseMessageId()) return this._emitError(new Error('Cannot parse messageId'))\n // Properties mqtt 5\n if (this.settings.protocolVersion === 5) {\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n // Parse granted QoSes\n packet.granted = []\n while (this._pos < this.packet.length) {\n this.packet.granted.push(this._list.readUInt8(this._pos++))\n }\n }\n }\n\n // parse packets like puback, pubrec, pubrel, pubcomp\n _parseConfirmation () {\n debug('_parseConfirmation: packet.cmd: `%s`', this.packet.cmd)\n const packet = this.packet\n\n this._parseMessageId()\n\n if (this.settings.protocolVersion === 5) {\n if (packet.length > 2) {\n // response code\n packet.reasonCode = this._parseByte()\n debug('_parseConfirmation: packet.reasonCode `%d`', packet.reasonCode)\n } else {\n packet.reasonCode = 0\n }\n\n if (packet.length > 3) {\n // properies mqtt 5\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n }\n\n return true\n }\n\n // parse disconnect packet\n _parseDisconnect () {\n const packet = this.packet\n debug('_parseDisconnect')\n\n if (this.settings.protocolVersion === 5) {\n // response code\n if (this._list.length > 0) {\n packet.reasonCode = this._parseByte()\n } else {\n packet.reasonCode = 0\n }\n // properies mqtt 5\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n }\n\n debug('_parseDisconnect result: true')\n return true\n }\n\n // parse auth packet\n _parseAuth () {\n debug('_parseAuth')\n const packet = this.packet\n\n if (this.settings.protocolVersion !== 5) {\n return this._emitError(new Error('Not supported auth packet for this version MQTT'))\n }\n\n // response code\n packet.reasonCode = this._parseByte()\n // properies mqtt 5\n const properties = this._parseProperties()\n if (Object.getOwnPropertyNames(properties).length) {\n packet.properties = properties\n }\n\n debug('_parseAuth: result: true')\n return true\n }\n\n _parseMessageId () {\n const packet = this.packet\n\n packet.messageId = this._parseNum()\n\n if (packet.messageId === null) {\n this._emitError(new Error('Cannot parse messageId'))\n return false\n }\n\n debug('_parseMessageId: packet.messageId %d', packet.messageId)\n return true\n }\n\n _parseString (maybeBuffer) {\n const length = this._parseNum()\n const end = length + this._pos\n\n if (length === -1 || end > this._list.length || end > this.packet.length) return null\n\n const result = this._list.toString('utf8', this._pos, end)\n this._pos += length\n debug('_parseString: result: %s', result)\n return result\n }\n\n _parseStringPair () {\n debug('_parseStringPair')\n return {\n name: this._parseString(),\n value: this._parseString()\n }\n }\n\n _parseBuffer () {\n const length = this._parseNum()\n const end = length + this._pos\n\n if (length === -1 || end > this._list.length || end > this.packet.length) return null\n\n const result = this._list.slice(this._pos, end)\n\n this._pos += length\n debug('_parseBuffer: result: %o', result)\n return result\n }\n\n _parseNum () {\n if (this._list.length - this._pos < 2) return -1\n\n const result = this._list.readUInt16BE(this._pos)\n this._pos += 2\n debug('_parseNum: result: %s', result)\n return result\n }\n\n _parse4ByteNum () {\n if (this._list.length - this._pos < 4) return -1\n\n const result = this._list.readUInt32BE(this._pos)\n this._pos += 4\n debug('_parse4ByteNum: result: %s', result)\n return result\n }\n\n _parseVarByteNum (fullInfoFlag) {\n debug('_parseVarByteNum')\n const maxBytes = 4\n let bytes = 0\n let mul = 1\n let value = 0\n let result = false\n let current\n const padding = this._pos ? this._pos : 0\n\n while (bytes < maxBytes && (padding + bytes) < this._list.length) {\n current = this._list.readUInt8(padding + bytes++)\n value += mul * (current & constants.VARBYTEINT_MASK)\n mul *= 0x80\n\n if ((current & constants.VARBYTEINT_FIN_MASK) === 0) {\n result = true\n break\n }\n if (this._list.length <= bytes) {\n break\n }\n }\n\n if (!result && bytes === maxBytes && this._list.length >= bytes) {\n this._emitError(new Error('Invalid variable byte integer'))\n }\n\n if (padding) {\n this._pos += bytes\n }\n\n result = result\n ? fullInfoFlag ? {\n bytes,\n value\n } : value\n : false\n\n debug('_parseVarByteNum: result: %o', result)\n return result\n }\n\n _parseByte () {\n let result\n if (this._pos < this._list.length) {\n result = this._list.readUInt8(this._pos)\n this._pos++\n }\n debug('_parseByte: result: %o', result)\n return result\n }\n\n _parseByType (type) {\n debug('_parseByType: type: %s', type)\n switch (type) {\n case 'byte': {\n return this._parseByte() !== 0\n }\n case 'int8': {\n return this._parseByte()\n }\n case 'int16': {\n return this._parseNum()\n }\n case 'int32': {\n return this._parse4ByteNum()\n }\n case 'var': {\n return this._parseVarByteNum()\n }\n case 'string': {\n return this._parseString()\n }\n case 'pair': {\n return this._parseStringPair()\n }\n case 'binary': {\n return this._parseBuffer()\n }\n }\n }\n\n _parseProperties () {\n debug('_parseProperties')\n const length = this._parseVarByteNum()\n const start = this._pos\n const end = start + length\n const result = {}\n while (this._pos < end) {\n const type = this._parseByte()\n if (!type) {\n this._emitError(new Error('Cannot parse property code type'))\n return false\n }\n const name = constants.propertiesCodes[type]\n if (!name) {\n this._emitError(new Error('Unknown property'))\n return false\n }\n // user properties process\n if (name === 'userProperties') {\n if (!result[name]) {\n result[name] = Object.create(null)\n }\n const currentUserProperty = this._parseByType(constants.propertiesTypes[name])\n if (result[name][currentUserProperty.name]) {\n if (Array.isArray(result[name][currentUserProperty.name])) {\n result[name][currentUserProperty.name].push(currentUserProperty.value)\n } else {\n const currentValue = result[name][currentUserProperty.name]\n result[name][currentUserProperty.name] = [currentValue]\n result[name][currentUserProperty.name].push(currentUserProperty.value)\n }\n } else {\n result[name][currentUserProperty.name] = currentUserProperty.value\n }\n continue\n }\n if (result[name]) {\n if (Array.isArray(result[name])) {\n result[name].push(this._parseByType(constants.propertiesTypes[name]))\n } else {\n result[name] = [result[name]]\n result[name].push(this._parseByType(constants.propertiesTypes[name]))\n }\n } else {\n result[name] = this._parseByType(constants.propertiesTypes[name])\n }\n }\n return result\n }\n\n _newPacket () {\n debug('_newPacket')\n if (this.packet) {\n this._list.consume(this.packet.length)\n debug('_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d', this.packet.cmd, this.packet.payload, this.packet.length)\n this.emit('packet', this.packet)\n }\n debug('_newPacket: new packet')\n this.packet = new Packet()\n\n this._pos = 0\n\n return true\n }\n\n _emitError (err) {\n debug('_emitError')\n this.error = err\n this.emit('error', err)\n }\n}\n\nmodule.exports = Parser\n", "const max = 65536\nconst cache = {}\n\n// in node 6 Buffer.subarray returns a Uint8Array instead of a Buffer\n// later versions return a Buffer\n// alternative is Buffer.slice but that creates a new buffer\n// creating new buffers takes time\n// SubOk is only false on node < 8\nconst SubOk = Buffer.isBuffer(Buffer.from([1, 2]).subarray(0, 1))\n\nfunction generateBuffer (i) {\n const buffer = Buffer.allocUnsafe(2)\n buffer.writeUInt8(i >> 8, 0)\n buffer.writeUInt8(i & 0x00FF, 0 + 1)\n\n return buffer\n}\n\nfunction generateCache () {\n for (let i = 0; i < max; i++) {\n cache[i] = generateBuffer(i)\n }\n}\n\nfunction genBufVariableByteInt (num) {\n const maxLength = 4 // max 4 bytes\n let digit = 0\n let pos = 0\n const buffer = Buffer.allocUnsafe(maxLength)\n\n do {\n digit = num % 128 | 0\n num = num / 128 | 0\n if (num > 0) digit = digit | 0x80\n\n buffer.writeUInt8(digit, pos++)\n } while (num > 0 && pos < maxLength)\n\n if (num > 0) {\n pos = 0\n }\n\n return SubOk ? buffer.subarray(0, pos) : buffer.slice(0, pos)\n}\n\nfunction generate4ByteBuffer (num) {\n const buffer = Buffer.allocUnsafe(4)\n buffer.writeUInt32BE(num, 0)\n return buffer\n}\n\nmodule.exports = {\n cache,\n generateCache,\n generateNumber: generateBuffer,\n genBufVariableByteInt,\n generate4ByteBuffer\n}\n", "'use strict';\n\nif (typeof process === 'undefined' ||\n !process.version ||\n process.version.indexOf('v0.') === 0 ||\n process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n module.exports = { nextTick: nextTick };\n} else {\n module.exports = process\n}\n\nfunction nextTick(fn, arg1, arg2, arg3) {\n if (typeof fn !== 'function') {\n throw new TypeError('\"callback\" argument must be a function');\n }\n var len = arguments.length;\n var args, i;\n switch (len) {\n case 0:\n case 1:\n return process.nextTick(fn);\n case 2:\n return process.nextTick(function afterTickOne() {\n fn.call(null, arg1);\n });\n case 3:\n return process.nextTick(function afterTickTwo() {\n fn.call(null, arg1, arg2);\n });\n case 4:\n return process.nextTick(function afterTickThree() {\n fn.call(null, arg1, arg2, arg3);\n });\n default:\n args = new Array(len - 1);\n i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n return process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n }\n}\n\n", "const protocol = require('./constants')\nconst empty = Buffer.allocUnsafe(0)\nconst zeroBuf = Buffer.from([0])\nconst numbers = require('./numbers')\nconst nextTick = require('process-nextick-args').nextTick\nconst debug = require('debug')('mqtt-packet:writeToStream')\n\nconst numCache = numbers.cache\nconst generateNumber = numbers.generateNumber\nconst generateCache = numbers.generateCache\nconst genBufVariableByteInt = numbers.genBufVariableByteInt\nconst generate4ByteBuffer = numbers.generate4ByteBuffer\nlet writeNumber = writeNumberCached\nlet toGenerate = true\n\nfunction generate (packet, stream, opts) {\n debug('generate called')\n if (stream.cork) {\n stream.cork()\n nextTick(uncork, stream)\n }\n\n if (toGenerate) {\n toGenerate = false\n generateCache()\n }\n debug('generate: packet.cmd: %s', packet.cmd)\n switch (packet.cmd) {\n case 'connect':\n return connect(packet, stream, opts)\n case 'connack':\n return connack(packet, stream, opts)\n case 'publish':\n return publish(packet, stream, opts)\n case 'puback':\n case 'pubrec':\n case 'pubrel':\n case 'pubcomp':\n return confirmation(packet, stream, opts)\n case 'subscribe':\n return subscribe(packet, stream, opts)\n case 'suback':\n return suback(packet, stream, opts)\n case 'unsubscribe':\n return unsubscribe(packet, stream, opts)\n case 'unsuback':\n return unsuback(packet, stream, opts)\n case 'pingreq':\n case 'pingresp':\n return emptyPacket(packet, stream, opts)\n case 'disconnect':\n return disconnect(packet, stream, opts)\n case 'auth':\n return auth(packet, stream, opts)\n default:\n stream.emit('error', new Error('Unknown command'))\n return false\n }\n}\n/**\n * Controls numbers cache.\n * Set to \"false\" to allocate buffers on-the-flight instead of pre-generated cache\n */\nObject.defineProperty(generate, 'cacheNumbers', {\n get () {\n return writeNumber === writeNumberCached\n },\n set (value) {\n if (value) {\n if (!numCache || Object.keys(numCache).length === 0) toGenerate = true\n writeNumber = writeNumberCached\n } else {\n toGenerate = false\n writeNumber = writeNumberGenerated\n }\n }\n})\n\nfunction uncork (stream) {\n stream.uncork()\n}\n\nfunction connect (packet, stream, opts) {\n const settings = packet || {}\n const protocolId = settings.protocolId || 'MQTT'\n let protocolVersion = settings.protocolVersion || 4\n const will = settings.will\n let clean = settings.clean\n const keepalive = settings.keepalive || 0\n const clientId = settings.clientId || ''\n const username = settings.username\n const password = settings.password\n /* mqtt5 new oprions */\n const properties = settings.properties\n\n if (clean === undefined) clean = true\n\n let length = 0\n\n // Must be a string and non-falsy\n if (!protocolId ||\n (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) {\n stream.emit('error', new Error('Invalid protocolId'))\n return false\n } else length += protocolId.length + 2\n\n // Must be 3 or 4 or 5\n if (protocolVersion !== 3 && protocolVersion !== 4 && protocolVersion !== 5) {\n stream.emit('error', new Error('Invalid protocol version'))\n return false\n } else length += 1\n\n // ClientId might be omitted in 3.1.1 and 5, but only if cleanSession is set to 1\n if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) &&\n (clientId || protocolVersion >= 4) && (clientId || clean)) {\n length += Buffer.byteLength(clientId) + 2\n } else {\n if (protocolVersion < 4) {\n stream.emit('error', new Error('clientId must be supplied before 3.1.1'))\n return false\n }\n if ((clean * 1) === 0) {\n stream.emit('error', new Error('clientId must be given if cleanSession set to 0'))\n return false\n }\n }\n\n // Must be a two byte number\n if (typeof keepalive !== 'number' ||\n keepalive < 0 ||\n keepalive > 65535 ||\n keepalive % 1 !== 0) {\n stream.emit('error', new Error('Invalid keepalive'))\n return false\n } else length += 2\n\n // Connect flags\n length += 1\n\n // Properties\n if (protocolVersion === 5) {\n var propertiesData = getProperties(stream, properties)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // If will exists...\n if (will) {\n // It must be an object\n if (typeof will !== 'object') {\n stream.emit('error', new Error('Invalid will'))\n return false\n }\n // It must have topic typeof string\n if (!will.topic || typeof will.topic !== 'string') {\n stream.emit('error', new Error('Invalid will topic'))\n return false\n } else {\n length += Buffer.byteLength(will.topic) + 2\n }\n\n // Payload\n length += 2 // payload length\n if (will.payload) {\n if (will.payload.length >= 0) {\n if (typeof will.payload === 'string') {\n length += Buffer.byteLength(will.payload)\n } else {\n length += will.payload.length\n }\n } else {\n stream.emit('error', new Error('Invalid will payload'))\n return false\n }\n }\n // will properties\n var willProperties = {}\n if (protocolVersion === 5) {\n willProperties = getProperties(stream, will.properties)\n if (!willProperties) { return false }\n length += willProperties.length\n }\n }\n\n // Username\n let providedUsername = false\n if (username != null) {\n if (isStringOrBuffer(username)) {\n providedUsername = true\n length += Buffer.byteLength(username) + 2\n } else {\n stream.emit('error', new Error('Invalid username'))\n return false\n }\n }\n\n // Password\n if (password != null) {\n if (!providedUsername) {\n stream.emit('error', new Error('Username is required to use password'))\n return false\n }\n\n if (isStringOrBuffer(password)) {\n length += byteLength(password) + 2\n } else {\n stream.emit('error', new Error('Invalid password'))\n return false\n }\n }\n\n // Generate header\n stream.write(protocol.CONNECT_HEADER)\n\n // Generate length\n writeVarByteInt(stream, length)\n\n // Generate protocol ID\n writeStringOrBuffer(stream, protocolId)\n\n if (settings.bridgeMode) {\n protocolVersion += 128\n }\n\n stream.write(\n protocolVersion === 131\n ? protocol.VERSION131\n : protocolVersion === 132\n ? protocol.VERSION132\n : protocolVersion === 4\n ? protocol.VERSION4\n : protocolVersion === 5\n ? protocol.VERSION5\n : protocol.VERSION3\n )\n\n // Connect flags\n let flags = 0\n flags |= (username != null) ? protocol.USERNAME_MASK : 0\n flags |= (password != null) ? protocol.PASSWORD_MASK : 0\n flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0\n flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0\n flags |= will ? protocol.WILL_FLAG_MASK : 0\n flags |= clean ? protocol.CLEAN_SESSION_MASK : 0\n\n stream.write(Buffer.from([flags]))\n\n // Keepalive\n writeNumber(stream, keepalive)\n\n // Properties\n if (protocolVersion === 5) {\n propertiesData.write()\n }\n\n // Client ID\n writeStringOrBuffer(stream, clientId)\n\n // Will\n if (will) {\n if (protocolVersion === 5) {\n willProperties.write()\n }\n writeString(stream, will.topic)\n writeStringOrBuffer(stream, will.payload)\n }\n\n // Username and password\n if (username != null) {\n writeStringOrBuffer(stream, username)\n }\n if (password != null) {\n writeStringOrBuffer(stream, password)\n }\n // This is a small packet that happens only once on a stream\n // We assume the stream is always free to receive more data after this\n return true\n}\n\nfunction connack (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const rc = version === 5 ? settings.reasonCode : settings.returnCode\n const properties = settings.properties\n let length = 2 // length of rc and sessionHeader\n\n // Check return code\n if (typeof rc !== 'number') {\n stream.emit('error', new Error('Invalid return code'))\n return false\n }\n // mqtt5 properties\n let propertiesData = null\n if (version === 5) {\n propertiesData = getProperties(stream, properties)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n stream.write(protocol.CONNACK_HEADER)\n // length\n writeVarByteInt(stream, length)\n stream.write(settings.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf)\n\n stream.write(Buffer.from([rc]))\n if (propertiesData != null) {\n propertiesData.write()\n }\n return true\n}\n\nfunction publish (packet, stream, opts) {\n debug('publish: packet: %o', packet)\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const qos = settings.qos || 0\n const retain = settings.retain ? protocol.RETAIN_MASK : 0\n const topic = settings.topic\n const payload = settings.payload || empty\n const id = settings.messageId\n const properties = settings.properties\n\n let length = 0\n\n // Topic must be a non-empty string or Buffer\n if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2\n else if (Buffer.isBuffer(topic)) length += topic.length + 2\n else {\n stream.emit('error', new Error('Invalid topic'))\n return false\n }\n\n // Get the payload length\n if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload)\n else length += payload.length\n\n // Message ID must a number if qos > 0\n if (qos && typeof id !== 'number') {\n stream.emit('error', new Error('Invalid messageId'))\n return false\n } else if (qos) length += 2\n\n // mqtt5 properties\n let propertiesData = null\n if (version === 5) {\n propertiesData = getProperties(stream, properties)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // Header\n stream.write(protocol.PUBLISH_HEADER[qos][settings.dup ? 1 : 0][retain ? 1 : 0])\n\n // Remaining length\n writeVarByteInt(stream, length)\n\n // Topic\n writeNumber(stream, byteLength(topic))\n stream.write(topic)\n\n // Message ID\n if (qos > 0) writeNumber(stream, id)\n\n // Properties\n if (propertiesData != null) {\n propertiesData.write()\n }\n\n // Payload\n debug('publish: payload: %o', payload)\n return stream.write(payload)\n}\n\n/* Puback, pubrec, pubrel and pubcomp */\nfunction confirmation (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const type = settings.cmd || 'puback'\n const id = settings.messageId\n const dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0\n let qos = 0\n const reasonCode = settings.reasonCode\n const properties = settings.properties\n let length = version === 5 ? 3 : 2\n\n if (type === 'pubrel') qos = 1\n\n // Check message ID\n if (typeof id !== 'number') {\n stream.emit('error', new Error('Invalid messageId'))\n return false\n }\n\n // properies mqtt 5\n let propertiesData = null\n if (version === 5) {\n // Confirm should not add empty property length with no properties (rfc 3.4.2.2.1)\n if (typeof properties === 'object') {\n propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n }\n\n // Header\n stream.write(protocol.ACKS[type][qos][dup][0])\n\n // Length\n writeVarByteInt(stream, length)\n\n // Message ID\n writeNumber(stream, id)\n\n // reason code in header\n if (version === 5) {\n stream.write(Buffer.from([reasonCode]))\n }\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n return true\n}\n\nfunction subscribe (packet, stream, opts) {\n debug('subscribe: packet: ')\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const dup = settings.dup ? protocol.DUP_MASK : 0\n const id = settings.messageId\n const subs = settings.subscriptions\n const properties = settings.properties\n\n let length = 0\n\n // Check message ID\n if (typeof id !== 'number') {\n stream.emit('error', new Error('Invalid messageId'))\n return false\n } else length += 2\n\n // properies mqtt 5\n let propertiesData = null\n if (version === 5) {\n propertiesData = getProperties(stream, properties)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // Check subscriptions\n if (typeof subs === 'object' && subs.length) {\n for (let i = 0; i < subs.length; i += 1) {\n const itopic = subs[i].topic\n const iqos = subs[i].qos\n\n if (typeof itopic !== 'string') {\n stream.emit('error', new Error('Invalid subscriptions - invalid topic'))\n return false\n }\n if (typeof iqos !== 'number') {\n stream.emit('error', new Error('Invalid subscriptions - invalid qos'))\n return false\n }\n\n if (version === 5) {\n const nl = subs[i].nl || false\n if (typeof nl !== 'boolean') {\n stream.emit('error', new Error('Invalid subscriptions - invalid No Local'))\n return false\n }\n const rap = subs[i].rap || false\n if (typeof rap !== 'boolean') {\n stream.emit('error', new Error('Invalid subscriptions - invalid Retain as Published'))\n return false\n }\n const rh = subs[i].rh || 0\n if (typeof rh !== 'number' || rh > 2) {\n stream.emit('error', new Error('Invalid subscriptions - invalid Retain Handling'))\n return false\n }\n }\n\n length += Buffer.byteLength(itopic) + 2 + 1\n }\n } else {\n stream.emit('error', new Error('Invalid subscriptions'))\n return false\n }\n\n // Generate header\n debug('subscribe: writing to stream: %o', protocol.SUBSCRIBE_HEADER)\n stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0])\n\n // Generate length\n writeVarByteInt(stream, length)\n\n // Generate message ID\n writeNumber(stream, id)\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n\n let result = true\n\n // Generate subs\n for (const sub of subs) {\n const jtopic = sub.topic\n const jqos = sub.qos\n const jnl = +sub.nl\n const jrap = +sub.rap\n const jrh = sub.rh\n let joptions\n\n // Write topic string\n writeString(stream, jtopic)\n\n // options process\n joptions = protocol.SUBSCRIBE_OPTIONS_QOS[jqos]\n if (version === 5) {\n joptions |= jnl ? protocol.SUBSCRIBE_OPTIONS_NL : 0\n joptions |= jrap ? protocol.SUBSCRIBE_OPTIONS_RAP : 0\n joptions |= jrh ? protocol.SUBSCRIBE_OPTIONS_RH[jrh] : 0\n }\n // Write options\n result = stream.write(Buffer.from([joptions]))\n }\n\n return result\n}\n\nfunction suback (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const id = settings.messageId\n const granted = settings.granted\n const properties = settings.properties\n let length = 0\n\n // Check message ID\n if (typeof id !== 'number') {\n stream.emit('error', new Error('Invalid messageId'))\n return false\n } else length += 2\n\n // Check granted qos vector\n if (typeof granted === 'object' && granted.length) {\n for (let i = 0; i < granted.length; i += 1) {\n if (typeof granted[i] !== 'number') {\n stream.emit('error', new Error('Invalid qos vector'))\n return false\n }\n length += 1\n }\n } else {\n stream.emit('error', new Error('Invalid qos vector'))\n return false\n }\n\n // properies mqtt 5\n let propertiesData = null\n if (version === 5) {\n propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // header\n stream.write(protocol.SUBACK_HEADER)\n\n // Length\n writeVarByteInt(stream, length)\n\n // Message ID\n writeNumber(stream, id)\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n\n return stream.write(Buffer.from(granted))\n}\n\nfunction unsubscribe (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const id = settings.messageId\n const dup = settings.dup ? protocol.DUP_MASK : 0\n const unsubs = settings.unsubscriptions\n const properties = settings.properties\n\n let length = 0\n\n // Check message ID\n if (typeof id !== 'number') {\n stream.emit('error', new Error('Invalid messageId'))\n return false\n } else {\n length += 2\n }\n // Check unsubs\n if (typeof unsubs === 'object' && unsubs.length) {\n for (let i = 0; i < unsubs.length; i += 1) {\n if (typeof unsubs[i] !== 'string') {\n stream.emit('error', new Error('Invalid unsubscriptions'))\n return false\n }\n length += Buffer.byteLength(unsubs[i]) + 2\n }\n } else {\n stream.emit('error', new Error('Invalid unsubscriptions'))\n return false\n }\n // properies mqtt 5\n let propertiesData = null\n if (version === 5) {\n propertiesData = getProperties(stream, properties)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // Header\n stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0])\n\n // Length\n writeVarByteInt(stream, length)\n\n // Message ID\n writeNumber(stream, id)\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n\n // Unsubs\n let result = true\n for (let j = 0; j < unsubs.length; j++) {\n result = writeString(stream, unsubs[j])\n }\n\n return result\n}\n\nfunction unsuback (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const id = settings.messageId\n const dup = settings.dup ? protocol.DUP_MASK : 0\n const granted = settings.granted\n const properties = settings.properties\n const type = settings.cmd\n const qos = 0\n\n let length = 2\n\n // Check message ID\n if (typeof id !== 'number') {\n stream.emit('error', new Error('Invalid messageId'))\n return false\n }\n\n // Check granted\n if (version === 5) {\n if (typeof granted === 'object' && granted.length) {\n for (let i = 0; i < granted.length; i += 1) {\n if (typeof granted[i] !== 'number') {\n stream.emit('error', new Error('Invalid qos vector'))\n return false\n }\n length += 1\n }\n } else {\n stream.emit('error', new Error('Invalid qos vector'))\n return false\n }\n }\n\n // properies mqtt 5\n let propertiesData = null\n if (version === 5) {\n propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // Header\n stream.write(protocol.ACKS[type][qos][dup][0])\n\n // Length\n writeVarByteInt(stream, length)\n\n // Message ID\n writeNumber(stream, id)\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n\n // payload\n if (version === 5) {\n stream.write(Buffer.from(granted))\n }\n return true\n}\n\nfunction emptyPacket (packet, stream, opts) {\n return stream.write(protocol.EMPTY[packet.cmd])\n}\n\nfunction disconnect (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const reasonCode = settings.reasonCode\n const properties = settings.properties\n let length = version === 5 ? 1 : 0\n\n // properies mqtt 5\n let propertiesData = null\n if (version === 5) {\n propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)\n if (!propertiesData) { return false }\n length += propertiesData.length\n }\n\n // Header\n stream.write(Buffer.from([protocol.codes.disconnect << 4]))\n\n // Length\n writeVarByteInt(stream, length)\n\n // reason code in header\n if (version === 5) {\n stream.write(Buffer.from([reasonCode]))\n }\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n\n return true\n}\n\nfunction auth (packet, stream, opts) {\n const version = opts ? opts.protocolVersion : 4\n const settings = packet || {}\n const reasonCode = settings.reasonCode\n const properties = settings.properties\n let length = version === 5 ? 1 : 0\n\n if (version !== 5) stream.emit('error', new Error('Invalid mqtt version for auth packet'))\n\n // properies mqtt 5\n const propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)\n if (!propertiesData) { return false }\n length += propertiesData.length\n\n // Header\n stream.write(Buffer.from([protocol.codes.auth << 4]))\n\n // Length\n writeVarByteInt(stream, length)\n\n // reason code in header\n stream.write(Buffer.from([reasonCode]))\n\n // properies mqtt 5\n if (propertiesData !== null) {\n propertiesData.write()\n }\n return true\n}\n\n/**\n * writeVarByteInt - write an MQTT style variable byte integer to the buffer\n *\n * @param buffer - destination\n * @param pos - offset\n * @param length - length (>0)\n * @returns number of bytes written\n *\n * @api private\n */\n\nconst varByteIntCache = {}\nfunction writeVarByteInt (stream, num) {\n if (num > protocol.VARBYTEINT_MAX) {\n stream.emit('error', new Error(`Invalid variable byte integer: ${num}`))\n return false\n }\n\n let buffer = varByteIntCache[num]\n\n if (!buffer) {\n buffer = genBufVariableByteInt(num)\n if (num < 16384) varByteIntCache[num] = buffer\n }\n debug('writeVarByteInt: writing to stream: %o', buffer)\n return stream.write(buffer)\n}\n\n/**\n * writeString - write a utf8 string to the buffer\n *\n * @param buffer - destination\n * @param pos - offset\n * @param string - string to write\n * @return number of bytes written\n *\n * @api private\n */\n\nfunction writeString (stream, string) {\n const strlen = Buffer.byteLength(string)\n writeNumber(stream, strlen)\n\n debug('writeString: %s', string)\n return stream.write(string, 'utf8')\n}\n\n/**\n * writeStringPair - write a utf8 string pairs to the buffer\n *\n * @param buffer - destination\n * @param name - string name to write\n * @param value - string value to write\n * @return number of bytes written\n *\n * @api private\n */\nfunction writeStringPair (stream, name, value) {\n writeString(stream, name)\n writeString(stream, value)\n}\n\n/**\n * writeNumber - write a two byte number to the buffer\n *\n * @param buffer - destination\n * @param pos - offset\n * @param number - number to write\n * @return number of bytes written\n *\n * @api private\n */\nfunction writeNumberCached (stream, number) {\n debug('writeNumberCached: number: %d', number)\n debug('writeNumberCached: %o', numCache[number])\n return stream.write(numCache[number])\n}\nfunction writeNumberGenerated (stream, number) {\n const generatedNumber = generateNumber(number)\n debug('writeNumberGenerated: %o', generatedNumber)\n return stream.write(generatedNumber)\n}\nfunction write4ByteNumber (stream, number) {\n const generated4ByteBuffer = generate4ByteBuffer(number)\n debug('write4ByteNumber: %o', generated4ByteBuffer)\n return stream.write(generated4ByteBuffer)\n}\n/**\n * writeStringOrBuffer - write a String or Buffer with the its length prefix\n *\n * @param buffer - destination\n * @param pos - offset\n * @param toWrite - String or Buffer\n * @return number of bytes written\n */\nfunction writeStringOrBuffer (stream, toWrite) {\n if (typeof toWrite === 'string') {\n writeString(stream, toWrite)\n } else if (toWrite) {\n writeNumber(stream, toWrite.length)\n stream.write(toWrite)\n } else writeNumber(stream, 0)\n}\n\nfunction getProperties (stream, properties) {\n /* connect properties */\n if (typeof properties !== 'object' || properties.length != null) {\n return {\n length: 1,\n write () {\n writeProperties(stream, {}, 0)\n }\n }\n }\n let propertiesLength = 0\n function getLengthProperty (name, value) {\n const type = protocol.propertiesTypes[name]\n let length = 0\n switch (type) {\n case 'byte': {\n if (typeof value !== 'boolean') {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + 1\n break\n }\n case 'int8': {\n if (typeof value !== 'number' || value < 0 || value > 0xff) {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + 1\n break\n }\n case 'binary': {\n if (value && value === null) {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + Buffer.byteLength(value) + 2\n break\n }\n case 'int16': {\n if (typeof value !== 'number' || value < 0 || value > 0xffff) {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + 2\n break\n }\n case 'int32': {\n if (typeof value !== 'number' || value < 0 || value > 0xffffffff) {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + 4\n break\n }\n case 'var': {\n // var byte integer is max 24 bits packed in 32 bits\n if (typeof value !== 'number' || value < 0 || value > 0x0fffffff) {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + Buffer.byteLength(genBufVariableByteInt(value))\n break\n }\n case 'string': {\n if (typeof value !== 'string') {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += 1 + 2 + Buffer.byteLength(value.toString())\n break\n }\n case 'pair': {\n if (typeof value !== 'object') {\n stream.emit('error', new Error(`Invalid ${name}: ${value}`))\n return false\n }\n length += Object.getOwnPropertyNames(value).reduce((result, name) => {\n const currentValue = value[name]\n if (Array.isArray(currentValue)) {\n result += currentValue.reduce((currentLength, value) => {\n currentLength += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value.toString())\n return currentLength\n }, 0)\n } else {\n result += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value[name].toString())\n }\n return result\n }, 0)\n break\n }\n default: {\n stream.emit('error', new Error(`Invalid property ${name}: ${value}`))\n return false\n }\n }\n return length\n }\n if (properties) {\n for (const propName in properties) {\n let propLength = 0\n let propValueLength = 0\n const propValue = properties[propName]\n if (Array.isArray(propValue)) {\n for (let valueIndex = 0; valueIndex < propValue.length; valueIndex++) {\n propValueLength = getLengthProperty(propName, propValue[valueIndex])\n if (!propValueLength) { return false }\n propLength += propValueLength\n }\n } else {\n propValueLength = getLengthProperty(propName, propValue)\n if (!propValueLength) { return false }\n propLength = propValueLength\n }\n if (!propLength) return false\n propertiesLength += propLength\n }\n }\n const propertiesLengthLength = Buffer.byteLength(genBufVariableByteInt(propertiesLength))\n\n return {\n length: propertiesLengthLength + propertiesLength,\n write () {\n writeProperties(stream, properties, propertiesLength)\n }\n }\n}\n\nfunction getPropertiesByMaximumPacketSize (stream, properties, opts, length) {\n const mayEmptyProps = ['reasonString', 'userProperties']\n const maximumPacketSize = opts && opts.properties && opts.properties.maximumPacketSize ? opts.properties.maximumPacketSize : 0\n\n let propertiesData = getProperties(stream, properties)\n if (maximumPacketSize) {\n while (length + propertiesData.length > maximumPacketSize) {\n const currentMayEmptyProp = mayEmptyProps.shift()\n if (currentMayEmptyProp && properties[currentMayEmptyProp]) {\n delete properties[currentMayEmptyProp]\n propertiesData = getProperties(stream, properties)\n } else {\n return false\n }\n }\n }\n return propertiesData\n}\n\nfunction writeProperty (stream, propName, value) {\n const type = protocol.propertiesTypes[propName]\n switch (type) {\n case 'byte': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n stream.write(Buffer.from([+value]))\n break\n }\n case 'int8': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n stream.write(Buffer.from([value]))\n break\n }\n case 'binary': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n writeStringOrBuffer(stream, value)\n break\n }\n case 'int16': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n writeNumber(stream, value)\n break\n }\n case 'int32': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n write4ByteNumber(stream, value)\n break\n }\n case 'var': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n writeVarByteInt(stream, value)\n break\n }\n case 'string': {\n stream.write(Buffer.from([protocol.properties[propName]]))\n writeString(stream, value)\n break\n }\n case 'pair': {\n Object.getOwnPropertyNames(value).forEach(name => {\n const currentValue = value[name]\n if (Array.isArray(currentValue)) {\n currentValue.forEach(value => {\n stream.write(Buffer.from([protocol.properties[propName]]))\n writeStringPair(stream, name.toString(), value.toString())\n })\n } else {\n stream.write(Buffer.from([protocol.properties[propName]]))\n writeStringPair(stream, name.toString(), currentValue.toString())\n }\n })\n break\n }\n default: {\n stream.emit('error', new Error(`Invalid property ${propName} value: ${value}`))\n return false\n }\n }\n}\n\nfunction writeProperties (stream, properties, propertiesLength) {\n /* write properties to stream */\n writeVarByteInt(stream, propertiesLength)\n for (const propName in properties) {\n if (Object.prototype.hasOwnProperty.call(properties, propName) && properties[propName] !== null) {\n const value = properties[propName]\n if (Array.isArray(value)) {\n for (let valueIndex = 0; valueIndex < value.length; valueIndex++) {\n writeProperty(stream, propName, value[valueIndex])\n }\n } else {\n writeProperty(stream, propName, value)\n }\n }\n }\n}\n\nfunction byteLength (bufOrString) {\n if (!bufOrString) return 0\n else if (bufOrString instanceof Buffer) return bufOrString.length\n else return Buffer.byteLength(bufOrString)\n}\n\nfunction isStringOrBuffer (field) {\n return typeof field === 'string' || field instanceof Buffer\n}\n\nmodule.exports = generate\n", "const writeToStream = require('./writeToStream')\nconst EventEmitter = require('events')\n\nfunction generate (packet, opts) {\n const stream = new Accumulator()\n writeToStream(packet, stream, opts)\n return stream.concat()\n}\n\nclass Accumulator extends EventEmitter {\n constructor () {\n super()\n this._array = new Array(20)\n this._i = 0\n }\n\n write (chunk) {\n this._array[this._i++] = chunk\n return true\n }\n\n concat () {\n let length = 0\n const lengths = new Array(this._array.length)\n const list = this._array\n let pos = 0\n let i\n\n for (i = 0; i < list.length && list[i] !== undefined; i++) {\n if (typeof list[i] !== 'string') lengths[i] = list[i].length\n else lengths[i] = Buffer.byteLength(list[i])\n\n length += lengths[i]\n }\n\n const result = Buffer.allocUnsafe(length)\n\n for (i = 0; i < list.length && list[i] !== undefined; i++) {\n if (typeof list[i] !== 'string') {\n list[i].copy(result, pos)\n pos += lengths[i]\n } else {\n result.write(list[i], pos)\n pos += lengths[i]\n }\n }\n\n return result\n }\n}\n\nmodule.exports = generate\n", "exports.parser = require('./parser').parser\nexports.generate = require('./generate')\nexports.writeToStream = require('./writeToStream')\n", "'use strict'\n\n/**\n * DefaultMessageAllocator constructor\n * @constructor\n */\nfunction DefaultMessageIdProvider () {\n if (!(this instanceof DefaultMessageIdProvider)) {\n return new DefaultMessageIdProvider()\n }\n\n /**\n * MessageIDs starting with 1\n * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810\n */\n this.nextId = Math.max(1, Math.floor(Math.random() * 65535))\n}\n\n/**\n * allocate\n *\n * Get the next messageId.\n * @return unsigned int\n */\nDefaultMessageIdProvider.prototype.allocate = function () {\n // id becomes current state of this.nextId and increments afterwards\n const id = this.nextId++\n // Ensure 16 bit unsigned int (max 65535, nextId got one higher)\n if (this.nextId === 65536) {\n this.nextId = 1\n }\n return id\n}\n\n/**\n * getLastAllocated\n * Get the last allocated messageId.\n * @return unsigned int\n */\nDefaultMessageIdProvider.prototype.getLastAllocated = function () {\n return (this.nextId === 1) ? 65535 : (this.nextId - 1)\n}\n\n/**\n * register\n * Register messageId. If success return true, otherwise return false.\n * @param { unsigned int } - messageId to register,\n * @return boolean\n */\nDefaultMessageIdProvider.prototype.register = function (messageId) {\n return true\n}\n\n/**\n * deallocate\n * Deallocate messageId.\n * @param { unsigned int } - messageId to deallocate,\n */\nDefaultMessageIdProvider.prototype.deallocate = function (messageId) {\n}\n\n/**\n * clear\n * Deallocate all messageIds.\n */\nDefaultMessageIdProvider.prototype.clear = function () {\n}\n\nmodule.exports = DefaultMessageIdProvider\n", "'use strict'\n\nfunction ReInterval (callback, interval, args) {\n var self = this;\n\n this._callback = callback;\n this._args = args;\n\n this._interval = setInterval(callback, interval, this._args);\n\n this.reschedule = function (interval) {\n // if no interval entered, use the interval passed in on creation\n if (!interval)\n interval = self._interval;\n\n if (self._interval)\n clearInterval(self._interval);\n self._interval = setInterval(self._callback, interval, self._args);\n };\n\n this.clear = function () {\n if (self._interval) {\n clearInterval(self._interval);\n self._interval = undefined;\n }\n };\n \n this.destroy = function () {\n if (self._interval) {\n clearInterval(self._interval);\n }\n self._callback = undefined;\n self._interval = undefined;\n self._args = undefined;\n };\n}\n\nfunction reInterval () {\n if (typeof arguments[0] !== 'function')\n throw new Error('callback needed');\n if (typeof arguments[1] !== 'number')\n throw new Error('interval needed');\n\n var args;\n\n if (arguments.length > 0) {\n args = new Array(arguments.length - 2);\n\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 2];\n }\n }\n\n return new ReInterval(arguments[0], arguments[1], args);\n}\n\nmodule.exports = reInterval;\n", "'use strict'\nmodule.exports = rfdc\n\nfunction copyBuffer (cur) {\n if (cur instanceof Buffer) {\n return Buffer.from(cur)\n }\n\n return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length)\n}\n\nfunction rfdc (opts) {\n opts = opts || {}\n\n if (opts.circles) return rfdcCircles(opts)\n return opts.proto ? cloneProto : clone\n\n function cloneArray (a, fn) {\n var keys = Object.keys(a)\n var a2 = new Array(keys.length)\n for (var i = 0; i < keys.length; i++) {\n var k = keys[i]\n var cur = a[k]\n if (typeof cur !== 'object' || cur === null) {\n a2[k] = cur\n } else if (cur instanceof Date) {\n a2[k] = new Date(cur)\n } else if (ArrayBuffer.isView(cur)) {\n a2[k] = copyBuffer(cur)\n } else {\n a2[k] = fn(cur)\n }\n }\n return a2\n }\n\n function clone (o) {\n if (typeof o !== 'object' || o === null) return o\n if (o instanceof Date) return new Date(o)\n if (Array.isArray(o)) return cloneArray(o, clone)\n if (o instanceof Map) return new Map(cloneArray(Array.from(o), clone))\n if (o instanceof Set) return new Set(cloneArray(Array.from(o), clone))\n var o2 = {}\n for (var k in o) {\n if (Object.hasOwnProperty.call(o, k) === false) continue\n var cur = o[k]\n if (typeof cur !== 'object' || cur === null) {\n o2[k] = cur\n } else if (cur instanceof Date) {\n o2[k] = new Date(cur)\n } else if (cur instanceof Map) {\n o2[k] = new Map(cloneArray(Array.from(cur), clone))\n } else if (cur instanceof Set) {\n o2[k] = new Set(cloneArray(Array.from(cur), clone))\n } else if (ArrayBuffer.isView(cur)) {\n o2[k] = copyBuffer(cur)\n } else {\n o2[k] = clone(cur)\n }\n }\n return o2\n }\n\n function cloneProto (o) {\n if (typeof o !== 'object' || o === null) return o\n if (o instanceof Date) return new Date(o)\n if (Array.isArray(o)) return cloneArray(o, cloneProto)\n if (o instanceof Map) return new Map(cloneArray(Array.from(o), cloneProto))\n if (o instanceof Set) return new Set(cloneArray(Array.from(o), cloneProto))\n var o2 = {}\n for (var k in o) {\n var cur = o[k]\n if (typeof cur !== 'object' || cur === null) {\n o2[k] = cur\n } else if (cur instanceof Date) {\n o2[k] = new Date(cur)\n } else if (cur instanceof Map) {\n o2[k] = new Map(cloneArray(Array.from(cur), cloneProto))\n } else if (cur instanceof Set) {\n o2[k] = new Set(cloneArray(Array.from(cur), cloneProto))\n } else if (ArrayBuffer.isView(cur)) {\n o2[k] = copyBuffer(cur)\n } else {\n o2[k] = cloneProto(cur)\n }\n }\n return o2\n }\n}\n\nfunction rfdcCircles (opts) {\n var refs = []\n var refsNew = []\n\n return opts.proto ? cloneProto : clone\n\n function cloneArray (a, fn) {\n var keys = Object.keys(a)\n var a2 = new Array(keys.length)\n for (var i = 0; i < keys.length; i++) {\n var k = keys[i]\n var cur = a[k]\n if (typeof cur !== 'object' || cur === null) {\n a2[k] = cur\n } else if (cur instanceof Date) {\n a2[k] = new Date(cur)\n } else if (ArrayBuffer.isView(cur)) {\n a2[k] = copyBuffer(cur)\n } else {\n var index = refs.indexOf(cur)\n if (index !== -1) {\n a2[k] = refsNew[index]\n } else {\n a2[k] = fn(cur)\n }\n }\n }\n return a2\n }\n\n function clone (o) {\n if (typeof o !== 'object' || o === null) return o\n if (o instanceof Date) return new Date(o)\n if (Array.isArray(o)) return cloneArray(o, clone)\n if (o instanceof Map) return new Map(cloneArray(Array.from(o), clone))\n if (o instanceof Set) return new Set(cloneArray(Array.from(o), clone))\n var o2 = {}\n refs.push(o)\n refsNew.push(o2)\n for (var k in o) {\n if (Object.hasOwnProperty.call(o, k) === false) continue\n var cur = o[k]\n if (typeof cur !== 'object' || cur === null) {\n o2[k] = cur\n } else if (cur instanceof Date) {\n o2[k] = new Date(cur)\n } else if (cur instanceof Map) {\n o2[k] = new Map(cloneArray(Array.from(cur), clone))\n } else if (cur instanceof Set) {\n o2[k] = new Set(cloneArray(Array.from(cur), clone))\n } else if (ArrayBuffer.isView(cur)) {\n o2[k] = copyBuffer(cur)\n } else {\n var i = refs.indexOf(cur)\n if (i !== -1) {\n o2[k] = refsNew[i]\n } else {\n o2[k] = clone(cur)\n }\n }\n }\n refs.pop()\n refsNew.pop()\n return o2\n }\n\n function cloneProto (o) {\n if (typeof o !== 'object' || o === null) return o\n if (o instanceof Date) return new Date(o)\n if (Array.isArray(o)) return cloneArray(o, cloneProto)\n if (o instanceof Map) return new Map(cloneArray(Array.from(o), cloneProto))\n if (o instanceof Set) return new Set(cloneArray(Array.from(o), cloneProto))\n var o2 = {}\n refs.push(o)\n refsNew.push(o2)\n for (var k in o) {\n var cur = o[k]\n if (typeof cur !== 'object' || cur === null) {\n o2[k] = cur\n } else if (cur instanceof Date) {\n o2[k] = new Date(cur)\n } else if (cur instanceof Map) {\n o2[k] = new Map(cloneArray(Array.from(cur), cloneProto))\n } else if (cur instanceof Set) {\n o2[k] = new Set(cloneArray(Array.from(cur), cloneProto))\n } else if (ArrayBuffer.isView(cur)) {\n o2[k] = copyBuffer(cur)\n } else {\n var i = refs.indexOf(cur)\n if (i !== -1) {\n o2[k] = refsNew[i]\n } else {\n o2[k] = cloneProto(cur)\n }\n }\n }\n refs.pop()\n refsNew.pop()\n return o2\n }\n}\n", "'use strict'\n\nmodule.exports = require('./index.js')()\n", "'use strict'\n\n/**\n * Validate a topic to see if it's valid or not.\n * A topic is valid if it follow below rules:\n * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'\n * - Rule #2: Part `#` must be located at the end of the mailbox\n *\n * @param {String} topic - A topic\n * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.\n */\nfunction validateTopic (topic) {\n const parts = topic.split('/')\n\n for (let i = 0; i < parts.length; i++) {\n if (parts[i] === '+') {\n continue\n }\n\n if (parts[i] === '#') {\n // for Rule #2\n return i === parts.length - 1\n }\n\n if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * Validate an array of topics to see if any of them is valid or not\n * @param {Array} topics - Array of topics\n * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one\n */\nfunction validateTopics (topics) {\n if (topics.length === 0) {\n return 'empty_topic_list'\n }\n for (let i = 0; i < topics.length; i++) {\n if (!validateTopic(topics[i])) {\n return topics[i]\n }\n }\n return null\n}\n\nmodule.exports = {\n validateTopics: validateTopics\n}\n", "'use strict'\n\n/**\n * Module dependencies\n */\nconst EventEmitter = require('events').EventEmitter\nconst Store = require('./store')\nconst TopicAliasRecv = require('./topic-alias-recv')\nconst TopicAliasSend = require('./topic-alias-send')\nconst mqttPacket = require('mqtt-packet')\nconst DefaultMessageIdProvider = require('./default-message-id-provider')\nconst Writable = require('readable-stream').Writable\nconst inherits = require('inherits')\nconst reInterval = require('reinterval')\nconst clone = require('rfdc/default')\nconst validations = require('./validations')\nconst xtend = require('xtend')\nconst debug = require('debug')('mqttjs:client')\nconst nextTick = process ? process.nextTick : function (callback) { setTimeout(callback, 0) }\nconst setImmediate = global.setImmediate || function (callback) {\n // works in node v0.8\n nextTick(callback)\n}\nconst defaultConnectOptions = {\n keepalive: 60,\n reschedulePings: true,\n protocolId: 'MQTT',\n protocolVersion: 4,\n reconnectPeriod: 1000,\n connectTimeout: 30 * 1000,\n clean: true,\n resubscribe: true\n}\n\nconst socketErrors = [\n 'ECONNREFUSED',\n 'EADDRINUSE',\n 'ECONNRESET',\n 'ENOTFOUND'\n]\n\n// Other Socket Errors: EADDRINUSE, ECONNRESET, ENOTFOUND.\n\nconst errors = {\n 0: '',\n 1: 'Unacceptable protocol version',\n 2: 'Identifier rejected',\n 3: 'Server unavailable',\n 4: 'Bad username or password',\n 5: 'Not authorized',\n 16: 'No matching subscribers',\n 17: 'No subscription existed',\n 128: 'Unspecified error',\n 129: 'Malformed Packet',\n 130: 'Protocol Error',\n 131: 'Implementation specific error',\n 132: 'Unsupported Protocol Version',\n 133: 'Client Identifier not valid',\n 134: 'Bad User Name or Password',\n 135: 'Not authorized',\n 136: 'Server unavailable',\n 137: 'Server busy',\n 138: 'Banned',\n 139: 'Server shutting down',\n 140: 'Bad authentication method',\n 141: 'Keep Alive timeout',\n 142: 'Session taken over',\n 143: 'Topic Filter invalid',\n 144: 'Topic Name invalid',\n 145: 'Packet identifier in use',\n 146: 'Packet Identifier not found',\n 147: 'Receive Maximum exceeded',\n 148: 'Topic Alias invalid',\n 149: 'Packet too large',\n 150: 'Message rate too high',\n 151: 'Quota exceeded',\n 152: 'Administrative action',\n 153: 'Payload format invalid',\n 154: 'Retain not supported',\n 155: 'QoS not supported',\n 156: 'Use another server',\n 157: 'Server moved',\n 158: 'Shared Subscriptions not supported',\n 159: 'Connection rate exceeded',\n 160: 'Maximum connect time',\n 161: 'Subscription Identifiers not supported',\n 162: 'Wildcard Subscriptions not supported'\n}\n\nfunction defaultId () {\n return 'mqttjs_' + Math.random().toString(16).substr(2, 8)\n}\n\nfunction applyTopicAlias (client, packet) {\n if (client.options.protocolVersion === 5) {\n if (packet.cmd === 'publish') {\n let alias\n if (packet.properties) {\n alias = packet.properties.topicAlias\n }\n const topic = packet.topic.toString()\n if (client.topicAliasSend) {\n if (alias) {\n if (topic.length !== 0) {\n // register topic alias\n debug('applyTopicAlias :: register topic: %s - alias: %d', topic, alias)\n if (!client.topicAliasSend.put(topic, alias)) {\n debug('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias)\n return new Error('Sending Topic Alias out of range')\n }\n }\n } else {\n if (topic.length !== 0) {\n if (client.options.autoAssignTopicAlias) {\n alias = client.topicAliasSend.getAliasByTopic(topic)\n if (alias) {\n packet.topic = ''\n packet.properties = { ...(packet.properties), topicAlias: alias }\n debug('applyTopicAlias :: auto assign(use) topic: %s - alias: %d', topic, alias)\n } else {\n alias = client.topicAliasSend.getLruAlias()\n client.topicAliasSend.put(topic, alias)\n packet.properties = { ...(packet.properties), topicAlias: alias }\n debug('applyTopicAlias :: auto assign topic: %s - alias: %d', topic, alias)\n }\n } else if (client.options.autoUseTopicAlias) {\n alias = client.topicAliasSend.getAliasByTopic(topic)\n if (alias) {\n packet.topic = ''\n packet.properties = { ...(packet.properties), topicAlias: alias }\n debug('applyTopicAlias :: auto use topic: %s - alias: %d', topic, alias)\n }\n }\n }\n }\n } else if (alias) {\n debug('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias)\n return new Error('Sending Topic Alias out of range')\n }\n }\n }\n}\n\nfunction removeTopicAliasAndRecoverTopicName (client, packet) {\n let alias\n if (packet.properties) {\n alias = packet.properties.topicAlias\n }\n\n let topic = packet.topic.toString()\n if (topic.length === 0) {\n // restore topic from alias\n if (typeof alias === 'undefined') {\n return new Error('Unregistered Topic Alias')\n } else {\n topic = client.topicAliasSend.getTopicByAlias(alias)\n if (typeof topic === 'undefined') {\n return new Error('Unregistered Topic Alias')\n } else {\n packet.topic = topic\n }\n }\n }\n if (alias) {\n delete packet.properties.topicAlias\n }\n}\n\nfunction sendPacket (client, packet, cb) {\n debug('sendPacket :: packet: %O', packet)\n debug('sendPacket :: emitting `packetsend`')\n\n client.emit('packetsend', packet)\n\n debug('sendPacket :: writing to stream')\n const result = mqttPacket.writeToStream(packet, client.stream, client.options)\n debug('sendPacket :: writeToStream result %s', result)\n if (!result && cb && cb !== nop) {\n debug('sendPacket :: handle events on `drain` once through callback.')\n client.stream.once('drain', cb)\n } else if (cb) {\n debug('sendPacket :: invoking cb')\n cb()\n }\n}\n\nfunction flush (queue) {\n if (queue) {\n debug('flush: queue exists? %b', !!(queue))\n Object.keys(queue).forEach(function (messageId) {\n if (typeof queue[messageId].cb === 'function') {\n queue[messageId].cb(new Error('Connection closed'))\n // This is suspicious. Why do we only delete this if we have a callbck?\n // If this is by-design, then adding no as callback would cause this to get deleted unintentionally.\n delete queue[messageId]\n }\n })\n }\n}\n\nfunction flushVolatile (queue) {\n if (queue) {\n debug('flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function')\n Object.keys(queue).forEach(function (messageId) {\n if (queue[messageId].volatile && typeof queue[messageId].cb === 'function') {\n queue[messageId].cb(new Error('Connection closed'))\n delete queue[messageId]\n }\n })\n }\n}\n\nfunction storeAndSend (client, packet, cb, cbStorePut) {\n debug('storeAndSend :: store packet with cmd %s to outgoingStore', packet.cmd)\n let storePacket = packet\n let err\n if (storePacket.cmd === 'publish') {\n // The original packet is for sending.\n // The cloned storePacket is for storing to resend on reconnect.\n // Topic Alias must not be used after disconnected.\n storePacket = clone(packet)\n err = removeTopicAliasAndRecoverTopicName(client, storePacket)\n if (err) {\n return cb && cb(err)\n }\n }\n client.outgoingStore.put(storePacket, function storedPacket (err) {\n if (err) {\n return cb && cb(err)\n }\n cbStorePut()\n sendPacket(client, packet, cb)\n })\n}\n\nfunction nop (error) {\n debug('nop ::', error)\n}\n\n/**\n * MqttClient constructor\n *\n * @param {Stream} stream - stream\n * @param {Object} [options] - connection options\n * (see Connection#connect)\n */\nfunction MqttClient (streamBuilder, options) {\n let k\n const that = this\n\n if (!(this instanceof MqttClient)) {\n return new MqttClient(streamBuilder, options)\n }\n\n this.options = options || {}\n\n // Defaults\n for (k in defaultConnectOptions) {\n if (typeof this.options[k] === 'undefined') {\n this.options[k] = defaultConnectOptions[k]\n } else {\n this.options[k] = options[k]\n }\n }\n\n debug('MqttClient :: options.protocol', options.protocol)\n debug('MqttClient :: options.protocolVersion', options.protocolVersion)\n debug('MqttClient :: options.username', options.username)\n debug('MqttClient :: options.keepalive', options.keepalive)\n debug('MqttClient :: options.reconnectPeriod', options.reconnectPeriod)\n debug('MqttClient :: options.rejectUnauthorized', options.rejectUnauthorized)\n debug('MqttClient :: options.topicAliasMaximum', options.topicAliasMaximum)\n\n this.options.clientId = (typeof options.clientId === 'string') ? options.clientId : defaultId()\n\n debug('MqttClient :: clientId', this.options.clientId)\n\n this.options.customHandleAcks = (options.protocolVersion === 5 && options.customHandleAcks) ? options.customHandleAcks : function () { arguments[3](0) }\n\n this.streamBuilder = streamBuilder\n\n this.messageIdProvider = (typeof this.options.messageIdProvider === 'undefined') ? new DefaultMessageIdProvider() : this.options.messageIdProvider\n\n // Inflight message storages\n this.outgoingStore = options.outgoingStore || new Store()\n this.incomingStore = options.incomingStore || new Store()\n\n // Should QoS zero messages be queued when the connection is broken?\n this.queueQoSZero = options.queueQoSZero === undefined ? true : options.queueQoSZero\n\n // map of subscribed topics to support reconnection\n this._resubscribeTopics = {}\n\n // map of a subscribe messageId and a topic\n this.messageIdToTopic = {}\n\n // Ping timer, setup in _setupPingTimer\n this.pingTimer = null\n // Is the client connected?\n this.connected = false\n // Are we disconnecting?\n this.disconnecting = false\n // Packet queue\n this.queue = []\n // connack timer\n this.connackTimer = null\n // Reconnect timer\n this.reconnectTimer = null\n // Is processing store?\n this._storeProcessing = false\n // Packet Ids are put into the store during store processing\n this._packetIdsDuringStoreProcessing = {}\n // Store processing queue\n this._storeProcessingQueue = []\n\n // Inflight callbacks\n this.outgoing = {}\n\n // True if connection is first time.\n this._firstConnection = true\n\n if (options.topicAliasMaximum > 0) {\n if (options.topicAliasMaximum > 0xffff) {\n debug('MqttClient :: options.topicAliasMaximum is out of range')\n } else {\n this.topicAliasRecv = new TopicAliasRecv(options.topicAliasMaximum)\n }\n }\n\n // Send queued packets\n this.on('connect', function () {\n const queue = this.queue\n\n function deliver () {\n const entry = queue.shift()\n debug('deliver :: entry %o', entry)\n let packet = null\n\n if (!entry) {\n that._resubscribe()\n return\n }\n\n packet = entry.packet\n debug('deliver :: call _sendPacket for %o', packet)\n let send = true\n if (packet.messageId && packet.messageId !== 0) {\n if (!that.messageIdProvider.register(packet.messageId)) {\n send = false\n }\n }\n if (send) {\n that._sendPacket(\n packet,\n function (err) {\n if (entry.cb) {\n entry.cb(err)\n }\n deliver()\n }\n )\n } else {\n debug('messageId: %d has already used. The message is skipped and removed.', packet.messageId)\n deliver()\n }\n }\n\n debug('connect :: sending queued packets')\n deliver()\n })\n\n this.on('close', function () {\n debug('close :: connected set to `false`')\n this.connected = false\n\n debug('close :: clearing connackTimer')\n clearTimeout(this.connackTimer)\n\n debug('close :: clearing ping timer')\n if (that.pingTimer !== null) {\n that.pingTimer.clear()\n that.pingTimer = null\n }\n\n if (this.topicAliasRecv) {\n this.topicAliasRecv.clear()\n }\n\n debug('close :: calling _setupReconnect')\n this._setupReconnect()\n })\n EventEmitter.call(this)\n\n debug('MqttClient :: setting up stream')\n this._setupStream()\n}\ninherits(MqttClient, EventEmitter)\n\n/**\n * setup the event handlers in the inner stream.\n *\n * @api private\n */\nMqttClient.prototype._setupStream = function () {\n const that = this\n const writable = new Writable()\n const parser = mqttPacket.parser(this.options)\n let completeParse = null\n const packets = []\n\n debug('_setupStream :: calling method to clear reconnect')\n this._clearReconnect()\n\n debug('_setupStream :: using streamBuilder provided to client to create stream')\n this.stream = this.streamBuilder(this)\n\n parser.on('packet', function (packet) {\n debug('parser :: on packet push to packets array.')\n packets.push(packet)\n })\n\n function nextTickWork () {\n if (packets.length) {\n nextTick(work)\n } else {\n const done = completeParse\n completeParse = null\n done()\n }\n }\n\n function work () {\n debug('work :: getting next packet in queue')\n const packet = packets.shift()\n\n if (packet) {\n debug('work :: packet pulled from queue')\n that._handlePacket(packet, nextTickWork)\n } else {\n debug('work :: no packets in queue')\n const done = completeParse\n completeParse = null\n debug('work :: done flag is %s', !!(done))\n if (done) done()\n }\n }\n\n writable._write = function (buf, enc, done) {\n completeParse = done\n debug('writable stream :: parsing buffer')\n parser.parse(buf)\n work()\n }\n\n function streamErrorHandler (error) {\n debug('streamErrorHandler :: error', error.message)\n if (socketErrors.includes(error.code)) {\n // handle error\n debug('streamErrorHandler :: emitting error')\n that.emit('error', error)\n } else {\n nop(error)\n }\n }\n\n debug('_setupStream :: pipe stream to writable stream')\n this.stream.pipe(writable)\n\n // Suppress connection errors\n this.stream.on('error', streamErrorHandler)\n\n // Echo stream close\n this.stream.on('close', function () {\n debug('(%s)stream :: on close', that.options.clientId)\n flushVolatile(that.outgoing)\n debug('stream: emit close to MqttClient')\n that.emit('close')\n })\n\n // Send a connect packet\n debug('_setupStream: sending packet `connect`')\n const connectPacket = Object.create(this.options)\n connectPacket.cmd = 'connect'\n if (this.topicAliasRecv) {\n if (!connectPacket.properties) {\n connectPacket.properties = {}\n }\n if (this.topicAliasRecv) {\n connectPacket.properties.topicAliasMaximum = this.topicAliasRecv.max\n }\n }\n // avoid message queue\n sendPacket(this, connectPacket)\n\n // Echo connection errors\n parser.on('error', this.emit.bind(this, 'error'))\n\n // auth\n if (this.options.properties) {\n if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData) {\n that.end(() =>\n this.emit('error', new Error('Packet has no Authentication Method')\n ))\n return this\n }\n if (this.options.properties.authenticationMethod && this.options.authPacket && typeof this.options.authPacket === 'object') {\n const authPacket = xtend({ cmd: 'auth', reasonCode: 0 }, this.options.authPacket)\n sendPacket(this, authPacket)\n }\n }\n\n // many drain listeners are needed for qos 1 callbacks if the connection is intermittent\n this.stream.setMaxListeners(1000)\n\n clearTimeout(this.connackTimer)\n this.connackTimer = setTimeout(function () {\n debug('!!connectTimeout hit!! Calling _cleanUp with force `true`')\n that._cleanUp(true)\n }, this.options.connectTimeout)\n}\n\nMqttClient.prototype._handlePacket = function (packet, done) {\n const options = this.options\n\n if (options.protocolVersion === 5 && options.properties && options.properties.maximumPacketSize && options.properties.maximumPacketSize < packet.length) {\n this.emit('error', new Error('exceeding packets size ' + packet.cmd))\n this.end({ reasonCode: 149, properties: { reasonString: 'Maximum packet size was exceeded' } })\n return this\n }\n debug('_handlePacket :: emitting packetreceive')\n this.emit('packetreceive', packet)\n\n switch (packet.cmd) {\n case 'publish':\n this._handlePublish(packet, done)\n break\n case 'puback':\n case 'pubrec':\n case 'pubcomp':\n case 'suback':\n case 'unsuback':\n this._handleAck(packet)\n done()\n break\n case 'pubrel':\n this._handlePubrel(packet, done)\n break\n case 'connack':\n this._handleConnack(packet)\n done()\n break\n case 'auth':\n this._handleAuth(packet)\n done()\n break\n case 'pingresp':\n this._handlePingresp(packet)\n done()\n break\n case 'disconnect':\n this._handleDisconnect(packet)\n done()\n break\n default:\n // do nothing\n // maybe we should do an error handling\n // or just log it\n break\n }\n}\n\nMqttClient.prototype._checkDisconnecting = function (callback) {\n if (this.disconnecting) {\n if (callback && callback !== nop) {\n callback(new Error('client disconnecting'))\n } else {\n this.emit('error', new Error('client disconnecting'))\n }\n }\n return this.disconnecting\n}\n\n/**\n * publish - publish to \n *\n * @param {String} topic - topic to publish to\n * @param {String, Buffer} message - message to publish\n * @param {Object} [opts] - publish options, includes:\n * {Number} qos - qos level to publish on\n * {Boolean} retain - whether or not to retain the message\n * {Boolean} dup - whether or not mark a message as duplicate\n * {Function} cbStorePut - function(){} called when message is put into `outgoingStore`\n * @param {Function} [callback] - function(err){}\n * called when publish succeeds or fails\n * @returns {MqttClient} this - for chaining\n * @api public\n *\n * @example client.publish('topic', 'message');\n * @example\n * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});\n * @example client.publish('topic', 'message', console.log);\n */\nMqttClient.prototype.publish = function (topic, message, opts, callback) {\n debug('publish :: message `%s` to topic `%s`', message, topic)\n const options = this.options\n\n // .publish(topic, payload, cb);\n if (typeof opts === 'function') {\n callback = opts\n opts = null\n }\n\n // default opts\n const defaultOpts = { qos: 0, retain: false, dup: false }\n opts = xtend(defaultOpts, opts)\n\n if (this._checkDisconnecting(callback)) {\n return this\n }\n\n const that = this\n const publishProc = function () {\n let messageId = 0\n if (opts.qos === 1 || opts.qos === 2) {\n messageId = that._nextId()\n if (messageId === null) {\n debug('No messageId left')\n return false\n }\n }\n const packet = {\n cmd: 'publish',\n topic: topic,\n payload: message,\n qos: opts.qos,\n retain: opts.retain,\n messageId: messageId,\n dup: opts.dup\n }\n\n if (options.protocolVersion === 5) {\n packet.properties = opts.properties\n }\n\n debug('publish :: qos', opts.qos)\n switch (opts.qos) {\n case 1:\n case 2:\n // Add to callbacks\n that.outgoing[packet.messageId] = {\n volatile: false,\n cb: callback || nop\n }\n debug('MqttClient:publish: packet cmd: %s', packet.cmd)\n that._sendPacket(packet, undefined, opts.cbStorePut)\n break\n default:\n debug('MqttClient:publish: packet cmd: %s', packet.cmd)\n that._sendPacket(packet, callback, opts.cbStorePut)\n break\n }\n return true\n }\n\n if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !publishProc()) {\n this._storeProcessingQueue.push(\n {\n invoke: publishProc,\n cbStorePut: opts.cbStorePut,\n callback: callback\n }\n )\n }\n return this\n}\n\n/**\n * subscribe - subscribe to \n *\n * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}\n * @param {Object} [opts] - optional subscription options, includes:\n * {Number} qos - subscribe qos level\n * @param {Function} [callback] - function(err, granted){} where:\n * {Error} err - subscription error (none at the moment!)\n * {Array} granted - array of {topic: 't', qos: 0}\n * @returns {MqttClient} this - for chaining\n * @api public\n * @example client.subscribe('topic');\n * @example client.subscribe('topic', {qos: 1});\n * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);\n * @example client.subscribe('topic', console.log);\n */\nMqttClient.prototype.subscribe = function () {\n const that = this\n const args = new Array(arguments.length)\n for (let i = 0; i < arguments.length; i++) {\n args[i] = arguments[i]\n }\n const subs = []\n let obj = args.shift()\n const resubscribe = obj.resubscribe\n let callback = args.pop() || nop\n let opts = args.pop()\n const version = this.options.protocolVersion\n\n delete obj.resubscribe\n\n if (typeof obj === 'string') {\n obj = [obj]\n }\n\n if (typeof callback !== 'function') {\n opts = callback\n callback = nop\n }\n\n const invalidTopic = validations.validateTopics(obj)\n if (invalidTopic !== null) {\n setImmediate(callback, new Error('Invalid topic ' + invalidTopic))\n return this\n }\n\n if (this._checkDisconnecting(callback)) {\n debug('subscribe: discconecting true')\n return this\n }\n\n const defaultOpts = {\n qos: 0\n }\n if (version === 5) {\n defaultOpts.nl = false\n defaultOpts.rap = false\n defaultOpts.rh = 0\n }\n opts = xtend(defaultOpts, opts)\n\n if (Array.isArray(obj)) {\n obj.forEach(function (topic) {\n debug('subscribe: array topic %s', topic)\n if (!Object.prototype.hasOwnProperty.call(that._resubscribeTopics, topic) ||\n that._resubscribeTopics[topic].qos < opts.qos ||\n resubscribe) {\n const currentOpts = {\n topic: topic,\n qos: opts.qos\n }\n if (version === 5) {\n currentOpts.nl = opts.nl\n currentOpts.rap = opts.rap\n currentOpts.rh = opts.rh\n currentOpts.properties = opts.properties\n }\n debug('subscribe: pushing topic `%s` and qos `%s` to subs list', currentOpts.topic, currentOpts.qos)\n subs.push(currentOpts)\n }\n })\n } else {\n Object\n .keys(obj)\n .forEach(function (k) {\n debug('subscribe: object topic %s', k)\n if (!Object.prototype.hasOwnProperty.call(that._resubscribeTopics, k) ||\n that._resubscribeTopics[k].qos < obj[k].qos ||\n resubscribe) {\n const currentOpts = {\n topic: k,\n qos: obj[k].qos\n }\n if (version === 5) {\n currentOpts.nl = obj[k].nl\n currentOpts.rap = obj[k].rap\n currentOpts.rh = obj[k].rh\n currentOpts.properties = opts.properties\n }\n debug('subscribe: pushing `%s` to subs list', currentOpts)\n subs.push(currentOpts)\n }\n })\n }\n\n if (!subs.length) {\n callback(null, [])\n return this\n }\n\n const subscribeProc = function () {\n const messageId = that._nextId()\n if (messageId === null) {\n debug('No messageId left')\n return false\n }\n\n const packet = {\n cmd: 'subscribe',\n subscriptions: subs,\n qos: 1,\n retain: false,\n dup: false,\n messageId: messageId\n }\n\n if (opts.properties) {\n packet.properties = opts.properties\n }\n\n // subscriptions to resubscribe to in case of disconnect\n if (that.options.resubscribe) {\n debug('subscribe :: resubscribe true')\n const topics = []\n subs.forEach(function (sub) {\n if (that.options.reconnectPeriod > 0) {\n const topic = { qos: sub.qos }\n if (version === 5) {\n topic.nl = sub.nl || false\n topic.rap = sub.rap || false\n topic.rh = sub.rh || 0\n topic.properties = sub.properties\n }\n that._resubscribeTopics[sub.topic] = topic\n topics.push(sub.topic)\n }\n })\n that.messageIdToTopic[packet.messageId] = topics\n }\n\n that.outgoing[packet.messageId] = {\n volatile: true,\n cb: function (err, packet) {\n if (!err) {\n const granted = packet.granted\n for (let i = 0; i < granted.length; i += 1) {\n subs[i].qos = granted[i]\n }\n }\n\n callback(err, subs)\n }\n }\n debug('subscribe :: call _sendPacket')\n that._sendPacket(packet)\n return true\n }\n\n if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !subscribeProc()) {\n this._storeProcessingQueue.push(\n {\n invoke: subscribeProc,\n callback: callback\n }\n )\n }\n\n return this\n}\n\n/**\n * unsubscribe - unsubscribe from topic(s)\n *\n * @param {String, Array} topic - topics to unsubscribe from\n * @param {Object} [opts] - optional subscription options, includes:\n * {Object} properties - properties of unsubscribe packet\n * @param {Function} [callback] - callback fired on unsuback\n * @returns {MqttClient} this - for chaining\n * @api public\n * @example client.unsubscribe('topic');\n * @example client.unsubscribe('topic', console.log);\n */\nMqttClient.prototype.unsubscribe = function () {\n const that = this\n const args = new Array(arguments.length)\n for (let i = 0; i < arguments.length; i++) {\n args[i] = arguments[i]\n }\n let topic = args.shift()\n let callback = args.pop() || nop\n let opts = args.pop()\n if (typeof topic === 'string') {\n topic = [topic]\n }\n\n if (typeof callback !== 'function') {\n opts = callback\n callback = nop\n }\n\n const invalidTopic = validations.validateTopics(topic)\n if (invalidTopic !== null) {\n setImmediate(callback, new Error('Invalid topic ' + invalidTopic))\n return this\n }\n\n if (that._checkDisconnecting(callback)) {\n return this\n }\n\n const unsubscribeProc = function () {\n const messageId = that._nextId()\n if (messageId === null) {\n debug('No messageId left')\n return false\n }\n const packet = {\n cmd: 'unsubscribe',\n qos: 1,\n messageId: messageId\n }\n\n if (typeof topic === 'string') {\n packet.unsubscriptions = [topic]\n } else if (Array.isArray(topic)) {\n packet.unsubscriptions = topic\n }\n\n if (that.options.resubscribe) {\n packet.unsubscriptions.forEach(function (topic) {\n delete that._resubscribeTopics[topic]\n })\n }\n\n if (typeof opts === 'object' && opts.properties) {\n packet.properties = opts.properties\n }\n\n that.outgoing[packet.messageId] = {\n volatile: true,\n cb: callback\n }\n\n debug('unsubscribe: call _sendPacket')\n that._sendPacket(packet)\n\n return true\n }\n\n if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !unsubscribeProc()) {\n this._storeProcessingQueue.push(\n {\n invoke: unsubscribeProc,\n callback: callback\n }\n )\n }\n\n return this\n}\n\n/**\n * end - close connection\n *\n * @returns {MqttClient} this - for chaining\n * @param {Boolean} force - do not wait for all in-flight messages to be acked\n * @param {Object} opts - added to the disconnect packet\n * @param {Function} cb - called when the client has been closed\n *\n * @api public\n */\nMqttClient.prototype.end = function (force, opts, cb) {\n const that = this\n\n debug('end :: (%s)', this.options.clientId)\n\n if (force == null || typeof force !== 'boolean') {\n cb = opts || nop\n opts = force\n force = false\n if (typeof opts !== 'object') {\n cb = opts\n opts = null\n if (typeof cb !== 'function') {\n cb = nop\n }\n }\n }\n\n if (typeof opts !== 'object') {\n cb = opts\n opts = null\n }\n\n debug('end :: cb? %s', !!cb)\n cb = cb || nop\n\n function closeStores () {\n debug('end :: closeStores: closing incoming and outgoing stores')\n that.disconnected = true\n that.incomingStore.close(function (e1) {\n that.outgoingStore.close(function (e2) {\n debug('end :: closeStores: emitting end')\n that.emit('end')\n if (cb) {\n const err = e1 || e2\n debug('end :: closeStores: invoking callback with args')\n cb(err)\n }\n })\n })\n if (that._deferredReconnect) {\n that._deferredReconnect()\n }\n }\n\n function finish () {\n // defer closesStores of an I/O cycle,\n // just to make sure things are\n // ok for websockets\n debug('end :: (%s) :: finish :: calling _cleanUp with force %s', that.options.clientId, force)\n that._cleanUp(force, () => {\n debug('end :: finish :: calling process.nextTick on closeStores')\n // const boundProcess = nextTick.bind(null, closeStores)\n nextTick(closeStores.bind(that))\n }, opts)\n }\n\n if (this.disconnecting) {\n cb()\n return this\n }\n\n this._clearReconnect()\n\n this.disconnecting = true\n\n if (!force && Object.keys(this.outgoing).length > 0) {\n // wait 10ms, just to be sure we received all of it\n debug('end :: (%s) :: calling finish in 10ms once outgoing is empty', that.options.clientId)\n this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))\n } else {\n debug('end :: (%s) :: immediately calling finish', that.options.clientId)\n finish()\n }\n\n return this\n}\n\n/**\n * removeOutgoingMessage - remove a message in outgoing store\n * the outgoing callback will be called withe Error('Message removed') if the message is removed\n *\n * @param {Number} messageId - messageId to remove message\n * @returns {MqttClient} this - for chaining\n * @api public\n *\n * @example client.removeOutgoingMessage(client.getLastAllocated());\n */\nMqttClient.prototype.removeOutgoingMessage = function (messageId) {\n const cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null\n delete this.outgoing[messageId]\n this.outgoingStore.del({ messageId: messageId }, function () {\n cb(new Error('Message removed'))\n })\n return this\n}\n\n/**\n * reconnect - connect again using the same options as connect()\n *\n * @param {Object} [opts] - optional reconnect options, includes:\n * {Store} incomingStore - a store for the incoming packets\n * {Store} outgoingStore - a store for the outgoing packets\n * if opts is not given, current stores are used\n * @returns {MqttClient} this - for chaining\n *\n * @api public\n */\nMqttClient.prototype.reconnect = function (opts) {\n debug('client reconnect')\n const that = this\n const f = function () {\n if (opts) {\n that.options.incomingStore = opts.incomingStore\n that.options.outgoingStore = opts.outgoingStore\n } else {\n that.options.incomingStore = null\n that.options.outgoingStore = null\n }\n that.incomingStore = that.options.incomingStore || new Store()\n that.outgoingStore = that.options.outgoingStore || new Store()\n that.disconnecting = false\n that.disconnected = false\n that._deferredReconnect = null\n that._reconnect()\n }\n\n if (this.disconnecting && !this.disconnected) {\n this._deferredReconnect = f\n } else {\n f()\n }\n return this\n}\n\n/**\n * _reconnect - implement reconnection\n * @api privateish\n */\nMqttClient.prototype._reconnect = function () {\n debug('_reconnect: emitting reconnect to client')\n this.emit('reconnect')\n if (this.connected) {\n this.end(() => { this._setupStream() })\n debug('client already connected. disconnecting first.')\n } else {\n debug('_reconnect: calling _setupStream')\n this._setupStream()\n }\n}\n\n/**\n * _setupReconnect - setup reconnect timer\n */\nMqttClient.prototype._setupReconnect = function () {\n const that = this\n\n if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {\n if (!this.reconnecting) {\n debug('_setupReconnect :: emit `offline` state')\n this.emit('offline')\n debug('_setupReconnect :: set `reconnecting` to `true`')\n this.reconnecting = true\n }\n debug('_setupReconnect :: setting reconnectTimer for %d ms', that.options.reconnectPeriod)\n that.reconnectTimer = setInterval(function () {\n debug('reconnectTimer :: reconnect triggered!')\n that._reconnect()\n }, that.options.reconnectPeriod)\n } else {\n debug('_setupReconnect :: doing nothing...')\n }\n}\n\n/**\n * _clearReconnect - clear the reconnect timer\n */\nMqttClient.prototype._clearReconnect = function () {\n debug('_clearReconnect : clearing reconnect timer')\n if (this.reconnectTimer) {\n clearInterval(this.reconnectTimer)\n this.reconnectTimer = null\n }\n}\n\n/**\n * _cleanUp - clean up on connection end\n * @api private\n */\nMqttClient.prototype._cleanUp = function (forced, done) {\n const opts = arguments[2]\n if (done) {\n debug('_cleanUp :: done callback provided for on stream close')\n this.stream.on('close', done)\n }\n\n debug('_cleanUp :: forced? %s', forced)\n if (forced) {\n if ((this.options.reconnectPeriod === 0) && this.options.clean) {\n flush(this.outgoing)\n }\n debug('_cleanUp :: (%s) :: destroying stream', this.options.clientId)\n this.stream.destroy()\n } else {\n const packet = xtend({ cmd: 'disconnect' }, opts)\n debug('_cleanUp :: (%s) :: call _sendPacket with disconnect packet', this.options.clientId)\n this._sendPacket(\n packet,\n setImmediate.bind(\n null,\n this.stream.end.bind(this.stream)\n )\n )\n }\n\n if (!this.disconnecting) {\n debug('_cleanUp :: client not disconnecting. Clearing and resetting reconnect.')\n this._clearReconnect()\n this._setupReconnect()\n }\n\n if (this.pingTimer !== null) {\n debug('_cleanUp :: clearing pingTimer')\n this.pingTimer.clear()\n this.pingTimer = null\n }\n\n if (done && !this.connected) {\n debug('_cleanUp :: (%s) :: removing stream `done` callback `close` listener', this.options.clientId)\n this.stream.removeListener('close', done)\n done()\n }\n}\n\n/**\n * _sendPacket - send or queue a packet\n * @param {Object} packet - packet options\n * @param {Function} cb - callback when the packet is sent\n * @param {Function} cbStorePut - called when message is put into outgoingStore\n * @api private\n */\nMqttClient.prototype._sendPacket = function (packet, cb, cbStorePut) {\n debug('_sendPacket :: (%s) :: start', this.options.clientId)\n cbStorePut = cbStorePut || nop\n cb = cb || nop\n\n const err = applyTopicAlias(this, packet)\n if (err) {\n cb(err)\n return\n }\n\n if (!this.connected) {\n // allow auth packets to be sent while authenticating with the broker (mqtt5 enhanced auth)\n if (packet.cmd === 'auth') {\n this._shiftPingInterval()\n sendPacket(this, packet, cb)\n return\n }\n\n debug('_sendPacket :: client not connected. Storing packet offline.')\n this._storePacket(packet, cb, cbStorePut)\n return\n }\n\n // When sending a packet, reschedule the ping timer\n this._shiftPingInterval()\n\n switch (packet.cmd) {\n case 'publish':\n break\n case 'pubrel':\n storeAndSend(this, packet, cb, cbStorePut)\n return\n default:\n sendPacket(this, packet, cb)\n return\n }\n\n switch (packet.qos) {\n case 2:\n case 1:\n storeAndSend(this, packet, cb, cbStorePut)\n break\n /**\n * no need of case here since it will be caught by default\n * and jshint comply that before default it must be a break\n * anyway it will result in -1 evaluation\n */\n case 0:\n /* falls through */\n default:\n sendPacket(this, packet, cb)\n break\n }\n debug('_sendPacket :: (%s) :: end', this.options.clientId)\n}\n\n/**\n * _storePacket - queue a packet\n * @param {Object} packet - packet options\n * @param {Function} cb - callback when the packet is sent\n * @param {Function} cbStorePut - called when message is put into outgoingStore\n * @api private\n */\nMqttClient.prototype._storePacket = function (packet, cb, cbStorePut) {\n debug('_storePacket :: packet: %o', packet)\n debug('_storePacket :: cb? %s', !!cb)\n cbStorePut = cbStorePut || nop\n\n let storePacket = packet\n if (storePacket.cmd === 'publish') {\n // The original packet is for sending.\n // The cloned storePacket is for storing to resend on reconnect.\n // Topic Alias must not be used after disconnected.\n storePacket = clone(packet)\n const err = removeTopicAliasAndRecoverTopicName(this, storePacket)\n if (err) {\n return cb && cb(err)\n }\n }\n // check that the packet is not a qos of 0, or that the command is not a publish\n if (((storePacket.qos || 0) === 0 && this.queueQoSZero) || storePacket.cmd !== 'publish') {\n this.queue.push({ packet: storePacket, cb: cb })\n } else if (storePacket.qos > 0) {\n cb = this.outgoing[storePacket.messageId] ? this.outgoing[storePacket.messageId].cb : null\n this.outgoingStore.put(storePacket, function (err) {\n if (err) {\n return cb && cb(err)\n }\n cbStorePut()\n })\n } else if (cb) {\n cb(new Error('No connection to broker'))\n }\n}\n\n/**\n * _setupPingTimer - setup the ping timer\n *\n * @api private\n */\nMqttClient.prototype._setupPingTimer = function () {\n debug('_setupPingTimer :: keepalive %d (seconds)', this.options.keepalive)\n const that = this\n\n if (!this.pingTimer && this.options.keepalive) {\n this.pingResp = true\n this.pingTimer = reInterval(function () {\n that._checkPing()\n }, this.options.keepalive * 1000)\n }\n}\n\n/**\n * _shiftPingInterval - reschedule the ping interval\n *\n * @api private\n */\nMqttClient.prototype._shiftPingInterval = function () {\n if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {\n this.pingTimer.reschedule(this.options.keepalive * 1000)\n }\n}\n/**\n * _checkPing - check if a pingresp has come back, and ping the server again\n *\n * @api private\n */\nMqttClient.prototype._checkPing = function () {\n debug('_checkPing :: checking ping...')\n if (this.pingResp) {\n debug('_checkPing :: ping response received. Clearing flag and sending `pingreq`')\n this.pingResp = false\n this._sendPacket({ cmd: 'pingreq' })\n } else {\n // do a forced cleanup since socket will be in bad shape\n debug('_checkPing :: calling _cleanUp with force true')\n this._cleanUp(true)\n }\n}\n\n/**\n * _handlePingresp - handle a pingresp\n *\n * @api private\n */\nMqttClient.prototype._handlePingresp = function () {\n this.pingResp = true\n}\n\n/**\n * _handleConnack\n *\n * @param {Object} packet\n * @api private\n */\nMqttClient.prototype._handleConnack = function (packet) {\n debug('_handleConnack')\n const options = this.options\n const version = options.protocolVersion\n const rc = version === 5 ? packet.reasonCode : packet.returnCode\n\n clearTimeout(this.connackTimer)\n delete this.topicAliasSend\n\n if (packet.properties) {\n if (packet.properties.topicAliasMaximum) {\n if (packet.properties.topicAliasMaximum > 0xffff) {\n this.emit('error', new Error('topicAliasMaximum from broker is out of range'))\n return\n }\n if (packet.properties.topicAliasMaximum > 0) {\n this.topicAliasSend = new TopicAliasSend(packet.properties.topicAliasMaximum)\n }\n }\n if (packet.properties.serverKeepAlive && options.keepalive) {\n options.keepalive = packet.properties.serverKeepAlive\n this._shiftPingInterval()\n }\n if (packet.properties.maximumPacketSize) {\n if (!options.properties) { options.properties = {} }\n options.properties.maximumPacketSize = packet.properties.maximumPacketSize\n }\n }\n\n if (rc === 0) {\n this.reconnecting = false\n this._onConnect(packet)\n } else if (rc > 0) {\n const err = new Error('Connection refused: ' + errors[rc])\n err.code = rc\n this.emit('error', err)\n }\n}\n\nMqttClient.prototype._handleAuth = function (packet) {\n const options = this.options\n const version = options.protocolVersion\n const rc = version === 5 ? packet.reasonCode : packet.returnCode\n\n if (version !== 5) {\n const err = new Error('Protocol error: Auth packets are only supported in MQTT 5. Your version:' + version)\n err.code = rc\n this.emit('error', err)\n return\n }\n\n const that = this\n this.handleAuth(packet, function (err, packet) {\n if (err) {\n that.emit('error', err)\n return\n }\n\n if (rc === 24) {\n that.reconnecting = false\n that._sendPacket(packet)\n } else {\n const error = new Error('Connection refused: ' + errors[rc])\n err.code = rc\n that.emit('error', error)\n }\n })\n}\n\n/**\n * @param packet the packet received by the broker\n * @return the auth packet to be returned to the broker\n * @api public\n */\nMqttClient.prototype.handleAuth = function (packet, callback) {\n callback()\n}\n\n/**\n * _handlePublish\n *\n * @param {Object} packet\n * @api private\n */\n/*\nthose late 2 case should be rewrite to comply with coding style:\n\ncase 1:\ncase 0:\n // do not wait sending a puback\n // no callback passed\n if (1 === qos) {\n this._sendPacket({\n cmd: 'puback',\n messageId: messageId\n });\n }\n // emit the message event for both qos 1 and 0\n this.emit('message', topic, message, packet);\n this.handleMessage(packet, done);\n break;\ndefault:\n // do nothing but every switch mus have a default\n // log or throw an error about unknown qos\n break;\n\nfor now i just suppressed the warnings\n*/\nMqttClient.prototype._handlePublish = function (packet, done) {\n debug('_handlePublish: packet %o', packet)\n done = typeof done !== 'undefined' ? done : nop\n let topic = packet.topic.toString()\n const message = packet.payload\n const qos = packet.qos\n const messageId = packet.messageId\n const that = this\n const options = this.options\n const validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]\n if (this.options.protocolVersion === 5) {\n let alias\n if (packet.properties) {\n alias = packet.properties.topicAlias\n }\n if (typeof alias !== 'undefined') {\n if (topic.length === 0) {\n if (alias > 0 && alias <= 0xffff) {\n const gotTopic = this.topicAliasRecv.getTopicByAlias(alias)\n if (gotTopic) {\n topic = gotTopic\n debug('_handlePublish :: topic complemented by alias. topic: %s - alias: %d', topic, alias)\n } else {\n debug('_handlePublish :: unregistered topic alias. alias: %d', alias)\n this.emit('error', new Error('Received unregistered Topic Alias'))\n return\n }\n } else {\n debug('_handlePublish :: topic alias out of range. alias: %d', alias)\n this.emit('error', new Error('Received Topic Alias is out of range'))\n return\n }\n } else {\n if (this.topicAliasRecv.put(topic, alias)) {\n debug('_handlePublish :: registered topic: %s - alias: %d', topic, alias)\n } else {\n debug('_handlePublish :: topic alias out of range. alias: %d', alias)\n this.emit('error', new Error('Received Topic Alias is out of range'))\n return\n }\n }\n }\n }\n debug('_handlePublish: qos %d', qos)\n switch (qos) {\n case 2: {\n options.customHandleAcks(topic, message, packet, function (error, code) {\n if (!(error instanceof Error)) {\n code = error\n error = null\n }\n if (error) { return that.emit('error', error) }\n if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for pubrec')) }\n if (code) {\n that._sendPacket({ cmd: 'pubrec', messageId: messageId, reasonCode: code }, done)\n } else {\n that.incomingStore.put(packet, function () {\n that._sendPacket({ cmd: 'pubrec', messageId: messageId }, done)\n })\n }\n })\n break\n }\n case 1: {\n // emit the message event\n options.customHandleAcks(topic, message, packet, function (error, code) {\n if (!(error instanceof Error)) {\n code = error\n error = null\n }\n if (error) { return that.emit('error', error) }\n if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for puback')) }\n if (!code) { that.emit('message', topic, message, packet) }\n that.handleMessage(packet, function (err) {\n if (err) {\n return done && done(err)\n }\n that._sendPacket({ cmd: 'puback', messageId: messageId, reasonCode: code }, done)\n })\n })\n break\n }\n case 0:\n // emit the message event\n this.emit('message', topic, message, packet)\n this.handleMessage(packet, done)\n break\n default:\n // do nothing\n debug('_handlePublish: unknown QoS. Doing nothing.')\n // log or throw an error about unknown qos\n break\n }\n}\n\n/**\n * Handle messages with backpressure support, one at a time.\n * Override at will.\n *\n * @param Packet packet the packet\n * @param Function callback call when finished\n * @api public\n */\nMqttClient.prototype.handleMessage = function (packet, callback) {\n callback()\n}\n\n/**\n * _handleAck\n *\n * @param {Object} packet\n * @api private\n */\n\nMqttClient.prototype._handleAck = function (packet) {\n /* eslint no-fallthrough: \"off\" */\n const messageId = packet.messageId\n const type = packet.cmd\n let response = null\n const cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null\n const that = this\n let err\n\n // Checking `!cb` happens to work, but it's not technically \"correct\".\n //\n // Why? This code assumes that \"no callback\" is the same as that \"we're not\n // waiting for responses\" (puback, pubrec, pubcomp, suback, or unsuback).\n //\n // It would be better to check `if (!this.outgoing[messageId])` here, but\n // there's no reason to change it and risk (another) regression.\n //\n // The only reason this code works is becaues code in MqttClient.publish,\n // MqttClinet.subscribe, and MqttClient.unsubscribe ensures that we will\n // have a callback even if the user doesn't pass one in.)\n if (!cb) {\n debug('_handleAck :: Server sent an ack in error. Ignoring.')\n // Server sent an ack in error, ignore it.\n return\n }\n\n // Process\n debug('_handleAck :: packet type', type)\n switch (type) {\n case 'pubcomp':\n // same thing as puback for QoS 2\n case 'puback': {\n const pubackRC = packet.reasonCode\n // Callback - we're done\n if (pubackRC && pubackRC > 0 && pubackRC !== 16) {\n err = new Error('Publish error: ' + errors[pubackRC])\n err.code = pubackRC\n cb(err, packet)\n }\n delete this.outgoing[messageId]\n this.outgoingStore.del(packet, cb)\n this.messageIdProvider.deallocate(messageId)\n this._invokeStoreProcessingQueue()\n break\n }\n case 'pubrec': {\n response = {\n cmd: 'pubrel',\n qos: 2,\n messageId: messageId\n }\n const pubrecRC = packet.reasonCode\n\n if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {\n err = new Error('Publish error: ' + errors[pubrecRC])\n err.code = pubrecRC\n cb(err, packet)\n } else {\n this._sendPacket(response)\n }\n break\n }\n case 'suback': {\n delete this.outgoing[messageId]\n this.messageIdProvider.deallocate(messageId)\n for (let grantedI = 0; grantedI < packet.granted.length; grantedI++) {\n if ((packet.granted[grantedI] & 0x80) !== 0) {\n // suback with Failure status\n const topics = this.messageIdToTopic[messageId]\n if (topics) {\n topics.forEach(function (topic) {\n delete that._resubscribeTopics[topic]\n })\n }\n }\n }\n this._invokeStoreProcessingQueue()\n cb(null, packet)\n break\n }\n case 'unsuback': {\n delete this.outgoing[messageId]\n this.messageIdProvider.deallocate(messageId)\n this._invokeStoreProcessingQueue()\n cb(null)\n break\n }\n default:\n that.emit('error', new Error('unrecognized packet type'))\n }\n\n if (this.disconnecting &&\n Object.keys(this.outgoing).length === 0) {\n this.emit('outgoingEmpty')\n }\n}\n\n/**\n * _handlePubrel\n *\n * @param {Object} packet\n * @api private\n */\nMqttClient.prototype._handlePubrel = function (packet, callback) {\n debug('handling pubrel packet')\n callback = typeof callback !== 'undefined' ? callback : nop\n const messageId = packet.messageId\n const that = this\n\n const comp = { cmd: 'pubcomp', messageId: messageId }\n\n that.incomingStore.get(packet, function (err, pub) {\n if (!err) {\n that.emit('message', pub.topic, pub.payload, pub)\n that.handleMessage(pub, function (err) {\n if (err) {\n return callback(err)\n }\n that.incomingStore.del(pub, nop)\n that._sendPacket(comp, callback)\n })\n } else {\n that._sendPacket(comp, callback)\n }\n })\n}\n\n/**\n * _handleDisconnect\n *\n * @param {Object} packet\n * @api private\n */\nMqttClient.prototype._handleDisconnect = function (packet) {\n this.emit('disconnect', packet)\n}\n\n/**\n * _nextId\n * @return unsigned int\n */\nMqttClient.prototype._nextId = function () {\n return this.messageIdProvider.allocate()\n}\n\n/**\n * getLastMessageId\n * @return unsigned int\n */\nMqttClient.prototype.getLastMessageId = function () {\n return this.messageIdProvider.getLastAllocated()\n}\n\n/**\n * _resubscribe\n * @api private\n */\nMqttClient.prototype._resubscribe = function () {\n debug('_resubscribe')\n const _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)\n if (!this._firstConnection &&\n (this.options.clean || (this.options.protocolVersion === 5 && !this.connackPacket.sessionPresent)) &&\n _resubscribeTopicsKeys.length > 0) {\n if (this.options.resubscribe) {\n if (this.options.protocolVersion === 5) {\n debug('_resubscribe: protocolVersion 5')\n for (let topicI = 0; topicI < _resubscribeTopicsKeys.length; topicI++) {\n const resubscribeTopic = {}\n resubscribeTopic[_resubscribeTopicsKeys[topicI]] = this._resubscribeTopics[_resubscribeTopicsKeys[topicI]]\n resubscribeTopic.resubscribe = true\n this.subscribe(resubscribeTopic, { properties: resubscribeTopic[_resubscribeTopicsKeys[topicI]].properties })\n }\n } else {\n this._resubscribeTopics.resubscribe = true\n this.subscribe(this._resubscribeTopics)\n }\n } else {\n this._resubscribeTopics = {}\n }\n }\n\n this._firstConnection = false\n}\n\n/**\n * _onConnect\n *\n * @api private\n */\nMqttClient.prototype._onConnect = function (packet) {\n if (this.disconnected) {\n this.emit('connect', packet)\n return\n }\n\n const that = this\n\n this.connackPacket = packet\n this.messageIdProvider.clear()\n this._setupPingTimer()\n\n this.connected = true\n\n function startStreamProcess () {\n let outStore = that.outgoingStore.createStream()\n\n function clearStoreProcessing () {\n that._storeProcessing = false\n that._packetIdsDuringStoreProcessing = {}\n }\n\n that.once('close', remove)\n outStore.on('error', function (err) {\n clearStoreProcessing()\n that._flushStoreProcessingQueue()\n that.removeListener('close', remove)\n that.emit('error', err)\n })\n\n function remove () {\n outStore.destroy()\n outStore = null\n that._flushStoreProcessingQueue()\n clearStoreProcessing()\n }\n\n function storeDeliver () {\n // edge case, we wrapped this twice\n if (!outStore) {\n return\n }\n that._storeProcessing = true\n\n const packet = outStore.read(1)\n\n let cb\n\n if (!packet) {\n // read when data is available in the future\n outStore.once('readable', storeDeliver)\n return\n }\n\n // Skip already processed store packets\n if (that._packetIdsDuringStoreProcessing[packet.messageId]) {\n storeDeliver()\n return\n }\n\n // Avoid unnecessary stream read operations when disconnected\n if (!that.disconnecting && !that.reconnectTimer) {\n cb = that.outgoing[packet.messageId] ? that.outgoing[packet.messageId].cb : null\n that.outgoing[packet.messageId] = {\n volatile: false,\n cb: function (err, status) {\n // Ensure that the original callback passed in to publish gets invoked\n if (cb) {\n cb(err, status)\n }\n\n storeDeliver()\n }\n }\n that._packetIdsDuringStoreProcessing[packet.messageId] = true\n if (that.messageIdProvider.register(packet.messageId)) {\n that._sendPacket(packet)\n } else {\n debug('messageId: %d has already used.', packet.messageId)\n }\n } else if (outStore.destroy) {\n outStore.destroy()\n }\n }\n\n outStore.on('end', function () {\n let allProcessed = true\n for (const id in that._packetIdsDuringStoreProcessing) {\n if (!that._packetIdsDuringStoreProcessing[id]) {\n allProcessed = false\n break\n }\n }\n if (allProcessed) {\n clearStoreProcessing()\n that.removeListener('close', remove)\n that._invokeAllStoreProcessingQueue()\n that.emit('connect', packet)\n } else {\n startStreamProcess()\n }\n })\n storeDeliver()\n }\n // start flowing\n startStreamProcess()\n}\n\nMqttClient.prototype._invokeStoreProcessingQueue = function () {\n if (this._storeProcessingQueue.length > 0) {\n const f = this._storeProcessingQueue[0]\n if (f && f.invoke()) {\n this._storeProcessingQueue.shift()\n return true\n }\n }\n return false\n}\n\nMqttClient.prototype._invokeAllStoreProcessingQueue = function () {\n while (this._invokeStoreProcessingQueue()) { /* empty */ }\n}\n\nMqttClient.prototype._flushStoreProcessingQueue = function () {\n for (const f of this._storeProcessingQueue) {\n if (f.cbStorePut) f.cbStorePut(new Error('Connection closed'))\n if (f.callback) f.callback(new Error('Connection closed'))\n }\n this._storeProcessingQueue.splice(0)\n}\n\nmodule.exports = MqttClient\n", "/*! https://mths.be/punycode v1.4.1 by @mathias */\n\n\n/** Highest positive signed 32-bit float value */\nvar maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1\n\n/** Bootstring parameters */\nvar base = 36;\nvar tMin = 1;\nvar tMax = 26;\nvar skew = 38;\nvar damp = 700;\nvar initialBias = 72;\nvar initialN = 128; // 0x80\nvar delimiter = '-'; // '\\x2D'\n\n/** Regular expressions */\nvar regexPunycode = /^xn--/;\nvar regexNonASCII = /[^\\x20-\\x7E]/; // unprintable ASCII chars + non-ASCII chars\nvar regexSeparators = /[\\x2E\\u3002\\uFF0E\\uFF61]/g; // RFC 3490 separators\n\n/** Error messages */\nvar errors = {\n 'overflow': 'Overflow: input needs wider integers to process',\n 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',\n 'invalid-input': 'Invalid input'\n};\n\n/** Convenience shortcuts */\nvar baseMinusTMin = base - tMin;\nvar floor = Math.floor;\nvar stringFromCharCode = String.fromCharCode;\n\n/*--------------------------------------------------------------------------*/\n\n/**\n * A generic error utility function.\n * @private\n * @param {String} type The error type.\n * @returns {Error} Throws a `RangeError` with the applicable error message.\n */\nfunction error(type) {\n throw new RangeError(errors[type]);\n}\n\n/**\n * A generic `Array#map` utility function.\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} callback The function that gets called for every array\n * item.\n * @returns {Array} A new array of values returned by the callback function.\n */\nfunction map(array, fn) {\n var length = array.length;\n var result = [];\n while (length--) {\n result[length] = fn(array[length]);\n }\n return result;\n}\n\n/**\n * A simple `Array#map`-like wrapper to work with domain name strings or email\n * addresses.\n * @private\n * @param {String} domain The domain name or email address.\n * @param {Function} callback The function that gets called for every\n * character.\n * @returns {Array} A new string of characters returned by the callback\n * function.\n */\nfunction mapDomain(string, fn) {\n var parts = string.split('@');\n var result = '';\n if (parts.length > 1) {\n // In email addresses, only the domain name should be punycoded. Leave\n // the local part (i.e. everything up to `@`) intact.\n result = parts[0] + '@';\n string = parts[1];\n }\n // Avoid `split(regex)` for IE8 compatibility. See #17.\n string = string.replace(regexSeparators, '\\x2E');\n var labels = string.split('.');\n var encoded = map(labels, fn).join('.');\n return result + encoded;\n}\n\n/**\n * Creates an array containing the numeric code points of each Unicode\n * character in the string. While JavaScript uses UCS-2 internally,\n * this function will convert a pair of surrogate halves (each of which\n * UCS-2 exposes as separate characters) into a single code point,\n * matching UTF-16.\n * @see `punycode.ucs2.encode`\n * @see \n * @memberOf punycode.ucs2\n * @name decode\n * @param {String} string The Unicode input string (UCS-2).\n * @returns {Array} The new array of code points.\n */\nfunction ucs2decode(string) {\n var output = [],\n counter = 0,\n length = string.length,\n value,\n extra;\n while (counter < length) {\n value = string.charCodeAt(counter++);\n if (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n // high surrogate, and there is a next character\n extra = string.charCodeAt(counter++);\n if ((extra & 0xFC00) == 0xDC00) { // low surrogate\n output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n } else {\n // unmatched surrogate; only append this code unit, in case the next\n // code unit is the high surrogate of a surrogate pair\n output.push(value);\n counter--;\n }\n } else {\n output.push(value);\n }\n }\n return output;\n}\n\n/**\n * Creates a string based on an array of numeric code points.\n * @see `punycode.ucs2.decode`\n * @memberOf punycode.ucs2\n * @name encode\n * @param {Array} codePoints The array of numeric code points.\n * @returns {String} The new Unicode string (UCS-2).\n */\nfunction ucs2encode(array) {\n return map(array, function(value) {\n var output = '';\n if (value > 0xFFFF) {\n value -= 0x10000;\n output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);\n value = 0xDC00 | value & 0x3FF;\n }\n output += stringFromCharCode(value);\n return output;\n }).join('');\n}\n\n/**\n * Converts a basic code point into a digit/integer.\n * @see `digitToBasic()`\n * @private\n * @param {Number} codePoint The basic numeric code point value.\n * @returns {Number} The numeric value of a basic code point (for use in\n * representing integers) in the range `0` to `base - 1`, or `base` if\n * the code point does not represent a value.\n */\nfunction basicToDigit(codePoint) {\n if (codePoint - 48 < 10) {\n return codePoint - 22;\n }\n if (codePoint - 65 < 26) {\n return codePoint - 65;\n }\n if (codePoint - 97 < 26) {\n return codePoint - 97;\n }\n return base;\n}\n\n/**\n * Converts a digit/integer into a basic code point.\n * @see `basicToDigit()`\n * @private\n * @param {Number} digit The numeric value of a basic code point.\n * @returns {Number} The basic code point whose value (when used for\n * representing integers) is `digit`, which needs to be in the range\n * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is\n * used; else, the lowercase form is used. The behavior is undefined\n * if `flag` is non-zero and `digit` has no uppercase form.\n */\nfunction digitToBasic(digit, flag) {\n // 0..25 map to ASCII a..z or A..Z\n // 26..35 map to ASCII 0..9\n return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);\n}\n\n/**\n * Bias adaptation function as per section 3.4 of RFC 3492.\n * https://tools.ietf.org/html/rfc3492#section-3.4\n * @private\n */\nfunction adapt(delta, numPoints, firstTime) {\n var k = 0;\n delta = firstTime ? floor(delta / damp) : delta >> 1;\n delta += floor(delta / numPoints);\n for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {\n delta = floor(delta / baseMinusTMin);\n }\n return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n}\n\n/**\n * Converts a Punycode string of ASCII-only symbols to a string of Unicode\n * symbols.\n * @memberOf punycode\n * @param {String} input The Punycode string of ASCII-only symbols.\n * @returns {String} The resulting string of Unicode symbols.\n */\nexport function decode(input) {\n // Don't use UCS-2\n var output = [],\n inputLength = input.length,\n out,\n i = 0,\n n = initialN,\n bias = initialBias,\n basic,\n j,\n index,\n oldi,\n w,\n k,\n digit,\n t,\n /** Cached calculation results */\n baseMinusT;\n\n // Handle the basic code points: let `basic` be the number of input code\n // points before the last delimiter, or `0` if there is none, then copy\n // the first basic code points to the output.\n\n basic = input.lastIndexOf(delimiter);\n if (basic < 0) {\n basic = 0;\n }\n\n for (j = 0; j < basic; ++j) {\n // if it's not a basic code point\n if (input.charCodeAt(j) >= 0x80) {\n error('not-basic');\n }\n output.push(input.charCodeAt(j));\n }\n\n // Main decoding loop: start just after the last delimiter if any basic code\n // points were copied; start at the beginning otherwise.\n\n for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */ ) {\n\n // `index` is the index of the next character to be consumed.\n // Decode a generalized variable-length integer into `delta`,\n // which gets added to `i`. The overflow checking is easier\n // if we increase `i` as we go, then subtract off its starting\n // value at the end to obtain `delta`.\n for (oldi = i, w = 1, k = base; /* no condition */ ; k += base) {\n\n if (index >= inputLength) {\n error('invalid-input');\n }\n\n digit = basicToDigit(input.charCodeAt(index++));\n\n if (digit >= base || digit > floor((maxInt - i) / w)) {\n error('overflow');\n }\n\n i += digit * w;\n t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\n if (digit < t) {\n break;\n }\n\n baseMinusT = base - t;\n if (w > floor(maxInt / baseMinusT)) {\n error('overflow');\n }\n\n w *= baseMinusT;\n\n }\n\n out = output.length + 1;\n bias = adapt(i - oldi, out, oldi == 0);\n\n // `i` was supposed to wrap around from `out` to `0`,\n // incrementing `n` each time, so we'll fix that now:\n if (floor(i / out) > maxInt - n) {\n error('overflow');\n }\n\n n += floor(i / out);\n i %= out;\n\n // Insert `n` at position `i` of the output\n output.splice(i++, 0, n);\n\n }\n\n return ucs2encode(output);\n}\n\n/**\n * Converts a string of Unicode symbols (e.g. a domain name label) to a\n * Punycode string of ASCII-only symbols.\n * @memberOf punycode\n * @param {String} input The string of Unicode symbols.\n * @returns {String} The resulting Punycode string of ASCII-only symbols.\n */\nexport function encode(input) {\n var n,\n delta,\n handledCPCount,\n basicLength,\n bias,\n j,\n m,\n q,\n k,\n t,\n currentValue,\n output = [],\n /** `inputLength` will hold the number of code points in `input`. */\n inputLength,\n /** Cached calculation results */\n handledCPCountPlusOne,\n baseMinusT,\n qMinusT;\n\n // Convert the input in UCS-2 to Unicode\n input = ucs2decode(input);\n\n // Cache the length\n inputLength = input.length;\n\n // Initialize the state\n n = initialN;\n delta = 0;\n bias = initialBias;\n\n // Handle the basic code points\n for (j = 0; j < inputLength; ++j) {\n currentValue = input[j];\n if (currentValue < 0x80) {\n output.push(stringFromCharCode(currentValue));\n }\n }\n\n handledCPCount = basicLength = output.length;\n\n // `handledCPCount` is the number of code points that have been handled;\n // `basicLength` is the number of basic code points.\n\n // Finish the basic string - if it is not empty - with a delimiter\n if (basicLength) {\n output.push(delimiter);\n }\n\n // Main encoding loop:\n while (handledCPCount < inputLength) {\n\n // All non-basic code points < n have been handled already. Find the next\n // larger one:\n for (m = maxInt, j = 0; j < inputLength; ++j) {\n currentValue = input[j];\n if (currentValue >= n && currentValue < m) {\n m = currentValue;\n }\n }\n\n // Increase `delta` enough to advance the decoder's state to ,\n // but guard against overflow\n handledCPCountPlusOne = handledCPCount + 1;\n if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {\n error('overflow');\n }\n\n delta += (m - n) * handledCPCountPlusOne;\n n = m;\n\n for (j = 0; j < inputLength; ++j) {\n currentValue = input[j];\n\n if (currentValue < n && ++delta > maxInt) {\n error('overflow');\n }\n\n if (currentValue == n) {\n // Represent delta as a generalized variable-length integer\n for (q = delta, k = base; /* no condition */ ; k += base) {\n t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n if (q < t) {\n break;\n }\n qMinusT = q - t;\n baseMinusT = base - t;\n output.push(\n stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))\n );\n q = floor(qMinusT / baseMinusT);\n }\n\n output.push(stringFromCharCode(digitToBasic(q, 0)));\n bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);\n delta = 0;\n ++handledCPCount;\n }\n }\n\n ++delta;\n ++n;\n\n }\n return output.join('');\n}\n\n/**\n * Converts a Punycode string representing a domain name or an email address\n * to Unicode. Only the Punycoded parts of the input will be converted, i.e.\n * it doesn't matter if you call it on a string that has already been\n * converted to Unicode.\n * @memberOf punycode\n * @param {String} input The Punycoded domain name or email address to\n * convert to Unicode.\n * @returns {String} The Unicode representation of the given Punycode\n * string.\n */\nexport function toUnicode(input) {\n return mapDomain(input, function(string) {\n return regexPunycode.test(string) ?\n decode(string.slice(4).toLowerCase()) :\n string;\n });\n}\n\n/**\n * Converts a Unicode string representing a domain name or an email address to\n * Punycode. Only the non-ASCII parts of the domain name will be converted,\n * i.e. it doesn't matter if you call it with a domain that's already in\n * ASCII.\n * @memberOf punycode\n * @param {String} input The domain name or email address to convert, as a\n * Unicode string.\n * @returns {String} The Punycode representation of the given domain name or\n * email address.\n */\nexport function toASCII(input) {\n return mapDomain(input, function(string) {\n return regexNonASCII.test(string) ?\n 'xn--' + encode(string) :\n string;\n });\n}\nexport var version = '1.4.1';\n/**\n * An object of methods to convert from JavaScript's internal character\n * representation (UCS-2) to Unicode code points, and back.\n * @see \n * @memberOf punycode\n * @type Object\n */\n\nexport var ucs2 = {\n decode: ucs2decode,\n encode: ucs2encode\n};\nexport default {\n version: version,\n ucs2: ucs2,\n toASCII: toASCII,\n toUnicode: toUnicode,\n encode: encode,\n decode: decode\n}\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n// If obj.hasOwnProperty has been overridden, then calling\n// obj.hasOwnProperty(prop) will break.\n// See: https://github.com/joyent/node/issues/1707\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\nvar isArray = Array.isArray || function (xs) {\n return Object.prototype.toString.call(xs) === '[object Array]';\n};\nfunction stringifyPrimitive(v) {\n switch (typeof v) {\n case 'string':\n return v;\n\n case 'boolean':\n return v ? 'true' : 'false';\n\n case 'number':\n return isFinite(v) ? v : '';\n\n default:\n return '';\n }\n}\n\nexport function stringify (obj, sep, eq, name) {\n sep = sep || '&';\n eq = eq || '=';\n if (obj === null) {\n obj = undefined;\n }\n\n if (typeof obj === 'object') {\n return map(objectKeys(obj), function(k) {\n var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;\n if (isArray(obj[k])) {\n return map(obj[k], function(v) {\n return ks + encodeURIComponent(stringifyPrimitive(v));\n }).join(sep);\n } else {\n return ks + encodeURIComponent(stringifyPrimitive(obj[k]));\n }\n }).join(sep);\n\n }\n\n if (!name) return '';\n return encodeURIComponent(stringifyPrimitive(name)) + eq +\n encodeURIComponent(stringifyPrimitive(obj));\n};\n\nfunction map (xs, f) {\n if (xs.map) return xs.map(f);\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n res.push(f(xs[i], i));\n }\n return res;\n}\n\nvar objectKeys = Object.keys || function (obj) {\n var res = [];\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);\n }\n return res;\n};\n\nexport function parse(qs, sep, eq, options) {\n sep = sep || '&';\n eq = eq || '=';\n var obj = {};\n\n if (typeof qs !== 'string' || qs.length === 0) {\n return obj;\n }\n\n var regexp = /\\+/g;\n qs = qs.split(sep);\n\n var maxKeys = 1000;\n if (options && typeof options.maxKeys === 'number') {\n maxKeys = options.maxKeys;\n }\n\n var len = qs.length;\n // maxKeys <= 0 means that we should not limit keys count\n if (maxKeys > 0 && len > maxKeys) {\n len = maxKeys;\n }\n\n for (var i = 0; i < len; ++i) {\n var x = qs[i].replace(regexp, '%20'),\n idx = x.indexOf(eq),\n kstr, vstr, k, v;\n\n if (idx >= 0) {\n kstr = x.substr(0, idx);\n vstr = x.substr(idx + 1);\n } else {\n kstr = x;\n vstr = '';\n }\n\n k = decodeURIComponent(kstr);\n v = decodeURIComponent(vstr);\n\n if (!hasOwnProperty(obj, k)) {\n obj[k] = v;\n } else if (isArray(obj[k])) {\n obj[k].push(v);\n } else {\n obj[k] = [obj[k], v];\n }\n }\n\n return obj;\n};\nexport default {\n encode: stringify,\n stringify: stringify,\n decode: parse,\n parse: parse\n}\nexport {stringify as encode, parse as decode};\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\nimport {toASCII} from 'punycode';\nimport {isObject,isString,isNullOrUndefined,isNull} from 'util';\nimport {parse as qsParse,stringify as qsStringify} from 'querystring';\nexport {\n urlParse as parse,\n urlResolve as resolve,\n urlResolveObject as resolveObject,\n urlFormat as format\n};\nexport default {\n parse: urlParse,\n resolve: urlResolve,\n resolveObject: urlResolveObject,\n format: urlFormat,\n Url: Url\n}\nexport function Url() {\n this.protocol = null;\n this.slashes = null;\n this.auth = null;\n this.host = null;\n this.port = null;\n this.hostname = null;\n this.hash = null;\n this.search = null;\n this.query = null;\n this.pathname = null;\n this.path = null;\n this.href = null;\n}\n\n// Reference: RFC 3986, RFC 1808, RFC 2396\n\n// define these here so at least they only have to be\n// compiled once on the first module load.\nvar protocolPattern = /^([a-z0-9.+-]+:)/i,\n portPattern = /:[0-9]*$/,\n\n // Special case for a simple path URL\n simplePathPattern = /^(\\/\\/?(?!\\/)[^\\?\\s]*)(\\?[^\\s]*)?$/,\n\n // RFC 2396: characters reserved for delimiting URLs.\n // We actually just auto-escape these.\n delims = ['<', '>', '\"', '`', ' ', '\\r', '\\n', '\\t'],\n\n // RFC 2396: characters not allowed for various reasons.\n unwise = ['{', '}', '|', '\\\\', '^', '`'].concat(delims),\n\n // Allowed by RFCs, but cause of XSS attacks. Always escape these.\n autoEscape = ['\\''].concat(unwise),\n // Characters that are never ever allowed in a hostname.\n // Note that any invalid chars are also handled, but these\n // are the ones that are *expected* to be seen, so we fast-path\n // them.\n nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),\n hostEndingChars = ['/', '?', '#'],\n hostnameMaxLen = 255,\n hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,\n hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,\n // protocols that can allow \"unsafe\" and \"unwise\" chars.\n unsafeProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that never have a hostname.\n hostlessProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that always contain a // bit.\n slashedProtocol = {\n 'http': true,\n 'https': true,\n 'ftp': true,\n 'gopher': true,\n 'file': true,\n 'http:': true,\n 'https:': true,\n 'ftp:': true,\n 'gopher:': true,\n 'file:': true\n };\n\nfunction urlParse(url, parseQueryString, slashesDenoteHost) {\n if (url && isObject(url) && url instanceof Url) return url;\n\n var u = new Url;\n u.parse(url, parseQueryString, slashesDenoteHost);\n return u;\n}\nUrl.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {\n return parse(this, url, parseQueryString, slashesDenoteHost);\n}\n\nfunction parse(self, url, parseQueryString, slashesDenoteHost) {\n if (!isString(url)) {\n throw new TypeError('Parameter \\'url\\' must be a string, not ' + typeof url);\n }\n\n // Copy chrome, IE, opera backslash-handling behavior.\n // Back slashes before the query string get converted to forward slashes\n // See: https://code.google.com/p/chromium/issues/detail?id=25916\n var queryIndex = url.indexOf('?'),\n splitter =\n (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',\n uSplit = url.split(splitter),\n slashRegex = /\\\\/g;\n uSplit[0] = uSplit[0].replace(slashRegex, '/');\n url = uSplit.join(splitter);\n\n var rest = url;\n\n // trim before proceeding.\n // This is to support parse stuff like \" http://foo.com \\n\"\n rest = rest.trim();\n\n if (!slashesDenoteHost && url.split('#').length === 1) {\n // Try fast path regexp\n var simplePath = simplePathPattern.exec(rest);\n if (simplePath) {\n self.path = rest;\n self.href = rest;\n self.pathname = simplePath[1];\n if (simplePath[2]) {\n self.search = simplePath[2];\n if (parseQueryString) {\n self.query = qsParse(self.search.substr(1));\n } else {\n self.query = self.search.substr(1);\n }\n } else if (parseQueryString) {\n self.search = '';\n self.query = {};\n }\n return self;\n }\n }\n\n var proto = protocolPattern.exec(rest);\n if (proto) {\n proto = proto[0];\n var lowerProto = proto.toLowerCase();\n self.protocol = lowerProto;\n rest = rest.substr(proto.length);\n }\n\n // figure out if it's got a host\n // user@server is *always* interpreted as a hostname, and url\n // resolution will treat //foo/bar as host=foo,path=bar because that's\n // how the browser resolves relative URLs.\n if (slashesDenoteHost || proto || rest.match(/^\\/\\/[^@\\/]+@[^@\\/]+/)) {\n var slashes = rest.substr(0, 2) === '//';\n if (slashes && !(proto && hostlessProtocol[proto])) {\n rest = rest.substr(2);\n self.slashes = true;\n }\n }\n var i, hec, l, p;\n if (!hostlessProtocol[proto] &&\n (slashes || (proto && !slashedProtocol[proto]))) {\n\n // there's a hostname.\n // the first instance of /, ?, ;, or # ends the host.\n //\n // If there is an @ in the hostname, then non-host chars *are* allowed\n // to the left of the last @ sign, unless some host-ending character\n // comes *before* the @-sign.\n // URLs are obnoxious.\n //\n // ex:\n // http://a@b@c/ => user:a@b host:c\n // http://a@b?@c => user:a host:c path:/?@c\n\n // v0.12 TODO(isaacs): This is not quite how Chrome does things.\n // Review our test case against browsers more comprehensively.\n\n // find the first instance of any hostEndingChars\n var hostEnd = -1;\n for (i = 0; i < hostEndingChars.length; i++) {\n hec = rest.indexOf(hostEndingChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n\n // at this point, either we have an explicit point where the\n // auth portion cannot go past, or the last @ char is the decider.\n var auth, atSign;\n if (hostEnd === -1) {\n // atSign can be anywhere.\n atSign = rest.lastIndexOf('@');\n } else {\n // atSign must be in auth portion.\n // http://a@b/c@d => host:b auth:a path:/c@d\n atSign = rest.lastIndexOf('@', hostEnd);\n }\n\n // Now we have a portion which is definitely the auth.\n // Pull that off.\n if (atSign !== -1) {\n auth = rest.slice(0, atSign);\n rest = rest.slice(atSign + 1);\n self.auth = decodeURIComponent(auth);\n }\n\n // the host is the remaining to the left of the first non-host char\n hostEnd = -1;\n for (i = 0; i < nonHostChars.length; i++) {\n hec = rest.indexOf(nonHostChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n // if we still have not hit it, then the entire thing is a host.\n if (hostEnd === -1)\n hostEnd = rest.length;\n\n self.host = rest.slice(0, hostEnd);\n rest = rest.slice(hostEnd);\n\n // pull out port.\n parseHost(self);\n\n // we've indicated that there is a hostname,\n // so even if it's empty, it has to be present.\n self.hostname = self.hostname || '';\n\n // if hostname begins with [ and ends with ]\n // assume that it's an IPv6 address.\n var ipv6Hostname = self.hostname[0] === '[' &&\n self.hostname[self.hostname.length - 1] === ']';\n\n // validate a little.\n if (!ipv6Hostname) {\n var hostparts = self.hostname.split(/\\./);\n for (i = 0, l = hostparts.length; i < l; i++) {\n var part = hostparts[i];\n if (!part) continue;\n if (!part.match(hostnamePartPattern)) {\n var newpart = '';\n for (var j = 0, k = part.length; j < k; j++) {\n if (part.charCodeAt(j) > 127) {\n // we replace non-ASCII char with a temporary placeholder\n // we need this to make sure size of hostname is not\n // broken by replacing non-ASCII by nothing\n newpart += 'x';\n } else {\n newpart += part[j];\n }\n }\n // we test again with ASCII char only\n if (!newpart.match(hostnamePartPattern)) {\n var validParts = hostparts.slice(0, i);\n var notHost = hostparts.slice(i + 1);\n var bit = part.match(hostnamePartStart);\n if (bit) {\n validParts.push(bit[1]);\n notHost.unshift(bit[2]);\n }\n if (notHost.length) {\n rest = '/' + notHost.join('.') + rest;\n }\n self.hostname = validParts.join('.');\n break;\n }\n }\n }\n }\n\n if (self.hostname.length > hostnameMaxLen) {\n self.hostname = '';\n } else {\n // hostnames are always lower case.\n self.hostname = self.hostname.toLowerCase();\n }\n\n if (!ipv6Hostname) {\n // IDNA Support: Returns a punycoded representation of \"domain\".\n // It only converts parts of the domain name that\n // have non-ASCII characters, i.e. it doesn't matter if\n // you call it with a domain that already is ASCII-only.\n self.hostname = toASCII(self.hostname);\n }\n\n p = self.port ? ':' + self.port : '';\n var h = self.hostname || '';\n self.host = h + p;\n self.href += self.host;\n\n // strip [ and ] from the hostname\n // the host field still retains them, though\n if (ipv6Hostname) {\n self.hostname = self.hostname.substr(1, self.hostname.length - 2);\n if (rest[0] !== '/') {\n rest = '/' + rest;\n }\n }\n }\n\n // now rest is set to the post-host stuff.\n // chop off any delim chars.\n if (!unsafeProtocol[lowerProto]) {\n\n // First, make 100% sure that any \"autoEscape\" chars get\n // escaped, even if encodeURIComponent doesn't think they\n // need to be.\n for (i = 0, l = autoEscape.length; i < l; i++) {\n var ae = autoEscape[i];\n if (rest.indexOf(ae) === -1)\n continue;\n var esc = encodeURIComponent(ae);\n if (esc === ae) {\n esc = escape(ae);\n }\n rest = rest.split(ae).join(esc);\n }\n }\n\n\n // chop off from the tail first.\n var hash = rest.indexOf('#');\n if (hash !== -1) {\n // got a fragment string.\n self.hash = rest.substr(hash);\n rest = rest.slice(0, hash);\n }\n var qm = rest.indexOf('?');\n if (qm !== -1) {\n self.search = rest.substr(qm);\n self.query = rest.substr(qm + 1);\n if (parseQueryString) {\n self.query = qsParse(self.query);\n }\n rest = rest.slice(0, qm);\n } else if (parseQueryString) {\n // no query string, but parseQueryString still requested\n self.search = '';\n self.query = {};\n }\n if (rest) self.pathname = rest;\n if (slashedProtocol[lowerProto] &&\n self.hostname && !self.pathname) {\n self.pathname = '/';\n }\n\n //to support http.request\n if (self.pathname || self.search) {\n p = self.pathname || '';\n var s = self.search || '';\n self.path = p + s;\n }\n\n // finally, reconstruct the href based on what has been validated.\n self.href = format(self);\n return self;\n}\n\n// format a parsed object into a url string\nfunction urlFormat(obj) {\n // ensure it's an object, and not a string url.\n // If it's an obj, this is a no-op.\n // this way, you can call url_format() on strings\n // to clean up potentially wonky urls.\n if (isString(obj)) obj = parse({}, obj);\n return format(obj);\n}\n\nfunction format(self) {\n var auth = self.auth || '';\n if (auth) {\n auth = encodeURIComponent(auth);\n auth = auth.replace(/%3A/i, ':');\n auth += '@';\n }\n\n var protocol = self.protocol || '',\n pathname = self.pathname || '',\n hash = self.hash || '',\n host = false,\n query = '';\n\n if (self.host) {\n host = auth + self.host;\n } else if (self.hostname) {\n host = auth + (self.hostname.indexOf(':') === -1 ?\n self.hostname :\n '[' + this.hostname + ']');\n if (self.port) {\n host += ':' + self.port;\n }\n }\n\n if (self.query &&\n isObject(self.query) &&\n Object.keys(self.query).length) {\n query = qsStringify(self.query);\n }\n\n var search = self.search || (query && ('?' + query)) || '';\n\n if (protocol && protocol.substr(-1) !== ':') protocol += ':';\n\n // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.\n // unless they had them to begin with.\n if (self.slashes ||\n (!protocol || slashedProtocol[protocol]) && host !== false) {\n host = '//' + (host || '');\n if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;\n } else if (!host) {\n host = '';\n }\n\n if (hash && hash.charAt(0) !== '#') hash = '#' + hash;\n if (search && search.charAt(0) !== '?') search = '?' + search;\n\n pathname = pathname.replace(/[?#]/g, function(match) {\n return encodeURIComponent(match);\n });\n search = search.replace('#', '%23');\n\n return protocol + host + pathname + search + hash;\n}\n\nUrl.prototype.format = function() {\n return format(this);\n}\n\nfunction urlResolve(source, relative) {\n return urlParse(source, false, true).resolve(relative);\n}\n\nUrl.prototype.resolve = function(relative) {\n return this.resolveObject(urlParse(relative, false, true)).format();\n};\n\nfunction urlResolveObject(source, relative) {\n if (!source) return relative;\n return urlParse(source, false, true).resolveObject(relative);\n}\n\nUrl.prototype.resolveObject = function(relative) {\n if (isString(relative)) {\n var rel = new Url();\n rel.parse(relative, false, true);\n relative = rel;\n }\n\n var result = new Url();\n var tkeys = Object.keys(this);\n for (var tk = 0; tk < tkeys.length; tk++) {\n var tkey = tkeys[tk];\n result[tkey] = this[tkey];\n }\n\n // hash is always overridden, no matter what.\n // even href=\"\" will remove it.\n result.hash = relative.hash;\n\n // if the relative url is empty, then there's nothing left to do here.\n if (relative.href === '') {\n result.href = result.format();\n return result;\n }\n\n // hrefs like //foo/bar always cut to the protocol.\n if (relative.slashes && !relative.protocol) {\n // take everything except the protocol from relative\n var rkeys = Object.keys(relative);\n for (var rk = 0; rk < rkeys.length; rk++) {\n var rkey = rkeys[rk];\n if (rkey !== 'protocol')\n result[rkey] = relative[rkey];\n }\n\n //urlParse appends trailing / to urls like http://www.example.com\n if (slashedProtocol[result.protocol] &&\n result.hostname && !result.pathname) {\n result.path = result.pathname = '/';\n }\n\n result.href = result.format();\n return result;\n }\n var relPath;\n if (relative.protocol && relative.protocol !== result.protocol) {\n // if it's a known url protocol, then changing\n // the protocol does weird things\n // first, if it's not file:, then we MUST have a host,\n // and if there was a path\n // to begin with, then we MUST have a path.\n // if it is file:, then the host is dropped,\n // because that's known to be hostless.\n // anything else is assumed to be absolute.\n if (!slashedProtocol[relative.protocol]) {\n var keys = Object.keys(relative);\n for (var v = 0; v < keys.length; v++) {\n var k = keys[v];\n result[k] = relative[k];\n }\n result.href = result.format();\n return result;\n }\n\n result.protocol = relative.protocol;\n if (!relative.host && !hostlessProtocol[relative.protocol]) {\n relPath = (relative.pathname || '').split('/');\n while (relPath.length && !(relative.host = relPath.shift()));\n if (!relative.host) relative.host = '';\n if (!relative.hostname) relative.hostname = '';\n if (relPath[0] !== '') relPath.unshift('');\n if (relPath.length < 2) relPath.unshift('');\n result.pathname = relPath.join('/');\n } else {\n result.pathname = relative.pathname;\n }\n result.search = relative.search;\n result.query = relative.query;\n result.host = relative.host || '';\n result.auth = relative.auth;\n result.hostname = relative.hostname || relative.host;\n result.port = relative.port;\n // to support http.request\n if (result.pathname || result.search) {\n var p = result.pathname || '';\n var s = result.search || '';\n result.path = p + s;\n }\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n }\n\n var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),\n isRelAbs = (\n relative.host ||\n relative.pathname && relative.pathname.charAt(0) === '/'\n ),\n mustEndAbs = (isRelAbs || isSourceAbs ||\n (result.host && relative.pathname)),\n removeAllDots = mustEndAbs,\n srcPath = result.pathname && result.pathname.split('/') || [],\n psychotic = result.protocol && !slashedProtocol[result.protocol];\n relPath = relative.pathname && relative.pathname.split('/') || [];\n // if the url is a non-slashed url, then relative\n // links like ../.. should be able\n // to crawl up to the hostname, as well. This is strange.\n // result.protocol has already been set by now.\n // Later on, put the first path part into the host field.\n if (psychotic) {\n result.hostname = '';\n result.port = null;\n if (result.host) {\n if (srcPath[0] === '') srcPath[0] = result.host;\n else srcPath.unshift(result.host);\n }\n result.host = '';\n if (relative.protocol) {\n relative.hostname = null;\n relative.port = null;\n if (relative.host) {\n if (relPath[0] === '') relPath[0] = relative.host;\n else relPath.unshift(relative.host);\n }\n relative.host = null;\n }\n mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');\n }\n var authInHost;\n if (isRelAbs) {\n // it's absolute.\n result.host = (relative.host || relative.host === '') ?\n relative.host : result.host;\n result.hostname = (relative.hostname || relative.hostname === '') ?\n relative.hostname : result.hostname;\n result.search = relative.search;\n result.query = relative.query;\n srcPath = relPath;\n // fall through to the dot-handling below.\n } else if (relPath.length) {\n // it's relative\n // throw away the existing file, and take the new path instead.\n if (!srcPath) srcPath = [];\n srcPath.pop();\n srcPath = srcPath.concat(relPath);\n result.search = relative.search;\n result.query = relative.query;\n } else if (!isNullOrUndefined(relative.search)) {\n // just pull out the search.\n // like href='?foo'.\n // Put this after the other two cases because it simplifies the booleans\n if (psychotic) {\n result.hostname = result.host = srcPath.shift();\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n result.search = relative.search;\n result.query = relative.query;\n //to support http.request\n if (!isNull(result.pathname) || !isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.href = result.format();\n return result;\n }\n\n if (!srcPath.length) {\n // no path at all. easy.\n // we've already handled the other stuff above.\n result.pathname = null;\n //to support http.request\n if (result.search) {\n result.path = '/' + result.search;\n } else {\n result.path = null;\n }\n result.href = result.format();\n return result;\n }\n\n // if a url ENDs in . or .., then it must get a trailing slash.\n // however, if it ends in anything else non-slashy,\n // then it must NOT get a trailing slash.\n var last = srcPath.slice(-1)[0];\n var hasTrailingSlash = (\n (result.host || relative.host || srcPath.length > 1) &&\n (last === '.' || last === '..') || last === '');\n\n // strip single dots, resolve double dots to parent dir\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = srcPath.length; i >= 0; i--) {\n last = srcPath[i];\n if (last === '.') {\n srcPath.splice(i, 1);\n } else if (last === '..') {\n srcPath.splice(i, 1);\n up++;\n } else if (up) {\n srcPath.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (!mustEndAbs && !removeAllDots) {\n for (; up--; up) {\n srcPath.unshift('..');\n }\n }\n\n if (mustEndAbs && srcPath[0] !== '' &&\n (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {\n srcPath.unshift('');\n }\n\n if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {\n srcPath.push('');\n }\n\n var isAbsolute = srcPath[0] === '' ||\n (srcPath[0] && srcPath[0].charAt(0) === '/');\n\n // put the host back\n if (psychotic) {\n result.hostname = result.host = isAbsolute ? '' :\n srcPath.length ? srcPath.shift() : '';\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n\n mustEndAbs = mustEndAbs || (result.host && srcPath.length);\n\n if (mustEndAbs && !isAbsolute) {\n srcPath.unshift('');\n }\n\n if (!srcPath.length) {\n result.pathname = null;\n result.path = null;\n } else {\n result.pathname = srcPath.join('/');\n }\n\n //to support request.http\n if (!isNull(result.pathname) || !isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.auth = relative.auth || result.auth;\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n};\n\nUrl.prototype.parseHost = function() {\n return parseHost(this);\n};\n\nfunction parseHost(self) {\n var host = self.host;\n var port = portPattern.exec(host);\n if (port) {\n port = port[0];\n if (port !== ':') {\n self.port = port.substr(1);\n }\n host = host.substr(0, host.length - port.length);\n }\n if (host) self.hostname = host;\n}\n", "\nconst polyfill = require('url')\n\nif (polyfill && polyfill.default) {\n module.exports = polyfill.default\n for (let k in polyfill) {\n module.exports[k] = polyfill[k]\n }\n} else if (polyfill) {\n module.exports = polyfill\n}\n\n\n", "export default {};\n", "\nconst polyfill = require('net')\n\nif (polyfill && polyfill.default) {\n module.exports = polyfill.default\n for (let k in polyfill) {\n module.exports[k] = polyfill[k]\n }\n} else if (polyfill) {\n module.exports = polyfill\n}\n\n\n", "'use strict'\nconst net = require('net')\nconst debug = require('debug')('mqttjs:tcp')\n\n/*\n variables port and host can be removed since\n you have all required information in opts object\n*/\nfunction streamBuilder (client, opts) {\n opts.port = opts.port || 1883\n opts.hostname = opts.hostname || opts.host || 'localhost'\n\n const port = opts.port\n const host = opts.hostname\n\n debug('port %d and host %s', port, host)\n return net.createConnection(port, host)\n}\n\nmodule.exports = streamBuilder\n", "export default {};\n", "\nconst polyfill = require('tls')\n\nif (polyfill && polyfill.default) {\n module.exports = polyfill.default\n for (let k in polyfill) {\n module.exports[k] = polyfill[k]\n }\n} else if (polyfill) {\n module.exports = polyfill\n}\n\n\n", "'use strict'\nconst tls = require('tls')\nconst net = require('net')\nconst debug = require('debug')('mqttjs:tls')\n\nfunction buildBuilder (mqttClient, opts) {\n opts.port = opts.port || 8883\n opts.host = opts.hostname || opts.host || 'localhost'\n\n if (net.isIP(opts.host) === 0) {\n opts.servername = opts.host\n }\n\n opts.rejectUnauthorized = opts.rejectUnauthorized !== false\n\n delete opts.path\n\n debug('port %d host %s rejectUnauthorized %b', opts.port, opts.host, opts.rejectUnauthorized)\n\n const connection = tls.connect(opts)\n /* eslint no-use-before-define: [2, \"nofunc\"] */\n connection.on('secureConnect', function () {\n if (opts.rejectUnauthorized && !connection.authorized) {\n connection.emit('error', new Error('TLS not authorized'))\n } else {\n connection.removeListener('error', handleTLSerrors)\n }\n })\n\n function handleTLSerrors (err) {\n // How can I get verify this error is a tls error?\n if (opts.rejectUnauthorized) {\n mqttClient.emit('error', err)\n }\n\n // close this connection to match the behaviour of net\n // otherwise all we get is an error from the connection\n // and close event doesn't fire. This is a work around\n // to enable the reconnect code to work the same as with\n // net.createConnection\n connection.end()\n }\n\n connection.on('error', handleTLSerrors)\n return connection\n}\n\nmodule.exports = buildBuilder\n", "// Returns a wrapper function that returns a wrapped callback\n// The wrapper function should do some stuff, and return a\n// presumably different callback function.\n// This makes sure that own properties are retained, so that\n// decorations and such are not lost along the way.\nmodule.exports = wrappy\nfunction wrappy (fn, cb) {\n if (fn && cb) return wrappy(fn)(cb)\n\n if (typeof fn !== 'function')\n throw new TypeError('need wrapper function')\n\n Object.keys(fn).forEach(function (k) {\n wrapper[k] = fn[k]\n })\n\n return wrapper\n\n function wrapper() {\n var args = new Array(arguments.length)\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i]\n }\n var ret = fn.apply(this, args)\n var cb = args[args.length-1]\n if (typeof ret === 'function' && ret !== cb) {\n Object.keys(cb).forEach(function (k) {\n ret[k] = cb[k]\n })\n }\n return ret\n }\n}\n", "var wrappy = require('wrappy')\nmodule.exports = wrappy(once)\nmodule.exports.strict = wrappy(onceStrict)\n\nonce.proto = once(function () {\n Object.defineProperty(Function.prototype, 'once', {\n value: function () {\n return once(this)\n },\n configurable: true\n })\n\n Object.defineProperty(Function.prototype, 'onceStrict', {\n value: function () {\n return onceStrict(this)\n },\n configurable: true\n })\n})\n\nfunction once (fn) {\n var f = function () {\n if (f.called) return f.value\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n f.called = false\n return f\n}\n\nfunction onceStrict (fn) {\n var f = function () {\n if (f.called)\n throw new Error(f.onceError)\n f.called = true\n return f.value = fn.apply(this, arguments)\n }\n var name = fn.name || 'Function wrapped with `once`'\n f.onceError = name + \" shouldn't be called more than once\"\n f.called = false\n return f\n}\n", "var once = require('once');\n\nvar noop = function() {};\n\nvar isRequest = function(stream) {\n\treturn stream.setHeader && typeof stream.abort === 'function';\n};\n\nvar isChildProcess = function(stream) {\n\treturn stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3\n};\n\nvar eos = function(stream, opts, callback) {\n\tif (typeof opts === 'function') return eos(stream, null, opts);\n\tif (!opts) opts = {};\n\n\tcallback = once(callback || noop);\n\n\tvar ws = stream._writableState;\n\tvar rs = stream._readableState;\n\tvar readable = opts.readable || (opts.readable !== false && stream.readable);\n\tvar writable = opts.writable || (opts.writable !== false && stream.writable);\n\tvar cancelled = false;\n\n\tvar onlegacyfinish = function() {\n\t\tif (!stream.writable) onfinish();\n\t};\n\n\tvar onfinish = function() {\n\t\twritable = false;\n\t\tif (!readable) callback.call(stream);\n\t};\n\n\tvar onend = function() {\n\t\treadable = false;\n\t\tif (!writable) callback.call(stream);\n\t};\n\n\tvar onexit = function(exitCode) {\n\t\tcallback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);\n\t};\n\n\tvar onerror = function(err) {\n\t\tcallback.call(stream, err);\n\t};\n\n\tvar onclose = function() {\n\t\tprocess.nextTick(onclosenexttick);\n\t};\n\n\tvar onclosenexttick = function() {\n\t\tif (cancelled) return;\n\t\tif (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));\n\t\tif (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));\n\t};\n\n\tvar onrequest = function() {\n\t\tstream.req.on('finish', onfinish);\n\t};\n\n\tif (isRequest(stream)) {\n\t\tstream.on('complete', onfinish);\n\t\tstream.on('abort', onclose);\n\t\tif (stream.req) onrequest();\n\t\telse stream.on('request', onrequest);\n\t} else if (writable && !ws) { // legacy streams\n\t\tstream.on('end', onlegacyfinish);\n\t\tstream.on('close', onlegacyfinish);\n\t}\n\n\tif (isChildProcess(stream)) stream.on('exit', onexit);\n\n\tstream.on('end', onend);\n\tstream.on('finish', onfinish);\n\tif (opts.error !== false) stream.on('error', onerror);\n\tstream.on('close', onclose);\n\n\treturn function() {\n\t\tcancelled = true;\n\t\tstream.removeListener('complete', onfinish);\n\t\tstream.removeListener('abort', onclose);\n\t\tstream.removeListener('request', onrequest);\n\t\tif (stream.req) stream.req.removeListener('finish', onfinish);\n\t\tstream.removeListener('end', onlegacyfinish);\n\t\tstream.removeListener('close', onlegacyfinish);\n\t\tstream.removeListener('finish', onfinish);\n\t\tstream.removeListener('exit', onexit);\n\t\tstream.removeListener('end', onend);\n\t\tstream.removeListener('error', onerror);\n\t\tstream.removeListener('close', onclose);\n\t};\n};\n\nmodule.exports = eos;\n", "module.exports = shift\n\nfunction shift (stream) {\n var rs = stream._readableState\n if (!rs) return null\n return (rs.objectMode || typeof stream._duplexState === 'number') ? stream.read() : stream.read(getStateLength(rs))\n}\n\nfunction getStateLength (state) {\n if (state.buffer.length) {\n // Since node 6.3.0 state.buffer is a BufferList not an array\n if (state.buffer.head) {\n return state.buffer.head.data.length\n }\n\n return state.buffer[0].length\n }\n\n return state.length\n}\n", "var stream = require('readable-stream')\nvar eos = require('end-of-stream')\nvar inherits = require('inherits')\nvar shift = require('stream-shift')\n\nvar SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from)\n ? Buffer.from([0])\n : new Buffer([0])\n\nvar onuncork = function(self, fn) {\n if (self._corked) self.once('uncork', fn)\n else fn()\n}\n\nvar autoDestroy = function (self, err) {\n if (self._autoDestroy) self.destroy(err)\n}\n\nvar destroyer = function(self, end) {\n return function(err) {\n if (err) autoDestroy(self, err.message === 'premature close' ? null : err)\n else if (end && !self._ended) self.end()\n }\n}\n\nvar end = function(ws, fn) {\n if (!ws) return fn()\n if (ws._writableState && ws._writableState.finished) return fn()\n if (ws._writableState) return ws.end(fn)\n ws.end()\n fn()\n}\n\nvar noop = function() {}\n\nvar toStreams2 = function(rs) {\n return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)\n}\n\nvar Duplexify = function(writable, readable, opts) {\n if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)\n stream.Duplex.call(this, opts)\n\n this._writable = null\n this._readable = null\n this._readable2 = null\n\n this._autoDestroy = !opts || opts.autoDestroy !== false\n this._forwardDestroy = !opts || opts.destroy !== false\n this._forwardEnd = !opts || opts.end !== false\n this._corked = 1 // start corked\n this._ondrain = null\n this._drained = false\n this._forwarding = false\n this._unwrite = null\n this._unread = null\n this._ended = false\n\n this.destroyed = false\n\n if (writable) this.setWritable(writable)\n if (readable) this.setReadable(readable)\n}\n\ninherits(Duplexify, stream.Duplex)\n\nDuplexify.obj = function(writable, readable, opts) {\n if (!opts) opts = {}\n opts.objectMode = true\n opts.highWaterMark = 16\n return new Duplexify(writable, readable, opts)\n}\n\nDuplexify.prototype.cork = function() {\n if (++this._corked === 1) this.emit('cork')\n}\n\nDuplexify.prototype.uncork = function() {\n if (this._corked && --this._corked === 0) this.emit('uncork')\n}\n\nDuplexify.prototype.setWritable = function(writable) {\n if (this._unwrite) this._unwrite()\n\n if (this.destroyed) {\n if (writable && writable.destroy) writable.destroy()\n return\n }\n\n if (writable === null || writable === false) {\n this.end()\n return\n }\n\n var self = this\n var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))\n\n var ondrain = function() {\n var ondrain = self._ondrain\n self._ondrain = null\n if (ondrain) ondrain()\n }\n\n var clear = function() {\n self._writable.removeListener('drain', ondrain)\n unend()\n }\n\n if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks\n\n this._writable = writable\n this._writable.on('drain', ondrain)\n this._unwrite = clear\n\n this.uncork() // always uncork setWritable\n}\n\nDuplexify.prototype.setReadable = function(readable) {\n if (this._unread) this._unread()\n\n if (this.destroyed) {\n if (readable && readable.destroy) readable.destroy()\n return\n }\n\n if (readable === null || readable === false) {\n this.push(null)\n this.resume()\n return\n }\n\n var self = this\n var unend = eos(readable, {writable:false, readable:true}, destroyer(this))\n\n var onreadable = function() {\n self._forward()\n }\n\n var onend = function() {\n self.push(null)\n }\n\n var clear = function() {\n self._readable2.removeListener('readable', onreadable)\n self._readable2.removeListener('end', onend)\n unend()\n }\n\n this._drained = true\n this._readable = readable\n this._readable2 = readable._readableState ? readable : toStreams2(readable)\n this._readable2.on('readable', onreadable)\n this._readable2.on('end', onend)\n this._unread = clear\n\n this._forward()\n}\n\nDuplexify.prototype._read = function() {\n this._drained = true\n this._forward()\n}\n\nDuplexify.prototype._forward = function() {\n if (this._forwarding || !this._readable2 || !this._drained) return\n this._forwarding = true\n\n var data\n\n while (this._drained && (data = shift(this._readable2)) !== null) {\n if (this.destroyed) continue\n this._drained = this.push(data)\n }\n\n this._forwarding = false\n}\n\nDuplexify.prototype.destroy = function(err, cb) {\n if (!cb) cb = noop\n if (this.destroyed) return cb(null)\n this.destroyed = true\n\n var self = this\n process.nextTick(function() {\n self._destroy(err)\n cb(null)\n })\n}\n\nDuplexify.prototype._destroy = function(err) {\n if (err) {\n var ondrain = this._ondrain\n this._ondrain = null\n if (ondrain) ondrain(err)\n else this.emit('error', err)\n }\n\n if (this._forwardDestroy) {\n if (this._readable && this._readable.destroy) this._readable.destroy()\n if (this._writable && this._writable.destroy) this._writable.destroy()\n }\n\n this.emit('close')\n}\n\nDuplexify.prototype._write = function(data, enc, cb) {\n if (this.destroyed) return\n if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))\n if (data === SIGNAL_FLUSH) return this._finish(cb)\n if (!this._writable) return cb()\n\n if (this._writable.write(data) === false) this._ondrain = cb\n else if (!this.destroyed) cb()\n}\n\nDuplexify.prototype._finish = function(cb) {\n var self = this\n this.emit('preend')\n onuncork(this, function() {\n end(self._forwardEnd && self._writable, function() {\n // haxx to not emit prefinish twice\n if (self._writableState.prefinished === false) self._writableState.prefinished = true\n self.emit('prefinish')\n onuncork(self, cb)\n })\n })\n}\n\nDuplexify.prototype.end = function(data, enc, cb) {\n if (typeof data === 'function') return this.end(null, null, data)\n if (typeof enc === 'function') return this.end(data, null, enc)\n this._ended = true\n if (data) this.write(data)\n if (!this._writableState.ending && !this._writableState.destroyed) this.write(SIGNAL_FLUSH)\n return stream.Writable.prototype.end.call(this, cb)\n}\n\nmodule.exports = Duplexify\n", "'use strict'\n\nconst { Buffer } = require('buffer')\nconst Transform = require('readable-stream').Transform\nconst duplexify = require('duplexify')\n\n/* global wx */\nlet socketTask, proxy, stream\n\nfunction buildProxy () {\n const proxy = new Transform()\n proxy._write = function (chunk, encoding, next) {\n socketTask.send({\n data: chunk.buffer,\n success: function () {\n next()\n },\n fail: function (errMsg) {\n next(new Error(errMsg))\n }\n })\n }\n proxy._flush = function socketEnd (done) {\n socketTask.close({\n success: function () {\n done()\n }\n })\n }\n\n return proxy\n}\n\nfunction setDefaultOpts (opts) {\n if (!opts.hostname) {\n opts.hostname = 'localhost'\n }\n if (!opts.path) {\n opts.path = '/'\n }\n\n if (!opts.wsOptions) {\n opts.wsOptions = {}\n }\n}\n\nfunction buildUrl (opts, client) {\n const protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'\n let url = protocol + '://' + opts.hostname + opts.path\n if (opts.port && opts.port !== 80 && opts.port !== 443) {\n url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path\n }\n if (typeof (opts.transformWsUrl) === 'function') {\n url = opts.transformWsUrl(url, opts, client)\n }\n return url\n}\n\nfunction bindEventHandler () {\n socketTask.onOpen(function () {\n stream.setReadable(proxy)\n stream.setWritable(proxy)\n stream.emit('connect')\n })\n\n socketTask.onMessage(function (res) {\n let data = res.data\n\n if (data instanceof ArrayBuffer) data = Buffer.from(data)\n else data = Buffer.from(data, 'utf8')\n proxy.push(data)\n })\n\n socketTask.onClose(function () {\n stream.end()\n stream.destroy()\n })\n\n socketTask.onError(function (res) {\n stream.destroy(new Error(res.errMsg))\n })\n}\n\nfunction buildStream (client, opts) {\n opts.hostname = opts.hostname || opts.host\n\n if (!opts.hostname) {\n throw new Error('Could not determine host. Specify host manually.')\n }\n\n const websocketSubProtocol =\n (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)\n ? 'mqttv3.1'\n : 'mqtt'\n\n setDefaultOpts(opts)\n\n const url = buildUrl(opts, client)\n socketTask = wx.connectSocket({\n url: url,\n protocols: [websocketSubProtocol]\n })\n\n proxy = buildProxy()\n stream = duplexify.obj()\n stream._destroy = function (err, cb) {\n socketTask.close({\n success: function () {\n cb && cb(err)\n }\n })\n }\n\n const destroyRef = stream.destroy\n stream.destroy = function () {\n stream.destroy = destroyRef\n\n const self = this\n setTimeout(function () {\n socketTask.close({\n fail: function () {\n self._destroy(new Error())\n }\n })\n }, 0)\n }.bind(stream)\n\n bindEventHandler()\n\n return stream\n}\n\nmodule.exports = buildStream\n", "'use strict'\n\nconst { Buffer } = require('buffer')\nconst Transform = require('readable-stream').Transform\nconst duplexify = require('duplexify')\n\n/* global FileReader */\nlet my\nlet proxy\nlet stream\nlet isInitialized = false\n\nfunction buildProxy () {\n const proxy = new Transform()\n proxy._write = function (chunk, encoding, next) {\n my.sendSocketMessage({\n data: chunk.buffer,\n success: function () {\n next()\n },\n fail: function () {\n next(new Error())\n }\n })\n }\n proxy._flush = function socketEnd (done) {\n my.closeSocket({\n success: function () {\n done()\n }\n })\n }\n\n return proxy\n}\n\nfunction setDefaultOpts (opts) {\n if (!opts.hostname) {\n opts.hostname = 'localhost'\n }\n if (!opts.path) {\n opts.path = '/'\n }\n\n if (!opts.wsOptions) {\n opts.wsOptions = {}\n }\n}\n\nfunction buildUrl (opts, client) {\n const protocol = opts.protocol === 'alis' ? 'wss' : 'ws'\n let url = protocol + '://' + opts.hostname + opts.path\n if (opts.port && opts.port !== 80 && opts.port !== 443) {\n url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path\n }\n if (typeof (opts.transformWsUrl) === 'function') {\n url = opts.transformWsUrl(url, opts, client)\n }\n return url\n}\n\nfunction bindEventHandler () {\n if (isInitialized) return\n\n isInitialized = true\n\n my.onSocketOpen(function () {\n stream.setReadable(proxy)\n stream.setWritable(proxy)\n stream.emit('connect')\n })\n\n my.onSocketMessage(function (res) {\n if (typeof res.data === 'string') {\n const buffer = Buffer.from(res.data, 'base64')\n proxy.push(buffer)\n } else {\n const reader = new FileReader()\n reader.addEventListener('load', function () {\n let data = reader.result\n\n if (data instanceof ArrayBuffer) data = Buffer.from(data)\n else data = Buffer.from(data, 'utf8')\n proxy.push(data)\n })\n reader.readAsArrayBuffer(res.data)\n }\n })\n\n my.onSocketClose(function () {\n stream.end()\n stream.destroy()\n })\n\n my.onSocketError(function (res) {\n stream.destroy(res)\n })\n}\n\nfunction buildStream (client, opts) {\n opts.hostname = opts.hostname || opts.host\n\n if (!opts.hostname) {\n throw new Error('Could not determine host. Specify host manually.')\n }\n\n const websocketSubProtocol =\n (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)\n ? 'mqttv3.1'\n : 'mqtt'\n\n setDefaultOpts(opts)\n\n const url = buildUrl(opts, client)\n my = opts.my\n my.connectSocket({\n url: url,\n protocols: websocketSubProtocol\n })\n\n proxy = buildProxy()\n stream = duplexify.obj()\n\n bindEventHandler()\n\n return stream\n}\n\nmodule.exports = buildStream\n", "'use strict';\n\nmodule.exports = function () {\n throw new Error(\n 'ws does not work in the browser. Browser clients must use the native ' +\n 'WebSocket object'\n );\n};\n", "'use strict'\n\nconst { Buffer } = require('buffer')\nconst WS = require('ws')\nconst debug = require('debug')('mqttjs:ws')\nconst duplexify = require('duplexify')\nconst Transform = require('readable-stream').Transform\n\nconst WSS_OPTIONS = [\n 'rejectUnauthorized',\n 'ca',\n 'cert',\n 'key',\n 'pfx',\n 'passphrase'\n]\n// eslint-disable-next-line camelcase\nconst IS_BROWSER = (typeof process !== 'undefined' && process.title === 'browser') || typeof __webpack_require__ === 'function'\nfunction buildUrl (opts, client) {\n let url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path\n if (typeof (opts.transformWsUrl) === 'function') {\n url = opts.transformWsUrl(url, opts, client)\n }\n return url\n}\n\nfunction setDefaultOpts (opts) {\n const options = opts\n if (!opts.hostname) {\n options.hostname = 'localhost'\n }\n if (!opts.port) {\n if (opts.protocol === 'wss') {\n options.port = 443\n } else {\n options.port = 80\n }\n }\n if (!opts.path) {\n options.path = '/'\n }\n\n if (!opts.wsOptions) {\n options.wsOptions = {}\n }\n if (!IS_BROWSER && opts.protocol === 'wss') {\n // Add cert/key/ca etc options\n WSS_OPTIONS.forEach(function (prop) {\n if (Object.prototype.hasOwnProperty.call(opts, prop) && !Object.prototype.hasOwnProperty.call(opts.wsOptions, prop)) {\n options.wsOptions[prop] = opts[prop]\n }\n })\n }\n\n return options\n}\n\nfunction setDefaultBrowserOpts (opts) {\n const options = setDefaultOpts(opts)\n\n if (!options.hostname) {\n options.hostname = options.host\n }\n\n if (!options.hostname) {\n // Throwing an error in a Web Worker if no `hostname` is given, because we\n // can not determine the `hostname` automatically. If connecting to\n // localhost, please supply the `hostname` as an argument.\n if (typeof (document) === 'undefined') {\n throw new Error('Could not determine host. Specify host manually.')\n }\n const parsed = new URL(document.URL)\n options.hostname = parsed.hostname\n\n if (!options.port) {\n options.port = parsed.port\n }\n }\n\n // objectMode should be defined for logic\n if (options.objectMode === undefined) {\n options.objectMode = !(options.binary === true || options.binary === undefined)\n }\n\n return options\n}\n\nfunction createWebSocket (client, url, opts) {\n debug('createWebSocket')\n debug('protocol: ' + opts.protocolId + ' ' + opts.protocolVersion)\n const websocketSubProtocol =\n (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)\n ? 'mqttv3.1'\n : 'mqtt'\n\n debug('creating new Websocket for url: ' + url + ' and protocol: ' + websocketSubProtocol)\n const socket = new WS(url, [websocketSubProtocol], opts.wsOptions)\n return socket\n}\n\nfunction createBrowserWebSocket (client, opts) {\n const websocketSubProtocol =\n (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)\n ? 'mqttv3.1'\n : 'mqtt'\n\n const url = buildUrl(opts, client)\n /* global WebSocket */\n const socket = new WebSocket(url, [websocketSubProtocol])\n socket.binaryType = 'arraybuffer'\n return socket\n}\n\nfunction streamBuilder (client, opts) {\n debug('streamBuilder')\n const options = setDefaultOpts(opts)\n const url = buildUrl(options, client)\n const socket = createWebSocket(client, url, options)\n const webSocketStream = WS.createWebSocketStream(socket, options.wsOptions)\n webSocketStream.url = url\n socket.on('close', () => { webSocketStream.destroy() })\n return webSocketStream\n}\n\nfunction browserStreamBuilder (client, opts) {\n debug('browserStreamBuilder')\n let stream\n const options = setDefaultBrowserOpts(opts)\n // sets the maximum socket buffer size before throttling\n const bufferSize = options.browserBufferSize || 1024 * 512\n\n const bufferTimeout = opts.browserBufferTimeout || 1000\n\n const coerceToBuffer = !opts.objectMode\n\n const socket = createBrowserWebSocket(client, opts)\n\n const proxy = buildProxy(opts, socketWriteBrowser, socketEndBrowser)\n\n if (!opts.objectMode) {\n proxy._writev = writev\n }\n proxy.on('close', () => { socket.close() })\n\n const eventListenerSupport = (typeof socket.addEventListener !== 'undefined')\n\n // was already open when passed in\n if (socket.readyState === socket.OPEN) {\n stream = proxy\n } else {\n stream = stream = duplexify(undefined, undefined, opts)\n if (!opts.objectMode) {\n stream._writev = writev\n }\n\n if (eventListenerSupport) {\n socket.addEventListener('open', onopen)\n } else {\n socket.onopen = onopen\n }\n }\n\n stream.socket = socket\n\n if (eventListenerSupport) {\n socket.addEventListener('close', onclose)\n socket.addEventListener('error', onerror)\n socket.addEventListener('message', onmessage)\n } else {\n socket.onclose = onclose\n socket.onerror = onerror\n socket.onmessage = onmessage\n }\n\n // methods for browserStreamBuilder\n\n function buildProxy (options, socketWrite, socketEnd) {\n const proxy = new Transform({\n objectModeMode: options.objectMode\n })\n\n proxy._write = socketWrite\n proxy._flush = socketEnd\n\n return proxy\n }\n\n function onopen () {\n stream.setReadable(proxy)\n stream.setWritable(proxy)\n stream.emit('connect')\n }\n\n function onclose () {\n stream.end()\n stream.destroy()\n }\n\n function onerror (err) {\n stream.destroy(err)\n }\n\n function onmessage (event) {\n let data = event.data\n if (data instanceof ArrayBuffer) data = Buffer.from(data)\n else data = Buffer.from(data, 'utf8')\n proxy.push(data)\n }\n\n // this is to be enabled only if objectMode is false\n function writev (chunks, cb) {\n const buffers = new Array(chunks.length)\n for (let i = 0; i < chunks.length; i++) {\n if (typeof chunks[i].chunk === 'string') {\n buffers[i] = Buffer.from(chunks[i], 'utf8')\n } else {\n buffers[i] = chunks[i].chunk\n }\n }\n\n this._write(Buffer.concat(buffers), 'binary', cb)\n }\n\n function socketWriteBrowser (chunk, enc, next) {\n if (socket.bufferedAmount > bufferSize) {\n // throttle data until buffered amount is reduced.\n setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)\n }\n\n if (coerceToBuffer && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, 'utf8')\n }\n\n try {\n socket.send(chunk)\n } catch (err) {\n return next(err)\n }\n\n next()\n }\n\n function socketEndBrowser (done) {\n socket.close()\n done()\n }\n\n // end methods for browserStreamBuilder\n\n return stream\n}\n\nif (IS_BROWSER) {\n module.exports = browserStreamBuilder\n} else {\n module.exports = streamBuilder\n}\n", "'use strict'\n\nconst MqttClient = require('../client')\nconst Store = require('../store')\nconst url = require('url')\nconst xtend = require('xtend')\nconst debug = require('debug')('mqttjs')\n\nconst protocols = {}\n\n// eslint-disable-next-line camelcase\nif ((typeof process !== 'undefined' && process.title !== 'browser') || typeof __webpack_require__ !== 'function') {\n protocols.mqtt = require('./tcp')\n protocols.tcp = require('./tcp')\n protocols.ssl = require('./tls')\n protocols.tls = require('./tls')\n protocols.mqtts = require('./tls')\n} else {\n protocols.wx = require('./wx')\n protocols.wxs = require('./wx')\n\n protocols.ali = require('./ali')\n protocols.alis = require('./ali')\n}\n\nprotocols.ws = require('./ws')\nprotocols.wss = require('./ws')\n\n/**\n * Parse the auth attribute and merge username and password in the options object.\n *\n * @param {Object} [opts] option object\n */\nfunction parseAuthOptions (opts) {\n let matches\n if (opts.auth) {\n matches = opts.auth.match(/^(.+):(.+)$/)\n if (matches) {\n opts.username = matches[1]\n opts.password = matches[2]\n } else {\n opts.username = opts.auth\n }\n }\n}\n\n/**\n * connect - connect to an MQTT broker.\n *\n * @param {String} [brokerUrl] - url of the broker, optional\n * @param {Object} opts - see MqttClient#constructor\n */\nfunction connect (brokerUrl, opts) {\n debug('connecting to an MQTT broker...')\n if ((typeof brokerUrl === 'object') && !opts) {\n opts = brokerUrl\n brokerUrl = null\n }\n\n opts = opts || {}\n\n if (brokerUrl) {\n // eslint-disable-next-line\n const parsed = url.parse(brokerUrl, true)\n if (parsed.port != null) {\n parsed.port = Number(parsed.port)\n }\n\n opts = xtend(parsed, opts)\n\n if (opts.protocol === null) {\n throw new Error('Missing protocol')\n }\n\n opts.protocol = opts.protocol.replace(/:$/, '')\n }\n\n // merge in the auth options if supplied\n parseAuthOptions(opts)\n\n // support clientId passed in the query string of the url\n if (opts.query && typeof opts.query.clientId === 'string') {\n opts.clientId = opts.query.clientId\n }\n\n if (opts.cert && opts.key) {\n if (opts.protocol) {\n if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {\n switch (opts.protocol) {\n case 'mqtt':\n opts.protocol = 'mqtts'\n break\n case 'ws':\n opts.protocol = 'wss'\n break\n case 'wx':\n opts.protocol = 'wxs'\n break\n case 'ali':\n opts.protocol = 'alis'\n break\n default:\n throw new Error('Unknown protocol for secure connection: \"' + opts.protocol + '\"!')\n }\n }\n } else {\n // A cert and key was provided, however no protocol was specified, so we will throw an error.\n throw new Error('Missing secure protocol key')\n }\n }\n\n if (!protocols[opts.protocol]) {\n const isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1\n opts.protocol = [\n 'mqtt',\n 'mqtts',\n 'ws',\n 'wss',\n 'wx',\n 'wxs',\n 'ali',\n 'alis'\n ].filter(function (key, index) {\n if (isSecure && index % 2 === 0) {\n // Skip insecure protocols when requesting a secure one.\n return false\n }\n return (typeof protocols[key] === 'function')\n })[0]\n }\n\n if (opts.clean === false && !opts.clientId) {\n throw new Error('Missing clientId for unclean clients')\n }\n\n if (opts.protocol) {\n opts.defaultProtocol = opts.protocol\n }\n\n function wrapper (client) {\n if (opts.servers) {\n if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {\n client._reconnectCount = 0\n }\n\n opts.host = opts.servers[client._reconnectCount].host\n opts.port = opts.servers[client._reconnectCount].port\n opts.protocol = (!opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol)\n opts.hostname = opts.host\n\n client._reconnectCount++\n }\n\n debug('calling streambuilder for', opts.protocol)\n return protocols[opts.protocol](client, opts)\n }\n const client = new MqttClient(wrapper, opts)\n client.on('error', function () { /* Automatically set up client error handling */ })\n return client\n}\n\nmodule.exports = connect\nmodule.exports.connect = connect\nmodule.exports.MqttClient = MqttClient\nmodule.exports.Store = Store\n", "// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation. Also,\n // find the complete implementation of crypto (msCrypto) on IE11.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}", "export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;", "import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;", "import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nvar byteToHex = [];\n\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr) {\n var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;", "import rng from './rng.js';\nimport stringify from './stringify.js'; // **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nvar _nodeId;\n\nvar _clockseq; // Previous uuid creation time\n\n\nvar _lastMSecs = 0;\nvar _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details\n\nfunction v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || new Array(16);\n options = options || {};\n var node = options.node || _nodeId;\n var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n\n if (node == null || clockseq == null) {\n var seedBytes = options.random || (options.rng || rng)();\n\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n }\n\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n } // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\n\n var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n\n var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)\n\n var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression\n\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n\n\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n } // Per 4.2.1.2 Throw error if too many uuids are requested\n\n\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\n msecs += 12219292800000; // `time_low`\n\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff; // `time_mid`\n\n var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff; // `time_high_and_version`\n\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\n b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\n b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`\n\n b[i++] = clockseq & 0xff; // `node`\n\n for (var n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf || stringify(b);\n}\n\nexport default v1;", "import validate from './validate.js';\n\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n var v;\n var arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nexport default parse;", "import stringify from './stringify.js';\nimport parse from './parse.js';\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n var bytes = [];\n\n for (var i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nexport var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexport var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexport default function (name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = parse(namespace);\n }\n\n if (namespace.length !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n var bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return stringify(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}", "/*\n * Browser-compatible JavaScript MD5\n *\n * Modification of JavaScript MD5\n * https://github.com/blueimp/JavaScript-MD5\n *\n * Copyright 2011, Sebastian Tschan\n * https://blueimp.net\n *\n * Licensed under the MIT license:\n * https://opensource.org/licenses/MIT\n *\n * Based on\n * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message\n * Digest Algorithm, as defined in RFC 1321.\n * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n * Distributed under the BSD License\n * See http://pajhome.org.uk/crypt/md5 for more info.\n */\nfunction md5(bytes) {\n if (typeof bytes === 'string') {\n var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = new Uint8Array(msg.length);\n\n for (var i = 0; i < msg.length; ++i) {\n bytes[i] = msg.charCodeAt(i);\n }\n }\n\n return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));\n}\n/*\n * Convert an array of little-endian words to an array of bytes\n */\n\n\nfunction md5ToHexEncodedArray(input) {\n var output = [];\n var length32 = input.length * 32;\n var hexTab = '0123456789abcdef';\n\n for (var i = 0; i < length32; i += 8) {\n var x = input[i >> 5] >>> i % 32 & 0xff;\n var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);\n output.push(hex);\n }\n\n return output;\n}\n/**\n * Calculate output length with padding and bit length\n */\n\n\nfunction getOutputLength(inputLength8) {\n return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;\n}\n/*\n * Calculate the MD5 of an array of little-endian words, and a bit length.\n */\n\n\nfunction wordsToMd5(x, len) {\n /* append padding */\n x[len >> 5] |= 0x80 << len % 32;\n x[getOutputLength(len) - 1] = len;\n var a = 1732584193;\n var b = -271733879;\n var c = -1732584194;\n var d = 271733878;\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a;\n var oldb = b;\n var oldc = c;\n var oldd = d;\n a = md5ff(a, b, c, d, x[i], 7, -680876936);\n d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);\n c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);\n b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);\n a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);\n d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);\n c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);\n b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);\n a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);\n d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);\n c = md5ff(c, d, a, b, x[i + 10], 17, -42063);\n b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);\n a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);\n d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);\n c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);\n b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);\n a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);\n d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);\n c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);\n b = md5gg(b, c, d, a, x[i], 20, -373897302);\n a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);\n d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);\n c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);\n b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);\n a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);\n d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);\n c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);\n b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);\n a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);\n d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);\n c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);\n b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);\n a = md5hh(a, b, c, d, x[i + 5], 4, -378558);\n d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);\n c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);\n b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);\n a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);\n d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);\n c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);\n b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);\n a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);\n d = md5hh(d, a, b, c, x[i], 11, -358537222);\n c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);\n b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);\n a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);\n d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);\n c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);\n b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);\n a = md5ii(a, b, c, d, x[i], 6, -198630844);\n d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);\n c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);\n b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);\n a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);\n d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);\n c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);\n b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);\n a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);\n d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);\n c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);\n b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);\n a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);\n d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);\n c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);\n b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);\n a = safeAdd(a, olda);\n b = safeAdd(b, oldb);\n c = safeAdd(c, oldc);\n d = safeAdd(d, oldd);\n }\n\n return [a, b, c, d];\n}\n/*\n * Convert an array bytes to an array of little-endian words\n * Characters >255 have their high-byte silently ignored.\n */\n\n\nfunction bytesToWords(input) {\n if (input.length === 0) {\n return [];\n }\n\n var length8 = input.length * 8;\n var output = new Uint32Array(getOutputLength(length8));\n\n for (var i = 0; i < length8; i += 8) {\n output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;\n }\n\n return output;\n}\n/*\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\n\n\nfunction safeAdd(x, y) {\n var lsw = (x & 0xffff) + (y & 0xffff);\n var msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return msw << 16 | lsw & 0xffff;\n}\n/*\n * Bitwise rotate a 32-bit number to the left.\n */\n\n\nfunction bitRotateLeft(num, cnt) {\n return num << cnt | num >>> 32 - cnt;\n}\n/*\n * These functions implement the four basic operations the algorithm uses.\n */\n\n\nfunction md5cmn(q, a, b, x, s, t) {\n return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);\n}\n\nfunction md5ff(a, b, c, d, x, s, t) {\n return md5cmn(b & c | ~b & d, a, b, x, s, t);\n}\n\nfunction md5gg(a, b, c, d, x, s, t) {\n return md5cmn(b & d | c & ~d, a, b, x, s, t);\n}\n\nfunction md5hh(a, b, c, d, x, s, t) {\n return md5cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction md5ii(a, b, c, d, x, s, t) {\n return md5cmn(c ^ (b | ~d), a, b, x, s, t);\n}\n\nexport default md5;", "import v35 from './v35.js';\nimport md5 from './md5.js';\nvar v3 = v35('v3', 0x30, md5);\nexport default v3;", "import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;", "// Adapted from Chris Veness' SHA1 code at\n// http://www.movable-type.co.uk/scripts/sha1.html\nfunction f(s, x, y, z) {\n switch (s) {\n case 0:\n return x & y ^ ~x & z;\n\n case 1:\n return x ^ y ^ z;\n\n case 2:\n return x & y ^ x & z ^ y & z;\n\n case 3:\n return x ^ y ^ z;\n }\n}\n\nfunction ROTL(x, n) {\n return x << n | x >>> 32 - n;\n}\n\nfunction sha1(bytes) {\n var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];\n var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n\n if (typeof bytes === 'string') {\n var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = [];\n\n for (var i = 0; i < msg.length; ++i) {\n bytes.push(msg.charCodeAt(i));\n }\n } else if (!Array.isArray(bytes)) {\n // Convert Array-like to Array\n bytes = Array.prototype.slice.call(bytes);\n }\n\n bytes.push(0x80);\n var l = bytes.length / 4 + 2;\n var N = Math.ceil(l / 16);\n var M = new Array(N);\n\n for (var _i = 0; _i < N; ++_i) {\n var arr = new Uint32Array(16);\n\n for (var j = 0; j < 16; ++j) {\n arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];\n }\n\n M[_i] = arr;\n }\n\n M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);\n M[N - 1][14] = Math.floor(M[N - 1][14]);\n M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;\n\n for (var _i2 = 0; _i2 < N; ++_i2) {\n var W = new Uint32Array(80);\n\n for (var t = 0; t < 16; ++t) {\n W[t] = M[_i2][t];\n }\n\n for (var _t = 16; _t < 80; ++_t) {\n W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);\n }\n\n var a = H[0];\n var b = H[1];\n var c = H[2];\n var d = H[3];\n var e = H[4];\n\n for (var _t2 = 0; _t2 < 80; ++_t2) {\n var s = Math.floor(_t2 / 20);\n var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;\n e = d;\n d = c;\n c = ROTL(b, 30) >>> 0;\n b = a;\n a = T;\n }\n\n H[0] = H[0] + a >>> 0;\n H[1] = H[1] + b >>> 0;\n H[2] = H[2] + c >>> 0;\n H[3] = H[3] + d >>> 0;\n H[4] = H[4] + e >>> 0;\n }\n\n return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];\n}\n\nexport default sha1;", "import v35 from './v35.js';\nimport sha1 from './sha1.js';\nvar v5 = v35('v5', 0x50, sha1);\nexport default v5;", "export default '00000000-0000-0000-0000-000000000000';", "import validate from './validate.js';\n\nfunction version(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n return parseInt(uuid.substr(14, 1), 16);\n}\n\nexport default version;", "export { default as v1 } from './v1.js';\nexport { default as v3 } from './v3.js';\nexport { default as v4 } from './v4.js';\nexport { default as v5 } from './v5.js';\nexport { default as NIL } from './nil.js';\nexport { default as version } from './version.js';\nexport { default as validate } from './validate.js';\nexport { default as stringify } from './stringify.js';\nexport { default as parse } from './parse.js';", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Application = exports.ApplicationTopic = void 0;\n/*\n app.ts\n wrapper around runtime control functions (via mqtt) and http api.\n access the mqtt client directly via Application.mqttClient.\n handlers for ApplicationTopics can be registered via:\n Application.register_handler(hdlr: msg_handler);\n*/\nconst api_1 = require(\"./api\");\nconst structs_1 = require(\"./structs\");\nconst utils_1 = require(\"./utils\");\nconst mqtt_1 = __importDefault(require(\"mqtt\"));\nconst uuid_1 = require(\"uuid\");\nvar ApplicationTopic;\n(function (ApplicationTopic) {\n ApplicationTopic[\"Root\"] = \"palletizer/\";\n ApplicationTopic[\"Version\"] = \"palletizer/version\";\n ApplicationTopic[\"Machines\"] = \"palletizer/machines\";\n ApplicationTopic[\"MachineSafety\"] = \"palletizer/safety/#\"; /* (component/machine)_name */\n ApplicationTopic[\"Control\"] = \"palletizer/control\";\n ApplicationTopic[\"State\"] = \"palletizer/state\";\n ApplicationTopic[\"Information\"] = \"palletizer/information\";\n ApplicationTopic[\"AppendInformation\"] = \"palletizer/information/append\";\n ApplicationTopic[\"StateRequest\"] = \"palletizer/request\";\n ApplicationTopic[\"Robot\"] = \"palletizer/robot_state\";\n ApplicationTopic[\"Alert\"] = \"palletizer/alert\";\n ApplicationTopic[\"AccessRequest\"] = \"accessrequest\";\n ApplicationTopic[\"Queue\"] = \"palletizer/run/queue\";\n ApplicationTopic[\"OperationalState\"] = \"palletizer/operationalState\";\n ApplicationTopic[\"SystemState\"] = \"palletizer/systemState\";\n ApplicationTopic[\"Estop\"] = \"palletizer/estop\";\n ApplicationTopic[\"PalletizerMode\"] = \"palletizer/manualModeOn\";\n ApplicationTopic[\"PalletizerIOs\"] = \"palletizer/ios\";\n ApplicationTopic[\"PendingSKUScan\"] = \"palletizer/pendingSKUScan\";\n ApplicationTopic[\"InvalidSKUScan\"] = \"palletizer/invalidSKUScan\";\n ApplicationTopic[\"BoxErectorPower\"] = \"boxerector/robot_power/state\";\n ApplicationTopic[\"BoxErectorControl\"] = \"boxerector/control\";\n ApplicationTopic[\"BoxErectorSystemState\"] = \"boxerector/systemState\";\n ApplicationTopic[\"BoxErectorOperationalState\"] = \"boxerector/operationalState\";\n ApplicationTopic[\"BoxErectorPowerRequest\"] = \"boxerector/robot_power/request\";\n ApplicationTopic[\"ConveyorManualStart\"] = \"conveyor/manualStart\";\n ApplicationTopic[\"PalletConfigUpdated\"] = \"palletizer/pallet_config_updated\";\n ApplicationTopic[\"SelectGripper\"] = \"palletizer/selectGripper\";\n ApplicationTopic[\"GripperSelected\"] = \"palletizer/gripperSelected\";\n ApplicationTopic[\"RestartCore\"] = \"restartCore\";\n ApplicationTopic[\"RestartEngine\"] = \"restartEngine\";\n})(ApplicationTopic = exports.ApplicationTopic || (exports.ApplicationTopic = {}));\nclass Application {\n constructor(ip, mqtt_port, api_port = 8001, use_websockets = false, on_mqtt_connect) {\n this.message_handlers = {};\n this.message_handler_id = 0;\n this.version = '';\n this.last_log_time = new Date();\n this.init_time = new Date();\n const broker_uri = (use_websockets ? 'ws://' : 'tcp://') + ip + ':' + String(mqtt_port);\n this.api = new api_1.API(ip, api_port);\n const options = { clientId: 'libapi-' + (0, uuid_1.v4)() };\n this.state = {\n operational_state: (0, structs_1.default_op_state)(),\n };\n this.information = [];\n this.systemState = { Title: 'System Status', Items: {} };\n this.boxErectorSystemState = { Title: 'None', Items: {} };\n this.genericState = { Title: 'None', Items: {} };\n if (this.api.isWebDeployment()) {\n this.mqttClient = {\n subscribe: function (topic) {\n console.log('wanted to subscribe to ' + topic);\n },\n publish: function (topic, msg) {\n console.log('wanted to publish ' + topic, msg.toString());\n },\n };\n }\n else {\n this.mqttClient = mqtt_1.default.connect(broker_uri, options);\n this._initMqttClient(on_mqtt_connect);\n }\n const my = this;\n this.alert = {\n error: function (pText) {\n return my._pushAlert(structs_1.InformationType.Error, pText);\n },\n warn: function (pText) {\n return my._pushAlert(structs_1.InformationType.Warning, pText);\n },\n info: function (pText) {\n return my._pushAlert(structs_1.InformationType.Status, pText);\n },\n };\n }\n _triggerDummyButton(pIndex) {\n const lTopic = ApplicationTopic.Root + `dummy/${pIndex}`;\n this.mqttClient.publish(lTopic, `Trigger ${pIndex}`);\n }\n setEstopState(pEstop) {\n this.mqttClient.publish(ApplicationTopic.Estop, JSON.stringify(pEstop), {\n retain: true,\n });\n }\n _publishFullState() {\n this.mqttClient.publish(ApplicationTopic.State, JSON.stringify(this.state), { retain: true });\n }\n setAuxText(txt) {\n this.state.operational_state.auxiliary_text = txt;\n this._publishFullState();\n }\n setPalletizerMode(pManualModeOn) {\n const lOnOff = pManualModeOn ? 1 : 0;\n this.mqttClient.publish(ApplicationTopic.PalletizerMode, JSON.stringify(lOnOff), {\n retain: true,\n });\n }\n registerMQTTHandler(hdlr) {\n const id = this.message_handler_id++;\n this.message_handlers[id] = hdlr;\n return id;\n }\n deregisterMQTTHandler(id) {\n if (id in this.message_handlers)\n delete this.message_handlers[id];\n }\n setState(st) {\n this.mqttClient.publish(ApplicationTopic.State, JSON.stringify(st), {\n retain: true,\n });\n return;\n }\n setRobotState(st) {\n if (!structs_1.PalletizerStatus[st])\n throw Error('Invalid PalletizerStatus');\n this.state.operational_state.status = st;\n this._publishFullState();\n }\n log(t, ...args) {\n const now = new Date();\n const info = {\n Type: t,\n Description: (0, utils_1.join_args)(...args),\n TimeStamp: (0, structs_1.getInfoTimeStamp)(this.init_time, this.last_log_time, now),\n };\n this.last_log_time = now;\n return this.api.InfoLogs.push(info);\n }\n info(...args) {\n this.log(structs_1.InformationType.Status, ...args);\n }\n warn(...args) {\n this.log(structs_1.InformationType.Warning, ...args);\n }\n error(...args) {\n this.log(structs_1.InformationType.Error, ...args);\n }\n _pubSystemState() {\n throw new Error('deprecated');\n // this.mqttClient.publish(\n // ApplicationTopic.SystemState,\n // JSON.stringify(this.systemState),\n // { retain: true }\n // );\n }\n setSystemState(pItems) {\n this.api.StatusItems.push(pItems);\n // this.systemState.Items = { ...this.systemState.Items, ...pItems };\n // this._pubSystemState();\n }\n setGenericState(pKey, pItems) {\n if (!(pKey in this.genericState))\n this.genericState[pKey] = {};\n this.genericState[pKey] = { ...this.genericState[pKey], ...pItems };\n this._pubGenericState();\n }\n modifyGenericState(pKey, pHandler) {\n if (!(pKey in this.genericState))\n this.genericState[pKey] = {};\n this.genericState[pKey] =\n pHandler(this.genericState[pKey]) || this.genericState[pKey];\n this._pubGenericState();\n }\n clearGenericState() {\n this.genericState = {};\n }\n _pubGenericState() {\n this.mqttClient.publish(ApplicationTopic.OperationalState, JSON.stringify(this.genericState), { retain: true });\n }\n async start_manual_mode() {\n const cm = {\n control_type: structs_1.ControlType.ManualMode,\n params: null,\n };\n return this.api.Commands.send(cm);\n }\n async get_position(tcp = structs_1.CALIB_TCP_INDEX.Box) {\n const cm = {\n control_type: structs_1.ControlType.GetPosition,\n params: { tcp: tcp },\n };\n return this.api.Commands.send(cm).then(d => d.data);\n }\n // begin_calibration() {\n // const cm: ControlMessage = {\n // control_type: ControlType.Calibrate,\n // params: {},\n // };\n // this.mqttClient.publish(ApplicationTopic.Control, JSON.stringify(cm));\n // }\n startScanning(pCreatingBox) {\n const cmsg = {\n control_type: structs_1.ControlType.StartScanning,\n params: { creating: pCreatingBox },\n };\n return this.api.Commands.send(cmsg);\n }\n clearPendingSKUScan(pCurrentPending) {\n const keys = Object.keys(pCurrentPending);\n const lNew = {};\n for (let k = 0; k < keys.length; k++) {\n lNew[keys[k]] = '';\n }\n this.mqttClient.publish(ApplicationTopic.PendingSKUScan, JSON.stringify(lNew));\n }\n clearInvalidSKUScan(pCurrentInvalid) {\n const keys = Object.keys(pCurrentInvalid);\n const lNew = {};\n for (let k = 0; k < keys.length; k++) {\n lNew[keys[k]] = '';\n }\n this.mqttClient.publish(ApplicationTopic.InvalidSKUScan, JSON.stringify(lNew));\n }\n clearBPM() {\n this.mqttClient.publish(ApplicationTopic.OperationalState, JSON.stringify(''));\n }\n restartCore() {\n this.mqttClient.publish(ApplicationTopic.RestartCore, JSON.stringify(''));\n }\n restartEngine() {\n this.mqttClient.publish(ApplicationTopic.RestartEngine, JSON.stringify(''));\n }\n openClampGripper() {\n const cmsg = {\n control_type: structs_1.ControlType.OpenClampGripper,\n params: null,\n };\n return this.api.Commands.send(cmsg);\n }\n runInfeedManual() {\n this.mqttClient.publish(ApplicationTopic.ConveyorManualStart, JSON.stringify(1));\n }\n start(pStartBay, pPalletIdxs) {\n const cmsg = {\n control_type: structs_1.ControlType.Start,\n params: { start_bay: pStartBay, pallet_start_idxs: pPalletIdxs },\n };\n return this.api.Commands.send(cmsg);\n // this.mqttClient.publish(ApplicationTopic.Control, JSON.stringify(cmsg));\n }\n async pause() {\n const cmsg = {\n control_type: structs_1.ControlType.Pause,\n params: null,\n };\n return this.api.Commands.send(cmsg);\n // this.mqttClient.publish(ApplicationTopic.Control, JSON.stringify(cmsg));\n }\n async stop() {\n const cmsg = {\n control_type: structs_1.ControlType.Stop,\n params: null,\n };\n return this.api.Commands.send(cmsg);\n // this.mqttClient.publish(ApplicationTopic.Control, JSON.stringify(cmsg));\n }\n async home() {\n const cmsg = {\n control_type: structs_1.ControlType.Home,\n params: null,\n };\n return this.api.Commands.send(cmsg);\n // this.mqttClient.publish(ApplicationTopic.Control, JSON.stringify(cmsg));\n }\n unlockLockDoor(pNewStatus) {\n this.mqttClient.publish(ApplicationTopic.AccessRequest, JSON.stringify(pNewStatus), {\n retain: true,\n });\n }\n selectGripper(pGripperName, pTcp) {\n this.mqttClient.publish(ApplicationTopic.SelectGripper, JSON.stringify({ name: pGripperName, tcp: pTcp }));\n }\n _pushAlert(pLevel, pDetail) {\n const lUUID = (0, uuid_1.v4)();\n this.mqttClient.publish(ApplicationTopic.Alert, JSON.stringify({\n level: pLevel,\n detail: String(pDetail),\n uuid: lUUID,\n }));\n return lUUID;\n }\n _initMqttClient(pOnConnect) {\n const my = this;\n const client = my.mqttClient;\n client.on('error', (e) => {\n console.log(e);\n });\n client.on('connect', () => {\n Object.values(ApplicationTopic).forEach((t) => {\n client.subscribe(t, () => {\n if (ApplicationTopic.State === t)\n client.publish(ApplicationTopic.StateRequest, 'state_req');\n });\n });\n if (pOnConnect)\n pOnConnect(client);\n });\n client.on('message', (t, buf) => {\n const msg_str = buf.toString();\n Object.values(my.message_handlers).forEach(h => h(t, msg_str));\n });\n }\n}\nexports.Application = Application;\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./structs\"), exports);\n__exportStar(require(\"./api\"), exports);\n__exportStar(require(\"./app\"), exports);\n", "/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n", "/** @license React v17.0.2\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=require(\"object-assign\"),n=60103,p=60106;exports.Fragment=60107;exports.StrictMode=60108;exports.Profiler=60114;var q=60109,r=60110,t=60112;exports.Suspense=60113;var u=60115,v=60116;\nif(\"function\"===typeof Symbol&&Symbol.for){var w=Symbol.for;n=w(\"react.element\");p=w(\"react.portal\");exports.Fragment=w(\"react.fragment\");exports.StrictMode=w(\"react.strict_mode\");exports.Profiler=w(\"react.profiler\");q=w(\"react.provider\");r=w(\"react.context\");t=w(\"react.forward_ref\");exports.Suspense=w(\"react.suspense\");u=w(\"react.memo\");v=w(\"react.lazy\")}var x=\"function\"===typeof Symbol&&Symbol.iterator;\nfunction y(a){if(null===a||\"object\"!==typeof a)return null;a=x&&a[x]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}function z(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;c1?arguments[1]:void 0)}},8457:function(t,e,n){\"use strict\";var o=n(9974),r=n(7908),i=n(3411),a=n(7659),s=n(7466),u=n(6135),c=n(8554),l=n(1246);t.exports=function(t){var e,n,f,p,d,h,v=r(t),g=\"function\"==typeof this?this:Array,y=arguments.length,m=y>1?arguments[1]:void 0,b=void 0!==m,x=l(v),w=0;if(b&&(m=o(m,y>2?arguments[2]:void 0,2)),null==x||g==Array&&a(x))for(n=new g(e=s(v.length));e>w;w++)h=b?m(v[w],w):v[w],u(n,w,h);else for(d=(p=c(v,x)).next,n=new g;!(f=d.call(p)).done;w++)h=b?i(p,m,[f.value,w],!0):f.value,u(n,w,h);return n.length=w,n}},1318:function(t,e,n){var o=n(5656),r=n(7466),i=n(1400),a=function(t){return function(e,n,a){var s,u=o(e),c=r(u.length),l=i(a,c);if(t&&n!=n){for(;c>l;)if((s=u[l++])!=s)return!0}else for(;c>l;l++)if((t||l in u)&&u[l]===n)return t||l||0;return!t&&-1}};t.exports={includes:a(!0),indexOf:a(!1)}},2092:function(t,e,n){var o=n(9974),r=n(8361),i=n(7908),a=n(7466),s=n(5417),u=[].push,c=function(t){var e=1==t,n=2==t,c=3==t,l=4==t,f=6==t,p=7==t,d=5==t||f;return function(h,v,g,y){for(var m,b,x=i(h),w=r(x),O=o(v,g,3),E=a(w.length),S=0,k=y||s,C=e?k(h,E):n||p?k(h,0):void 0;E>S;S++)if((d||S in w)&&(b=O(m=w[S],S,x),t))if(e)C[S]=b;else if(b)switch(t){case 3:return!0;case 5:return m;case 6:return S;case 2:u.call(C,m)}else switch(t){case 4:return!1;case 7:u.call(C,m)}return f?-1:c||l?l:C}};t.exports={forEach:c(0),map:c(1),filter:c(2),some:c(3),every:c(4),find:c(5),findIndex:c(6),filterReject:c(7)}},1194:function(t,e,n){var o=n(7293),r=n(5112),i=n(7392),a=r(\"species\");t.exports=function(t){return i>=51||!o((function(){var e=[];return(e.constructor={})[a]=function(){return{foo:1}},1!==e[t](Boolean).foo}))}},9341:function(t,e,n){\"use strict\";var o=n(7293);t.exports=function(t,e){var n=[][t];return!!n&&o((function(){n.call(null,e||function(){throw 1},1)}))}},3671:function(t,e,n){var o=n(3099),r=n(7908),i=n(8361),a=n(7466),s=function(t){return function(e,n,s,u){o(n);var c=r(e),l=i(c),f=a(c.length),p=t?f-1:0,d=t?-1:1;if(s<2)for(;;){if(p in l){u=l[p],p+=d;break}if(p+=d,t?p<0:f<=p)throw TypeError(\"Reduce of empty array with no initial value\")}for(;t?p>=0:f>p;p+=d)p in l&&(u=n(u,l[p],p,c));return u}};t.exports={left:s(!1),right:s(!0)}},4362:function(t){var e=Math.floor,n=function(t,i){var a=t.length,s=e(a/2);return a<8?o(t,i):r(n(t.slice(0,s),i),n(t.slice(s),i),i)},o=function(t,e){for(var n,o,r=t.length,i=1;i0;)t[o]=t[--o];o!==i++&&(t[o]=n)}return t},r=function(t,e,n){for(var o=t.length,r=e.length,i=0,a=0,s=[];i=74)&&(o=a.match(/Chrome\\/(\\d+)/))&&(r=o[1]),t.exports=r&&+r},8008:function(t,e,n){var o=n(8113).match(/AppleWebKit\\/(\\d+)\\./);t.exports=!!o&&+o[1]},748:function(t){t.exports=[\"constructor\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"toLocaleString\",\"toString\",\"valueOf\"]},2109:function(t,e,n){var o=n(7854),r=n(1236).f,i=n(8880),a=n(1320),s=n(3505),u=n(9920),c=n(4705);t.exports=function(t,e){var n,l,f,p,d,h=t.target,v=t.global,g=t.stat;if(n=v?o:g?o[h]||s(h,{}):(o[h]||{}).prototype)for(l in e){if(p=e[l],f=t.noTargetGet?(d=r(n,l))&&d.value:n[l],!c(v?l:h+(g?\".\":\"#\")+l,t.forced)&&void 0!==f){if(typeof p==typeof f)continue;u(p,f)}(t.sham||f&&f.sham)&&i(p,\"sham\",!0),a(n,l,p,t)}}},7293:function(t){t.exports=function(t){try{return!!t()}catch(t){return!0}}},7007:function(t,e,n){\"use strict\";n(4916);var o=n(1320),r=n(2261),i=n(7293),a=n(5112),s=n(8880),u=a(\"species\"),c=RegExp.prototype;t.exports=function(t,e,n,l){var f=a(t),p=!i((function(){var e={};return e[f]=function(){return 7},7!=\"\"[t](e)})),d=p&&!i((function(){var e=!1,n=/a/;return\"split\"===t&&((n={}).constructor={},n.constructor[u]=function(){return n},n.flags=\"\",n[f]=/./[f]),n.exec=function(){return e=!0,null},n[f](\"\"),!e}));if(!p||!d||n){var h=/./[f],v=e(f,\"\"[t],(function(t,e,n,o,i){var a=e.exec;return a===r||a===c.exec?p&&!i?{done:!0,value:h.call(e,n,o)}:{done:!0,value:t.call(n,e,o)}:{done:!1}}));o(String.prototype,t,v[0]),o(c,f,v[1])}l&&s(c[f],\"sham\",!0)}},9974:function(t,e,n){var o=n(3099);t.exports=function(t,e,n){if(o(t),void 0===e)return t;switch(n){case 0:return function(){return t.call(e)};case 1:return function(n){return t.call(e,n)};case 2:return function(n,o){return t.call(e,n,o)};case 3:return function(n,o,r){return t.call(e,n,o,r)}}return function(){return t.apply(e,arguments)}}},5005:function(t,e,n){var o=n(7854),r=function(t){return\"function\"==typeof t?t:void 0};t.exports=function(t,e){return arguments.length<2?r(o[t]):o[t]&&o[t][e]}},1246:function(t,e,n){var o=n(648),r=n(7497),i=n(5112)(\"iterator\");t.exports=function(t){if(null!=t)return t[i]||t[\"@@iterator\"]||r[o(t)]}},8554:function(t,e,n){var o=n(9670),r=n(1246);t.exports=function(t,e){var n=arguments.length<2?r(t):e;if(\"function\"!=typeof n)throw TypeError(String(t)+\" is not iterable\");return o(n.call(t))}},647:function(t,e,n){var o=n(7908),r=Math.floor,i=\"\".replace,a=/\\$([$&'`]|\\d{1,2}|<[^>]*>)/g,s=/\\$([$&'`]|\\d{1,2})/g;t.exports=function(t,e,n,u,c,l){var f=n+t.length,p=u.length,d=s;return void 0!==c&&(c=o(c),d=a),i.call(l,d,(function(o,i){var a;switch(i.charAt(0)){case\"$\":return\"$\";case\"&\":return t;case\"`\":return e.slice(0,n);case\"'\":return e.slice(f);case\"<\":a=c[i.slice(1,-1)];break;default:var s=+i;if(0===s)return o;if(s>p){var l=r(s/10);return 0===l?o:l<=p?void 0===u[l-1]?i.charAt(1):u[l-1]+i.charAt(1):o}a=u[s-1]}return void 0===a?\"\":a}))}},7854:function(t,e,n){var o=function(t){return t&&t.Math==Math&&t};t.exports=o(\"object\"==typeof globalThis&&globalThis)||o(\"object\"==typeof window&&window)||o(\"object\"==typeof self&&self)||o(\"object\"==typeof n.g&&n.g)||function(){return this}()||Function(\"return this\")()},6656:function(t,e,n){var o=n(7908),r={}.hasOwnProperty;t.exports=Object.hasOwn||function(t,e){return r.call(o(t),e)}},3501:function(t){t.exports={}},490:function(t,e,n){var o=n(5005);t.exports=o(\"document\",\"documentElement\")},4664:function(t,e,n){var o=n(9781),r=n(7293),i=n(317);t.exports=!o&&!r((function(){return 7!=Object.defineProperty(i(\"div\"),\"a\",{get:function(){return 7}}).a}))},8361:function(t,e,n){var o=n(7293),r=n(4326),i=\"\".split;t.exports=o((function(){return!Object(\"z\").propertyIsEnumerable(0)}))?function(t){return\"String\"==r(t)?i.call(t,\"\"):Object(t)}:Object},9587:function(t,e,n){var o=n(111),r=n(7674);t.exports=function(t,e,n){var i,a;return r&&\"function\"==typeof(i=e.constructor)&&i!==n&&o(a=i.prototype)&&a!==n.prototype&&r(t,a),t}},2788:function(t,e,n){var o=n(5465),r=Function.toString;\"function\"!=typeof o.inspectSource&&(o.inspectSource=function(t){return r.call(t)}),t.exports=o.inspectSource},9909:function(t,e,n){var o,r,i,a=n(8536),s=n(7854),u=n(111),c=n(8880),l=n(6656),f=n(5465),p=n(6200),d=n(3501),h=\"Object already initialized\",v=s.WeakMap;if(a||f.state){var g=f.state||(f.state=new v),y=g.get,m=g.has,b=g.set;o=function(t,e){if(m.call(g,t))throw new TypeError(h);return e.facade=t,b.call(g,t,e),e},r=function(t){return y.call(g,t)||{}},i=function(t){return m.call(g,t)}}else{var x=p(\"state\");d[x]=!0,o=function(t,e){if(l(t,x))throw new TypeError(h);return e.facade=t,c(t,x,e),e},r=function(t){return l(t,x)?t[x]:{}},i=function(t){return l(t,x)}}t.exports={set:o,get:r,has:i,enforce:function(t){return i(t)?r(t):o(t,{})},getterFor:function(t){return function(e){var n;if(!u(e)||(n=r(e)).type!==t)throw TypeError(\"Incompatible receiver, \"+t+\" required\");return n}}}},7659:function(t,e,n){var o=n(5112),r=n(7497),i=o(\"iterator\"),a=Array.prototype;t.exports=function(t){return void 0!==t&&(r.Array===t||a[i]===t)}},3157:function(t,e,n){var o=n(4326);t.exports=Array.isArray||function(t){return\"Array\"==o(t)}},4705:function(t,e,n){var o=n(7293),r=/#|\\.prototype\\./,i=function(t,e){var n=s[a(t)];return n==c||n!=u&&(\"function\"==typeof e?o(e):!!e)},a=i.normalize=function(t){return String(t).replace(r,\".\").toLowerCase()},s=i.data={},u=i.NATIVE=\"N\",c=i.POLYFILL=\"P\";t.exports=i},8730:function(t,e,n){var o=n(111),r=Math.floor;t.exports=function(t){return!o(t)&&isFinite(t)&&r(t)===t}},111:function(t){t.exports=function(t){return\"object\"==typeof t?null!==t:\"function\"==typeof t}},1913:function(t){t.exports=!1},7850:function(t,e,n){var o=n(111),r=n(4326),i=n(5112)(\"match\");t.exports=function(t){var e;return o(t)&&(void 0!==(e=t[i])?!!e:\"RegExp\"==r(t))}},2190:function(t,e,n){var o=n(5005),r=n(3307);t.exports=r?function(t){return\"symbol\"==typeof t}:function(t){var e=o(\"Symbol\");return\"function\"==typeof e&&Object(t)instanceof e}},9212:function(t,e,n){var o=n(9670);t.exports=function(t,e,n){var r,i;o(t);try{if(void 0===(r=t.return)){if(\"throw\"===e)throw n;return n}r=r.call(t)}catch(t){i=!0,r=t}if(\"throw\"===e)throw n;if(i)throw r;return o(r),n}},3383:function(t,e,n){\"use strict\";var o,r,i,a=n(7293),s=n(9518),u=n(8880),c=n(6656),l=n(5112),f=n(1913),p=l(\"iterator\"),d=!1;[].keys&&(\"next\"in(i=[].keys())?(r=s(s(i)))!==Object.prototype&&(o=r):d=!0);var h=null==o||a((function(){var t={};return o[p].call(t)!==t}));h&&(o={}),f&&!h||c(o,p)||u(o,p,(function(){return this})),t.exports={IteratorPrototype:o,BUGGY_SAFARI_ITERATORS:d}},7497:function(t){t.exports={}},133:function(t,e,n){var o=n(7392),r=n(7293);t.exports=!!Object.getOwnPropertySymbols&&!r((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&o&&o<41}))},8536:function(t,e,n){var o=n(7854),r=n(2788),i=o.WeakMap;t.exports=\"function\"==typeof i&&/native code/.test(r(i))},3929:function(t,e,n){var o=n(7850);t.exports=function(t){if(o(t))throw TypeError(\"The method doesn't accept regular expressions\");return t}},1574:function(t,e,n){\"use strict\";var o=n(9781),r=n(7293),i=n(1956),a=n(5181),s=n(5296),u=n(7908),c=n(8361),l=Object.assign,f=Object.defineProperty;t.exports=!l||r((function(){if(o&&1!==l({b:1},l(f({},\"a\",{enumerable:!0,get:function(){f(this,\"b\",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var t={},e={},n=Symbol(),r=\"abcdefghijklmnopqrst\";return t[n]=7,r.split(\"\").forEach((function(t){e[t]=t})),7!=l({},t)[n]||i(l({},e)).join(\"\")!=r}))?function(t,e){for(var n=u(t),r=arguments.length,l=1,f=a.f,p=s.f;r>l;)for(var d,h=c(arguments[l++]),v=f?i(h).concat(f(h)):i(h),g=v.length,y=0;g>y;)d=v[y++],o&&!p.call(h,d)||(n[d]=h[d]);return n}:l},30:function(t,e,n){var o,r=n(9670),i=n(6048),a=n(748),s=n(3501),u=n(490),c=n(317),l=n(6200)(\"IE_PROTO\"),f=function(){},p=function(t){return\"