mainnet-js 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/index.html +1 -1
  2. package/dist/{mainnet-2.0.1.js → mainnet-2.1.0.js} +18 -58
  3. package/dist/module/db/StorageProvider.d.ts +9 -9
  4. package/dist/module/db/StorageProvider.d.ts.map +1 -1
  5. package/dist/module/db/StorageProvider.js +2 -1
  6. package/dist/module/db/StorageProvider.js.map +1 -1
  7. package/dist/module/db/index.d.ts +1 -2
  8. package/dist/module/db/index.d.ts.map +1 -1
  9. package/dist/module/db/index.js +2 -2
  10. package/dist/module/db/index.js.map +1 -1
  11. package/dist/module/db/interface.d.ts +0 -12
  12. package/dist/module/db/interface.d.ts.map +1 -1
  13. package/dist/module/db/util.d.ts +0 -2
  14. package/dist/module/db/util.d.ts.map +1 -1
  15. package/dist/module/db/util.js +0 -23
  16. package/dist/module/db/util.js.map +1 -1
  17. package/dist/module/index.d.ts +0 -1
  18. package/dist/module/index.d.ts.map +1 -1
  19. package/dist/module/index.js +0 -4
  20. package/dist/module/index.js.map +1 -1
  21. package/dist/module/network/index.d.ts +1 -0
  22. package/dist/module/network/index.d.ts.map +1 -1
  23. package/dist/module/wallet/Base.d.ts +1 -1
  24. package/dist/module/wallet/Base.d.ts.map +1 -1
  25. package/dist/module/wallet/Base.js +6 -1
  26. package/dist/module/wallet/Base.js.map +1 -1
  27. package/dist/module/wallet/Bcmr.d.ts.map +1 -1
  28. package/dist/module/wallet/Bcmr.js +3 -1
  29. package/dist/module/wallet/Bcmr.js.map +1 -1
  30. package/dist/tsconfig.tsbuildinfo +1 -1
  31. package/package.json +2 -12
  32. package/src/db/StorageProvider.ts +9 -9
  33. package/src/db/index.ts +1 -2
  34. package/src/db/interface.ts +0 -14
  35. package/src/db/util.ts +0 -26
  36. package/src/index.ts +0 -5
  37. package/src/network/index.ts +1 -0
  38. package/src/wallet/Base.ts +9 -2
  39. package/src/wallet/Bcmr.ts +5 -1
  40. package/src/wallet/Wif.test.ts +0 -42
  41. package/dist/module/db/IndexedDBProvider.d.ts +0 -16
  42. package/dist/module/db/IndexedDBProvider.d.ts.map +0 -1
  43. package/dist/module/db/IndexedDBProvider.js +0 -80
  44. package/dist/module/db/IndexedDBProvider.js.map +0 -1
  45. package/dist/module/db/SqlProvider.d.ts +0 -40
  46. package/dist/module/db/SqlProvider.d.ts.map +0 -1
  47. package/dist/module/db/SqlProvider.js +0 -198
  48. package/dist/module/db/SqlProvider.js.map +0 -1
  49. package/dist/module/db/getStorageProvider.d.ts +0 -3
  50. package/dist/module/db/getStorageProvider.d.ts.map +0 -1
  51. package/dist/module/db/getStorageProvider.js +0 -19
  52. package/dist/module/db/getStorageProvider.js.map +0 -1
  53. package/dist/module/webhook/Webhook.d.ts +0 -36
  54. package/dist/module/webhook/Webhook.d.ts.map +0 -1
  55. package/dist/module/webhook/Webhook.js +0 -77
  56. package/dist/module/webhook/Webhook.js.map +0 -1
  57. package/dist/module/webhook/WebhookBch.d.ts +0 -14
  58. package/dist/module/webhook/WebhookBch.d.ts.map +0 -1
  59. package/dist/module/webhook/WebhookBch.js +0 -141
  60. package/dist/module/webhook/WebhookBch.js.map +0 -1
  61. package/dist/module/webhook/WebhookWorker.d.ts +0 -23
  62. package/dist/module/webhook/WebhookWorker.d.ts.map +0 -1
  63. package/dist/module/webhook/WebhookWorker.js +0 -94
  64. package/dist/module/webhook/WebhookWorker.js.map +0 -1
  65. package/dist/module/webhook/index.d.ts +0 -5
  66. package/dist/module/webhook/index.d.ts.map +0 -1
  67. package/dist/module/webhook/index.js +0 -5
  68. package/dist/module/webhook/index.js.map +0 -1
  69. package/dist/module/webhook/interface.d.ts +0 -8
  70. package/dist/module/webhook/interface.d.ts.map +0 -1
  71. package/dist/module/webhook/interface.js +0 -2
  72. package/dist/module/webhook/interface.js.map +0 -1
  73. package/src/Wallet.test.headless.js +0 -369
  74. package/src/Wallet.test.ts +0 -519
  75. package/src/db/IndexedDBProvider.test.ts +0 -69
  76. package/src/db/IndexedDBProvider.ts +0 -93
  77. package/src/db/SqlProvider.test.ts +0 -282
  78. package/src/db/SqlProvider.ts +0 -297
  79. package/src/db/getStorageProvider.ts +0 -20
  80. package/src/db/index.test.headless.js +0 -62
  81. package/src/db/index.test.ts +0 -64
  82. package/src/wallet/createWallet.test.ts +0 -155
  83. package/src/webhook/Webhook.test.ts +0 -9
  84. package/src/webhook/Webhook.ts +0 -99
  85. package/src/webhook/WebhookBch.test.ts +0 -323
  86. package/src/webhook/WebhookBch.ts +0 -198
  87. package/src/webhook/WebhookWorker.test.ts +0 -96
  88. package/src/webhook/WebhookWorker.ts +0 -119
  89. package/src/webhook/index.ts +0 -4
  90. package/src/webhook/interface.ts +0 -7
@@ -334,7 +334,7 @@ eval("/*!\n * The buffer module from node.js, for the browser.\n *\n * @author
334
334
  \***********************************************/
335
335
  /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
336
336
 
337
- eval("var Buffer = (__webpack_require__(/*! safe-buffer */ \"../../node_modules/safe-buffer/index.js\").Buffer)\nvar Transform = (__webpack_require__(/*! stream */ \"../../node_modules/stream-browserify/index.js\").Transform)\nvar StringDecoder = (__webpack_require__(/*! string_decoder */ \"../../node_modules/string_decoder/index.js\").StringDecoder)\nvar inherits = __webpack_require__(/*! inherits */ \"../../node_modules/inherits/inherits_browser.js\")\n\nfunction CipherBase (hashMode) {\n Transform.call(this)\n this.hashMode = typeof hashMode === 'string'\n if (this.hashMode) {\n this[hashMode] = this._finalOrDigest\n } else {\n this.final = this._finalOrDigest\n }\n if (this._final) {\n this.__final = this._final\n this._final = null\n }\n this._decoder = null\n this._encoding = null\n}\ninherits(CipherBase, Transform)\n\nCipherBase.prototype.update = function (data, inputEnc, outputEnc) {\n if (typeof data === 'string') {\n data = Buffer.from(data, inputEnc)\n }\n\n var outData = this._update(data)\n if (this.hashMode) return this\n\n if (outputEnc) {\n outData = this._toString(outData, outputEnc)\n }\n\n return outData\n}\n\nCipherBase.prototype.setAutoPadding = function () {}\nCipherBase.prototype.getAuthTag = function () {\n throw new Error('trying to get auth tag in unsupported state')\n}\n\nCipherBase.prototype.setAuthTag = function () {\n throw new Error('trying to set auth tag in unsupported state')\n}\n\nCipherBase.prototype.setAAD = function () {\n throw new Error('trying to set aad in unsupported state')\n}\n\nCipherBase.prototype._transform = function (data, _, next) {\n var err\n try {\n if (this.hashMode) {\n this._update(data)\n } else {\n this.push(this._update(data))\n }\n } catch (e) {\n err = e\n } finally {\n next(err)\n }\n}\nCipherBase.prototype._flush = function (done) {\n var err\n try {\n this.push(this.__final())\n } catch (e) {\n err = e\n }\n\n done(err)\n}\nCipherBase.prototype._finalOrDigest = function (outputEnc) {\n var outData = this.__final() || Buffer.alloc(0)\n if (outputEnc) {\n outData = this._toString(outData, outputEnc, true)\n }\n return outData\n}\n\nCipherBase.prototype._toString = function (value, enc, fin) {\n if (!this._decoder) {\n this._decoder = new StringDecoder(enc)\n this._encoding = enc\n }\n\n if (this._encoding !== enc) throw new Error('can\\'t switch encodings')\n\n var out = this._decoder.write(value)\n if (fin) {\n out += this._decoder.end()\n }\n\n return out\n}\n\nmodule.exports = CipherBase\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/cipher-base/index.js?");
337
+ eval("var Buffer = (__webpack_require__(/*! safe-buffer */ \"../../node_modules/safe-buffer/index.js\").Buffer)\nvar Transform = (__webpack_require__(/*! stream */ \"../../node_modules/stream-browserify/index.js\").Transform)\nvar StringDecoder = (__webpack_require__(/*! string_decoder */ \"../../node_modules/string_decoder/lib/string_decoder.js\").StringDecoder)\nvar inherits = __webpack_require__(/*! inherits */ \"../../node_modules/inherits/inherits_browser.js\")\n\nfunction CipherBase (hashMode) {\n Transform.call(this)\n this.hashMode = typeof hashMode === 'string'\n if (this.hashMode) {\n this[hashMode] = this._finalOrDigest\n } else {\n this.final = this._finalOrDigest\n }\n if (this._final) {\n this.__final = this._final\n this._final = null\n }\n this._decoder = null\n this._encoding = null\n}\ninherits(CipherBase, Transform)\n\nCipherBase.prototype.update = function (data, inputEnc, outputEnc) {\n if (typeof data === 'string') {\n data = Buffer.from(data, inputEnc)\n }\n\n var outData = this._update(data)\n if (this.hashMode) return this\n\n if (outputEnc) {\n outData = this._toString(outData, outputEnc)\n }\n\n return outData\n}\n\nCipherBase.prototype.setAutoPadding = function () {}\nCipherBase.prototype.getAuthTag = function () {\n throw new Error('trying to get auth tag in unsupported state')\n}\n\nCipherBase.prototype.setAuthTag = function () {\n throw new Error('trying to set auth tag in unsupported state')\n}\n\nCipherBase.prototype.setAAD = function () {\n throw new Error('trying to set aad in unsupported state')\n}\n\nCipherBase.prototype._transform = function (data, _, next) {\n var err\n try {\n if (this.hashMode) {\n this._update(data)\n } else {\n this.push(this._update(data))\n }\n } catch (e) {\n err = e\n } finally {\n next(err)\n }\n}\nCipherBase.prototype._flush = function (done) {\n var err\n try {\n this.push(this.__final())\n } catch (e) {\n err = e\n }\n\n done(err)\n}\nCipherBase.prototype._finalOrDigest = function (outputEnc) {\n var outData = this.__final() || Buffer.alloc(0)\n if (outputEnc) {\n outData = this._toString(outData, outputEnc, true)\n }\n return outData\n}\n\nCipherBase.prototype._toString = function (value, enc, fin) {\n if (!this._decoder) {\n this._decoder = new StringDecoder(enc)\n this._encoding = enc\n }\n\n if (this._encoding !== enc) throw new Error('can\\'t switch encodings')\n\n var out = this._decoder.write(value)\n if (fin) {\n out += this._decoder.end()\n }\n\n return out\n}\n\nmodule.exports = CipherBase\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/cipher-base/index.js?");
338
338
 
339
339
  /***/ }),
340
340
 
@@ -574,7 +574,7 @@ eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission
574
574
  \******************************************************************/
575
575
  /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
576
576
 
577
- eval("// 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\nmodule.exports = Readable;\n/*<replacement>*/\n\nvar Duplex;\n/*</replacement>*/\n\nReadable.ReadableState = ReadableState;\n/*<replacement>*/\n\nvar EE = (__webpack_require__(/*! events */ \"../../node_modules/events/events.js\").EventEmitter);\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/*</replacement>*/\n\n/*<replacement>*/\n\n\nvar Stream = __webpack_require__(/*! ./internal/streams/stream */ \"../../node_modules/readable-stream/lib/internal/streams/stream-browser.js\");\n/*</replacement>*/\n\n\nvar Buffer = (__webpack_require__(/*! buffer */ \"../../node_modules/buffer/index.js\").Buffer);\n\nvar OurUint8Array = __webpack_require__.g.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/*<replacement>*/\n\n\nvar debugUtil = __webpack_require__(/*! util */ \"?983a\");\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/*</replacement>*/\n\n\nvar BufferList = __webpack_require__(/*! ./internal/streams/buffer_list */ \"../../node_modules/readable-stream/lib/internal/streams/buffer_list.js\");\n\nvar destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ \"../../node_modules/readable-stream/lib/internal/streams/destroy.js\");\n\nvar _require = __webpack_require__(/*! ./internal/streams/state */ \"../../node_modules/readable-stream/lib/internal/streams/state.js\"),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = (__webpack_require__(/*! ../errors */ \"../../node_modules/readable-stream/errors-browser.js\").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\n__webpack_require__(/*! inherits */ \"../../node_modules/inherits/inherits_browser.js\")(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 || __webpack_require__(/*! ./_stream_duplex */ \"../../node_modules/readable-stream/lib/_stream_duplex.js\");\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 = (__webpack_require__(/*! string_decoder/ */ \"../../node_modules/readable-stream/node_modules/string_decoder/lib/string_decoder.js\").StringDecoder);\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"../../node_modules/readable-stream/lib/_stream_duplex.js\");\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 = (__webpack_require__(/*! string_decoder/ */ \"../../node_modules/readable-stream/node_modules/string_decoder/lib/string_decoder.js\").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 = __webpack_require__(/*! ./internal/streams/async_iterator */ \"../../node_modules/readable-stream/lib/internal/streams/async_iterator.js\");\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 = __webpack_require__(/*! ./internal/streams/from */ \"../../node_modules/readable-stream/lib/internal/streams/from-browser.js\");\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}\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/readable-stream/lib/_stream_readable.js?");
577
+ eval("// 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\nmodule.exports = Readable;\n/*<replacement>*/\n\nvar Duplex;\n/*</replacement>*/\n\nReadable.ReadableState = ReadableState;\n/*<replacement>*/\n\nvar EE = (__webpack_require__(/*! events */ \"../../node_modules/events/events.js\").EventEmitter);\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/*</replacement>*/\n\n/*<replacement>*/\n\n\nvar Stream = __webpack_require__(/*! ./internal/streams/stream */ \"../../node_modules/readable-stream/lib/internal/streams/stream-browser.js\");\n/*</replacement>*/\n\n\nvar Buffer = (__webpack_require__(/*! buffer */ \"../../node_modules/buffer/index.js\").Buffer);\n\nvar OurUint8Array = __webpack_require__.g.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/*<replacement>*/\n\n\nvar debugUtil = __webpack_require__(/*! util */ \"?983a\");\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/*</replacement>*/\n\n\nvar BufferList = __webpack_require__(/*! ./internal/streams/buffer_list */ \"../../node_modules/readable-stream/lib/internal/streams/buffer_list.js\");\n\nvar destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ \"../../node_modules/readable-stream/lib/internal/streams/destroy.js\");\n\nvar _require = __webpack_require__(/*! ./internal/streams/state */ \"../../node_modules/readable-stream/lib/internal/streams/state.js\"),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = (__webpack_require__(/*! ../errors */ \"../../node_modules/readable-stream/errors-browser.js\").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\n__webpack_require__(/*! inherits */ \"../../node_modules/inherits/inherits_browser.js\")(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 || __webpack_require__(/*! ./_stream_duplex */ \"../../node_modules/readable-stream/lib/_stream_duplex.js\");\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 = (__webpack_require__(/*! string_decoder/ */ \"../../node_modules/string_decoder/lib/string_decoder.js\").StringDecoder);\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"../../node_modules/readable-stream/lib/_stream_duplex.js\");\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 = (__webpack_require__(/*! string_decoder/ */ \"../../node_modules/string_decoder/lib/string_decoder.js\").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 = __webpack_require__(/*! ./internal/streams/async_iterator */ \"../../node_modules/readable-stream/lib/internal/streams/async_iterator.js\");\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 = __webpack_require__(/*! ./internal/streams/from */ \"../../node_modules/readable-stream/lib/internal/streams/from-browser.js\");\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}\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/readable-stream/lib/_stream_readable.js?");
578
578
 
579
579
  /***/ }),
580
580
 
@@ -678,16 +678,6 @@ eval("module.exports = __webpack_require__(/*! events */ \"../../node_modules/ev
678
678
 
679
679
  /***/ }),
680
680
 
681
- /***/ "../../node_modules/readable-stream/node_modules/string_decoder/lib/string_decoder.js":
682
- /*!********************************************************************************************!*\
683
- !*** ../../node_modules/readable-stream/node_modules/string_decoder/lib/string_decoder.js ***!
684
- \********************************************************************************************/
685
- /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
686
-
687
- eval("// 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\n/*<replacement>*/\n\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"../../node_modules/safe-buffer/index.js\").Buffer);\n/*</replacement>*/\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}\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/readable-stream/node_modules/string_decoder/lib/string_decoder.js?");
688
-
689
- /***/ }),
690
-
691
681
  /***/ "../../node_modules/readable-stream/readable-browser.js":
692
682
  /*!**************************************************************!*\
693
683
  !*** ../../node_modules/readable-stream/readable-browser.js ***!
@@ -808,13 +798,13 @@ eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission
808
798
 
809
799
  /***/ }),
810
800
 
811
- /***/ "../../node_modules/string_decoder/index.js":
812
- /*!**************************************************!*\
813
- !*** ../../node_modules/string_decoder/index.js ***!
814
- \**************************************************/
801
+ /***/ "../../node_modules/string_decoder/lib/string_decoder.js":
802
+ /*!***************************************************************!*\
803
+ !*** ../../node_modules/string_decoder/lib/string_decoder.js ***!
804
+ \***************************************************************/
815
805
  /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
816
806
 
817
- eval("// 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\nvar Buffer = (__webpack_require__(/*! buffer */ \"../../node_modules/buffer/index.js\").Buffer);\n\nvar isBufferEncoding = Buffer.isEncoding\n || function(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': return true;\n default: return false;\n }\n }\n\n\nfunction assertEncoding(encoding) {\n if (encoding && !isBufferEncoding(encoding)) {\n throw new Error('Unknown encoding: ' + encoding);\n }\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. CESU-8 is handled as part of the UTF-8 encoding.\n//\n// @TODO Handling all encodings inside a single object makes it very difficult\n// to reason about this code, so it should be split up in the future.\n// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code\n// points as used by CESU-8.\nvar StringDecoder = exports.StringDecoder = function(encoding) {\n this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');\n assertEncoding(encoding);\n switch (this.encoding) {\n case 'utf8':\n // CESU-8 represents each of Surrogate Pair by 3-bytes\n this.surrogateSize = 3;\n break;\n case 'ucs2':\n case 'utf16le':\n // UTF-16 represents each of Surrogate Pair by 2-bytes\n this.surrogateSize = 2;\n this.detectIncompleteChar = utf16DetectIncompleteChar;\n break;\n case 'base64':\n // Base-64 stores 3 bytes in 4 chars, and pads the remainder.\n this.surrogateSize = 3;\n this.detectIncompleteChar = base64DetectIncompleteChar;\n break;\n default:\n this.write = passThroughWrite;\n return;\n }\n\n // Enough space to store all bytes of a single character. UTF-8 needs 4\n // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).\n this.charBuffer = new Buffer(6);\n // Number of bytes received for the current incomplete multi-byte character.\n this.charReceived = 0;\n // Number of bytes expected for the current incomplete multi-byte character.\n this.charLength = 0;\n};\n\n\n// write decodes the given buffer and returns it as JS string that is\n// guaranteed to not contain any partial multi-byte characters. Any partial\n// character found at the end of the buffer is buffered up, and will be\n// returned when calling write again with the remaining bytes.\n//\n// Note: Converting a Buffer containing an orphan surrogate to a String\n// currently works, but converting a String to a Buffer (via `new Buffer`, or\n// Buffer#write) will replace incomplete surrogates with the unicode\n// replacement character. See https://codereview.chromium.org/121173009/ .\nStringDecoder.prototype.write = function(buffer) {\n var charStr = '';\n // if our last write ended with an incomplete multibyte character\n while (this.charLength) {\n // determine how many remaining bytes this buffer has to offer for this char\n var available = (buffer.length >= this.charLength - this.charReceived) ?\n this.charLength - this.charReceived :\n buffer.length;\n\n // add the new bytes to the char buffer\n buffer.copy(this.charBuffer, this.charReceived, 0, available);\n this.charReceived += available;\n\n if (this.charReceived < this.charLength) {\n // still not enough chars in this buffer? wait for more ...\n return '';\n }\n\n // remove bytes belonging to the current character from the buffer\n buffer = buffer.slice(available, buffer.length);\n\n // get the character that was split\n charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);\n\n // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character\n var charCode = charStr.charCodeAt(charStr.length - 1);\n if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n this.charLength += this.surrogateSize;\n charStr = '';\n continue;\n }\n this.charReceived = this.charLength = 0;\n\n // if there are no more bytes in this buffer, just emit our char\n if (buffer.length === 0) {\n return charStr;\n }\n break;\n }\n\n // determine and set charLength / charReceived\n this.detectIncompleteChar(buffer);\n\n var end = buffer.length;\n if (this.charLength) {\n // buffer the incomplete character bytes we got\n buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);\n end -= this.charReceived;\n }\n\n charStr += buffer.toString(this.encoding, 0, end);\n\n var end = charStr.length - 1;\n var charCode = charStr.charCodeAt(end);\n // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character\n if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n var size = this.surrogateSize;\n this.charLength += size;\n this.charReceived += size;\n this.charBuffer.copy(this.charBuffer, size, 0, size);\n buffer.copy(this.charBuffer, 0, 0, size);\n return charStr.substring(0, end);\n }\n\n // or just emit the charStr\n return charStr;\n};\n\n// detectIncompleteChar determines if there is an incomplete UTF-8 character at\n// the end of the given buffer. If so, it sets this.charLength to the byte\n// length that character, and sets this.charReceived to the number of bytes\n// that are available for this character.\nStringDecoder.prototype.detectIncompleteChar = function(buffer) {\n // determine how many bytes we have to check at the end of this buffer\n var i = (buffer.length >= 3) ? 3 : buffer.length;\n\n // Figure out if one of the last i bytes of our buffer announces an\n // incomplete char.\n for (; i > 0; i--) {\n var c = buffer[buffer.length - i];\n\n // See http://en.wikipedia.org/wiki/UTF-8#Description\n\n // 110XXXXX\n if (i == 1 && c >> 5 == 0x06) {\n this.charLength = 2;\n break;\n }\n\n // 1110XXXX\n if (i <= 2 && c >> 4 == 0x0E) {\n this.charLength = 3;\n break;\n }\n\n // 11110XXX\n if (i <= 3 && c >> 3 == 0x1E) {\n this.charLength = 4;\n break;\n }\n }\n this.charReceived = i;\n};\n\nStringDecoder.prototype.end = function(buffer) {\n var res = '';\n if (buffer && buffer.length)\n res = this.write(buffer);\n\n if (this.charReceived) {\n var cr = this.charReceived;\n var buf = this.charBuffer;\n var enc = this.encoding;\n res += buf.slice(0, cr).toString(enc);\n }\n\n return res;\n};\n\nfunction passThroughWrite(buffer) {\n return buffer.toString(this.encoding);\n}\n\nfunction utf16DetectIncompleteChar(buffer) {\n this.charReceived = buffer.length % 2;\n this.charLength = this.charReceived ? 2 : 0;\n}\n\nfunction base64DetectIncompleteChar(buffer) {\n this.charReceived = buffer.length % 3;\n this.charLength = this.charReceived ? 3 : 0;\n}\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/string_decoder/index.js?");
807
+ eval("// 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\n/*<replacement>*/\n\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"../../node_modules/safe-buffer/index.js\").Buffer);\n/*</replacement>*/\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}\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/string_decoder/lib/string_decoder.js?");
818
808
 
819
809
  /***/ }),
820
810
 
@@ -858,23 +848,13 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
858
848
 
859
849
  /***/ }),
860
850
 
861
- /***/ "./src/db/IndexedDBProvider.ts":
862
- /*!*************************************!*\
863
- !*** ./src/db/IndexedDBProvider.ts ***!
864
- \*************************************/
865
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
866
-
867
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ IndexedDBProvider)\n/* harmony export */ });\n/* harmony import */ var dexie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! dexie */ \"../../node_modules/dexie/dist/modern/dexie.mjs\");\n\nclass IndexedDBProvider extends dexie__WEBPACK_IMPORTED_MODULE_0__[\"default\"] {\n constructor(dbName) {\n super(dbName);\n this.version(3).stores({\n wallet: \"name\",\n });\n this.db = this.table(\"wallet\");\n }\n async init() {\n return this;\n }\n async close() {\n return this;\n }\n getInfo() {\n return \"indexedDB\";\n }\n async addWallet(name, walletId) {\n return this.transaction(\"rw\", this.db, async () => {\n if ((await this.db.where({ name: name }).count()) === 0) {\n await this.db.add({ name: name, wallet: walletId }).catch((e) => {\n throw Error(e);\n });\n return true;\n }\n else {\n return false;\n }\n }).catch((e) => {\n throw e.stack || e;\n });\n }\n async getWallet(name) {\n let obj = await this.db.get({ name: name });\n if (obj) {\n return obj;\n }\n else {\n return;\n }\n }\n async getWallets() {\n let walletObjects = await this.transaction(\"r\", this.db, async () => {\n return await this.db.where(\"id\").above(0).toArray();\n });\n if (walletObjects) {\n const WalletArray = await Promise.all(walletObjects.map(async (obj) => {\n return obj;\n }));\n return WalletArray;\n }\n else {\n return [];\n }\n }\n async updateWallet(name, walletId) {\n this.transaction(\"rw\", this.db, async () => {\n const collection = this.db.where({ name: name });\n if ((await collection.count()) === 0) {\n return false;\n }\n else {\n const wallet = (await collection.first());\n await this.db\n .put({ id: wallet.id, name: name, wallet: walletId }, wallet.id)\n .catch((e) => {\n throw Error(e);\n });\n return true;\n }\n }).catch((e) => {\n throw e.stack || e;\n });\n }\n async walletExists(name) {\n return (await this.getWallet(name)) !== undefined;\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/IndexedDBProvider.ts?");
868
-
869
- /***/ }),
870
-
871
- /***/ "./src/db/getStorageProvider.ts":
872
- /*!**************************************!*\
873
- !*** ./src/db/getStorageProvider.ts ***!
874
- \**************************************/
851
+ /***/ "./src/db/StorageProvider.ts":
852
+ /*!***********************************!*\
853
+ !*** ./src/db/StorageProvider.ts ***!
854
+ \***********************************/
875
855
  /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
876
856
 
877
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"getStorageProvider\": () => (/* binding */ getStorageProvider)\n/* harmony export */ });\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _IndexedDBProvider_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./IndexedDBProvider.js */ \"./src/db/IndexedDBProvider.ts\");\n/* harmony import */ var _SqlProvider_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SqlProvider.js */ \"?7652\");\n/* harmony import */ var _SqlProvider_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_SqlProvider_js__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./util.js */ \"./src/db/util.ts\");\n\n\n\n\nfunction getStorageProvider(dbName) {\n if ((0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_1__.getRuntimePlatform)() !== \"node\" && (0,_util_js__WEBPACK_IMPORTED_MODULE_2__.indexedDbIsAvailable)()) {\n return new _IndexedDBProvider_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"](dbName);\n }\n else {\n if (\"DATABASE_URL\" in process.env) {\n return new (_SqlProvider_js__WEBPACK_IMPORTED_MODULE_0___default())(dbName);\n }\n else {\n console.warn(\"DATABASE_URL was not configured, storage unavailable\");\n return;\n }\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/getStorageProvider.ts?");
857
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ StorageProvider)\n/* harmony export */ });\nclass StorageProvider {\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/StorageProvider.ts?");
878
858
 
879
859
  /***/ }),
880
860
 
@@ -884,7 +864,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
884
864
  \*************************/
885
865
  /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
886
866
 
887
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"IndexedDBProvider\": () => (/* reexport safe */ _IndexedDBProvider_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"]),\n/* harmony export */ \"SqlProvider\": () => (/* reexport default from dynamic */ _SqlProvider_js__WEBPACK_IMPORTED_MODULE_1___default.a)\n/* harmony export */ });\n/* harmony import */ var _IndexedDBProvider_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./IndexedDBProvider.js */ \"./src/db/IndexedDBProvider.ts\");\n/* harmony import */ var _SqlProvider_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./SqlProvider.js */ \"?7652\");\n/* harmony import */ var _SqlProvider_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_SqlProvider_js__WEBPACK_IMPORTED_MODULE_1__);\n\n\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/index.ts?");
867
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"StorageProvider\": () => (/* reexport safe */ _StorageProvider_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"])\n/* harmony export */ });\n/* harmony import */ var _StorageProvider_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./StorageProvider.js */ \"./src/db/StorageProvider.ts\");\n\n\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/index.ts?");
888
868
 
889
869
  /***/ }),
890
870
 
@@ -894,7 +874,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
894
874
  \************************/
895
875
  /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
896
876
 
897
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"indexedDbIsAvailable\": () => (/* binding */ indexedDbIsAvailable)\n/* harmony export */ });\n/* unused harmony export getSslConfig */\n/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"../../node_modules/buffer/index.js\")[\"Buffer\"];\nfunction indexedDbIsAvailable() {\n return \"indexedDB\" in globalThis;\n}\nfunction getSslConfig() {\n const ca = process.env.DATABASE_SSL_CA\n ? Buffer.from(process.env.DATABASE_SSL_CA, \"base64\").toString(\"ascii\")\n : undefined;\n const key = process.env.DATABASE_SSL_KEY\n ? Buffer.from(process.env.DATABASE_SSL_KEY, \"base64\").toString(\"ascii\")\n : undefined;\n const cert = process.env.DATABASE_SSL_CERT\n ? Buffer.from(process.env.DATABASE_SSL_CERT, \"base64\").toString(\"ascii\")\n : undefined;\n let ssl = {\n rejectUnauthorized: process.env.DATABASE_SSL_REJECT_UNAUTHORIZED == \"false\" ? false : true,\n ca: ca,\n key: key,\n cert: cert,\n };\n if (ssl.ca || ssl.cert || ssl.key) {\n return ssl;\n }\n else {\n return;\n }\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/util.ts?");
877
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"indexedDbIsAvailable\": () => (/* binding */ indexedDbIsAvailable)\n/* harmony export */ });\nfunction indexedDbIsAvailable() {\n return \"indexedDB\" in globalThis;\n}\n\n\n//# sourceURL=webpack://mainnet-js/./src/db/util.ts?");
898
878
 
899
879
  /***/ }),
900
880
 
@@ -924,7 +904,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
924
904
  \**********************/
925
905
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
926
906
 
927
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BCMR\": () => (/* reexport safe */ _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_5__.BCMR),\n/* harmony export */ \"BalanceResponse\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.BalanceResponse),\n/* harmony export */ \"BaseWallet\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_8__.BaseWallet),\n/* harmony export */ \"CONST\": () => (/* reexport module object */ _constant_js__WEBPACK_IMPORTED_MODULE_19__),\n/* harmony export */ \"Config\": () => (/* reexport safe */ _config_js__WEBPACK_IMPORTED_MODULE_12__.Config),\n/* harmony export */ \"Connection\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_6__.Connection),\n/* harmony export */ \"DefaultProvider\": () => (/* reexport safe */ _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__.DefaultProvider),\n/* harmony export */ \"ElectrumNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_6__.ElectrumNetworkProvider),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.ExchangeRate),\n/* harmony export */ \"IndexedDBProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_0__.IndexedDBProvider),\n/* harmony export */ \"Mainnet\": () => (/* reexport module object */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__),\n/* harmony export */ \"NFTCapability\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_20__.NFTCapability),\n/* harmony export */ \"Network\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_20__.Network),\n/* harmony export */ \"NetworkType\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_13__.NetworkType),\n/* harmony export */ \"OpReturnData\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.OpReturnData),\n/* harmony export */ \"RegTestWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.RegTestWifWallet),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.RuntimePlatform),\n/* harmony export */ \"SendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.SendResponse),\n/* harmony export */ \"SignedMessage\": () => (/* reexport safe */ _message_signed_js__WEBPACK_IMPORTED_MODULE_7__.SignedMessage),\n/* harmony export */ \"SqlProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_0__.SqlProvider),\n/* harmony export */ \"TestNetWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.TestNetWifWallet),\n/* harmony export */ \"TokenBurnRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.TokenSendRequest),\n/* harmony export */ \"UnitEnum\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_13__.UnitEnum),\n/* harmony export */ \"Wallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.Wallet),\n/* harmony export */ \"WalletTypeEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_14__.WalletTypeEnum),\n/* harmony export */ \"WatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__.WifWallet),\n/* harmony export */ \"XPubKey\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.XPubKey),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.checkTokenaddr),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convert),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.convertObject),\n/* harmony export */ \"createWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.createWallet),\n/* harmony export */ \"createWalletResponse\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.createWalletResponse),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.derivedNetwork),\n/* harmony export */ \"disconnectProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_6__.disconnectProviders),\n/* harmony export */ \"expect\": () => (/* reexport safe */ _test_expect_js__WEBPACK_IMPORTED_MODULE_2__.expect),\n/* harmony export */ \"fromUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.fromUtxoId),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_6__.getNetworkProvider),\n/* harmony export */ \"getRandomInt\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getRandomInt),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getUsdRate),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.hexToBin),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_6__.initProviders),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.isValidAddress),\n/* harmony export */ \"libauth\": () => (/* reexport module object */ _libauth_js__WEBPACK_IMPORTED_MODULE_17__),\n/* harmony export */ \"mine\": () => (/* reexport safe */ _mine_index_js__WEBPACK_IMPORTED_MODULE_1__.mine),\n/* harmony export */ \"namedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.namedWallet),\n/* harmony export */ \"namedWalletExists\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.namedWalletExists),\n/* harmony export */ \"qrAddress\": () => (/* reexport safe */ _qr_Qr_js__WEBPACK_IMPORTED_MODULE_18__.qrAddress),\n/* harmony export */ \"randomValues\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.randomValues),\n/* harmony export */ \"removeAxiosMock\": () => (/* reexport safe */ _test_axios_js__WEBPACK_IMPORTED_MODULE_3__.removeAxiosMock),\n/* harmony export */ \"replaceNamedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.replaceNamedWallet),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sanitizeUnit),\n/* harmony export */ \"setupAxiosMock\": () => (/* reexport safe */ _test_axios_js__WEBPACK_IMPORTED_MODULE_3__.setupAxiosMock),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sha256),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.sumUtxoValue),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.toTokenaddr),\n/* harmony export */ \"toUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__.toUtxoId),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_16__.utf8ToBin),\n/* harmony export */ \"walletClassMap\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.walletClassMap),\n/* harmony export */ \"walletFromId\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__.walletFromId)\n/* harmony export */ });\n/* harmony import */ var _db_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./db/index.js */ \"./src/db/index.ts\");\n/* harmony import */ var _mine_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mine/index.js */ \"./src/mine/index.ts\");\n/* harmony import */ var _test_expect_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./test/expect.js */ \"./src/test/expect.ts\");\n/* harmony import */ var _test_axios_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./test/axios.js */ \"./src/test/axios.ts\");\n/* harmony import */ var _webhook_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./webhook/index.js */ \"?6f8b\");\n/* harmony import */ var _webhook_index_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_webhook_index_js__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {};\n/* harmony reexport (unknown) */ for(const __WEBPACK_IMPORT_KEY__ in _webhook_index_js__WEBPACK_IMPORTED_MODULE_4__) if([\"default\",\"SignedMessage\",\"BaseWallet\",\"DefaultProvider\",\"Config\",\"NetworkType\",\"UnitEnum\",\"WalletTypeEnum\",\"Mainnet\",\"libauth\",\"CONST\",\"IndexedDBProvider\",\"SqlProvider\",\"mine\",\"expect\",\"removeAxiosMock\",\"setupAxiosMock\"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) __WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = () => _webhook_index_js__WEBPACK_IMPORTED_MODULE_4__[__WEBPACK_IMPORT_KEY__]\n/* harmony reexport (unknown) */ __webpack_require__.d(__webpack_exports__, __WEBPACK_REEXPORT_OBJECT__);\n/* harmony import */ var _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./wallet/Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./network/index.js */ \"./src/network/index.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _wallet_Base_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./wallet/Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./wallet/createWallet.js */ \"./src/wallet/createWallet.ts\");\n/* harmony import */ var _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./network/configuration.js */ \"./src/network/configuration.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./config.js */ \"./src/config.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./wallet/enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./util/index.js */ \"./src/util/index.ts\");\n/* harmony import */ var _libauth_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./libauth.js */ \"./src/libauth.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./interface.js */ \"./src/interface.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_5__, _network_index_js__WEBPACK_IMPORTED_MODULE_6__, _message_signed_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__, _enum_js__WEBPACK_IMPORTED_MODULE_13__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__, _util_index_js__WEBPACK_IMPORTED_MODULE_16__, _libauth_js__WEBPACK_IMPORTED_MODULE_17__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_18__]);\n([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_5__, _network_index_js__WEBPACK_IMPORTED_MODULE_6__, _message_signed_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_9__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_10__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_11__, _enum_js__WEBPACK_IMPORTED_MODULE_13__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_15__, _util_index_js__WEBPACK_IMPORTED_MODULE_16__, _libauth_js__WEBPACK_IMPORTED_MODULE_17__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_18__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n\n// provider\n\n// config\n\n// Enum\n\n\n// models\n\n// utils\n\n\n\n// libauth\n\n// qr\n\n// constants\n\n\n// interfaces\n\n// export function cube(x: number) {\n// return x * x * x;\n// }\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/index.ts?");
907
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BCMR\": () => (/* reexport safe */ _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__.BCMR),\n/* harmony export */ \"BalanceResponse\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.BalanceResponse),\n/* harmony export */ \"BaseWallet\": () => (/* reexport safe */ _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__.BaseWallet),\n/* harmony export */ \"CONST\": () => (/* reexport module object */ _constant_js__WEBPACK_IMPORTED_MODULE_18__),\n/* harmony export */ \"Config\": () => (/* reexport safe */ _config_js__WEBPACK_IMPORTED_MODULE_11__.Config),\n/* harmony export */ \"Connection\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.Connection),\n/* harmony export */ \"DefaultProvider\": () => (/* reexport safe */ _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__.DefaultProvider),\n/* harmony export */ \"ElectrumNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.ElectrumNetworkProvider),\n/* harmony export */ \"ExchangeRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.ExchangeRate),\n/* harmony export */ \"Mainnet\": () => (/* reexport module object */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__),\n/* harmony export */ \"NFTCapability\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_19__.NFTCapability),\n/* harmony export */ \"Network\": () => (/* reexport safe */ _interface_js__WEBPACK_IMPORTED_MODULE_19__.Network),\n/* harmony export */ \"NetworkType\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_12__.NetworkType),\n/* harmony export */ \"OpReturnData\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.OpReturnData),\n/* harmony export */ \"RegTestWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWallet),\n/* harmony export */ \"RegTestWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWatchWallet),\n/* harmony export */ \"RegTestWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.RegTestWifWallet),\n/* harmony export */ \"RuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.RuntimePlatform),\n/* harmony export */ \"SendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.SendRequest),\n/* harmony export */ \"SendResponse\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.SendResponse),\n/* harmony export */ \"SignedMessage\": () => (/* reexport safe */ _message_signed_js__WEBPACK_IMPORTED_MODULE_6__.SignedMessage),\n/* harmony export */ \"StorageProvider\": () => (/* reexport safe */ _db_index_js__WEBPACK_IMPORTED_MODULE_0__.StorageProvider),\n/* harmony export */ \"TestNetWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWallet),\n/* harmony export */ \"TestNetWatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWatchWallet),\n/* harmony export */ \"TestNetWifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.TestNetWifWallet),\n/* harmony export */ \"TokenBurnRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenBurnRequest),\n/* harmony export */ \"TokenGenesisRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenGenesisRequest),\n/* harmony export */ \"TokenMintRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenMintRequest),\n/* harmony export */ \"TokenSendRequest\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.TokenSendRequest),\n/* harmony export */ \"UnitEnum\": () => (/* reexport safe */ _enum_js__WEBPACK_IMPORTED_MODULE_12__.UnitEnum),\n/* harmony export */ \"Wallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.Wallet),\n/* harmony export */ \"WalletTypeEnum\": () => (/* reexport safe */ _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__.WalletTypeEnum),\n/* harmony export */ \"WatchWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.WatchWallet),\n/* harmony export */ \"WifWallet\": () => (/* reexport safe */ _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__.WifWallet),\n/* harmony export */ \"XPubKey\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.XPubKey),\n/* harmony export */ \"amountInSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.amountInSatoshi),\n/* harmony export */ \"asSendRequestObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.asSendRequestObject),\n/* harmony export */ \"atob\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.atob),\n/* harmony export */ \"balanceFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.balanceFromSatoshi),\n/* harmony export */ \"balanceResponseFromSatoshi\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.balanceResponseFromSatoshi),\n/* harmony export */ \"binToBase64\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.binToBase64),\n/* harmony export */ \"binToHex\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.binToHex),\n/* harmony export */ \"btoa\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.btoa),\n/* harmony export */ \"checkTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.checkTokenaddr),\n/* harmony export */ \"convert\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.convert),\n/* harmony export */ \"convertObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.convertObject),\n/* harmony export */ \"createWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.createWallet),\n/* harmony export */ \"createWalletResponse\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.createWalletResponse),\n/* harmony export */ \"delay\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.delay),\n/* harmony export */ \"deriveCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.deriveCashaddr),\n/* harmony export */ \"derivePublicKeyHash\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.derivePublicKeyHash),\n/* harmony export */ \"deriveTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.deriveTokenaddr),\n/* harmony export */ \"derivedNetwork\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.derivedNetwork),\n/* harmony export */ \"disconnectProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.disconnectProviders),\n/* harmony export */ \"expect\": () => (/* reexport safe */ _test_expect_js__WEBPACK_IMPORTED_MODULE_2__.expect),\n/* harmony export */ \"fromUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.fromUtxoId),\n/* harmony export */ \"getAddrsByXpubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getAddrsByXpubKey),\n/* harmony export */ \"getAddrsByXpubKeyObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getAddrsByXpubKeyObject),\n/* harmony export */ \"getNetworkProvider\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.getNetworkProvider),\n/* harmony export */ \"getRandomInt\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getRandomInt),\n/* harmony export */ \"getRuntimePlatform\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getRuntimePlatform),\n/* harmony export */ \"getUsdRate\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getUsdRate),\n/* harmony export */ \"getXPubKey\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXPubKey),\n/* harmony export */ \"getXpubKeyInfo\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXpubKeyInfo),\n/* harmony export */ \"getXpubKeyInfoObject\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.getXpubKeyInfoObject),\n/* harmony export */ \"hash160\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.hash160),\n/* harmony export */ \"hexToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.hexToBin),\n/* harmony export */ \"initProviders\": () => (/* reexport safe */ _network_index_js__WEBPACK_IMPORTED_MODULE_5__.initProviders),\n/* harmony export */ \"isTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.isTokenaddr),\n/* harmony export */ \"isValidAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.isValidAddress),\n/* harmony export */ \"libauth\": () => (/* reexport module object */ _libauth_js__WEBPACK_IMPORTED_MODULE_16__),\n/* harmony export */ \"mine\": () => (/* reexport safe */ _mine_index_js__WEBPACK_IMPORTED_MODULE_1__.mine),\n/* harmony export */ \"namedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.namedWallet),\n/* harmony export */ \"namedWalletExists\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.namedWalletExists),\n/* harmony export */ \"qrAddress\": () => (/* reexport safe */ _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__.qrAddress),\n/* harmony export */ \"randomValues\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.randomValues),\n/* harmony export */ \"removeAxiosMock\": () => (/* reexport safe */ _test_axios_js__WEBPACK_IMPORTED_MODULE_3__.removeAxiosMock),\n/* harmony export */ \"replaceNamedWallet\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.replaceNamedWallet),\n/* harmony export */ \"sanitizeAddress\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sanitizeAddress),\n/* harmony export */ \"sanitizeUnit\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sanitizeUnit),\n/* harmony export */ \"setupAxiosMock\": () => (/* reexport safe */ _test_axios_js__WEBPACK_IMPORTED_MODULE_3__.setupAxiosMock),\n/* harmony export */ \"sha256\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sha256),\n/* harmony export */ \"sumUtxoValue\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.sumUtxoValue),\n/* harmony export */ \"toCashaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.toCashaddr),\n/* harmony export */ \"toTokenaddr\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.toTokenaddr),\n/* harmony export */ \"toUtxoId\": () => (/* reexport safe */ _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__.toUtxoId),\n/* harmony export */ \"utf8ToBin\": () => (/* reexport safe */ _util_index_js__WEBPACK_IMPORTED_MODULE_15__.utf8ToBin),\n/* harmony export */ \"walletClassMap\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.walletClassMap),\n/* harmony export */ \"walletFromId\": () => (/* reexport safe */ _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__.walletFromId)\n/* harmony export */ });\n/* harmony import */ var _db_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./db/index.js */ \"./src/db/index.ts\");\n/* harmony import */ var _mine_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mine/index.js */ \"./src/mine/index.ts\");\n/* harmony import */ var _test_expect_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./test/expect.js */ \"./src/test/expect.ts\");\n/* harmony import */ var _test_axios_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./test/axios.js */ \"./src/test/axios.ts\");\n/* harmony import */ var _wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./wallet/Bcmr.js */ \"./src/wallet/Bcmr.ts\");\n/* harmony import */ var _network_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./network/index.js */ \"./src/network/index.ts\");\n/* harmony import */ var _message_signed_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./message/signed.js */ \"./src/message/signed.ts\");\n/* harmony import */ var _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./wallet/Base.js */ \"./src/wallet/Base.ts\");\n/* harmony import */ var _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./wallet/Wif.js */ \"./src/wallet/Wif.ts\");\n/* harmony import */ var _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./wallet/createWallet.js */ \"./src/wallet/createWallet.ts\");\n/* harmony import */ var _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./network/configuration.js */ \"./src/network/configuration.ts\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./config.js */ \"./src/config.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _wallet_enum_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./wallet/enum.js */ \"./src/wallet/enum.ts\");\n/* harmony import */ var _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./wallet/model.js */ \"./src/wallet/model.ts\");\n/* harmony import */ var _util_index_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./util/index.js */ \"./src/util/index.ts\");\n/* harmony import */ var _libauth_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./libauth.js */ \"./src/libauth.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _constant_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./constant.js */ \"./src/constant.ts\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./interface.js */ \"./src/interface.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__, _network_index_js__WEBPACK_IMPORTED_MODULE_5__, _message_signed_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__, _enum_js__WEBPACK_IMPORTED_MODULE_12__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__, _util_index_js__WEBPACK_IMPORTED_MODULE_15__, _libauth_js__WEBPACK_IMPORTED_MODULE_16__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__]);\n([_wallet_Bcmr_js__WEBPACK_IMPORTED_MODULE_4__, _network_index_js__WEBPACK_IMPORTED_MODULE_5__, _message_signed_js__WEBPACK_IMPORTED_MODULE_6__, _wallet_Base_js__WEBPACK_IMPORTED_MODULE_7__, _wallet_Wif_js__WEBPACK_IMPORTED_MODULE_8__, _wallet_createWallet_js__WEBPACK_IMPORTED_MODULE_9__, _network_configuration_js__WEBPACK_IMPORTED_MODULE_10__, _enum_js__WEBPACK_IMPORTED_MODULE_12__, _wallet_model_js__WEBPACK_IMPORTED_MODULE_14__, _util_index_js__WEBPACK_IMPORTED_MODULE_15__, _libauth_js__WEBPACK_IMPORTED_MODULE_16__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_17__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n\n\n\n\n\n// provider\n\n// config\n\n// Enum\n\n\n// models\n\n// utils\n\n\n\n// libauth\n\n// qr\n\n// constants\n\n\n// interfaces\n\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/index.ts?");
928
908
 
929
909
  /***/ }),
930
910
 
@@ -1404,7 +1384,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1404
1384
  \****************************/
1405
1385
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
1406
1386
 
1407
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BaseWallet\": () => (/* binding */ BaseWallet),\n/* harmony export */ \"getNamedWalletId\": () => (/* binding */ getNamedWalletId)\n/* harmony export */ });\n/* harmony import */ var _db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../db/getStorageProvider.js */ \"./src/db/getStorageProvider.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_enum_js__WEBPACK_IMPORTED_MODULE_0__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__]);\n([_enum_js__WEBPACK_IMPORTED_MODULE_0__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n/**\n * A class to hold features used by all wallets\n * @class BaseWallet\n */\nclass BaseWallet {\n //#endregion Accessors\n //#region Constructors and Statics\n /**\n * constructor for a new wallet\n * @param {string} name name of the wallet\n * @param network network for wallet\n *\n * @throws {Error} if called on BaseWallet\n */\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Seed) {\n this.derivationPath = \"m/44'/0'/0'/0/0\";\n this.parentDerivationPath = \"m/44'/0'/0'\";\n this.name = name;\n this.network = network;\n this.walletType = walletType;\n this.provider = this.getNetworkProvider(this.network);\n this.isTestnet = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet ? false : true;\n }\n //#region Accessors\n getNetworkProvider(\n // @ts-ignore\n network = _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet) {\n throw Error(\"getNetworkProvider called on base wallet\");\n }\n /**\n * getDepositAddress - get a wallet deposit address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositAddress|/wallet/deposit_address} for REST endpoint\n *\n * @returns The deposit address as a string\n */\n getDepositAddress() {\n return this.address;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * a high-level function\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositQr|/wallet/deposit_qr} for REST endpoint\n *\n * @returns The qrcode for the address\n */\n getDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__.qrAddress)(this.getDepositAddress());\n }\n // Get mnemonic and derivation path for wallet\n getSeed() {\n if (!this.mnemonic) {\n throw Error(\"Wallet mnemonic seed phrase not set\");\n }\n if (!this.derivationPath) {\n throw Error(\"Wallet derivation path not set\");\n }\n return {\n seed: this.mnemonic,\n derivationPath: this.derivationPath,\n parentDerivationPath: this.parentDerivationPath,\n };\n }\n /**\n * fromId - create a wallet from encoded walletId string\n *\n * @param walletId walletId options to steer the creation process\n *\n * @returns wallet instantiated accordingly to the walletId rules\n */\n static async fromId(walletId) {\n return new this().fromId(walletId);\n }\n /**\n * fromSeed - create a wallet using the seed phrase and derivation path\n *\n * unless specified the derivation path m/44'/245'/0'/0/0 will be userd\n * this derivation path is standard for Electron Cash SLP and other SLP enabled wallets\n *\n * @param seed BIP39 12 word seed phrase\n * @param derivationPath BIP44 HD wallet derivation path to get a single the private key from hierarchy\n *\n * @returns instantiated wallet\n */\n static async fromSeed(seed, derivationPath) {\n return new this().fromSeed(seed, derivationPath);\n }\n /**\n * newRandom - create a random wallet\n *\n * if `name` parameter is specified, the wallet will also be persisted to DB\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async newRandom(name = \"\", dbName) {\n return new this().newRandom(name, dbName);\n }\n /**\n * watchOnly - create a watch-only wallet\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress, token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async watchOnly(address) {\n return new this().watchOnly(address);\n }\n /**\n * named - create a named wallet\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n * @param force force recreate wallet in the database if a record already exist\n *\n * @returns instantiated wallet\n */\n static async named(name, dbName, force) {\n return new this().named(name, dbName, force);\n }\n /**\n * replaceNamed - replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async replaceNamed(name, walletId, dbName) {\n return new this().replaceNamed(name, walletId, dbName);\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n static async namedExists(name, dbName) {\n return new this().namedExists(name, dbName);\n }\n //#endregion Constructors\n //#region Protected implementations\n /**\n * generate creates a new wallet\n * @throws {Error} if called on BaseWallet\n */\n generate() {\n throw Error(\"generate called on base wallet\");\n }\n /**\n * fromId - creates a wallet from serialized string\n *\n * @throws {Error} if called on BaseWallet\n */\n fromId(walletId) {\n let [walletType, networkGiven, arg1, arg2] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n switch (walletType) {\n case \"watch\":\n if (arg2) {\n // watch:testnet:bchtest:qq1234567\n return this.watchOnly(`${arg1}:${arg2}`);\n }\n // watch:testnet:qq1234567\n return this.watchOnly(`${arg1}`);\n case \"named\":\n if (arg2) {\n // named:testnet:wallet_1:my_database\n return this.named(arg1, arg2);\n }\n else {\n // named:testnet:wallet_1\n return this.named(arg1);\n }\n case \"seed\":\n if (arg2) {\n // seed:testnet:table later ... stove kitten pluck:m/44'/0'/0'/0/0\n return this.fromSeed(arg1, arg2);\n }\n // seed:testnet:table later ... stove kitten pluck\n return this.fromSeed(arg1);\n default:\n throw Error(`Unknown wallet type '${walletType}'`);\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(\n // @ts-ignore\n mnemonic, \n // @ts-ignore\n derivationPath) {\n throw Error(\"fromSeed called on base wallet\");\n }\n /**\n * newRandom (internal) if the wallet is named, get or create it; otherwise create a random\n * unnamed wallet\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n */\n async newRandom(name, dbName) {\n if (name.length > 0) {\n return this.named(name, dbName);\n }\n else {\n return this.generate();\n }\n }\n // @ts-ignore\n async watchOnly(address) {\n throw Error(\"fromSeed called on base wallet\");\n }\n /**\n * named (internal) get a named wallet from the database or create a new one.\n * Note: this function should behave identically if\n *\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n * @param {boolean} forceNew attempt to overwrite an existing wallet\n *\n * @throws {Error} if forceNew is true and the wallet already exists\n * @returns a promise to a named wallet\n */\n async named(name, dbName, forceNew = false) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : this.network;\n let db = (0,_db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__.getStorageProvider)(dbName);\n // If there is a database, force saving or error\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n if (savedWalletRecord) {\n await db.close();\n if (forceNew) {\n throw Error(`A wallet with the name ${name} already exists in ${dbName}`);\n }\n let recoveredWallet = await this.fromId(savedWalletRecord.wallet);\n recoveredWallet.name = savedWalletRecord.name;\n return recoveredWallet;\n }\n else {\n let wallet = await this.generate();\n await db.addWallet(wallet.name, wallet.toDbString());\n await db.close();\n return wallet;\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * replaceNamed - Replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n async replaceNamed(name, walletId, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : this.network;\n let db = (0,_db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__.getStorageProvider)(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await this.fromId(walletId);\n if (savedWalletRecord) {\n await db.updateWallet(name, walletId);\n }\n else {\n await db.addWallet(name, walletId);\n }\n await db.close();\n return this;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n async namedExists(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n dbName = dbName ? dbName : this.network;\n let db = (0,_db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__.getStorageProvider)(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n return savedWalletRecord !== undefined;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n //#endregion Protected implementations\n //#region Serialization\n /**\n * toDbString - store the serialized version of the wallet in the database, not just the name\n *\n * @throws {Error} if called on BaseWallet\n */\n toDbString() {\n if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Watch) {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n return \"\";\n }\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n if (this.name) {\n return `named:${this.network}:${this.name}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Watch) {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n return \"\";\n }\n //#endregion Serialization\n //#region Funds\n // @ts-ignore\n async getBalance(rawUnit) {\n throw Error(\"sendMax called on base wallet\");\n }\n // @ts-ignore\n async getMaxAmountToSend(params) {\n throw Error(\"getMaxAmountToSend called on base wallet\");\n }\n // @ts-ignore\n async send(requests, options) {\n throw Error(\"send called on base wallet\");\n }\n // @ts-ignore\n async sendMax(address, options) {\n throw Error(\"sendMax called on base wallet\");\n }\n}\n/**\n * _checkContextSafety (internal) if running in nodejs, will disable saving\n * mainnet wallets on public servers if ALLOW_MAINNET_USER_WALLETS is set to false\n * @param {BaseWallet} wallet a wallet\n */\nconst _checkContextSafety = function (wallet) {\n if ((0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_4__.getRuntimePlatform)() === \"node\") {\n if (process.env.ALLOW_MAINNET_USER_WALLETS === `false`) {\n if (wallet.network === _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet) {\n throw Error(`Refusing to save wallet in an open public database, remove ALLOW_MAINNET_USER_WALLETS=\"false\", if this service is secure and private`);\n }\n }\n }\n};\n/**\n * getNamedWalletId - get the full wallet id from the database\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\nasync function getNamedWalletId(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n dbName = dbName ? dbName : dbName;\n let db = (0,_db_getStorageProvider_js__WEBPACK_IMPORTED_MODULE_3__.getStorageProvider)(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n if (savedWalletRecord !== undefined) {\n return savedWalletRecord.wallet;\n }\n else {\n throw Error(`No record was found for ${name} in db: ${dbName}`);\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Base.ts?");
1387
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BaseWallet\": () => (/* binding */ BaseWallet),\n/* harmony export */ \"getNamedWalletId\": () => (/* binding */ getNamedWalletId)\n/* harmony export */ });\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../enum.js */ \"./src/enum.ts\");\n/* harmony import */ var _util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/getRuntimePlatform.js */ \"./src/util/getRuntimePlatform.ts\");\n/* harmony import */ var _qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../qr/Qr.js */ \"./src/qr/Qr.ts\");\n/* harmony import */ var _enum_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./enum.js */ \"./src/wallet/enum.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_enum_js__WEBPACK_IMPORTED_MODULE_0__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__]);\n([_enum_js__WEBPACK_IMPORTED_MODULE_0__, _qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n/**\n * A class to hold features used by all wallets\n * @class BaseWallet\n */\nclass BaseWallet {\n //#endregion Accessors\n //#region Constructors and Statics\n /**\n * constructor for a new wallet\n * @param {string} name name of the wallet\n * @param network network for wallet\n *\n * @throws {Error} if called on BaseWallet\n */\n constructor(name = \"\", network = _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet, walletType = _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Seed) {\n this.derivationPath = \"m/44'/0'/0'/0/0\";\n this.parentDerivationPath = \"m/44'/0'/0'\";\n this.name = name;\n this.network = network;\n this.walletType = walletType;\n this.provider = this.getNetworkProvider(this.network);\n this.isTestnet = this.network === _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet ? false : true;\n }\n //#region Accessors\n getNetworkProvider(\n // @ts-ignore\n network = _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet) {\n throw Error(\"getNetworkProvider called on base wallet\");\n }\n /**\n * getDepositAddress - get a wallet deposit address\n *\n * a high-level function,\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositAddress|/wallet/deposit_address} for REST endpoint\n *\n * @returns The deposit address as a string\n */\n getDepositAddress() {\n return this.address;\n }\n /**\n * getDepositQr - get an address qrcode, encoded for display on the web\n *\n * a high-level function\n *\n * @see {@link https://rest-unstable.mainnet.cash/api-docs/#/wallet/depositQr|/wallet/deposit_qr} for REST endpoint\n *\n * @returns The qrcode for the address\n */\n getDepositQr() {\n return (0,_qr_Qr_js__WEBPACK_IMPORTED_MODULE_2__.qrAddress)(this.getDepositAddress());\n }\n // Get mnemonic and derivation path for wallet\n getSeed() {\n if (!this.mnemonic) {\n throw Error(\"Wallet mnemonic seed phrase not set\");\n }\n if (!this.derivationPath) {\n throw Error(\"Wallet derivation path not set\");\n }\n return {\n seed: this.mnemonic,\n derivationPath: this.derivationPath,\n parentDerivationPath: this.parentDerivationPath,\n };\n }\n /**\n * fromId - create a wallet from encoded walletId string\n *\n * @param walletId walletId options to steer the creation process\n *\n * @returns wallet instantiated accordingly to the walletId rules\n */\n static async fromId(walletId) {\n return new this().fromId(walletId);\n }\n /**\n * fromSeed - create a wallet using the seed phrase and derivation path\n *\n * unless specified the derivation path m/44'/245'/0'/0/0 will be userd\n * this derivation path is standard for Electron Cash SLP and other SLP enabled wallets\n *\n * @param seed BIP39 12 word seed phrase\n * @param derivationPath BIP44 HD wallet derivation path to get a single the private key from hierarchy\n *\n * @returns instantiated wallet\n */\n static async fromSeed(seed, derivationPath) {\n return new this().fromSeed(seed, derivationPath);\n }\n /**\n * newRandom - create a random wallet\n *\n * if `name` parameter is specified, the wallet will also be persisted to DB\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async newRandom(name = \"\", dbName) {\n return new this().newRandom(name, dbName);\n }\n /**\n * watchOnly - create a watch-only wallet\n *\n * such kind of wallet does not have a private key and is unable to spend any funds\n * however it still allows to use many utility functions such as getting and watching balance, etc.\n *\n * @param address cashaddress, token aware cashaddress of a wallet\n *\n * @returns instantiated wallet\n */\n static async watchOnly(address) {\n return new this().watchOnly(address);\n }\n /**\n * named - create a named wallet\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n * @param force force recreate wallet in the database if a record already exist\n *\n * @returns instantiated wallet\n */\n static async named(name, dbName, force) {\n return new this().named(name, dbName, force);\n }\n /**\n * replaceNamed - replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n static async replaceNamed(name, walletId, dbName) {\n return new this().replaceNamed(name, walletId, dbName);\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n static async namedExists(name, dbName) {\n return new this().namedExists(name, dbName);\n }\n //#endregion Constructors\n //#region Protected implementations\n /**\n * generate creates a new wallet\n * @throws {Error} if called on BaseWallet\n */\n generate() {\n throw Error(\"generate called on base wallet\");\n }\n /**\n * fromId - creates a wallet from serialized string\n *\n * @throws {Error} if called on BaseWallet\n */\n fromId(walletId) {\n let [walletType, networkGiven, arg1, arg2] = walletId.split(\":\");\n if (this.network != networkGiven) {\n throw Error(`Network prefix ${networkGiven} to a ${this.network} wallet`);\n }\n switch (walletType) {\n case \"watch\":\n if (arg2) {\n // watch:testnet:bchtest:qq1234567\n return this.watchOnly(`${arg1}:${arg2}`);\n }\n // watch:testnet:qq1234567\n return this.watchOnly(`${arg1}`);\n case \"named\":\n if (arg2) {\n // named:testnet:wallet_1:my_database\n return this.named(arg1, arg2);\n }\n else {\n // named:testnet:wallet_1\n return this.named(arg1);\n }\n case \"seed\":\n if (arg2) {\n // seed:testnet:table later ... stove kitten pluck:m/44'/0'/0'/0/0\n return this.fromSeed(arg1, arg2);\n }\n // seed:testnet:table later ... stove kitten pluck\n return this.fromSeed(arg1);\n default:\n throw Error(`Unknown wallet type '${walletType}'`);\n }\n }\n // Initialize wallet from a mnemonic phrase\n async fromSeed(\n // @ts-ignore\n mnemonic, \n // @ts-ignore\n derivationPath) {\n throw Error(\"fromSeed called on base wallet\");\n }\n /**\n * newRandom (internal) if the wallet is named, get or create it; otherwise create a random\n * unnamed wallet\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n */\n async newRandom(name, dbName) {\n if (name.length > 0) {\n return this.named(name, dbName);\n }\n else {\n return this.generate();\n }\n }\n // @ts-ignore\n async watchOnly(address) {\n throw Error(\"fromSeed called on base wallet\");\n }\n /**\n * named (internal) get a named wallet from the database or create a new one.\n * Note: this function should behave identically if\n *\n * @param {string} name name of the wallet\n * @param {string} dbName database name the wallet is stored in\n * @param {boolean} forceNew attempt to overwrite an existing wallet\n *\n * @throws {Error} if forceNew is true and the wallet already exists\n * @returns a promise to a named wallet\n */\n async named(name, dbName, forceNew = false) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : this.network;\n let db = getStorageProvider(dbName);\n // If there is a database, force saving or error\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n if (savedWalletRecord) {\n await db.close();\n if (forceNew) {\n throw Error(`A wallet with the name ${name} already exists in ${dbName}`);\n }\n let recoveredWallet = await this.fromId(savedWalletRecord.wallet);\n recoveredWallet.name = savedWalletRecord.name;\n return recoveredWallet;\n }\n else {\n let wallet = await this.generate();\n await db.addWallet(wallet.name, wallet.toDbString());\n await db.close();\n return wallet;\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * replaceNamed - Replace (recover) named wallet with a new walletId\n *\n * If wallet with a provided name does not exist yet, it will be created with a `walletId` supplied\n * If wallet exists it will be overwritten without exception\n *\n * @param name user friendly wallet alias\n * @param walletId walletId options to steer the creation process\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns instantiated wallet\n */\n async replaceNamed(name, walletId, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n this.name = name;\n dbName = dbName ? dbName : this.network;\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await this.fromId(walletId);\n if (savedWalletRecord) {\n await db.updateWallet(name, walletId);\n }\n else {\n await db.addWallet(name, walletId);\n }\n await db.close();\n return this;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n /**\n * namedExists - check if a named wallet already exists\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\n async namedExists(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n _checkContextSafety(this);\n dbName = dbName ? dbName : this.network;\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n return savedWalletRecord !== undefined;\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n }\n //#endregion Protected implementations\n //#region Serialization\n /**\n * toDbString - store the serialized version of the wallet in the database, not just the name\n *\n * @throws {Error} if called on BaseWallet\n */\n toDbString() {\n if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Watch) {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n return \"\";\n }\n // Returns the serialized wallet as a string\n // If storing in a database, set asNamed to false to store secrets\n // In all other cases, the a named wallet is deserialized from the database\n // by the name key\n toString() {\n if (this.name) {\n return `named:${this.network}:${this.name}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Seed) {\n return `${this.walletType}:${this.network}:${this.mnemonic}:${this.derivationPath}`;\n }\n else if (this.walletType == _enum_js__WEBPACK_IMPORTED_MODULE_1__.WalletTypeEnum.Watch) {\n return `${this.walletType}:${this.network}:${this.getDepositAddress()}`;\n }\n return \"\";\n }\n //#endregion Serialization\n //#region Funds\n // @ts-ignore\n async getBalance(rawUnit) {\n throw Error(\"sendMax called on base wallet\");\n }\n // @ts-ignore\n async getMaxAmountToSend(params) {\n throw Error(\"getMaxAmountToSend called on base wallet\");\n }\n // @ts-ignore\n async send(requests, options) {\n throw Error(\"send called on base wallet\");\n }\n // @ts-ignore\n async sendMax(address, options) {\n throw Error(\"sendMax called on base wallet\");\n }\n}\n/**\n * _checkContextSafety (internal) if running in nodejs, will disable saving\n * mainnet wallets on public servers if ALLOW_MAINNET_USER_WALLETS is set to false\n * @param {BaseWallet} wallet a wallet\n */\nconst _checkContextSafety = function (wallet) {\n if ((0,_util_getRuntimePlatform_js__WEBPACK_IMPORTED_MODULE_3__.getRuntimePlatform)() === \"node\") {\n if (process.env.ALLOW_MAINNET_USER_WALLETS === `false`) {\n if (wallet.network === _enum_js__WEBPACK_IMPORTED_MODULE_0__.NetworkType.Mainnet) {\n throw Error(`Refusing to save wallet in an open public database, remove ALLOW_MAINNET_USER_WALLETS=\"false\", if this service is secure and private`);\n }\n }\n }\n};\n/**\n * getNamedWalletId - get the full wallet id from the database\n *\n * @param name user friendly wallet alias\n * @param dbName name under which the wallet will be stored in the database\n *\n * @returns boolean\n */\nasync function getNamedWalletId(name, dbName) {\n if (name.length === 0) {\n throw Error(\"Named wallets must have a non-empty name\");\n }\n dbName = dbName ? dbName : dbName;\n let db = getStorageProvider(dbName);\n if (db) {\n await db.init();\n let savedWalletRecord = await db.getWallet(name);\n await db.close();\n if (savedWalletRecord !== undefined) {\n return savedWalletRecord.wallet;\n }\n else {\n throw Error(`No record was found for ${name} in db: ${dbName}`);\n }\n }\n else {\n throw Error(\"No database was available or configured to store the named wallet.\");\n }\n}\nfunction getStorageProvider(dbName) {\n if (!BaseWallet.StorageProvider) {\n return undefined;\n }\n return new BaseWallet.StorageProvider(dbName);\n}\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Base.ts?");
1408
1388
 
1409
1389
  /***/ }),
1410
1390
 
@@ -1414,7 +1394,7 @@ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__
1414
1394
  \****************************/
1415
1395
  /***/ ((module, __webpack_exports__, __webpack_require__) => {
1416
1396
 
1417
- eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BCMR\": () => (/* binding */ BCMR)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"../../node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _network_Connection_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../network/Connection.js */ \"./src/network/Connection.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__, _model_js__WEBPACK_IMPORTED_MODULE_4__, _network_Connection_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__, _model_js__WEBPACK_IMPORTED_MODULE_4__, _network_Connection_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n// Implementation of CHIP-BCMR v2.0.0-draft, refer to https://github.com/bitjson/chip-bcmr\nclass BCMR {\n static getRegistries() {\n return this.metadataRegistries;\n }\n static resetRegistries() {\n this.metadataRegistries = [];\n }\n /**\n * fetchMetadataRegistry Fetch the BCMR registry JSON file from a remote URI, optionally verifying its content hash\n *\n * @param {string} uri URI of the registry to fetch from\n * @param {string?} contentHash SHA256 hash of the resource the `uri` parameter points at.\n * If specified, calculates the hash of the data fetched from `uri` and matches it with provided one.\n * Yields an error upon mismatch.\n *\n * @returns {Registry} resolved registry\n */\n static async fetchMetadataRegistry(uri, contentHash) {\n if (uri.indexOf(\"https://\") < 0) {\n uri = `https://${uri}`;\n }\n // content hashes HTTPS Publication Outputs per spec\n if (contentHash) {\n // request as text and verify hash\n const response = await axios__WEBPACK_IMPORTED_MODULE_0___default().get(uri, {\n responseType: \"text\",\n transformResponse: (val) => {\n return val;\n },\n });\n const hash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.utf8ToBin)(response.data)));\n if (contentHash != hash) {\n throw new Error(`Content hash mismatch for URI: ${uri}\\nreceived: ${hash}\\nrequired: ${contentHash}`);\n }\n return JSON.parse(response.data);\n }\n // request as JSON\n const response = await axios__WEBPACK_IMPORTED_MODULE_0___default().get(uri);\n return response.data;\n }\n /**\n * addMetadataRegistry Add the metadata registry to the list of tracked registries\n *\n * @param {Registry} registry Registry object per schema specification, see https://raw.githubusercontent.com/bitjson/chip-bcmr/master/bcmr-v1.schema.json\n *\n */\n static addMetadataRegistry(registry) {\n if (this.metadataRegistries.some((val) => JSON.stringify(val) === JSON.stringify(registry))) {\n return;\n }\n this.metadataRegistries.push(registry);\n }\n /**\n * addMetadataRegistryFromUri Add the metadata registry by fetching a JSON file from a remote URI, optionally verifying its content hash\n *\n * @param {string} uri URI of the registry to fetch from\n * @param {string?} contentHash SHA256 hash of the resource the `uri` parameter points at.\n * If specified, calculates the hash of the data fetched from `uri` and matches it with provided one.\n * Yields an error upon mismatch.\n *\n */\n static async addMetadataRegistryFromUri(uri, contentHash) {\n const registry = await this.fetchMetadataRegistry(uri, contentHash);\n this.addMetadataRegistry(registry);\n }\n // helper function to enforce the constraints on the 0th output, decode the BCMR's OP_RETURN data\n // returns resolved AuthChainElement\n static makeAuthChainElement(rawTx, hash) {\n let opReturns;\n let spends0thOutput = false;\n if (rawTx.hasOwnProperty(\"vout\")) {\n const electrumTransaction = rawTx;\n opReturns = electrumTransaction.vout\n .filter((val) => val.scriptPubKey.type === \"nulldata\")\n .map((val) => val.scriptPubKey.hex);\n spends0thOutput = electrumTransaction.vin.some((val) => val.vout === 0);\n }\n else {\n const libauthTransaction = rawTx;\n opReturns = libauthTransaction.outputs\n .map((val) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(val.lockingBytecode))\n .filter((val) => val.indexOf(\"6a\") === 0);\n spends0thOutput = libauthTransaction.inputs.some((val) => val.outpointIndex === 0);\n }\n if (!spends0thOutput) {\n throw new Error(\"Invalid authchain transaction (does not spend 0th output of previous transaction)\");\n }\n const bcmrOpReturns = opReturns.filter((val) => val.indexOf(\"6a0442434d52\") === 0 ||\n val.indexOf(\"6a4c0442434d52\") === 0 ||\n val.indexOf(\"6a4d040042434d52\") === 0 ||\n val.indexOf(\"6a4e0400000042434d52\") === 0);\n if (bcmrOpReturns.length === 0) {\n return {\n txHash: hash,\n contentHash: \"\",\n uris: [],\n httpsUrl: \"\",\n };\n }\n const opReturnHex = opReturns[0];\n const chunks = _model_js__WEBPACK_IMPORTED_MODULE_4__.OpReturnData.parseBinary((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(opReturnHex));\n if (chunks.length < 2) {\n throw new Error(`Malformed BCMR output: ${opReturnHex}`);\n }\n const result = {\n txHash: hash,\n contentHash: \"\",\n uris: [],\n httpsUrl: \"\",\n };\n if (chunks.length === 2) {\n // IPFS Publication Output\n result.contentHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(chunks[1]);\n const ipfsCid = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToUtf8)(chunks[1]);\n result.uris = [`ipfs://${ipfsCid}`];\n result.httpsUrl = `https://dweb.link/ipfs/${ipfsCid}`;\n }\n else {\n // URI Publication Output\n // content hash is in OP_SHA256 byte order per spec\n result.contentHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(chunks[1].slice());\n const uris = chunks.slice(2);\n for (const uri of uris) {\n const uriString = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToUtf8)(uri);\n result.uris.push(uriString);\n if (result.httpsUrl) {\n continue;\n }\n if (uriString.indexOf(\"ipfs://\") === 0) {\n const ipfsCid = uriString.replace(\"ipfs://\", \"\");\n result.httpsUrl = `https://dweb.link/ipfs/${ipfsCid}`;\n }\n else if (uriString.indexOf(\"https://\") === 0) {\n result.httpsUrl = uriString;\n }\n else if (uriString.indexOf(\"https://\") === -1) {\n result.httpsUrl = uriString;\n // case for domain name specifier, like example.com\n if (uriString.indexOf(\"/\") === -1) {\n const parts = uriString.toLowerCase().split(\".\");\n if (!(parts?.[0]?.indexOf(\"baf\") === 0 && parts?.[1] === \"ipfs\")) {\n result.httpsUrl = `${result.httpsUrl}/.well-known/bitcoin-cash-metadata-registry.json`;\n }\n }\n result.httpsUrl = `https://${result.httpsUrl}`;\n }\n else {\n throw new Error(`Unsupported uri type: ${uriString}`);\n }\n }\n }\n return result;\n }\n /**\n * buildAuthChain Build an authchain - Zeroth-Descendant Transaction Chain, refer to https://github.com/bitjson/chip-bcmr#zeroth-descendant-transaction-chains\n * The authchain in this implementation is specific to resolve to a valid metadata registry\n *\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {Network?} options.network (default=mainnet) network to query the data from\n * @param {boolean?} options.resolveBase (default=false) boolean flag to indicate that autchain building should resolve and verify elements back to base or be stopped at this exact chain element\n * @param {boolean?} options.followToHead (default=true) boolean flag to indicate that autchain building should progress to head or be stopped at this exact chain element\n * @param {ElectrumRawTransaction?} options.rawTx cached raw transaction obtained previously, spares a Fulcrum call\n * @param {TxI[]?} options.historyCache cached address history to be reused if authchain building proceeds with the same address, spares a flurry of Fulcrum calls\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async buildAuthChain(options) {\n if (options.network === undefined) {\n options.network = _interface_js__WEBPACK_IMPORTED_MODULE_5__.Network.MAINNET;\n }\n if (options.followToHead === undefined) {\n options.followToHead = true;\n }\n if (options.resolveBase === undefined) {\n options.resolveBase = false;\n }\n const provider = (await (0,_network_Connection_js__WEBPACK_IMPORTED_MODULE_6__.initProvider)(options.network));\n if (options.rawTx === undefined) {\n options.rawTx = await provider.getRawTransactionObject(options.transactionHash);\n }\n // figure out the autchain by moving towards authhead\n const getAuthChainChild = async () => {\n const history = options.historyCache ||\n (await provider.getHistory(options.rawTx.vout[0].scriptPubKey.addresses[0]));\n const thisTx = history.find((val) => val.tx_hash === options.transactionHash);\n let filteredHistory = history.filter((val) => val.height > 0\n ? val.height >= thisTx.height || val.height <= 0\n : val.height <= 0 && val.tx_hash !== thisTx.tx_hash);\n for (const historyTx of filteredHistory) {\n const historyRawTx = await provider.getRawTransactionObject(historyTx.tx_hash);\n const authChainVin = historyRawTx.vin.find((val) => val.txid === options.transactionHash && val.vout === 0);\n // if we've found continuation of authchain, we shall recurse into it\n if (authChainVin) {\n // reuse queried address history if the next element in chain is the same address\n const historyCache = options.rawTx.vout[0].scriptPubKey.addresses[0] ===\n historyRawTx.vout[0].scriptPubKey.addresses[0]\n ? filteredHistory\n : undefined;\n // combine the authchain element with the rest obtained\n return { rawTx: historyRawTx, historyCache };\n }\n }\n return undefined;\n };\n // make authchain element and combine with the rest obtained\n let element;\n try {\n element = BCMR.makeAuthChainElement(options.rawTx, options.rawTx.hash);\n }\n catch (error) {\n // special case for cashtoken authchain lookup by categoryId - allow to fail first lookup and inspect the genesis transaction\n // follow authchain to head and look for BCMR outputs\n const child = await getAuthChainChild();\n if (child) {\n return await BCMR.buildAuthChain({\n ...options,\n transactionHash: child.rawTx.hash,\n rawTx: child.rawTx,\n historyCache: child.historyCache,\n });\n }\n else {\n throw error;\n }\n }\n let chainBase = [];\n if (options.resolveBase) {\n // check for accelerated path if \"authchain\" extension is in registry\n const registry = await this.fetchMetadataRegistry(element.httpsUrl, element.contentHash);\n if (registry.extensions &&\n registry.extensions[\"authchain\"] &&\n Object.keys(registry.extensions[\"authchain\"]).length) {\n const chainTxArray = Object.values(registry.extensions[\"authchain\"]);\n chainBase = chainTxArray\n .map((tx) => {\n const transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(tx);\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.decodeTransaction)(transactionBin);\n if (typeof decoded === \"string\") {\n throw new Error(`Error decoding transaction ${JSON.stringify(tx)}, ${decoded}`);\n }\n const hash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash(transactionBin)).reverse());\n return { decoded, hash };\n })\n .map(({ decoded, hash }) => BCMR.makeAuthChainElement(decoded, hash));\n }\n else {\n // simply go back in history towards authhead\n let stop = false;\n let tx = { ...options.rawTx };\n let maxElements = 10;\n while (stop == false || maxElements === 0) {\n const vin = tx.vin.find((val) => val.vout === 0);\n tx = await provider.getRawTransactionObject(vin.txid);\n try {\n const pastElement = BCMR.makeAuthChainElement(tx, tx.hash);\n chainBase.unshift(pastElement);\n maxElements--;\n }\n catch {\n stop = true;\n }\n }\n }\n }\n // if we follow to head, we need to locate the next transaction spending our 0th output\n // and repeat the building process recursively\n if (options.followToHead) {\n const child = await getAuthChainChild();\n if (child) {\n const chainHead = await BCMR.buildAuthChain({\n transactionHash: child.rawTx.hash,\n network: options.network,\n rawTx: child.rawTx,\n historyCache: child.historyCache,\n followToHead: options.followToHead,\n resolveBase: false,\n });\n // combine the authchain element with the rest obtained\n return [...chainBase, element, ...chainHead].filter((val) => val.httpsUrl.length);\n }\n }\n // return the last chain element (or the only found in an edge case)\n return [...chainBase, element].filter((val) => val.httpsUrl.length);\n }\n /**\n * fetchAuthChainFromChaingraph Fetch the authchain information from a trusted external indexer\n * The authchain in this implementation is specific to resolve to a valid metadata registry\n *\n * @param {string} options.chaingraphUrl (required) URL of a chaingraph indexer instance to fetch info from\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {string?} options.network (default=undefined) network to query the data from, specific to the queried instance,\n * can be 'mainnet', 'chipnet', or anything else.\n * if left undefined all chaingraph transactions will be looked at, disregarding the chain\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async fetchAuthChainFromChaingraph(options) {\n if (!options.chaingraphUrl) {\n throw new Error(\"Provide `chaingraphUrl` param.\");\n }\n const response = await axios__WEBPACK_IMPORTED_MODULE_0___default().post(options.chaingraphUrl, {\n operationName: null,\n variables: {},\n query: `\n{\n transaction(\n where: {\n hash:{_eq:\"\\\\\\\\x${options.transactionHash}\"},\n ${options.network ? `node_validation_timeline:{node:{name:{_ilike:\"%${options.network}%\"}}}` : \"\"}\n }\n ) {\n hash\n authchains {\n authchain_length\n migrations(\n where: {\n transaction: {\n outputs: { locking_bytecode_pattern: { _like: \"6a04%\" } }\n }\n }\n ) {\n transaction {\n hash\n inputs(where:{ outpoint_index: { _eq:\"0\" } }){\n outpoint_index\n }\n outputs(where: { locking_bytecode_pattern: { _like: \"6a04%\" } }) {\n output_index\n locking_bytecode\n }\n }\n }\n }\n }\n}`,\n }, {\n responseType: \"json\",\n headers: {\n Accept: \"*/*\",\n \"Content-Type\": \"application/json\",\n },\n });\n const result = [];\n const migrations = response.data.data.transaction[0]?.authchains[0].migrations;\n if (!migrations) {\n return result;\n }\n for (const migration of migrations) {\n const transaction = migration.transaction[0];\n if (!transaction) {\n continue;\n }\n transaction.inputs.forEach((input) => (input.outpointIndex = Number(input.outpoint_index)));\n transaction.outputs.forEach((output) => {\n output.outputIndex = Number(output.output_index);\n output.lockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(output.locking_bytecode.replace(\"\\\\x\", \"\"));\n });\n const txHash = transaction.hash.replace(\"\\\\x\", \"\");\n result.push(BCMR.makeAuthChainElement(transaction, txHash));\n }\n return result.filter((element) => element.contentHash.length && element.httpsUrl.length);\n }\n /**\n * addMetadataRegistryAuthChain Add BCMR metadata registry by resolving an authchain\n *\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {Network?} options.network (default=mainnet) network to query the data from\n * @param {boolean?} options.followToHead (default=true) boolean flag to indicate that autchain building should progress to head (most recent registry version) or be stopped at this exact chain element\n * @param {ElectrumRawTransaction?} options.rawTx cached raw transaction obtained previously, spares a Fulcrum call\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async addMetadataRegistryAuthChain(options) {\n const authChain = await this.buildAuthChain({\n ...options,\n resolveBase: false,\n });\n if (!authChain.length) {\n throw new Error(`There were no BCMR entries in the resolved authchain ${JSON.stringify(authChain, null, 2)}`);\n }\n const registry = await this.fetchMetadataRegistry(authChain.reverse()[0].httpsUrl);\n this.addMetadataRegistry(registry);\n return authChain;\n }\n /**\n * getTokenInfo Return the token info (or the identity snapshot as per spec)\n *\n * @param {string} tokenId token id to look up\n *\n * @returns {IdentitySnapshot?} return the info for the token found, otherwise undefined\n */\n static getTokenInfo(tokenId) {\n for (const registry of this.metadataRegistries.slice().reverse()) {\n const history = registry.identities?.[tokenId];\n if (!history) {\n continue;\n }\n const latestIdentityIndex = Object.keys(history)[0];\n if (latestIdentityIndex === undefined) {\n continue;\n }\n return history[latestIdentityIndex];\n }\n return undefined;\n }\n}\n// List of tracked registries\nBCMR.metadataRegistries = [];\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Bcmr.ts?");
1397
+ eval("__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"BCMR\": () => (/* binding */ BCMR)\n/* harmony export */ });\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/hex.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/crypto/default-crypto-instances.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/format/utf8.js\");\n/* harmony import */ var _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @bitauth/libauth */ \"../../node_modules/@bitauth/libauth/build/lib/message/transaction-encoding.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"../../node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../interface.js */ \"./src/interface.ts\");\n/* harmony import */ var _network_Connection_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../network/Connection.js */ \"./src/network/Connection.ts\");\n/* harmony import */ var _model_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./model.js */ \"./src/wallet/model.ts\");\nvar __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__, _model_js__WEBPACK_IMPORTED_MODULE_4__, _network_Connection_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__]);\n([_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__, _model_js__WEBPACK_IMPORTED_MODULE_4__, _network_Connection_js__WEBPACK_IMPORTED_MODULE_6__, _bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);\n\n\n\n\n\n// Implementation of CHIP-BCMR v2.0.0-draft, refer to https://github.com/bitjson/chip-bcmr\nclass BCMR {\n static getRegistries() {\n return this.metadataRegistries;\n }\n static resetRegistries() {\n this.metadataRegistries = [];\n }\n /**\n * fetchMetadataRegistry Fetch the BCMR registry JSON file from a remote URI, optionally verifying its content hash\n *\n * @param {string} uri URI of the registry to fetch from\n * @param {string?} contentHash SHA256 hash of the resource the `uri` parameter points at.\n * If specified, calculates the hash of the data fetched from `uri` and matches it with provided one.\n * Yields an error upon mismatch.\n *\n * @returns {Registry} resolved registry\n */\n static async fetchMetadataRegistry(uri, contentHash) {\n if (uri.indexOf(\"https://\") < 0) {\n uri = `https://${uri}`;\n }\n // content hashes HTTPS Publication Outputs per spec\n if (contentHash) {\n // request as text and verify hash\n const response = await axios__WEBPACK_IMPORTED_MODULE_0___default().get(uri, {\n responseType: \"text\",\n transformResponse: (val) => {\n return val;\n },\n });\n const hash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.utf8ToBin)(response.data)));\n if (contentHash != hash) {\n throw new Error(`Content hash mismatch for URI: ${uri}\\nreceived: ${hash}\\nrequired: ${contentHash}`);\n }\n return JSON.parse(response.data);\n }\n // request as JSON\n const response = await axios__WEBPACK_IMPORTED_MODULE_0___default().get(uri);\n return response.data;\n }\n /**\n * addMetadataRegistry Add the metadata registry to the list of tracked registries\n *\n * @param {Registry} registry Registry object per schema specification, see https://raw.githubusercontent.com/bitjson/chip-bcmr/master/bcmr-v1.schema.json\n *\n */\n static addMetadataRegistry(registry) {\n if (this.metadataRegistries.some((val) => JSON.stringify(val) === JSON.stringify(registry))) {\n return;\n }\n this.metadataRegistries.push(registry);\n }\n /**\n * addMetadataRegistryFromUri Add the metadata registry by fetching a JSON file from a remote URI, optionally verifying its content hash\n *\n * @param {string} uri URI of the registry to fetch from\n * @param {string?} contentHash SHA256 hash of the resource the `uri` parameter points at.\n * If specified, calculates the hash of the data fetched from `uri` and matches it with provided one.\n * Yields an error upon mismatch.\n *\n */\n static async addMetadataRegistryFromUri(uri, contentHash) {\n const registry = await this.fetchMetadataRegistry(uri, contentHash);\n this.addMetadataRegistry(registry);\n }\n // helper function to enforce the constraints on the 0th output, decode the BCMR's OP_RETURN data\n // returns resolved AuthChainElement\n static makeAuthChainElement(rawTx, hash) {\n let opReturns;\n let spends0thOutput = false;\n if (rawTx.hasOwnProperty(\"vout\")) {\n const electrumTransaction = rawTx;\n opReturns = electrumTransaction.vout\n .filter((val) => val.scriptPubKey.type === \"nulldata\")\n .map((val) => val.scriptPubKey.hex);\n spends0thOutput = electrumTransaction.vin.some((val) => val.vout === 0);\n }\n else {\n const libauthTransaction = rawTx;\n opReturns = libauthTransaction.outputs\n .map((val) => (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(val.lockingBytecode))\n .filter((val) => val.indexOf(\"6a\") === 0);\n spends0thOutput = libauthTransaction.inputs.some((val) => val.outpointIndex === 0);\n }\n if (!spends0thOutput) {\n throw new Error(\"Invalid authchain transaction (does not spend 0th output of previous transaction)\");\n }\n const bcmrOpReturns = opReturns.filter((val) => val.indexOf(\"6a0442434d52\") === 0 ||\n val.indexOf(\"6a4c0442434d52\") === 0 ||\n val.indexOf(\"6a4d040042434d52\") === 0 ||\n val.indexOf(\"6a4e0400000042434d52\") === 0);\n if (bcmrOpReturns.length === 0) {\n return {\n txHash: hash,\n contentHash: \"\",\n uris: [],\n httpsUrl: \"\",\n };\n }\n const opReturnHex = opReturns[0];\n const chunks = _model_js__WEBPACK_IMPORTED_MODULE_4__.OpReturnData.parseBinary((0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(opReturnHex));\n if (chunks.length < 2) {\n throw new Error(`Malformed BCMR output: ${opReturnHex}`);\n }\n const result = {\n txHash: hash,\n contentHash: \"\",\n uris: [],\n httpsUrl: \"\",\n };\n if (chunks.length === 2) {\n // IPFS Publication Output\n result.contentHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(chunks[1]);\n const ipfsCid = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToUtf8)(chunks[1]);\n result.uris = [`ipfs://${ipfsCid}`];\n result.httpsUrl = `https://dweb.link/ipfs/${ipfsCid}`;\n }\n else {\n // URI Publication Output\n // content hash is in OP_SHA256 byte order per spec\n result.contentHash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(chunks[1].slice());\n const uris = chunks.slice(2);\n for (const uri of uris) {\n const uriString = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_3__.binToUtf8)(uri);\n result.uris.push(uriString);\n if (result.httpsUrl) {\n continue;\n }\n if (uriString.indexOf(\"ipfs://\") === 0) {\n const ipfsCid = uriString.replace(\"ipfs://\", \"\");\n result.httpsUrl = `https://dweb.link/ipfs/${ipfsCid}`;\n }\n else if (uriString.indexOf(\"https://\") === 0) {\n result.httpsUrl = uriString;\n }\n else if (uriString.indexOf(\"https://\") === -1) {\n result.httpsUrl = uriString;\n // case for domain name specifier, like example.com\n if (uriString.indexOf(\"/\") === -1) {\n const parts = uriString.toLowerCase().split(\".\");\n if (!(parts?.[0]?.indexOf(\"baf\") === 0 && parts?.[1] === \"ipfs\")) {\n result.httpsUrl = `${result.httpsUrl}/.well-known/bitcoin-cash-metadata-registry.json`;\n }\n }\n result.httpsUrl = `https://${result.httpsUrl}`;\n }\n else {\n throw new Error(`Unsupported uri type: ${uriString}`);\n }\n }\n }\n return result;\n }\n /**\n * buildAuthChain Build an authchain - Zeroth-Descendant Transaction Chain, refer to https://github.com/bitjson/chip-bcmr#zeroth-descendant-transaction-chains\n * The authchain in this implementation is specific to resolve to a valid metadata registry\n *\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {Network?} options.network (default=mainnet) network to query the data from\n * @param {boolean?} options.resolveBase (default=false) boolean flag to indicate that autchain building should resolve and verify elements back to base or be stopped at this exact chain element\n * @param {boolean?} options.followToHead (default=true) boolean flag to indicate that autchain building should progress to head or be stopped at this exact chain element\n * @param {ElectrumRawTransaction?} options.rawTx cached raw transaction obtained previously, spares a Fulcrum call\n * @param {TxI[]?} options.historyCache cached address history to be reused if authchain building proceeds with the same address, spares a flurry of Fulcrum calls\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async buildAuthChain(options) {\n if (options.network === undefined) {\n options.network = _interface_js__WEBPACK_IMPORTED_MODULE_5__.Network.MAINNET;\n }\n if (options.followToHead === undefined) {\n options.followToHead = true;\n }\n if (options.resolveBase === undefined) {\n options.resolveBase = false;\n }\n const provider = (await (0,_network_Connection_js__WEBPACK_IMPORTED_MODULE_6__.initProvider)(options.network));\n if (options.rawTx === undefined) {\n options.rawTx = await provider.getRawTransactionObject(options.transactionHash);\n }\n // figure out the autchain by moving towards authhead\n const getAuthChainChild = async () => {\n const history = options.historyCache ||\n (await provider.getHistory(options.rawTx.vout[0].scriptPubKey.addresses[0]));\n const thisTx = history.find((val) => val.tx_hash === options.transactionHash);\n let filteredHistory = history.filter((val) => val.height > 0\n ? val.height >= thisTx.height || val.height <= 0\n : val.height <= 0 && val.tx_hash !== thisTx.tx_hash);\n for (const historyTx of filteredHistory) {\n const historyRawTx = await provider.getRawTransactionObject(historyTx.tx_hash);\n const authChainVin = historyRawTx.vin.find((val) => val.txid === options.transactionHash && val.vout === 0);\n // if we've found continuation of authchain, we shall recurse into it\n if (authChainVin) {\n // reuse queried address history if the next element in chain is the same address\n const historyCache = options.rawTx.vout[0].scriptPubKey.addresses[0] ===\n historyRawTx.vout[0].scriptPubKey.addresses[0]\n ? filteredHistory\n : undefined;\n // combine the authchain element with the rest obtained\n return { rawTx: historyRawTx, historyCache };\n }\n }\n return undefined;\n };\n // make authchain element and combine with the rest obtained\n let element;\n try {\n element = BCMR.makeAuthChainElement(options.rawTx, options.rawTx.hash);\n }\n catch (error) {\n // special case for cashtoken authchain lookup by categoryId - allow to fail first lookup and inspect the genesis transaction\n // follow authchain to head and look for BCMR outputs\n const child = await getAuthChainChild();\n if (child) {\n return await BCMR.buildAuthChain({\n ...options,\n transactionHash: child.rawTx.hash,\n rawTx: child.rawTx,\n historyCache: child.historyCache,\n });\n }\n else {\n throw error;\n }\n }\n let chainBase = [];\n if (options.resolveBase) {\n // check for accelerated path if \"authchain\" extension is in registry\n const registry = await this.fetchMetadataRegistry(element.httpsUrl, element.contentHash);\n if (registry.extensions &&\n registry.extensions[\"authchain\"] &&\n Object.keys(registry.extensions[\"authchain\"]).length) {\n const chainTxArray = Object.values(registry.extensions[\"authchain\"]);\n chainBase = chainTxArray\n .map((tx) => {\n const transactionBin = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(tx);\n const decoded = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_7__.decodeTransaction)(transactionBin);\n if (typeof decoded === \"string\") {\n throw new Error(`Error decoding transaction ${JSON.stringify(tx)}, ${decoded}`);\n }\n const hash = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.binToHex)(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash(_bitauth_libauth__WEBPACK_IMPORTED_MODULE_2__.sha256.hash(transactionBin)).reverse());\n return { decoded, hash };\n })\n .map(({ decoded, hash }) => BCMR.makeAuthChainElement(decoded, hash));\n }\n else {\n // simply go back in history towards authhead\n let stop = false;\n let tx = { ...options.rawTx };\n let maxElements = 10;\n while (stop == false || maxElements === 0) {\n const vin = tx.vin.find((val) => val.vout === 0);\n tx = await provider.getRawTransactionObject(vin.txid);\n try {\n const pastElement = BCMR.makeAuthChainElement(tx, tx.hash);\n chainBase.unshift(pastElement);\n maxElements--;\n }\n catch {\n stop = true;\n }\n }\n }\n }\n // if we follow to head, we need to locate the next transaction spending our 0th output\n // and repeat the building process recursively\n if (options.followToHead) {\n const child = await getAuthChainChild();\n if (child) {\n const chainHead = await BCMR.buildAuthChain({\n transactionHash: child.rawTx.hash,\n network: options.network,\n rawTx: child.rawTx,\n historyCache: child.historyCache,\n followToHead: options.followToHead,\n resolveBase: false,\n });\n // combine the authchain element with the rest obtained\n return [...chainBase, element, ...chainHead].filter((val) => val.httpsUrl.length);\n }\n }\n // return the last chain element (or the only found in an edge case)\n return [...chainBase, element].filter((val) => val.httpsUrl.length);\n }\n /**\n * fetchAuthChainFromChaingraph Fetch the authchain information from a trusted external indexer\n * The authchain in this implementation is specific to resolve to a valid metadata registry\n *\n * @param {string} options.chaingraphUrl (required) URL of a chaingraph indexer instance to fetch info from\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {string?} options.network (default=undefined) network to query the data from, specific to the queried instance,\n * can be 'mainnet', 'chipnet', or anything else.\n * if left undefined all chaingraph transactions will be looked at, disregarding the chain\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async fetchAuthChainFromChaingraph(options) {\n if (!options.chaingraphUrl) {\n throw new Error(\"Provide `chaingraphUrl` param.\");\n }\n const response = await axios__WEBPACK_IMPORTED_MODULE_0___default().post(options.chaingraphUrl, {\n operationName: null,\n variables: {},\n query: `\n{\n transaction(\n where: {\n hash:{_eq:\"\\\\\\\\x${options.transactionHash}\"},\n ${options.network\n ? `node_validation_timeline:{node:{name:{_ilike:\"%${options.network}%\"}}}`\n : \"\"}\n }\n ) {\n hash\n authchains {\n authchain_length\n migrations(\n where: {\n transaction: {\n outputs: { locking_bytecode_pattern: { _like: \"6a04%\" } }\n }\n }\n ) {\n transaction {\n hash\n inputs(where:{ outpoint_index: { _eq:\"0\" } }){\n outpoint_index\n }\n outputs(where: { locking_bytecode_pattern: { _like: \"6a04%\" } }) {\n output_index\n locking_bytecode\n }\n }\n }\n }\n }\n}`,\n }, {\n responseType: \"json\",\n headers: {\n Accept: \"*/*\",\n \"Content-Type\": \"application/json\",\n },\n });\n const result = [];\n const migrations = response.data.data.transaction[0]?.authchains[0].migrations;\n if (!migrations) {\n return result;\n }\n for (const migration of migrations) {\n const transaction = migration.transaction[0];\n if (!transaction) {\n continue;\n }\n transaction.inputs.forEach((input) => (input.outpointIndex = Number(input.outpoint_index)));\n transaction.outputs.forEach((output) => {\n output.outputIndex = Number(output.output_index);\n output.lockingBytecode = (0,_bitauth_libauth__WEBPACK_IMPORTED_MODULE_1__.hexToBin)(output.locking_bytecode.replace(\"\\\\x\", \"\"));\n });\n const txHash = transaction.hash.replace(\"\\\\x\", \"\");\n result.push(BCMR.makeAuthChainElement(transaction, txHash));\n }\n return result.filter((element) => element.contentHash.length && element.httpsUrl.length);\n }\n /**\n * addMetadataRegistryAuthChain Add BCMR metadata registry by resolving an authchain\n *\n * @param {string} options.transactionHash (required) transaction hash from which to build the auth chain\n * @param {Network?} options.network (default=mainnet) network to query the data from\n * @param {boolean?} options.followToHead (default=true) boolean flag to indicate that autchain building should progress to head (most recent registry version) or be stopped at this exact chain element\n * @param {ElectrumRawTransaction?} options.rawTx cached raw transaction obtained previously, spares a Fulcrum call\n *\n * @returns {AuthChain} returns the resolved authchain\n */\n static async addMetadataRegistryAuthChain(options) {\n const authChain = await this.buildAuthChain({\n ...options,\n resolveBase: false,\n });\n if (!authChain.length) {\n throw new Error(`There were no BCMR entries in the resolved authchain ${JSON.stringify(authChain, null, 2)}`);\n }\n const registry = await this.fetchMetadataRegistry(authChain.reverse()[0].httpsUrl);\n this.addMetadataRegistry(registry);\n return authChain;\n }\n /**\n * getTokenInfo Return the token info (or the identity snapshot as per spec)\n *\n * @param {string} tokenId token id to look up\n *\n * @returns {IdentitySnapshot?} return the info for the token found, otherwise undefined\n */\n static getTokenInfo(tokenId) {\n for (const registry of this.metadataRegistries.slice().reverse()) {\n const history = registry.identities?.[tokenId];\n if (!history) {\n continue;\n }\n const latestIdentityIndex = Object.keys(history)[0];\n if (latestIdentityIndex === undefined) {\n continue;\n }\n return history[latestIdentityIndex];\n }\n return undefined;\n }\n}\n// List of tracked registries\nBCMR.metadataRegistries = [];\n\n__webpack_async_result__();\n} catch(e) { __webpack_async_result__(e); } });\n\n//# sourceURL=webpack://mainnet-js/./src/wallet/Bcmr.ts?");
1418
1398
 
1419
1399
  /***/ }),
1420
1400
 
@@ -1528,16 +1508,6 @@ eval("/* (ignored) */\n\n//# sourceURL=webpack://mainnet-js/util_(ignored)?");
1528
1508
 
1529
1509
  /***/ }),
1530
1510
 
1531
- /***/ "?7652":
1532
- /*!**********************************!*\
1533
- !*** ./SqlProvider.js (ignored) ***!
1534
- \**********************************/
1535
- /***/ (() => {
1536
-
1537
- eval("/* (ignored) */\n\n//# sourceURL=webpack://mainnet-js/./SqlProvider.js_(ignored)?");
1538
-
1539
- /***/ }),
1540
-
1541
1511
  /***/ "?67af":
1542
1512
  /*!*******************************!*\
1543
1513
  !*** child_process (ignored) ***!
@@ -1558,16 +1528,6 @@ eval("/* (ignored) */\n\n//# sourceURL=webpack://mainnet-js/crypto_(ignored)?");
1558
1528
 
1559
1529
  /***/ }),
1560
1530
 
1561
- /***/ "?6f8b":
1562
- /*!************************************!*\
1563
- !*** ./webhook/index.js (ignored) ***!
1564
- \************************************/
1565
- /***/ (() => {
1566
-
1567
- eval("/* (ignored) */\n\n//# sourceURL=webpack://mainnet-js/./webhook/index.js_(ignored)?");
1568
-
1569
- /***/ }),
1570
-
1571
1531
  /***/ "../../node_modules/@bitauth/libauth/build/lib/address/base58-address.js":
1572
1532
  /*!*******************************************************************************!*\
1573
1533
  !*** ../../node_modules/@bitauth/libauth/build/lib/address/base58-address.js ***!
@@ -2364,7 +2324,7 @@ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harm
2364
2324
  \******************************************************/
2365
2325
  /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2366
2326
 
2367
- eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ Dexie$1)\n/* harmony export */ });\n/* unused harmony exports Dexie, RangeSet, liveQuery, mergeRanges, rangesOverlap */\n/*\n * Dexie.js - a minimalistic wrapper for IndexedDB\n * ===============================================\n *\n * By David Fahlander, david.fahlander@gmail.com\n *\n * Version 3.2.2, Wed Apr 27 2022\n *\n * https://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n */\n \nconst _global = typeof globalThis !== 'undefined' ? globalThis :\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\n\nconst keys = Object.keys;\nconst isArray = Array.isArray;\nif (typeof Promise !== 'undefined' && !_global.Promise) {\n _global.Promise = Promise;\n}\nfunction extend(obj, extension) {\n if (typeof extension !== 'object')\n return obj;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj;\n}\nconst getProto = Object.getPrototypeOf;\nconst _hasOwn = {}.hasOwnProperty;\nfunction hasOwn(obj, prop) {\n return _hasOwn.call(obj, prop);\n}\nfunction props(proto, extension) {\n if (typeof extension === 'function')\n extension = extension(getProto(proto));\n (typeof Reflect === \"undefined\" ? keys : Reflect.ownKeys)(extension).forEach(key => {\n setProp(proto, key, extension[key]);\n });\n}\nconst defineProperty = Object.defineProperty;\nfunction setProp(obj, prop, functionOrGetSet, options) {\n defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\n { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } :\n { value: functionOrGetSet, configurable: true, writable: true }, options));\n}\nfunction derive(Child) {\n return {\n from: function (Parent) {\n Child.prototype = Object.create(Parent.prototype);\n setProp(Child.prototype, \"constructor\", Child);\n return {\n extend: props.bind(null, Child.prototype)\n };\n }\n };\n}\nconst getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nfunction getPropertyDescriptor(obj, prop) {\n const pd = getOwnPropertyDescriptor(obj, prop);\n let proto;\n return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop);\n}\nconst _slice = [].slice;\nfunction slice(args, start, end) {\n return _slice.call(args, start, end);\n}\nfunction override(origFunc, overridedFactory) {\n return overridedFactory(origFunc);\n}\nfunction assert(b) {\n if (!b)\n throw new Error(\"Assertion Failed\");\n}\nfunction asap$1(fn) {\n if (_global.setImmediate)\n setImmediate(fn);\n else\n setTimeout(fn, 0);\n}\nfunction arrayToObject(array, extractor) {\n return array.reduce((result, item, i) => {\n var nameAndValue = extractor(item, i);\n if (nameAndValue)\n result[nameAndValue[0]] = nameAndValue[1];\n return result;\n }, {});\n}\nfunction tryCatch(fn, onerror, args) {\n try {\n fn.apply(null, args);\n }\n catch (ex) {\n onerror && onerror(ex);\n }\n}\nfunction getByKeyPath(obj, keyPath) {\n if (hasOwn(obj, keyPath))\n return obj[keyPath];\n if (!keyPath)\n return obj;\n if (typeof keyPath !== 'string') {\n var rv = [];\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n var val = getByKeyPath(obj, keyPath[i]);\n rv.push(val);\n }\n return rv;\n }\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var innerObj = obj[keyPath.substr(0, period)];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return undefined;\n}\nfunction setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined)\n return;\n if ('isFrozen' in Object && Object.isFrozen(obj))\n return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n }\n else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === \"\")\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(currentKeyPath)))\n obj.splice(currentKeyPath, 1);\n else\n delete obj[currentKeyPath];\n }\n else\n obj[currentKeyPath] = value;\n else {\n var innerObj = obj[currentKeyPath];\n if (!innerObj || !hasOwn(obj, currentKeyPath))\n innerObj = (obj[currentKeyPath] = {});\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n }\n else {\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(keyPath)))\n obj.splice(keyPath, 1);\n else\n delete obj[keyPath];\n }\n else\n obj[keyPath] = value;\n }\n }\n}\nfunction delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string')\n setByKeyPath(obj, keyPath, undefined);\n else if ('length' in keyPath)\n [].map.call(keyPath, function (kp) {\n setByKeyPath(obj, kp, undefined);\n });\n}\nfunction shallowClone(obj) {\n var rv = {};\n for (var m in obj) {\n if (hasOwn(obj, m))\n rv[m] = obj[m];\n }\n return rv;\n}\nconst concat = [].concat;\nfunction flatten(a) {\n return concat.apply([], a);\n}\nconst intrinsicTypeNames = \"Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey\"\n .split(',').concat(flatten([8, 16, 32, 64].map(num => [\"Int\", \"Uint\", \"Float\"].map(t => t + num + \"Array\")))).filter(t => _global[t]);\nconst intrinsicTypes = intrinsicTypeNames.map(t => _global[t]);\narrayToObject(intrinsicTypeNames, x => [x, true]);\nlet circularRefs = null;\nfunction deepClone(any) {\n circularRefs = typeof WeakMap !== 'undefined' && new WeakMap();\n const rv = innerDeepClone(any);\n circularRefs = null;\n return rv;\n}\nfunction innerDeepClone(any) {\n if (!any || typeof any !== 'object')\n return any;\n let rv = circularRefs && circularRefs.get(any);\n if (rv)\n return rv;\n if (isArray(any)) {\n rv = [];\n circularRefs && circularRefs.set(any, rv);\n for (var i = 0, l = any.length; i < l; ++i) {\n rv.push(innerDeepClone(any[i]));\n }\n }\n else if (intrinsicTypes.indexOf(any.constructor) >= 0) {\n rv = any;\n }\n else {\n const proto = getProto(any);\n rv = proto === Object.prototype ? {} : Object.create(proto);\n circularRefs && circularRefs.set(any, rv);\n for (var prop in any) {\n if (hasOwn(any, prop)) {\n rv[prop] = innerDeepClone(any[prop]);\n }\n }\n }\n return rv;\n}\nconst { toString } = {};\nfunction toStringTag(o) {\n return toString.call(o).slice(8, -1);\n}\nconst iteratorSymbol = typeof Symbol !== 'undefined' ?\n Symbol.iterator :\n '@@iterator';\nconst getIteratorOf = typeof iteratorSymbol === \"symbol\" ? function (x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\nconst NO_CHAR_ARRAY = {};\nfunction getArrayOf(arrayLike) {\n var i, a, x, it;\n if (arguments.length === 1) {\n if (isArray(arrayLike))\n return arrayLike.slice();\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string')\n return [arrayLike];\n if ((it = getIteratorOf(arrayLike))) {\n a = [];\n while ((x = it.next()), !x.done)\n a.push(x.value);\n return a;\n }\n if (arrayLike == null)\n return [arrayLike];\n i = arrayLike.length;\n if (typeof i === 'number') {\n a = new Array(i);\n while (i--)\n a[i] = arrayLike[i];\n return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--)\n a[i] = arguments[i];\n return a;\n}\nconst isAsyncFunction = typeof Symbol !== 'undefined'\n ? (fn) => fn[Symbol.toStringTag] === 'AsyncFunction'\n : () => false;\n\nvar debug = typeof location !== 'undefined' &&\n /^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\nfunction setDebug(value, filter) {\n debug = value;\n libraryFilter = filter;\n}\nvar libraryFilter = () => true;\nconst NEEDS_THROW_FOR_STACK = !new Error(\"\").stack;\nfunction getErrorWithStack() {\n if (NEEDS_THROW_FOR_STACK)\n try {\n getErrorWithStack.arguments;\n throw new Error();\n }\n catch (e) {\n return e;\n }\n return new Error();\n}\nfunction prettyStack(exception, numIgnoredFrames) {\n var stack = exception.stack;\n if (!stack)\n return \"\";\n numIgnoredFrames = (numIgnoredFrames || 0);\n if (stack.indexOf(exception.name) === 0)\n numIgnoredFrames += (exception.name + exception.message).split('\\n').length;\n return stack.split('\\n')\n .slice(numIgnoredFrames)\n .filter(libraryFilter)\n .map(frame => \"\\n\" + frame)\n .join('');\n}\n\nvar dexieErrorNames = [\n 'Modify',\n 'Bulk',\n 'OpenFailed',\n 'VersionChange',\n 'Schema',\n 'Upgrade',\n 'InvalidTable',\n 'MissingAPI',\n 'NoSuchDatabase',\n 'InvalidArgument',\n 'SubTransaction',\n 'Unsupported',\n 'Internal',\n 'DatabaseClosed',\n 'PrematureCommit',\n 'ForeignAwait'\n];\nvar idbDomErrorNames = [\n 'Unknown',\n 'Constraint',\n 'Data',\n 'TransactionInactive',\n 'ReadOnly',\n 'Version',\n 'NotFound',\n 'InvalidState',\n 'InvalidAccess',\n 'Abort',\n 'Timeout',\n 'QuotaExceeded',\n 'Syntax',\n 'DataClone'\n];\nvar errorList = dexieErrorNames.concat(idbDomErrorNames);\nvar defaultTexts = {\n VersionChanged: \"Database version changed by other database connection\",\n DatabaseClosed: \"Database has been closed\",\n Abort: \"Transaction aborted\",\n TransactionInactive: \"Transaction has already completed or failed\",\n MissingAPI: \"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb\"\n};\nfunction DexieError(name, msg) {\n this._e = getErrorWithStack();\n this.name = name;\n this.message = msg;\n}\nderive(DexieError).from(Error).extend({\n stack: {\n get: function () {\n return this._stack ||\n (this._stack = this.name + \": \" + this.message + prettyStack(this._e, 2));\n }\n },\n toString: function () { return this.name + \": \" + this.message; }\n});\nfunction getMultiErrorMessage(msg, failures) {\n return msg + \". Errors: \" + Object.keys(failures)\n .map(key => failures[key].toString())\n .filter((v, i, s) => s.indexOf(v) === i)\n .join('\\n');\n}\nfunction ModifyError(msg, failures, successCount, failedKeys) {\n this._e = getErrorWithStack();\n this.failures = failures;\n this.failedKeys = failedKeys;\n this.successCount = successCount;\n this.message = getMultiErrorMessage(msg, failures);\n}\nderive(ModifyError).from(DexieError);\nfunction BulkError(msg, failures) {\n this._e = getErrorWithStack();\n this.name = \"BulkError\";\n this.failures = Object.keys(failures).map(pos => failures[pos]);\n this.failuresByPos = failures;\n this.message = getMultiErrorMessage(msg, failures);\n}\nderive(BulkError).from(DexieError);\nvar errnames = errorList.reduce((obj, name) => (obj[name] = name + \"Error\", obj), {});\nconst BaseException = DexieError;\nvar exceptions = errorList.reduce((obj, name) => {\n var fullName = name + \"Error\";\n function DexieError(msgOrInner, inner) {\n this._e = getErrorWithStack();\n this.name = fullName;\n if (!msgOrInner) {\n this.message = defaultTexts[name] || fullName;\n this.inner = null;\n }\n else if (typeof msgOrInner === 'string') {\n this.message = `${msgOrInner}${!inner ? '' : '\\n ' + inner}`;\n this.inner = inner || null;\n }\n else if (typeof msgOrInner === 'object') {\n this.message = `${msgOrInner.name} ${msgOrInner.message}`;\n this.inner = msgOrInner;\n }\n }\n derive(DexieError).from(BaseException);\n obj[name] = DexieError;\n return obj;\n}, {});\nexceptions.Syntax = SyntaxError;\nexceptions.Type = TypeError;\nexceptions.Range = RangeError;\nvar exceptionMap = idbDomErrorNames.reduce((obj, name) => {\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\nfunction mapError(domError, message) {\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name])\n return domError;\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\n if (\"stack\" in domError) {\n setProp(rv, \"stack\", { get: function () {\n return this.inner.stack;\n } });\n }\n return rv;\n}\nvar fullNameExceptions = errorList.reduce((obj, name) => {\n if ([\"Syntax\", \"Type\", \"Range\"].indexOf(name) === -1)\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;\n\nfunction nop() { }\nfunction mirror(val) { return val; }\nfunction pureFunctionChain(f1, f2) {\n if (f1 == null || f1 === mirror)\n return f2;\n return function (val) {\n return f2(f1(val));\n };\n}\nfunction callBoth(on1, on2) {\n return function () {\n on1.apply(this, arguments);\n on2.apply(this, arguments);\n };\n}\nfunction hookCreatingChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res !== undefined)\n arguments[0] = res;\n var onsuccess = this.onsuccess,\n onerror = this.onerror;\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess)\n this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror)\n this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res2 !== undefined ? res2 : res;\n };\n}\nfunction hookDeletingChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function () {\n f1.apply(this, arguments);\n var onsuccess = this.onsuccess,\n onerror = this.onerror;\n this.onsuccess = this.onerror = null;\n f2.apply(this, arguments);\n if (onsuccess)\n this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror)\n this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n };\n}\nfunction hookUpdatingChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function (modifications) {\n var res = f1.apply(this, arguments);\n extend(modifications, res);\n var onsuccess = this.onsuccess,\n onerror = this.onerror;\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess)\n this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror)\n this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res === undefined ?\n (res2 === undefined ? undefined : res2) :\n (extend(res, res2));\n };\n}\nfunction reverseStoppableEventChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function () {\n if (f2.apply(this, arguments) === false)\n return false;\n return f1.apply(this, arguments);\n };\n}\nfunction promisableChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this, i = arguments.length, args = new Array(i);\n while (i--)\n args[i] = arguments[i];\n return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n\nvar INTERNAL = {};\nconst LONG_STACKS_CLIP_LIMIT = 100,\nMAX_LONG_STACKS = 20, ZONE_ECHO_LIMIT = 100, [resolvedNativePromise, nativePromiseProto, resolvedGlobalPromise] = typeof Promise === 'undefined' ?\n [] :\n (() => {\n let globalP = Promise.resolve();\n if (typeof crypto === 'undefined' || !crypto.subtle)\n return [globalP, getProto(globalP), globalP];\n const nativeP = crypto.subtle.digest(\"SHA-512\", new Uint8Array([0]));\n return [\n nativeP,\n getProto(nativeP),\n globalP\n ];\n })(), nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\nconst NativePromise = resolvedNativePromise && resolvedNativePromise.constructor;\nconst patchGlobalPromise = !!resolvedGlobalPromise;\nvar stack_being_generated = false;\nvar schedulePhysicalTick = resolvedGlobalPromise ?\n () => { resolvedGlobalPromise.then(physicalTick); }\n :\n _global.setImmediate ?\n setImmediate.bind(null, physicalTick) :\n _global.MutationObserver ?\n () => {\n var hiddenDiv = document.createElement(\"div\");\n (new MutationObserver(() => {\n physicalTick();\n hiddenDiv = null;\n })).observe(hiddenDiv, { attributes: true });\n hiddenDiv.setAttribute('i', '1');\n } :\n () => { setTimeout(physicalTick, 0); };\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\nvar isOutsideMicroTick = true,\nneedsNewPhysicalTick = true,\nunhandledErrors = [],\nrejectingErrors = [],\ncurrentFulfiller = null, rejectionMapper = mirror;\nvar globalPSD = {\n id: 'global',\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: globalError,\n pgp: false,\n env: {},\n finalize: function () {\n this.unhandleds.forEach(uh => {\n try {\n globalError(uh[0], uh[1]);\n }\n catch (e) { }\n });\n }\n};\nvar PSD = globalPSD;\nvar microtickQueue = [];\nvar numScheduledCalls = 0;\nvar tickFinalizers = [];\nfunction DexiePromise(fn) {\n if (typeof this !== 'object')\n throw new TypeError('Promises must be constructed via new');\n this._listeners = [];\n this.onuncatched = nop;\n this._lib = false;\n var psd = (this._PSD = PSD);\n if (debug) {\n this._stackHolder = getErrorWithStack();\n this._prev = null;\n this._numPrev = 0;\n }\n if (typeof fn !== 'function') {\n if (fn !== INTERNAL)\n throw new TypeError('Not a function');\n this._state = arguments[1];\n this._value = arguments[2];\n if (this._state === false)\n handleRejection(this, this._value);\n return;\n }\n this._state = null;\n this._value = null;\n ++psd.ref;\n executePromiseTask(this, fn);\n}\nconst thenProp = {\n get: function () {\n var psd = PSD, microTaskId = totalEchoes;\n function then(onFulfilled, onRejected) {\n var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\n const cleanup = possibleAwait && !decrementExpectedAwaits();\n var rv = new DexiePromise((resolve, reject) => {\n propagateToListener(this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), resolve, reject, psd));\n });\n debug && linkToPreviousPromise(rv, this);\n return rv;\n }\n then.prototype = INTERNAL;\n return then;\n },\n set: function (value) {\n setProp(this, 'then', value && value.prototype === INTERNAL ?\n thenProp :\n {\n get: function () {\n return value;\n },\n set: thenProp.set\n });\n }\n};\nprops(DexiePromise.prototype, {\n then: thenProp,\n _then: function (onFulfilled, onRejected) {\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD));\n },\n catch: function (onRejected) {\n if (arguments.length === 1)\n return this.then(null, onRejected);\n var type = arguments[0], handler = arguments[1];\n return typeof type === 'function' ? this.then(null, err =>\n err instanceof type ? handler(err) : PromiseReject(err))\n : this.then(null, err =>\n err && err.name === type ? handler(err) : PromiseReject(err));\n },\n finally: function (onFinally) {\n return this.then(value => {\n onFinally();\n return value;\n }, err => {\n onFinally();\n return PromiseReject(err);\n });\n },\n stack: {\n get: function () {\n if (this._stack)\n return this._stack;\n try {\n stack_being_generated = true;\n var stacks = getStack(this, [], MAX_LONG_STACKS);\n var stack = stacks.join(\"\\nFrom previous: \");\n if (this._state !== null)\n this._stack = stack;\n return stack;\n }\n finally {\n stack_being_generated = false;\n }\n }\n },\n timeout: function (ms, msg) {\n return ms < Infinity ?\n new DexiePromise((resolve, reject) => {\n var handle = setTimeout(() => reject(new exceptions.Timeout(msg)), ms);\n this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\n }) : this;\n }\n});\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag)\n setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise');\nglobalPSD.env = snapShot();\nfunction Listener(onFulfilled, onRejected, resolve, reject, zone) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.resolve = resolve;\n this.reject = reject;\n this.psd = zone;\n}\nprops(DexiePromise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments)\n .map(onPossibleParallellAsync);\n return new DexiePromise(function (resolve, reject) {\n if (values.length === 0)\n resolve([]);\n var remaining = values.length;\n values.forEach((a, i) => DexiePromise.resolve(a).then(x => {\n values[i] = x;\n if (!--remaining)\n resolve(values);\n }, reject));\n });\n },\n resolve: value => {\n if (value instanceof DexiePromise)\n return value;\n if (value && typeof value.then === 'function')\n return new DexiePromise((resolve, reject) => {\n value.then(resolve, reject);\n });\n var rv = new DexiePromise(INTERNAL, true, value);\n linkToPreviousPromise(rv, currentFulfiller);\n return rv;\n },\n reject: PromiseReject,\n race: function () {\n var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n values.map(value => DexiePromise.resolve(value).then(resolve, reject));\n });\n },\n PSD: {\n get: () => PSD,\n set: value => PSD = value\n },\n totalEchoes: { get: () => totalEchoes },\n newPSD: newScope,\n usePSD: usePSD,\n scheduler: {\n get: () => asap,\n set: value => { asap = value; }\n },\n rejectionMapper: {\n get: () => rejectionMapper,\n set: value => { rejectionMapper = value; }\n },\n follow: (fn, zoneProps) => {\n return new DexiePromise((resolve, reject) => {\n return newScope((resolve, reject) => {\n var psd = PSD;\n psd.unhandleds = [];\n psd.onunhandled = reject;\n psd.finalize = callBoth(function () {\n run_at_end_of_this_or_next_physical_tick(() => {\n this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, zoneProps, resolve, reject);\n });\n }\n});\nif (NativePromise) {\n if (NativePromise.allSettled)\n setProp(DexiePromise, \"allSettled\", function () {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise(resolve => {\n if (possiblePromises.length === 0)\n resolve([]);\n let remaining = possiblePromises.length;\n const results = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(value => results[i] = { status: \"fulfilled\", value }, reason => results[i] = { status: \"rejected\", reason })\n .then(() => --remaining || resolve(results)));\n });\n });\n if (NativePromise.any && typeof AggregateError !== 'undefined')\n setProp(DexiePromise, \"any\", function () {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n if (possiblePromises.length === 0)\n reject(new AggregateError([]));\n let remaining = possiblePromises.length;\n const failures = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(value => resolve(value), failure => {\n failures[i] = failure;\n if (!--remaining)\n reject(new AggregateError(failures));\n }));\n });\n });\n}\nfunction executePromiseTask(promise, fn) {\n try {\n fn(value => {\n if (promise._state !== null)\n return;\n if (value === promise)\n throw new TypeError('A promise cannot be resolved with itself.');\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n if (value && typeof value.then === 'function') {\n executePromiseTask(promise, (resolve, reject) => {\n value instanceof DexiePromise ?\n value._then(resolve, reject) :\n value.then(resolve, reject);\n });\n }\n else {\n promise._state = true;\n promise._value = value;\n propagateAllListeners(promise);\n }\n if (shouldExecuteTick)\n endMicroTickScope();\n }, handleRejection.bind(null, promise));\n }\n catch (ex) {\n handleRejection(promise, ex);\n }\n}\nfunction handleRejection(promise, reason) {\n rejectingErrors.push(reason);\n if (promise._state !== null)\n return;\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n reason = rejectionMapper(reason);\n promise._state = false;\n promise._value = reason;\n debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(() => {\n var origProp = getPropertyDescriptor(reason, \"stack\");\n reason._promise = promise;\n setProp(reason, \"stack\", {\n get: () => stack_being_generated ?\n origProp && (origProp.get ?\n origProp.get.apply(reason) :\n origProp.value) :\n promise.stack\n });\n });\n addPossiblyUnhandledError(promise);\n propagateAllListeners(promise);\n if (shouldExecuteTick)\n endMicroTickScope();\n}\nfunction propagateAllListeners(promise) {\n var listeners = promise._listeners;\n promise._listeners = [];\n for (var i = 0, len = listeners.length; i < len; ++i) {\n propagateToListener(promise, listeners[i]);\n }\n var psd = promise._PSD;\n --psd.ref || psd.finalize();\n if (numScheduledCalls === 0) {\n ++numScheduledCalls;\n asap(() => {\n if (--numScheduledCalls === 0)\n finalizePhysicalTick();\n }, []);\n }\n}\nfunction propagateToListener(promise, listener) {\n if (promise._state === null) {\n promise._listeners.push(listener);\n return;\n }\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\n if (cb === null) {\n return (promise._state ? listener.resolve : listener.reject)(promise._value);\n }\n ++listener.psd.ref;\n ++numScheduledCalls;\n asap(callListener, [cb, promise, listener]);\n}\nfunction callListener(cb, promise, listener) {\n try {\n currentFulfiller = promise;\n var ret, value = promise._value;\n if (promise._state) {\n ret = cb(value);\n }\n else {\n if (rejectingErrors.length)\n rejectingErrors = [];\n ret = cb(value);\n if (rejectingErrors.indexOf(value) === -1)\n markErrorAsHandled(promise);\n }\n listener.resolve(ret);\n }\n catch (e) {\n listener.reject(e);\n }\n finally {\n currentFulfiller = null;\n if (--numScheduledCalls === 0)\n finalizePhysicalTick();\n --listener.psd.ref || listener.psd.finalize();\n }\n}\nfunction getStack(promise, stacks, limit) {\n if (stacks.length === limit)\n return stacks;\n var stack = \"\";\n if (promise._state === false) {\n var failure = promise._value, errorName, message;\n if (failure != null) {\n errorName = failure.name || \"Error\";\n message = failure.message || failure;\n stack = prettyStack(failure, 0);\n }\n else {\n errorName = failure;\n message = \"\";\n }\n stacks.push(errorName + (message ? \": \" + message : \"\") + stack);\n }\n if (debug) {\n stack = prettyStack(promise._stackHolder, 2);\n if (stack && stacks.indexOf(stack) === -1)\n stacks.push(stack);\n if (promise._prev)\n getStack(promise._prev, stacks, limit);\n }\n return stacks;\n}\nfunction linkToPreviousPromise(promise, prev) {\n var numPrev = prev ? prev._numPrev + 1 : 0;\n if (numPrev < LONG_STACKS_CLIP_LIMIT) {\n promise._prev = prev;\n promise._numPrev = numPrev;\n }\n}\nfunction physicalTick() {\n beginMicroTickScope() && endMicroTickScope();\n}\nfunction beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\nfunction endMicroTickScope() {\n var callbacks, i, l;\n do {\n while (microtickQueue.length > 0) {\n callbacks = microtickQueue;\n microtickQueue = [];\n l = callbacks.length;\n for (i = 0; i < l; ++i) {\n var item = callbacks[i];\n item[0].apply(null, item[1]);\n }\n }\n } while (microtickQueue.length > 0);\n isOutsideMicroTick = true;\n needsNewPhysicalTick = true;\n}\nfunction finalizePhysicalTick() {\n var unhandledErrs = unhandledErrors;\n unhandledErrors = [];\n unhandledErrs.forEach(p => {\n p._PSD.onunhandled.call(null, p._value, p);\n });\n var finalizers = tickFinalizers.slice(0);\n var i = finalizers.length;\n while (i)\n finalizers[--i]();\n}\nfunction run_at_end_of_this_or_next_physical_tick(fn) {\n function finalizer() {\n fn();\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\n }\n tickFinalizers.push(finalizer);\n ++numScheduledCalls;\n asap(() => {\n if (--numScheduledCalls === 0)\n finalizePhysicalTick();\n }, []);\n}\nfunction addPossiblyUnhandledError(promise) {\n if (!unhandledErrors.some(p => p._value === promise._value))\n unhandledErrors.push(promise);\n}\nfunction markErrorAsHandled(promise) {\n var i = unhandledErrors.length;\n while (i)\n if (unhandledErrors[--i]._value === promise._value) {\n unhandledErrors.splice(i, 1);\n return;\n }\n}\nfunction PromiseReject(reason) {\n return new DexiePromise(INTERNAL, false, reason);\n}\nfunction wrap(fn, errorCatcher) {\n var psd = PSD;\n return function () {\n var wasRootExec = beginMicroTickScope(), outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn.apply(this, arguments);\n }\n catch (e) {\n errorCatcher && errorCatcher(e);\n }\n finally {\n switchToZone(outerScope, false);\n if (wasRootExec)\n endMicroTickScope();\n }\n };\n}\nconst task = { awaits: 0, echoes: 0, id: 0 };\nvar taskCounter = 0;\nvar zoneStack = [];\nvar zoneEchoes = 0;\nvar totalEchoes = 0;\nvar zone_id_counter = 0;\nfunction newScope(fn, props, a1, a2) {\n var parent = PSD, psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n psd.id = ++zone_id_counter;\n var globalEnv = globalPSD.env;\n psd.env = patchGlobalPromise ? {\n Promise: DexiePromise,\n PromiseProp: { value: DexiePromise, configurable: true, writable: true },\n all: DexiePromise.all,\n race: DexiePromise.race,\n allSettled: DexiePromise.allSettled,\n any: DexiePromise.any,\n resolve: DexiePromise.resolve,\n reject: DexiePromise.reject,\n nthen: getPatchedPromiseThen(globalEnv.nthen, psd),\n gthen: getPatchedPromiseThen(globalEnv.gthen, psd)\n } : {};\n if (props)\n extend(psd, props);\n ++parent.ref;\n psd.finalize = function () {\n --this.parent.ref || this.parent.finalize();\n };\n var rv = usePSD(psd, fn, a1, a2);\n if (psd.ref === 0)\n psd.finalize();\n return rv;\n}\nfunction incrementExpectedAwaits() {\n if (!task.id)\n task.id = ++taskCounter;\n ++task.awaits;\n task.echoes += ZONE_ECHO_LIMIT;\n return task.id;\n}\nfunction decrementExpectedAwaits() {\n if (!task.awaits)\n return false;\n if (--task.awaits === 0)\n task.id = 0;\n task.echoes = task.awaits * ZONE_ECHO_LIMIT;\n return true;\n}\nif (('' + nativePromiseThen).indexOf('[native code]') === -1) {\n incrementExpectedAwaits = decrementExpectedAwaits = nop;\n}\nfunction onPossibleParallellAsync(possiblePromise) {\n if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) {\n incrementExpectedAwaits();\n return possiblePromise.then(x => {\n decrementExpectedAwaits();\n return x;\n }, e => {\n decrementExpectedAwaits();\n return rejection(e);\n });\n }\n return possiblePromise;\n}\nfunction zoneEnterEcho(targetZone) {\n ++totalEchoes;\n if (!task.echoes || --task.echoes === 0) {\n task.echoes = task.id = 0;\n }\n zoneStack.push(PSD);\n switchToZone(targetZone, true);\n}\nfunction zoneLeaveEcho() {\n var zone = zoneStack[zoneStack.length - 1];\n zoneStack.pop();\n switchToZone(zone, false);\n}\nfunction switchToZone(targetZone, bEnteringZone) {\n var currentZone = PSD;\n if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) {\n enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho);\n }\n if (targetZone === PSD)\n return;\n PSD = targetZone;\n if (currentZone === globalPSD)\n globalPSD.env = snapShot();\n if (patchGlobalPromise) {\n var GlobalPromise = globalPSD.env.Promise;\n var targetEnv = targetZone.env;\n nativePromiseProto.then = targetEnv.nthen;\n GlobalPromise.prototype.then = targetEnv.gthen;\n if (currentZone.global || targetZone.global) {\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\n GlobalPromise.all = targetEnv.all;\n GlobalPromise.race = targetEnv.race;\n GlobalPromise.resolve = targetEnv.resolve;\n GlobalPromise.reject = targetEnv.reject;\n if (targetEnv.allSettled)\n GlobalPromise.allSettled = targetEnv.allSettled;\n if (targetEnv.any)\n GlobalPromise.any = targetEnv.any;\n }\n }\n}\nfunction snapShot() {\n var GlobalPromise = _global.Promise;\n return patchGlobalPromise ? {\n Promise: GlobalPromise,\n PromiseProp: Object.getOwnPropertyDescriptor(_global, \"Promise\"),\n all: GlobalPromise.all,\n race: GlobalPromise.race,\n allSettled: GlobalPromise.allSettled,\n any: GlobalPromise.any,\n resolve: GlobalPromise.resolve,\n reject: GlobalPromise.reject,\n nthen: nativePromiseProto.then,\n gthen: GlobalPromise.prototype.then\n } : {};\n}\nfunction usePSD(psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn(a1, a2, a3);\n }\n finally {\n switchToZone(outerScope, false);\n }\n}\nfunction enqueueNativeMicroTask(job) {\n nativePromiseThen.call(resolvedNativePromise, job);\n}\nfunction nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) {\n return typeof fn !== 'function' ? fn : function () {\n var outerZone = PSD;\n if (possibleAwait)\n incrementExpectedAwaits();\n switchToZone(zone, true);\n try {\n return fn.apply(this, arguments);\n }\n finally {\n switchToZone(outerZone, false);\n if (cleanup)\n enqueueNativeMicroTask(decrementExpectedAwaits);\n }\n };\n}\nfunction getPatchedPromiseThen(origThen, zone) {\n return function (onResolved, onRejected) {\n return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone), nativeAwaitCompatibleWrap(onRejected, zone));\n };\n}\nconst UNHANDLEDREJECTION = \"unhandledrejection\";\nfunction globalError(err, promise) {\n var rv;\n try {\n rv = promise.onuncatched(err);\n }\n catch (e) { }\n if (rv !== false)\n try {\n var event, eventData = { promise: promise, reason: err };\n if (_global.document && document.createEvent) {\n event = document.createEvent('Event');\n event.initEvent(UNHANDLEDREJECTION, true, true);\n extend(event, eventData);\n }\n else if (_global.CustomEvent) {\n event = new CustomEvent(UNHANDLEDREJECTION, { detail: eventData });\n extend(event, eventData);\n }\n if (event && _global.dispatchEvent) {\n dispatchEvent(event);\n if (!_global.PromiseRejectionEvent && _global.onunhandledrejection)\n try {\n _global.onunhandledrejection(event);\n }\n catch (_) { }\n }\n if (debug && event && !event.defaultPrevented) {\n console.warn(`Unhandled rejection: ${err.stack || err}`);\n }\n }\n catch (e) { }\n}\nvar rejection = DexiePromise.reject;\n\nfunction tempTransaction(db, mode, storeNames, fn) {\n if (!db.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) {\n if (db._state.openComplete) {\n return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError));\n }\n if (!db._state.isBeingOpened) {\n if (!db._options.autoOpen)\n return rejection(new exceptions.DatabaseClosed());\n db.open().catch(nop);\n }\n return db._state.dbReadyPromise.then(() => tempTransaction(db, mode, storeNames, fn));\n }\n else {\n var trans = db._createTransaction(mode, storeNames, db._dbSchema);\n try {\n trans.create();\n db._state.PR1398_maxLoop = 3;\n }\n catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(() => tempTransaction(db, mode, storeNames, fn));\n }\n return rejection(ex);\n }\n return trans._promise(mode, (resolve, reject) => {\n return newScope(() => {\n PSD.trans = trans;\n return fn(resolve, reject, trans);\n });\n }).then(result => {\n return trans._completion.then(() => result);\n });\n }\n}\n\nconst DEXIE_VERSION = '3.2.2';\nconst maxString = String.fromCharCode(65535);\nconst minKey = -Infinity;\nconst INVALID_KEY_ARGUMENT = \"Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.\";\nconst STRING_EXPECTED = \"String expected.\";\nconst connections = [];\nconst isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent);\nconst hasIEDeleteObjectStoreBug = isIEOrEdge;\nconst hangsOnDeleteLargeKeyRange = isIEOrEdge;\nconst dexieStackFrameFilter = frame => !/(dexie\\.js|dexie\\.min\\.js)/.test(frame);\nconst DBNAMES_DB = '__dbnames';\nconst READONLY = 'readonly';\nconst READWRITE = 'readwrite';\n\nfunction combine(filter1, filter2) {\n return filter1 ?\n filter2 ?\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\n filter1 :\n filter2;\n}\n\nconst AnyRange = {\n type: 3 ,\n lower: -Infinity,\n lowerOpen: false,\n upper: [[]],\n upperOpen: false\n};\n\nfunction workaroundForUndefinedPrimKey(keyPath) {\n return typeof keyPath === \"string\" && !/\\./.test(keyPath)\n ? (obj) => {\n if (obj[keyPath] === undefined && (keyPath in obj)) {\n obj = deepClone(obj);\n delete obj[keyPath];\n }\n return obj;\n }\n : (obj) => obj;\n}\n\nclass Table {\n _trans(mode, fn, writeLocked) {\n const trans = this._tx || PSD.trans;\n const tableName = this.name;\n function checkTableInTransaction(resolve, reject, trans) {\n if (!trans.schema[tableName])\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\");\n return fn(trans.idbtrans, trans);\n }\n const wasRootExec = beginMicroTickScope();\n try {\n return trans && trans.db === this.db ?\n trans === PSD.trans ?\n trans._promise(mode, checkTableInTransaction, writeLocked) :\n newScope(() => trans._promise(mode, checkTableInTransaction, writeLocked), { trans: trans, transless: PSD.transless || PSD }) :\n tempTransaction(this.db, mode, [this.name], checkTableInTransaction);\n }\n finally {\n if (wasRootExec)\n endMicroTickScope();\n }\n }\n get(keyOrCrit, cb) {\n if (keyOrCrit && keyOrCrit.constructor === Object)\n return this.where(keyOrCrit).first(cb);\n return this._trans('readonly', (trans) => {\n return this.core.get({ trans, key: keyOrCrit })\n .then(res => this.hook.reading.fire(res));\n }).then(cb);\n }\n where(indexOrCrit) {\n if (typeof indexOrCrit === 'string')\n return new this.db.WhereClause(this, indexOrCrit);\n if (isArray(indexOrCrit))\n return new this.db.WhereClause(this, `[${indexOrCrit.join('+')}]`);\n const keyPaths = keys(indexOrCrit);\n if (keyPaths.length === 1)\n return this\n .where(keyPaths[0])\n .equals(indexOrCrit[keyPaths[0]]);\n const compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix => ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0) &&\n ix.keyPath.every(keyPath => keyPaths.indexOf(keyPath) >= 0))[0];\n if (compoundIndex && this.db._maxKey !== maxString)\n return this\n .where(compoundIndex.name)\n .equals(compoundIndex.keyPath.map(kp => indexOrCrit[kp]));\n if (!compoundIndex && debug)\n console.warn(`The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit of a ` +\n `compound index [${keyPaths.join('+')}]`);\n const { idxByName } = this.schema;\n const idb = this.db._deps.indexedDB;\n function equals(a, b) {\n try {\n return idb.cmp(a, b) === 0;\n }\n catch (e) {\n return false;\n }\n }\n const [idx, filterFunction] = keyPaths.reduce(([prevIndex, prevFilterFn], keyPath) => {\n const index = idxByName[keyPath];\n const value = indexOrCrit[keyPath];\n return [\n prevIndex || index,\n prevIndex || !index ?\n combine(prevFilterFn, index && index.multi ?\n x => {\n const prop = getByKeyPath(x, keyPath);\n return isArray(prop) && prop.some(item => equals(value, item));\n } : x => equals(value, getByKeyPath(x, keyPath)))\n : prevFilterFn\n ];\n }, [null, null]);\n return idx ?\n this.where(idx.name).equals(indexOrCrit[idx.keyPath])\n .filter(filterFunction) :\n compoundIndex ?\n this.filter(filterFunction) :\n this.where(keyPaths).equals('');\n }\n filter(filterFunction) {\n return this.toCollection().and(filterFunction);\n }\n count(thenShortcut) {\n return this.toCollection().count(thenShortcut);\n }\n offset(offset) {\n return this.toCollection().offset(offset);\n }\n limit(numRows) {\n return this.toCollection().limit(numRows);\n }\n each(callback) {\n return this.toCollection().each(callback);\n }\n toArray(thenShortcut) {\n return this.toCollection().toArray(thenShortcut);\n }\n toCollection() {\n return new this.db.Collection(new this.db.WhereClause(this));\n }\n orderBy(index) {\n return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ?\n `[${index.join('+')}]` :\n index));\n }\n reverse() {\n return this.toCollection().reverse();\n }\n mapToClass(constructor) {\n this.schema.mappedClass = constructor;\n const readHook = obj => {\n if (!obj)\n return obj;\n const res = Object.create(constructor.prototype);\n for (var m in obj)\n if (hasOwn(obj, m))\n try {\n res[m] = obj[m];\n }\n catch (_) { }\n return res;\n };\n if (this.schema.readHook) {\n this.hook.reading.unsubscribe(this.schema.readHook);\n }\n this.schema.readHook = readHook;\n this.hook(\"reading\", readHook);\n return constructor;\n }\n defineClass() {\n function Class(content) {\n extend(this, content);\n }\n return this.mapToClass(Class);\n }\n add(obj, key) {\n const { auto, keyPath } = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', trans => {\n return this.core.mutate({ trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd] });\n }).then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n try {\n setByKeyPath(obj, keyPath, lastResult);\n }\n catch (_) { }\n }\n return lastResult;\n });\n }\n update(keyOrObject, modifications) {\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\n const key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined)\n return rejection(new exceptions.InvalidArgument(\"Given object does not contain its primary key\"));\n try {\n if (typeof modifications !== \"function\") {\n keys(modifications).forEach(keyPath => {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n }\n else {\n modifications(keyOrObject, { value: keyOrObject, primKey: key });\n }\n }\n catch (_a) {\n }\n return this.where(\":id\").equals(key).modify(modifications);\n }\n else {\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\n }\n }\n put(obj, key) {\n const { auto, keyPath } = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', trans => this.core.mutate({ trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null }))\n .then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n try {\n setByKeyPath(obj, keyPath, lastResult);\n }\n catch (_) { }\n }\n return lastResult;\n });\n }\n delete(key) {\n return this._trans('readwrite', trans => this.core.mutate({ trans, type: 'delete', keys: [key] }))\n .then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined);\n }\n clear() {\n return this._trans('readwrite', trans => this.core.mutate({ trans, type: 'deleteRange', range: AnyRange }))\n .then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined);\n }\n bulkGet(keys) {\n return this._trans('readonly', trans => {\n return this.core.getMany({\n keys,\n trans\n }).then(result => result.map(res => this.hook.reading.fire(res)));\n });\n }\n bulkAdd(objects, keysOrOptions, options) {\n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions);\n const wantResults = options ? options.allKeys : undefined;\n return this._trans('readwrite', trans => {\n const { auto, keyPath } = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n const numObjects = objects.length;\n let objectsToAdd = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n return this.core.mutate({ trans, type: 'add', keys: keys, values: objectsToAdd, wantResults })\n .then(({ numFailures, results, lastResult, failures }) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0)\n return result;\n throw new BulkError(`${this.name}.bulkAdd(): ${numFailures} of ${numObjects} operations failed`, failures);\n });\n });\n }\n bulkPut(objects, keysOrOptions, options) {\n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions);\n const wantResults = options ? options.allKeys : undefined;\n return this._trans('readwrite', trans => {\n const { auto, keyPath } = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n const numObjects = objects.length;\n let objectsToPut = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n return this.core.mutate({ trans, type: 'put', keys: keys, values: objectsToPut, wantResults })\n .then(({ numFailures, results, lastResult, failures }) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0)\n return result;\n throw new BulkError(`${this.name}.bulkPut(): ${numFailures} of ${numObjects} operations failed`, failures);\n });\n });\n }\n bulkDelete(keys) {\n const numKeys = keys.length;\n return this._trans('readwrite', trans => {\n return this.core.mutate({ trans, type: 'delete', keys: keys });\n }).then(({ numFailures, lastResult, failures }) => {\n if (numFailures === 0)\n return lastResult;\n throw new BulkError(`${this.name}.bulkDelete(): ${numFailures} of ${numKeys} operations failed`, failures);\n });\n }\n}\n\nfunction Events(ctx) {\n var evs = {};\n var rv = function (eventName, subscriber) {\n if (subscriber) {\n var i = arguments.length, args = new Array(i - 1);\n while (--i)\n args[i - 1] = arguments[i];\n evs[eventName].subscribe.apply(null, args);\n return ctx;\n }\n else if (typeof (eventName) === 'string') {\n return evs[eventName];\n }\n };\n rv.addEventType = add;\n for (var i = 1, l = arguments.length; i < l; ++i) {\n add(arguments[i]);\n }\n return rv;\n function add(eventName, chainFunction, defaultFunction) {\n if (typeof eventName === 'object')\n return addConfiguredEvents(eventName);\n if (!chainFunction)\n chainFunction = reverseStoppableEventChain;\n if (!defaultFunction)\n defaultFunction = nop;\n var context = {\n subscribers: [],\n fire: defaultFunction,\n subscribe: function (cb) {\n if (context.subscribers.indexOf(cb) === -1) {\n context.subscribers.push(cb);\n context.fire = chainFunction(context.fire, cb);\n }\n },\n unsubscribe: function (cb) {\n context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; });\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\n }\n };\n evs[eventName] = rv[eventName] = context;\n return context;\n }\n function addConfiguredEvents(cfg) {\n keys(cfg).forEach(function (eventName) {\n var args = cfg[eventName];\n if (isArray(args)) {\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\n }\n else if (args === 'asap') {\n var context = add(eventName, mirror, function fire() {\n var i = arguments.length, args = new Array(i);\n while (i--)\n args[i] = arguments[i];\n context.subscribers.forEach(function (fn) {\n asap$1(function fireEvent() {\n fn.apply(null, args);\n });\n });\n });\n }\n else\n throw new exceptions.InvalidArgument(\"Invalid event config\");\n });\n }\n}\n\nfunction makeClassConstructor(prototype, constructor) {\n derive(constructor).from({ prototype });\n return constructor;\n}\n\nfunction createTableConstructor(db) {\n return makeClassConstructor(Table.prototype, function Table(name, tableSchema, trans) {\n this.db = db;\n this._tx = trans;\n this.name = name;\n this.schema = tableSchema;\n this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n });\n });\n}\n\nfunction isPlainKeyRange(ctx, ignoreLimitFilter) {\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n}\nfunction addFilter(ctx, fn) {\n ctx.filter = combine(ctx.filter, fn);\n}\nfunction addReplayFilter(ctx, factory, isLimitFilter) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? () => combine(curr(), factory()) : factory;\n ctx.justLimit = isLimitFilter && !curr;\n}\nfunction addMatchFilter(ctx, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n}\nfunction getIndexOrStore(ctx, coreSchema) {\n if (ctx.isPrimKey)\n return coreSchema.primaryKey;\n const index = coreSchema.getIndexByKeyPath(ctx.index);\n if (!index)\n throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + coreSchema.name + \" is not indexed\");\n return index;\n}\nfunction openCursor(ctx, coreTable, trans) {\n const index = getIndexOrStore(ctx, coreTable.schema);\n return coreTable.openCursor({\n trans,\n values: !ctx.keysOnly,\n reverse: ctx.dir === 'prev',\n unique: !!ctx.unique,\n query: {\n index,\n range: ctx.range\n }\n });\n}\nfunction iter(ctx, fn, coreTrans, coreTable) {\n const filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n return iterate(openCursor(ctx, coreTable, coreTrans), combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper);\n }\n else {\n const set = {};\n const union = (item, cursor, advance) => {\n if (!filter || filter(cursor, advance, result => cursor.stop(result), err => cursor.fail(err))) {\n var primaryKey = cursor.primaryKey;\n var key = '' + primaryKey;\n if (key === '[object ArrayBuffer]')\n key = '' + new Uint8Array(primaryKey);\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n };\n return Promise.all([\n ctx.or._iterate(union, coreTrans),\n iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper)\n ]);\n }\n}\nfunction iterate(cursorPromise, filter, fn, valueMapper) {\n var mappedFn = valueMapper ? (x, c, a) => fn(valueMapper(x), c, a) : fn;\n var wrappedFn = wrap(mappedFn);\n return cursorPromise.then(cursor => {\n if (cursor) {\n return cursor.start(() => {\n var c = () => cursor.continue();\n if (!filter || filter(cursor, advancer => c = advancer, val => { cursor.stop(val); c = nop; }, e => { cursor.fail(e); c = nop; }))\n wrappedFn(cursor.value, cursor, advancer => c = advancer);\n c();\n });\n }\n });\n}\n\nfunction cmp(a, b) {\n try {\n const ta = type(a);\n const tb = type(b);\n if (ta !== tb) {\n if (ta === 'Array')\n return 1;\n if (tb === 'Array')\n return -1;\n if (ta === 'binary')\n return 1;\n if (tb === 'binary')\n return -1;\n if (ta === 'string')\n return 1;\n if (tb === 'string')\n return -1;\n if (ta === 'Date')\n return 1;\n if (tb !== 'Date')\n return NaN;\n return -1;\n }\n switch (ta) {\n case 'number':\n case 'Date':\n case 'string':\n return a > b ? 1 : a < b ? -1 : 0;\n case 'binary': {\n return compareUint8Arrays(getUint8Array(a), getUint8Array(b));\n }\n case 'Array':\n return compareArrays(a, b);\n }\n }\n catch (_a) { }\n return NaN;\n}\nfunction compareArrays(a, b) {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n const res = cmp(a[i], b[i]);\n if (res !== 0)\n return res;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\nfunction compareUint8Arrays(a, b) {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n if (a[i] !== b[i])\n return a[i] < b[i] ? -1 : 1;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\nfunction type(x) {\n const t = typeof x;\n if (t !== 'object')\n return t;\n if (ArrayBuffer.isView(x))\n return 'binary';\n const tsTag = toStringTag(x);\n return tsTag === 'ArrayBuffer' ? 'binary' : tsTag;\n}\nfunction getUint8Array(a) {\n if (a instanceof Uint8Array)\n return a;\n if (ArrayBuffer.isView(a))\n return new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n return new Uint8Array(a);\n}\n\nclass Collection {\n _read(fn, cb) {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readonly', fn).then(cb);\n }\n _write(fn) {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readwrite', fn, \"locked\");\n }\n _addAlgorithm(fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n }\n _iterate(fn, coreTrans) {\n return iter(this._ctx, fn, coreTrans, this._ctx.table.core);\n }\n clone(props) {\n var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx);\n if (props)\n extend(ctx, props);\n rv._ctx = ctx;\n return rv;\n }\n raw() {\n this._ctx.valueMapper = null;\n return this;\n }\n each(fn) {\n var ctx = this._ctx;\n return this._read(trans => iter(ctx, fn, trans, ctx.table.core));\n }\n count(cb) {\n return this._read(trans => {\n const ctx = this._ctx;\n const coreTable = ctx.table.core;\n if (isPlainKeyRange(ctx, true)) {\n return coreTable.count({\n trans,\n query: {\n index: getIndexOrStore(ctx, coreTable.schema),\n range: ctx.range\n }\n }).then(count => Math.min(count, ctx.limit));\n }\n else {\n var count = 0;\n return iter(ctx, () => { ++count; return false; }, trans, coreTable)\n .then(() => count);\n }\n }).then(cb);\n }\n sortBy(keyPath, cb) {\n const parts = keyPath.split('.').reverse(), lastPart = parts[0], lastIndex = parts.length - 1;\n function getval(obj, i) {\n if (i)\n return getval(obj[parts[i]], i - 1);\n return obj[lastPart];\n }\n var order = this._ctx.dir === \"next\" ? 1 : -1;\n function sorter(a, b) {\n var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex);\n return aVal < bVal ? -order : aVal > bVal ? order : 0;\n }\n return this.toArray(function (a) {\n return a.sort(sorter);\n }).then(cb);\n }\n toArray(cb) {\n return this._read(trans => {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n const { valueMapper } = ctx;\n const index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n limit: ctx.limit,\n values: true,\n query: {\n index,\n range: ctx.range\n }\n }).then(({ result }) => valueMapper ? result.map(valueMapper) : result);\n }\n else {\n const a = [];\n return iter(ctx, item => a.push(item), trans, ctx.table.core).then(() => a);\n }\n }, cb);\n }\n offset(offset) {\n var ctx = this._ctx;\n if (offset <= 0)\n return this;\n ctx.offset += offset;\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return (cursor, advance) => {\n if (offsetLeft === 0)\n return true;\n if (offsetLeft === 1) {\n --offsetLeft;\n return false;\n }\n advance(() => {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n }\n else {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return () => (--offsetLeft < 0);\n });\n }\n return this;\n }\n limit(numRows) {\n this._ctx.limit = Math.min(this._ctx.limit, numRows);\n addReplayFilter(this._ctx, () => {\n var rowsLeft = numRows;\n return function (cursor, advance, resolve) {\n if (--rowsLeft <= 0)\n advance(resolve);\n return rowsLeft >= 0;\n };\n }, true);\n return this;\n }\n until(filterFunction, bIncludeStopEntry) {\n addFilter(this._ctx, function (cursor, advance, resolve) {\n if (filterFunction(cursor.value)) {\n advance(resolve);\n return bIncludeStopEntry;\n }\n else {\n return true;\n }\n });\n return this;\n }\n first(cb) {\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\n }\n last(cb) {\n return this.reverse().first(cb);\n }\n filter(filterFunction) {\n addFilter(this._ctx, function (cursor) {\n return filterFunction(cursor.value);\n });\n addMatchFilter(this._ctx, filterFunction);\n return this;\n }\n and(filter) {\n return this.filter(filter);\n }\n or(indexName) {\n return new this.db.WhereClause(this._ctx.table, indexName, this);\n }\n reverse() {\n this._ctx.dir = (this._ctx.dir === \"prev\" ? \"next\" : \"prev\");\n if (this._ondirectionchange)\n this._ondirectionchange(this._ctx.dir);\n return this;\n }\n desc() {\n return this.reverse();\n }\n eachKey(cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\n }\n eachUniqueKey(cb) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n }\n eachPrimaryKey(cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\n }\n keys(cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.key);\n }).then(function () {\n return a;\n }).then(cb);\n }\n primaryKeys(cb) {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n return this._read(trans => {\n var index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n values: false,\n limit: ctx.limit,\n query: {\n index,\n range: ctx.range\n }\n });\n }).then(({ result }) => result).then(cb);\n }\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.primaryKey);\n }).then(function () {\n return a;\n }).then(cb);\n }\n uniqueKeys(cb) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n }\n firstKey(cb) {\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\n }\n lastKey(cb) {\n return this.reverse().firstKey(cb);\n }\n distinct() {\n var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\n if (!idx || !idx.multi)\n return this;\n var set = {};\n addFilter(this._ctx, function (cursor) {\n var strKey = cursor.primaryKey.toString();\n var found = hasOwn(set, strKey);\n set[strKey] = true;\n return !found;\n });\n return this;\n }\n modify(changes) {\n var ctx = this._ctx;\n return this._write(trans => {\n var modifyer;\n if (typeof changes === 'function') {\n modifyer = changes;\n }\n else {\n var keyPaths = keys(changes);\n var numKeys = keyPaths.length;\n modifyer = function (item) {\n var anythingModified = false;\n for (var i = 0; i < numKeys; ++i) {\n var keyPath = keyPaths[i], val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val);\n anythingModified = true;\n }\n }\n return anythingModified;\n };\n }\n const coreTable = ctx.table.core;\n const { outbound, extractKey } = coreTable.schema.primaryKey;\n const limit = this.db._options.modifyChunkSize || 200;\n const totalFailures = [];\n let successCount = 0;\n const failedKeys = [];\n const applyMutateResult = (expectedCount, res) => {\n const { failures, numFailures } = res;\n successCount += expectedCount - numFailures;\n for (let pos of keys(failures)) {\n totalFailures.push(failures[pos]);\n }\n };\n return this.clone().primaryKeys().then(keys => {\n const nextChunk = (offset) => {\n const count = Math.min(limit, keys.length - offset);\n return coreTable.getMany({\n trans,\n keys: keys.slice(offset, offset + count),\n cache: \"immutable\"\n }).then(values => {\n const addValues = [];\n const putValues = [];\n const putKeys = outbound ? [] : null;\n const deleteKeys = [];\n for (let i = 0; i < count; ++i) {\n const origValue = values[i];\n const ctx = {\n value: deepClone(origValue),\n primKey: keys[offset + i]\n };\n if (modifyer.call(ctx, ctx.value, ctx) !== false) {\n if (ctx.value == null) {\n deleteKeys.push(keys[offset + i]);\n }\n else if (!outbound && cmp(extractKey(origValue), extractKey(ctx.value)) !== 0) {\n deleteKeys.push(keys[offset + i]);\n addValues.push(ctx.value);\n }\n else {\n putValues.push(ctx.value);\n if (outbound)\n putKeys.push(keys[offset + i]);\n }\n }\n }\n const criteria = isPlainKeyRange(ctx) &&\n ctx.limit === Infinity &&\n (typeof changes !== 'function' || changes === deleteCallback) && {\n index: ctx.index,\n range: ctx.range\n };\n return Promise.resolve(addValues.length > 0 &&\n coreTable.mutate({ trans, type: 'add', values: addValues })\n .then(res => {\n for (let pos in res.failures) {\n deleteKeys.splice(parseInt(pos), 1);\n }\n applyMutateResult(addValues.length, res);\n })).then(() => (putValues.length > 0 || (criteria && typeof changes === 'object')) &&\n coreTable.mutate({\n trans,\n type: 'put',\n keys: putKeys,\n values: putValues,\n criteria,\n changeSpec: typeof changes !== 'function'\n && changes\n }).then(res => applyMutateResult(putValues.length, res))).then(() => (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) &&\n coreTable.mutate({\n trans,\n type: 'delete',\n keys: deleteKeys,\n criteria\n }).then(res => applyMutateResult(deleteKeys.length, res))).then(() => {\n return keys.length > offset + count && nextChunk(offset + limit);\n });\n });\n };\n return nextChunk(0).then(() => {\n if (totalFailures.length > 0)\n throw new ModifyError(\"Error modifying one or more objects\", totalFailures, successCount, failedKeys);\n return keys.length;\n });\n });\n });\n }\n delete() {\n var ctx = this._ctx, range = ctx.range;\n if (isPlainKeyRange(ctx) &&\n ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || range.type === 3 ))\n {\n return this._write(trans => {\n const { primaryKey } = ctx.table.core.schema;\n const coreRange = range;\n return ctx.table.core.count({ trans, query: { index: primaryKey, range: coreRange } }).then(count => {\n return ctx.table.core.mutate({ trans, type: 'deleteRange', range: coreRange })\n .then(({ failures, lastResult, results, numFailures }) => {\n if (numFailures)\n throw new ModifyError(\"Could not delete some values\", Object.keys(failures).map(pos => failures[pos]), count - numFailures);\n return count - numFailures;\n });\n });\n });\n }\n return this.modify(deleteCallback);\n }\n}\nconst deleteCallback = (value, ctx) => ctx.value = null;\n\nfunction createCollectionConstructor(db) {\n return makeClassConstructor(Collection.prototype, function Collection(whereClause, keyRangeGenerator) {\n this.db = db;\n let keyRange = AnyRange, error = null;\n if (keyRangeGenerator)\n try {\n keyRange = keyRangeGenerator();\n }\n catch (ex) {\n error = ex;\n }\n const whereCtx = whereClause._ctx;\n const table = whereCtx.table;\n const readingHook = table.hook.reading.fire;\n this._ctx = {\n table: table,\n index: whereCtx.index,\n isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)),\n range: keyRange,\n keysOnly: false,\n dir: \"next\",\n unique: \"\",\n algorithm: null,\n filter: null,\n replayFilter: null,\n justLimit: true,\n isMatch: null,\n offset: 0,\n limit: Infinity,\n error: error,\n or: whereCtx.or,\n valueMapper: readingHook !== mirror ? readingHook : null\n };\n });\n}\n\nfunction simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n}\nfunction simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n}\n\nfunction fail(collectionOrWhereClause, err, T) {\n var collection = collectionOrWhereClause instanceof WhereClause ?\n new collectionOrWhereClause.Collection(collectionOrWhereClause) :\n collectionOrWhereClause;\n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n}\nfunction emptyCollection(whereClause) {\n return new whereClause.Collection(whereClause, () => rangeEqual(\"\")).limit(0);\n}\nfunction upperFactory(dir) {\n return dir === \"next\" ?\n (s) => s.toUpperCase() :\n (s) => s.toLowerCase();\n}\nfunction lowerFactory(dir) {\n return dir === \"next\" ?\n (s) => s.toLowerCase() :\n (s) => s.toUpperCase();\n}\nfunction nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\n var length = Math.min(key.length, lowerNeedle.length);\n var llp = -1;\n for (var i = 0; i < length; ++i) {\n var lwrKeyChar = lowerKey[i];\n if (lwrKeyChar !== lowerNeedle[i]) {\n if (cmp(key[i], upperNeedle[i]) < 0)\n return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\n if (cmp(key[i], lowerNeedle[i]) < 0)\n return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\n if (llp >= 0)\n return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\n return null;\n }\n if (cmp(key[i], lwrKeyChar) < 0)\n llp = i;\n }\n if (length < lowerNeedle.length && dir === \"next\")\n return key + upperNeedle.substr(key.length);\n if (length < key.length && dir === \"prev\")\n return key.substr(0, upperNeedle.length);\n return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1));\n}\nfunction addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) {\n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length;\n if (!needles.every(s => typeof s === 'string')) {\n return fail(whereClause, STRING_EXPECTED);\n }\n function initDirection(dir) {\n upper = upperFactory(dir);\n lower = lowerFactory(dir);\n compare = (dir === \"next\" ? simpleCompare : simpleCompareReverse);\n var needleBounds = needles.map(function (needle) {\n return { lower: lower(needle), upper: upper(needle) };\n }).sort(function (a, b) {\n return compare(a.lower, b.lower);\n });\n upperNeedles = needleBounds.map(function (nb) { return nb.upper; });\n lowerNeedles = needleBounds.map(function (nb) { return nb.lower; });\n direction = dir;\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\n }\n initDirection(\"next\");\n var c = new whereClause.Collection(whereClause, () => createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix));\n c._ondirectionchange = function (direction) {\n initDirection(direction);\n };\n var firstPossibleNeedle = 0;\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n if (typeof key !== 'string')\n return false;\n var lowerKey = lower(key);\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\n return true;\n }\n else {\n var lowestPossibleCasing = null;\n for (var i = firstPossibleNeedle; i < needlesLen; ++i) {\n var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction);\n if (casing === null && lowestPossibleCasing === null)\n firstPossibleNeedle = i + 1;\n else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\n }\n else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n}\nfunction createRange(lower, upper, lowerOpen, upperOpen) {\n return {\n type: 2 ,\n lower,\n upper,\n lowerOpen,\n upperOpen\n };\n}\nfunction rangeEqual(value) {\n return {\n type: 1 ,\n lower: value,\n upper: value\n };\n}\n\nclass WhereClause {\n get Collection() {\n return this._ctx.table.db.Collection;\n }\n between(lower, upper, includeLower, includeUpper) {\n includeLower = includeLower !== false;\n includeUpper = includeUpper === true;\n try {\n if ((this._cmp(lower, upper) > 0) ||\n (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\n return emptyCollection(this);\n return new this.Collection(this, () => createRange(lower, upper, !includeLower, !includeUpper));\n }\n catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n }\n equals(value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => rangeEqual(value));\n }\n above(value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, true));\n }\n aboveOrEqual(value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, false));\n }\n below(value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value, false, true));\n }\n belowOrEqual(value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value));\n }\n startsWith(str) {\n if (typeof str !== 'string')\n return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n }\n startsWithIgnoreCase(str) {\n if (str === \"\")\n return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, (x, a) => x.indexOf(a[0]) === 0, [str], maxString);\n }\n equalsIgnoreCase(str) {\n return addIgnoreCaseAlgorithm(this, (x, a) => x === a[0], [str], \"\");\n }\n anyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0)\n return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.indexOf(x) !== -1, set, \"\");\n }\n startsWithAnyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0)\n return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.some(n => x.indexOf(n) === 0), set, maxString);\n }\n anyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n let compare = this._cmp;\n try {\n set.sort(compare);\n }\n catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n if (set.length === 0)\n return emptyCollection(this);\n const c = new this.Collection(this, () => createRange(set[0], set[set.length - 1]));\n c._ondirectionchange = direction => {\n compare = (direction === \"next\" ?\n this._ascending :\n this._descending);\n set.sort(compare);\n };\n let i = 0;\n c._addAlgorithm((cursor, advance, resolve) => {\n const key = cursor.key;\n while (compare(key, set[i]) > 0) {\n ++i;\n if (i === set.length) {\n advance(resolve);\n return false;\n }\n }\n if (compare(key, set[i]) === 0) {\n return true;\n }\n else {\n advance(() => { cursor.continue(set[i]); });\n return false;\n }\n });\n return c;\n }\n notEqual(value) {\n return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false });\n }\n noneOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0)\n return new this.Collection(this);\n try {\n set.sort(this._ascending);\n }\n catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n const ranges = set.reduce((res, val) => res ?\n res.concat([[res[res.length - 1][1], val]]) :\n [[minKey, val]], null);\n ranges.push([set[set.length - 1], this.db._maxKey]);\n return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false });\n }\n inAnyRange(ranges, options) {\n const cmp = this._cmp, ascending = this._ascending, descending = this._descending, min = this._min, max = this._max;\n if (ranges.length === 0)\n return emptyCollection(this);\n if (!ranges.every(range => range[0] !== undefined &&\n range[1] !== undefined &&\n ascending(range[0], range[1]) <= 0)) {\n return fail(this, \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\", exceptions.InvalidArgument);\n }\n const includeLowers = !options || options.includeLowers !== false;\n const includeUppers = options && options.includeUppers === true;\n function addRange(ranges, newRange) {\n let i = 0, l = ranges.length;\n for (; i < l; ++i) {\n const range = ranges[i];\n if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) {\n range[0] = min(range[0], newRange[0]);\n range[1] = max(range[1], newRange[1]);\n break;\n }\n }\n if (i === l)\n ranges.push(newRange);\n return ranges;\n }\n let sortDirection = ascending;\n function rangeSorter(a, b) { return sortDirection(a[0], b[0]); }\n let set;\n try {\n set = ranges.reduce(addRange, []);\n set.sort(rangeSorter);\n }\n catch (ex) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n let rangePos = 0;\n const keyIsBeyondCurrentEntry = includeUppers ?\n key => ascending(key, set[rangePos][1]) > 0 :\n key => ascending(key, set[rangePos][1]) >= 0;\n const keyIsBeforeCurrentEntry = includeLowers ?\n key => descending(key, set[rangePos][0]) > 0 :\n key => descending(key, set[rangePos][0]) >= 0;\n function keyWithinCurrentRange(key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n let checkKey = keyIsBeyondCurrentEntry;\n const c = new this.Collection(this, () => createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers));\n c._ondirectionchange = direction => {\n if (direction === \"next\") {\n checkKey = keyIsBeyondCurrentEntry;\n sortDirection = ascending;\n }\n else {\n checkKey = keyIsBeforeCurrentEntry;\n sortDirection = descending;\n }\n set.sort(rangeSorter);\n };\n c._addAlgorithm((cursor, advance, resolve) => {\n var key = cursor.key;\n while (checkKey(key)) {\n ++rangePos;\n if (rangePos === set.length) {\n advance(resolve);\n return false;\n }\n }\n if (keyWithinCurrentRange(key)) {\n return true;\n }\n else if (this._cmp(key, set[rangePos][1]) === 0 || this._cmp(key, set[rangePos][0]) === 0) {\n return false;\n }\n else {\n advance(() => {\n if (sortDirection === ascending)\n cursor.continue(set[rangePos][0]);\n else\n cursor.continue(set[rangePos][1]);\n });\n return false;\n }\n });\n return c;\n }\n startsWithAnyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (!set.every(s => typeof s === 'string')) {\n return fail(this, \"startsWithAnyOf() only works with strings\");\n }\n if (set.length === 0)\n return emptyCollection(this);\n return this.inAnyRange(set.map((str) => [str, str + maxString]));\n }\n}\n\nfunction createWhereClauseConstructor(db) {\n return makeClassConstructor(WhereClause.prototype, function WhereClause(table, index, orCollection) {\n this.db = db;\n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n or: orCollection\n };\n const indexedDB = db._deps.indexedDB;\n if (!indexedDB)\n throw new exceptions.MissingAPI();\n this._cmp = this._ascending = indexedDB.cmp.bind(indexedDB);\n this._descending = (a, b) => indexedDB.cmp(b, a);\n this._max = (a, b) => indexedDB.cmp(a, b) > 0 ? a : b;\n this._min = (a, b) => indexedDB.cmp(a, b) < 0 ? a : b;\n this._IDBKeyRange = db._deps.IDBKeyRange;\n });\n}\n\nfunction eventRejectHandler(reject) {\n return wrap(function (event) {\n preventDefault(event);\n reject(event.target.error);\n return false;\n });\n}\nfunction preventDefault(event) {\n if (event.stopPropagation)\n event.stopPropagation();\n if (event.preventDefault)\n event.preventDefault();\n}\n\nconst DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated';\nconst STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1';\nconst globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME);\n\nclass Transaction {\n _lock() {\n assert(!PSD.global);\n ++this._reculock;\n if (this._reculock === 1 && !PSD.global)\n PSD.lockOwnerFor = this;\n return this;\n }\n _unlock() {\n assert(!PSD.global);\n if (--this._reculock === 0) {\n if (!PSD.global)\n PSD.lockOwnerFor = null;\n while (this._blockedFuncs.length > 0 && !this._locked()) {\n var fnAndPSD = this._blockedFuncs.shift();\n try {\n usePSD(fnAndPSD[1], fnAndPSD[0]);\n }\n catch (e) { }\n }\n }\n return this;\n }\n _locked() {\n return this._reculock && PSD.lockOwnerFor !== this;\n }\n create(idbtrans) {\n if (!this.mode)\n return this;\n const idbdb = this.db.idbdb;\n const dbOpenError = this.db._state.dbOpenError;\n assert(!this.idbtrans);\n if (!idbtrans && !idbdb) {\n switch (dbOpenError && dbOpenError.name) {\n case \"DatabaseClosedError\":\n throw new exceptions.DatabaseClosed(dbOpenError);\n case \"MissingAPIError\":\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\n default:\n throw new exceptions.OpenFailed(dbOpenError);\n }\n }\n if (!this.active)\n throw new exceptions.TransactionInactive();\n assert(this._completion._state === null);\n idbtrans = this.idbtrans = idbtrans ||\n (this.db.core\n ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })\n : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }));\n idbtrans.onerror = wrap(ev => {\n preventDefault(ev);\n this._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(ev => {\n preventDefault(ev);\n this.active && this._reject(new exceptions.Abort(idbtrans.error));\n this.active = false;\n this.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(() => {\n this.active = false;\n this._resolve();\n if ('mutatedParts' in idbtrans) {\n globalEvents.storagemutated.fire(idbtrans[\"mutatedParts\"]);\n }\n });\n return this;\n }\n _promise(mode, fn, bWriteLock) {\n if (mode === 'readwrite' && this.mode !== 'readwrite')\n return rejection(new exceptions.ReadOnly(\"Transaction is readonly\"));\n if (!this.active)\n return rejection(new exceptions.TransactionInactive());\n if (this._locked()) {\n return new DexiePromise((resolve, reject) => {\n this._blockedFuncs.push([() => {\n this._promise(mode, fn, bWriteLock).then(resolve, reject);\n }, PSD]);\n });\n }\n else if (bWriteLock) {\n return newScope(() => {\n var p = new DexiePromise((resolve, reject) => {\n this._lock();\n const rv = fn(resolve, reject, this);\n if (rv && rv.then)\n rv.then(resolve, reject);\n });\n p.finally(() => this._unlock());\n p._lib = true;\n return p;\n });\n }\n else {\n var p = new DexiePromise((resolve, reject) => {\n var rv = fn(resolve, reject, this);\n if (rv && rv.then)\n rv.then(resolve, reject);\n });\n p._lib = true;\n return p;\n }\n }\n _root() {\n return this.parent ? this.parent._root() : this;\n }\n waitFor(promiseLike) {\n var root = this._root();\n const promise = DexiePromise.resolve(promiseLike);\n if (root._waitingFor) {\n root._waitingFor = root._waitingFor.then(() => promise);\n }\n else {\n root._waitingFor = promise;\n root._waitingQueue = [];\n var store = root.idbtrans.objectStore(root.storeNames[0]);\n (function spin() {\n ++root._spinCount;\n while (root._waitingQueue.length)\n (root._waitingQueue.shift())();\n if (root._waitingFor)\n store.get(-Infinity).onsuccess = spin;\n }());\n }\n var currentWaitPromise = root._waitingFor;\n return new DexiePromise((resolve, reject) => {\n promise.then(res => root._waitingQueue.push(wrap(resolve.bind(null, res))), err => root._waitingQueue.push(wrap(reject.bind(null, err)))).finally(() => {\n if (root._waitingFor === currentWaitPromise) {\n root._waitingFor = null;\n }\n });\n });\n }\n abort() {\n if (this.active) {\n this.active = false;\n if (this.idbtrans)\n this.idbtrans.abort();\n this._reject(new exceptions.Abort());\n }\n }\n table(tableName) {\n const memoizedTables = (this._memoizedTables || (this._memoizedTables = {}));\n if (hasOwn(memoizedTables, tableName))\n return memoizedTables[tableName];\n const tableSchema = this.schema[tableName];\n if (!tableSchema) {\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\");\n }\n const transactionBoundTable = new this.db.Table(tableName, tableSchema, this);\n transactionBoundTable.core = this.db.core.table(tableName);\n memoizedTables[tableName] = transactionBoundTable;\n return transactionBoundTable;\n }\n}\n\nfunction createTransactionConstructor(db) {\n return makeClassConstructor(Transaction.prototype, function Transaction(mode, storeNames, dbschema, chromeTransactionDurability, parent) {\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.schema = dbschema;\n this.chromeTransactionDurability = chromeTransactionDurability;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._resolve = null;\n this._reject = null;\n this._waitingFor = null;\n this._waitingQueue = null;\n this._spinCount = 0;\n this._completion = new DexiePromise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n this._completion.then(() => {\n this.active = false;\n this.on.complete.fire();\n }, e => {\n var wasActive = this.active;\n this.active = false;\n this.on.error.fire(e);\n this.parent ?\n this.parent._reject(e) :\n wasActive && this.idbtrans && this.idbtrans.abort();\n return rejection(e);\n });\n });\n}\n\nfunction createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey) {\n return {\n name,\n keyPath,\n unique,\n multi,\n auto,\n compound,\n src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + nameFromKeyPath(keyPath)\n };\n}\nfunction nameFromKeyPath(keyPath) {\n return typeof keyPath === 'string' ?\n keyPath :\n keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : \"\";\n}\n\nfunction createTableSchema(name, primKey, indexes) {\n return {\n name,\n primKey,\n indexes,\n mappedClass: null,\n idxByName: arrayToObject(indexes, index => [index.name, index])\n };\n}\n\nfunction safariMultiStoreFix(storeNames) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\nlet getMaxKey = (IdbKeyRange) => {\n try {\n IdbKeyRange.only([[]]);\n getMaxKey = () => [[]];\n return [[]];\n }\n catch (e) {\n getMaxKey = () => maxString;\n return maxString;\n }\n};\n\nfunction getKeyExtractor(keyPath) {\n if (keyPath == null) {\n return () => undefined;\n }\n else if (typeof keyPath === 'string') {\n return getSinglePathKeyExtractor(keyPath);\n }\n else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\nfunction getSinglePathKeyExtractor(keyPath) {\n const split = keyPath.split('.');\n if (split.length === 1) {\n return obj => obj[keyPath];\n }\n else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n\nfunction arrayify(arrayLike) {\n return [].slice.call(arrayLike);\n}\nlet _id_counter = 0;\nfunction getKeyPathAlias(keyPath) {\n return keyPath == null ?\n \":id\" :\n typeof keyPath === 'string' ?\n keyPath :\n `[${keyPath.join('+')}]`;\n}\nfunction createDBCore(db, IdbKeyRange, tmpTrans) {\n function extractSchema(db, trans) {\n const tables = arrayify(db.objectStoreNames);\n return {\n schema: {\n name: db.name,\n tables: tables.map(table => trans.objectStore(table)).map(store => {\n const { keyPath, autoIncrement } = store;\n const compound = isArray(keyPath);\n const outbound = keyPath == null;\n const indexByKeyPath = {};\n const result = {\n name: store.name,\n primaryKey: {\n name: null,\n isPrimaryKey: true,\n outbound,\n compound,\n keyPath,\n autoIncrement,\n unique: true,\n extractKey: getKeyExtractor(keyPath)\n },\n indexes: arrayify(store.indexNames).map(indexName => store.index(indexName))\n .map(index => {\n const { name, unique, multiEntry, keyPath } = index;\n const compound = isArray(keyPath);\n const result = {\n name,\n compound,\n keyPath,\n unique,\n multiEntry,\n extractKey: getKeyExtractor(keyPath)\n };\n indexByKeyPath[getKeyPathAlias(keyPath)] = result;\n return result;\n }),\n getIndexByKeyPath: (keyPath) => indexByKeyPath[getKeyPathAlias(keyPath)]\n };\n indexByKeyPath[\":id\"] = result.primaryKey;\n if (keyPath != null) {\n indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey;\n }\n return result;\n })\n },\n hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) &&\n !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604)\n };\n }\n function makeIDBKeyRange(range) {\n if (range.type === 3 )\n return null;\n if (range.type === 4 )\n throw new Error(\"Cannot convert never type to IDBKeyRange\");\n const { lower, upper, lowerOpen, upperOpen } = range;\n const idbRange = lower === undefined ?\n upper === undefined ?\n null :\n IdbKeyRange.upperBound(upper, !!upperOpen) :\n upper === undefined ?\n IdbKeyRange.lowerBound(lower, !!lowerOpen) :\n IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen);\n return idbRange;\n }\n function createDbCoreTable(tableSchema) {\n const tableName = tableSchema.name;\n function mutate({ trans, type, keys, values, range }) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = trans.objectStore(tableName);\n const outbound = store.keyPath == null;\n const isAddOrPut = type === \"put\" || type === \"add\";\n if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange')\n throw new Error(\"Invalid operation type: \" + type);\n const { length } = keys || values || { length: 1 };\n if (keys && values && keys.length !== values.length) {\n throw new Error(\"Given keys array must have same length as given values array.\");\n }\n if (length === 0)\n return resolve({ numFailures: 0, failures: {}, results: [], lastResult: undefined });\n let req;\n const reqs = [];\n const failures = [];\n let numFailures = 0;\n const errorHandler = event => {\n ++numFailures;\n preventDefault(event);\n };\n if (type === 'deleteRange') {\n if (range.type === 4 )\n return resolve({ numFailures, failures, results: [], lastResult: undefined });\n if (range.type === 3 )\n reqs.push(req = store.clear());\n else\n reqs.push(req = store.delete(makeIDBKeyRange(range)));\n }\n else {\n const [args1, args2] = isAddOrPut ?\n outbound ?\n [values, keys] :\n [values, null] :\n [keys, null];\n if (isAddOrPut) {\n for (let i = 0; i < length; ++i) {\n reqs.push(req = (args2 && args2[i] !== undefined ?\n store[type](args1[i], args2[i]) :\n store[type](args1[i])));\n req.onerror = errorHandler;\n }\n }\n else {\n for (let i = 0; i < length; ++i) {\n reqs.push(req = store[type](args1[i]));\n req.onerror = errorHandler;\n }\n }\n }\n const done = event => {\n const lastResult = event.target.result;\n reqs.forEach((req, i) => req.error != null && (failures[i] = req.error));\n resolve({\n numFailures,\n failures,\n results: type === \"delete\" ? keys : reqs.map(req => req.result),\n lastResult\n });\n };\n req.onerror = event => {\n errorHandler(event);\n done(event);\n };\n req.onsuccess = done;\n });\n }\n function openCursor({ trans, values, query, reverse, unique }) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const { index, range } = query;\n const store = trans.objectStore(tableName);\n const source = index.isPrimaryKey ?\n store :\n store.index(index.name);\n const direction = reverse ?\n unique ?\n \"prevunique\" :\n \"prev\" :\n unique ?\n \"nextunique\" :\n \"next\";\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(makeIDBKeyRange(range), direction) :\n source.openKeyCursor(makeIDBKeyRange(range), direction);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(ev => {\n const cursor = req.result;\n if (!cursor) {\n resolve(null);\n return;\n }\n cursor.___id = ++_id_counter;\n cursor.done = false;\n const _cursorContinue = cursor.continue.bind(cursor);\n let _cursorContinuePrimaryKey = cursor.continuePrimaryKey;\n if (_cursorContinuePrimaryKey)\n _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor);\n const _cursorAdvance = cursor.advance.bind(cursor);\n const doThrowCursorIsNotStarted = () => { throw new Error(\"Cursor not started\"); };\n const doThrowCursorIsStopped = () => { throw new Error(\"Cursor not stopped\"); };\n cursor.trans = trans;\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted;\n cursor.fail = wrap(reject);\n cursor.next = function () {\n let gotOne = 1;\n return this.start(() => gotOne-- ? this.continue() : this.stop()).then(() => this);\n };\n cursor.start = (callback) => {\n const iterationPromise = new Promise((resolveIteration, rejectIteration) => {\n resolveIteration = wrap(resolveIteration);\n req.onerror = eventRejectHandler(rejectIteration);\n cursor.fail = rejectIteration;\n cursor.stop = value => {\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped;\n resolveIteration(value);\n };\n });\n const guardedCallback = () => {\n if (req.result) {\n try {\n callback();\n }\n catch (err) {\n cursor.fail(err);\n }\n }\n else {\n cursor.done = true;\n cursor.start = () => { throw new Error(\"Cursor behind last entry\"); };\n cursor.stop();\n }\n };\n req.onsuccess = wrap(ev => {\n req.onsuccess = guardedCallback;\n guardedCallback();\n });\n cursor.continue = _cursorContinue;\n cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n cursor.advance = _cursorAdvance;\n guardedCallback();\n return iterationPromise;\n };\n resolve(cursor);\n }, reject);\n });\n }\n function query(hasGetAll) {\n return (request) => {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const { trans, values, limit, query } = request;\n const nonInfinitLimit = limit === Infinity ? undefined : limit;\n const { index, range } = query;\n const store = trans.objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n if (limit === 0)\n return resolve({ result: [] });\n if (hasGetAll) {\n const req = values ?\n source.getAll(idbKeyRange, nonInfinitLimit) :\n source.getAllKeys(idbKeyRange, nonInfinitLimit);\n req.onsuccess = event => resolve({ result: event.target.result });\n req.onerror = eventRejectHandler(reject);\n }\n else {\n let count = 0;\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(idbKeyRange) :\n source.openKeyCursor(idbKeyRange);\n const result = [];\n req.onsuccess = event => {\n const cursor = req.result;\n if (!cursor)\n return resolve({ result });\n result.push(values ? cursor.value : cursor.primaryKey);\n if (++count === limit)\n return resolve({ result });\n cursor.continue();\n };\n req.onerror = eventRejectHandler(reject);\n }\n });\n };\n }\n return {\n name: tableName,\n schema: tableSchema,\n mutate,\n getMany({ trans, keys }) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = trans.objectStore(tableName);\n const length = keys.length;\n const result = new Array(length);\n let keyCount = 0;\n let callbackCount = 0;\n let req;\n const successHandler = event => {\n const req = event.target;\n if ((result[req._pos] = req.result) != null)\n ;\n if (++callbackCount === keyCount)\n resolve(result);\n };\n const errorHandler = eventRejectHandler(reject);\n for (let i = 0; i < length; ++i) {\n const key = keys[i];\n if (key != null) {\n req = store.get(keys[i]);\n req._pos = i;\n req.onsuccess = successHandler;\n req.onerror = errorHandler;\n ++keyCount;\n }\n }\n if (keyCount === 0)\n resolve(result);\n });\n },\n get({ trans, key }) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = trans.objectStore(tableName);\n const req = store.get(key);\n req.onsuccess = event => resolve(event.target.result);\n req.onerror = eventRejectHandler(reject);\n });\n },\n query: query(hasGetAll),\n openCursor,\n count({ query, trans }) {\n const { index, range } = query;\n return new Promise((resolve, reject) => {\n const store = trans.objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n const req = idbKeyRange ? source.count(idbKeyRange) : source.count();\n req.onsuccess = wrap(ev => resolve(ev.target.result));\n req.onerror = eventRejectHandler(reject);\n });\n }\n };\n }\n const { schema, hasGetAll } = extractSchema(db, tmpTrans);\n const tables = schema.tables.map(tableSchema => createDbCoreTable(tableSchema));\n const tableMap = {};\n tables.forEach(table => tableMap[table.name] = table);\n return {\n stack: \"dbcore\",\n transaction: db.transaction.bind(db),\n table(name) {\n const result = tableMap[name];\n if (!result)\n throw new Error(`Table '${name}' not found`);\n return tableMap[name];\n },\n MIN_KEY: -Infinity,\n MAX_KEY: getMaxKey(IdbKeyRange),\n schema\n };\n}\n\nfunction createMiddlewareStack(stackImpl, middlewares) {\n return middlewares.reduce((down, { create }) => ({ ...down, ...create(down) }), stackImpl);\n}\nfunction createMiddlewareStacks(middlewares, idbdb, { IDBKeyRange, indexedDB }, tmpTrans) {\n const dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore);\n return {\n dbcore\n };\n}\nfunction generateMiddlewareStacks({ _novip: db }, tmpTrans) {\n const idbdb = tmpTrans.db;\n const stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans);\n db.core = stacks.dbcore;\n db.tables.forEach(table => {\n const tableName = table.name;\n if (db.core.schema.tables.some(tbl => tbl.name === tableName)) {\n table.core = db.core.table(tableName);\n if (db[tableName] instanceof db.Table) {\n db[tableName].core = table.core;\n }\n }\n });\n}\n\nfunction setApiOnPlace({ _novip: db }, objs, tableNames, dbschema) {\n tableNames.forEach(tableName => {\n const schema = dbschema[tableName];\n objs.forEach(obj => {\n const propDesc = getPropertyDescriptor(obj, tableName);\n if (!propDesc || (\"value\" in propDesc && propDesc.value === undefined)) {\n if (obj === db.Transaction.prototype || obj instanceof db.Transaction) {\n setProp(obj, tableName, {\n get() { return this.table(tableName); },\n set(value) {\n defineProperty(this, tableName, { value, writable: true, configurable: true, enumerable: true });\n }\n });\n }\n else {\n obj[tableName] = new db.Table(tableName, schema);\n }\n }\n });\n });\n}\nfunction removeTablesApi({ _novip: db }, objs) {\n objs.forEach(obj => {\n for (let key in obj) {\n if (obj[key] instanceof db.Table)\n delete obj[key];\n }\n });\n}\nfunction lowerVersionFirst(a, b) {\n return a._cfg.version - b._cfg.version;\n}\nfunction runUpgraders(db, oldVersion, idbUpgradeTrans, reject) {\n const globalSchema = db._dbSchema;\n const trans = db._createTransaction('readwrite', db._storeNames, globalSchema);\n trans.create(idbUpgradeTrans);\n trans._completion.catch(reject);\n const rejectTransaction = trans._reject.bind(trans);\n const transless = PSD.transless || PSD;\n newScope(() => {\n PSD.trans = trans;\n PSD.transless = transless;\n if (oldVersion === 0) {\n keys(globalSchema).forEach(tableName => {\n createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n generateMiddlewareStacks(db, idbUpgradeTrans);\n DexiePromise.follow(() => db.on.populate.fire(trans)).catch(rejectTransaction);\n }\n else\n updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans).catch(rejectTransaction);\n });\n}\nfunction updateTablesAndIndexes({ _novip: db }, oldVersion, trans, idbUpgradeTrans) {\n const queue = [];\n const versions = db._versions;\n let globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans);\n let anyContentUpgraderHasRun = false;\n const versToRun = versions.filter(v => v._cfg.version >= oldVersion);\n versToRun.forEach(version => {\n queue.push(() => {\n const oldSchema = globalSchema;\n const newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans);\n adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans);\n globalSchema = db._dbSchema = newSchema;\n const diff = getSchemaDiff(oldSchema, newSchema);\n diff.add.forEach(tuple => {\n createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n diff.change.forEach(change => {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n }\n else {\n const store = idbUpgradeTrans.objectStore(change.name);\n change.add.forEach(idx => addIndex(store, idx));\n change.change.forEach(idx => {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n change.del.forEach(idxName => store.deleteIndex(idxName));\n }\n });\n const contentUpgrade = version._cfg.contentUpgrade;\n if (contentUpgrade && version._cfg.version > oldVersion) {\n generateMiddlewareStacks(db, idbUpgradeTrans);\n trans._memoizedTables = {};\n anyContentUpgraderHasRun = true;\n let upgradeSchema = shallowClone(newSchema);\n diff.del.forEach(table => {\n upgradeSchema[table] = oldSchema[table];\n });\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema), upgradeSchema);\n trans.schema = upgradeSchema;\n const contentUpgradeIsAsync = isAsyncFunction(contentUpgrade);\n if (contentUpgradeIsAsync) {\n incrementExpectedAwaits();\n }\n let returnValue;\n const promiseFollowed = DexiePromise.follow(() => {\n returnValue = contentUpgrade(trans);\n if (returnValue) {\n if (contentUpgradeIsAsync) {\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n }\n }\n });\n return (returnValue && typeof returnValue.then === 'function' ?\n DexiePromise.resolve(returnValue) : promiseFollowed.then(() => returnValue));\n }\n });\n queue.push(idbtrans => {\n if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) {\n const newSchema = version._cfg.dbschema;\n deleteRemovedTables(newSchema, idbtrans);\n }\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema);\n trans.schema = db._dbSchema;\n });\n });\n function runQueue() {\n return queue.length ? DexiePromise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) :\n DexiePromise.resolve();\n }\n return runQueue().then(() => {\n createMissingTables(globalSchema, idbUpgradeTrans);\n });\n}\nfunction getSchemaDiff(oldSchema, newSchema) {\n const diff = {\n del: [],\n add: [],\n change: []\n };\n let table;\n for (table in oldSchema) {\n if (!newSchema[table])\n diff.del.push(table);\n }\n for (table in newSchema) {\n const oldDef = oldSchema[table], newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n }\n else {\n const change = {\n name: table,\n def: newDef,\n recreate: false,\n del: [],\n add: [],\n change: []\n };\n if ((\n '' + (oldDef.primKey.keyPath || '')) !== ('' + (newDef.primKey.keyPath || '')) ||\n (oldDef.primKey.auto !== newDef.primKey.auto && !isIEOrEdge))\n {\n change.recreate = true;\n diff.change.push(change);\n }\n else {\n const oldIndexes = oldDef.idxByName;\n const newIndexes = newDef.idxByName;\n let idxName;\n for (idxName in oldIndexes) {\n if (!newIndexes[idxName])\n change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n const oldIdx = oldIndexes[idxName], newIdx = newIndexes[idxName];\n if (!oldIdx)\n change.add.push(newIdx);\n else if (oldIdx.src !== newIdx.src)\n change.change.push(newIdx);\n }\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\n diff.change.push(change);\n }\n }\n }\n }\n return diff;\n}\nfunction createTable(idbtrans, tableName, primKey, indexes) {\n const store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ?\n { keyPath: primKey.keyPath, autoIncrement: primKey.auto } :\n { autoIncrement: primKey.auto });\n indexes.forEach(idx => addIndex(store, idx));\n return store;\n}\nfunction createMissingTables(newSchema, idbtrans) {\n keys(newSchema).forEach(tableName => {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n}\nfunction deleteRemovedTables(newSchema, idbtrans) {\n [].slice.call(idbtrans.db.objectStoreNames).forEach(storeName => newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName));\n}\nfunction addIndex(store, idx) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n}\nfunction buildGlobalSchema(db, idbdb, tmpTrans) {\n const globalSchema = {};\n const dbStoreNames = slice(idbdb.objectStoreNames, 0);\n dbStoreNames.forEach(storeName => {\n const store = tmpTrans.objectStore(storeName);\n let keyPath = store.keyPath;\n const primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || \"\", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== \"string\", true);\n const indexes = [];\n for (let j = 0; j < store.indexNames.length; ++j) {\n const idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n var index = createIndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== \"string\", false);\n indexes.push(index);\n }\n globalSchema[storeName] = createTableSchema(storeName, primKey, indexes);\n });\n return globalSchema;\n}\nfunction readGlobalSchema({ _novip: db }, idbdb, tmpTrans) {\n db.verno = idbdb.version / 10;\n const globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans);\n db._storeNames = slice(idbdb.objectStoreNames, 0);\n setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema);\n}\nfunction verifyInstalledSchema(db, tmpTrans) {\n const installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans);\n const diff = getSchemaDiff(installedSchema, db._dbSchema);\n return !(diff.add.length || diff.change.some(ch => ch.add.length || ch.change.length));\n}\nfunction adjustToExistingIndexNames({ _novip: db }, schema, idbtrans) {\n const storeNames = idbtrans.db.objectStoreNames;\n for (let i = 0; i < storeNames.length; ++i) {\n const storeName = storeNames[i];\n const store = idbtrans.objectStore(storeName);\n db._hasGetAll = 'getAll' in store;\n for (let j = 0; j < store.indexNames.length; ++j) {\n const indexName = store.indexNames[j];\n const keyPath = store.index(indexName).keyPath;\n const dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n const indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) {\n indexSpec.name = indexName;\n delete schema[storeName].idxByName[dexieName];\n schema[storeName].idxByName[indexName] = indexSpec;\n }\n }\n }\n }\n if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604) {\n db._hasGetAll = false;\n }\n}\nfunction parseIndexSyntax(primKeyAndIndexes) {\n return primKeyAndIndexes.split(',').map((index, indexNum) => {\n index = index.trim();\n const name = index.replace(/([&*]|\\+\\+)/g, \"\");\n const keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n return createIndexSpec(name, keyPath || null, /\\&/.test(index), /\\*/.test(index), /\\+\\+/.test(index), isArray(keyPath), indexNum === 0);\n });\n}\n\nclass Version {\n _parseStoresSpec(stores, outSchema) {\n keys(stores).forEach(tableName => {\n if (stores[tableName] !== null) {\n var indexes = parseIndexSyntax(stores[tableName]);\n var primKey = indexes.shift();\n if (primKey.multi)\n throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\n indexes.forEach(idx => {\n if (idx.auto)\n throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\n if (!idx.keyPath)\n throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\n });\n outSchema[tableName] = createTableSchema(tableName, primKey, indexes);\n }\n });\n }\n stores(stores) {\n const db = this.db;\n this._cfg.storesSource = this._cfg.storesSource ?\n extend(this._cfg.storesSource, stores) :\n stores;\n const versions = db._versions;\n const storesSpec = {};\n let dbschema = {};\n versions.forEach(version => {\n extend(storesSpec, version._cfg.storesSource);\n dbschema = (version._cfg.dbschema = {});\n version._parseStoresSpec(storesSpec, dbschema);\n });\n db._dbSchema = dbschema;\n removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]);\n setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);\n db._storeNames = keys(dbschema);\n return this;\n }\n upgrade(upgradeFunction) {\n this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction);\n return this;\n }\n}\n\nfunction createVersionConstructor(db) {\n return makeClassConstructor(Version.prototype, function Version(versionNumber) {\n this.db = db;\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n });\n}\n\nfunction getDbNamesTable(indexedDB, IDBKeyRange) {\n let dbNamesDB = indexedDB[\"_dbNamesDB\"];\n if (!dbNamesDB) {\n dbNamesDB = indexedDB[\"_dbNamesDB\"] = new Dexie$1(DBNAMES_DB, {\n addons: [],\n indexedDB,\n IDBKeyRange,\n });\n dbNamesDB.version(1).stores({ dbnames: \"name\" });\n }\n return dbNamesDB.table(\"dbnames\");\n}\nfunction hasDatabasesNative(indexedDB) {\n return indexedDB && typeof indexedDB.databases === \"function\";\n}\nfunction getDatabaseNames({ indexedDB, IDBKeyRange, }) {\n return hasDatabasesNative(indexedDB)\n ? Promise.resolve(indexedDB.databases()).then((infos) => infos\n .map((info) => info.name)\n .filter((name) => name !== DBNAMES_DB))\n : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys();\n}\nfunction _onDatabaseCreated({ indexedDB, IDBKeyRange }, name) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).put({ name }).catch(nop);\n}\nfunction _onDatabaseDeleted({ indexedDB, IDBKeyRange }, name) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop);\n}\n\nfunction vip(fn) {\n return newScope(function () {\n PSD.letThrough = true;\n return fn();\n });\n}\n\nfunction idbReady() {\n var isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return clearInterval(intervalId); });\n}\n\nfunction dexieOpen(db) {\n const state = db._state;\n const { indexedDB } = db._deps;\n if (state.isBeingOpened || db.idbdb)\n return state.dbReadyPromise.then(() => state.dbOpenError ?\n rejection(state.dbOpenError) :\n db);\n debug && (state.openCanceller._stackHolder = getErrorWithStack());\n state.isBeingOpened = true;\n state.dbOpenError = null;\n state.openComplete = false;\n const openCanceller = state.openCanceller;\n function throwIfCancelled() {\n if (state.openCanceller !== openCanceller)\n throw new exceptions.DatabaseClosed('db.open() was cancelled');\n }\n let resolveDbReady = state.dbReadyResolve,\n upgradeTransaction = null, wasCreated = false;\n return DexiePromise.race([openCanceller, (typeof navigator === 'undefined' ? DexiePromise.resolve() : idbReady()).then(() => new DexiePromise((resolve, reject) => {\n throwIfCancelled();\n if (!indexedDB)\n throw new exceptions.MissingAPI();\n const dbName = db.name;\n const req = state.autoSchema ?\n indexedDB.open(dbName) :\n indexedDB.open(dbName, Math.round(db.verno * 10));\n if (!req)\n throw new exceptions.MissingAPI();\n req.onerror = eventRejectHandler(reject);\n req.onblocked = wrap(db._fireOnBlocked);\n req.onupgradeneeded = wrap(e => {\n upgradeTransaction = req.transaction;\n if (state.autoSchema && !db._options.allowEmptyDB) {\n req.onerror = preventDefault;\n upgradeTransaction.abort();\n req.result.close();\n const delreq = indexedDB.deleteDatabase(dbName);\n delreq.onsuccess = delreq.onerror = wrap(() => {\n reject(new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`));\n });\n }\n else {\n upgradeTransaction.onerror = eventRejectHandler(reject);\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion;\n wasCreated = oldVer < 1;\n db._novip.idbdb = req.result;\n runUpgraders(db, oldVer / 10, upgradeTransaction, reject);\n }\n }, reject);\n req.onsuccess = wrap(() => {\n upgradeTransaction = null;\n const idbdb = db._novip.idbdb = req.result;\n const objectStoreNames = slice(idbdb.objectStoreNames);\n if (objectStoreNames.length > 0)\n try {\n const tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly');\n if (state.autoSchema)\n readGlobalSchema(db, idbdb, tmpTrans);\n else {\n adjustToExistingIndexNames(db, db._dbSchema, tmpTrans);\n if (!verifyInstalledSchema(db, tmpTrans)) {\n console.warn(`Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.`);\n }\n }\n generateMiddlewareStacks(db, tmpTrans);\n }\n catch (e) {\n }\n connections.push(db);\n idbdb.onversionchange = wrap(ev => {\n state.vcFired = true;\n db.on(\"versionchange\").fire(ev);\n });\n idbdb.onclose = wrap(ev => {\n db.on(\"close\").fire(ev);\n });\n if (wasCreated)\n _onDatabaseCreated(db._deps, dbName);\n resolve();\n }, reject);\n }))]).then(() => {\n throwIfCancelled();\n state.onReadyBeingFired = [];\n return DexiePromise.resolve(vip(() => db.on.ready.fire(db.vip))).then(function fireRemainders() {\n if (state.onReadyBeingFired.length > 0) {\n let remainders = state.onReadyBeingFired.reduce(promisableChain, nop);\n state.onReadyBeingFired = [];\n return DexiePromise.resolve(vip(() => remainders(db.vip))).then(fireRemainders);\n }\n });\n }).finally(() => {\n state.onReadyBeingFired = null;\n state.isBeingOpened = false;\n }).then(() => {\n return db;\n }).catch(err => {\n state.dbOpenError = err;\n try {\n upgradeTransaction && upgradeTransaction.abort();\n }\n catch (_a) { }\n if (openCanceller === state.openCanceller) {\n db._close();\n }\n return rejection(err);\n }).finally(() => {\n state.openComplete = true;\n resolveDbReady();\n });\n}\n\nfunction awaitIterator(iterator) {\n var callNext = result => iterator.next(result), doThrow = error => iterator.throw(error), onSuccess = step(callNext), onError = step(doThrow);\n function step(getNext) {\n return (val) => {\n var next = getNext(val), value = next.value;\n return next.done ? value :\n (!value || typeof value.then !== 'function' ?\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\n value.then(onSuccess, onError));\n };\n }\n return step(callNext)();\n}\n\nfunction extractTransactionArgs(mode, _tableArgs_, scopeFunc) {\n var i = arguments.length;\n if (i < 2)\n throw new exceptions.InvalidArgument(\"Too few arguments\");\n var args = new Array(i - 1);\n while (--i)\n args[i - 1] = arguments[i];\n scopeFunc = args.pop();\n var tables = flatten(args);\n return [mode, tables, scopeFunc];\n}\nfunction enterTransactionScope(db, mode, storeNames, parentTransaction, scopeFunc) {\n return DexiePromise.resolve().then(() => {\n const transless = PSD.transless || PSD;\n const trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction);\n const zoneProps = {\n trans: trans,\n transless: transless\n };\n if (parentTransaction) {\n trans.idbtrans = parentTransaction.idbtrans;\n }\n else {\n try {\n trans.create();\n db._state.PR1398_maxLoop = 3;\n }\n catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(() => enterTransactionScope(db, mode, storeNames, null, scopeFunc));\n }\n return rejection(ex);\n }\n }\n const scopeFuncIsAsync = isAsyncFunction(scopeFunc);\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n let returnValue;\n const promiseFollowed = DexiePromise.follow(() => {\n returnValue = scopeFunc.call(trans, trans);\n if (returnValue) {\n if (scopeFuncIsAsync) {\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n }\n else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\n returnValue = awaitIterator(returnValue);\n }\n }\n }, zoneProps);\n return (returnValue && typeof returnValue.then === 'function' ?\n DexiePromise.resolve(returnValue).then(x => trans.active ?\n x\n : rejection(new exceptions.PrematureCommit(\"Transaction committed too early. See http://bit.ly/2kdckMn\")))\n : promiseFollowed.then(() => returnValue)).then(x => {\n if (parentTransaction)\n trans._resolve();\n return trans._completion.then(() => x);\n }).catch(e => {\n trans._reject(e);\n return rejection(e);\n });\n });\n}\n\nfunction pad(a, value, count) {\n const result = isArray(a) ? a.slice() : [a];\n for (let i = 0; i < count; ++i)\n result.push(value);\n return result;\n}\nfunction createVirtualIndexMiddleware(down) {\n return {\n ...down,\n table(tableName) {\n const table = down.table(tableName);\n const { schema } = table;\n const indexLookup = {};\n const allVirtualIndexes = [];\n function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) {\n const keyPathAlias = getKeyPathAlias(keyPath);\n const indexList = (indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []);\n const keyLength = keyPath == null ? 0 : typeof keyPath === 'string' ? 1 : keyPath.length;\n const isVirtual = keyTail > 0;\n const virtualIndex = {\n ...lowLevelIndex,\n isVirtual,\n keyTail,\n keyLength,\n extractKey: getKeyExtractor(keyPath),\n unique: !isVirtual && lowLevelIndex.unique\n };\n indexList.push(virtualIndex);\n if (!virtualIndex.isPrimaryKey) {\n allVirtualIndexes.push(virtualIndex);\n }\n if (keyLength > 1) {\n const virtualKeyPath = keyLength === 2 ?\n keyPath[0] :\n keyPath.slice(0, keyLength - 1);\n addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex);\n }\n indexList.sort((a, b) => a.keyTail - b.keyTail);\n return virtualIndex;\n }\n const primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey);\n indexLookup[\":id\"] = [primaryKey];\n for (const index of schema.indexes) {\n addVirtualIndexes(index.keyPath, 0, index);\n }\n function findBestIndex(keyPath) {\n const result = indexLookup[getKeyPathAlias(keyPath)];\n return result && result[0];\n }\n function translateRange(range, keyTail) {\n return {\n type: range.type === 1 ?\n 2 :\n range.type,\n lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail),\n lowerOpen: true,\n upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail),\n upperOpen: true\n };\n }\n function translateRequest(req) {\n const index = req.query.index;\n return index.isVirtual ? {\n ...req,\n query: {\n index,\n range: translateRange(req.query.range, index.keyTail)\n }\n } : req;\n }\n const result = {\n ...table,\n schema: {\n ...schema,\n primaryKey,\n indexes: allVirtualIndexes,\n getIndexByKeyPath: findBestIndex\n },\n count(req) {\n return table.count(translateRequest(req));\n },\n query(req) {\n return table.query(translateRequest(req));\n },\n openCursor(req) {\n const { keyTail, isVirtual, keyLength } = req.query.index;\n if (!isVirtual)\n return table.openCursor(req);\n function createVirtualCursor(cursor) {\n function _continue(key) {\n key != null ?\n cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) :\n req.unique ?\n cursor.continue(cursor.key.slice(0, keyLength)\n .concat(req.reverse\n ? down.MIN_KEY\n : down.MAX_KEY, keyTail)) :\n cursor.continue();\n }\n const virtualCursor = Object.create(cursor, {\n continue: { value: _continue },\n continuePrimaryKey: {\n value(key, primaryKey) {\n cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey);\n }\n },\n primaryKey: {\n get() {\n return cursor.primaryKey;\n }\n },\n key: {\n get() {\n const key = cursor.key;\n return keyLength === 1 ?\n key[0] :\n key.slice(0, keyLength);\n }\n },\n value: {\n get() {\n return cursor.value;\n }\n }\n });\n return virtualCursor;\n }\n return table.openCursor(translateRequest(req))\n .then(cursor => cursor && createVirtualCursor(cursor));\n }\n };\n return result;\n }\n };\n}\nconst virtualIndexMiddleware = {\n stack: \"dbcore\",\n name: \"VirtualIndexMiddleware\",\n level: 1,\n create: createVirtualIndexMiddleware\n};\n\nfunction getObjectDiff(a, b, rv, prfx) {\n rv = rv || {};\n prfx = prfx || '';\n keys(a).forEach((prop) => {\n if (!hasOwn(b, prop)) {\n rv[prfx + prop] = undefined;\n }\n else {\n var ap = a[prop], bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) {\n const apTypeName = toStringTag(ap);\n const bpTypeName = toStringTag(bp);\n if (apTypeName !== bpTypeName) {\n rv[prfx + prop] = b[prop];\n }\n else if (apTypeName === 'Object') {\n getObjectDiff(ap, bp, rv, prfx + prop + '.');\n }\n else if (ap !== bp) {\n rv[prfx + prop] = b[prop];\n }\n }\n else if (ap !== bp)\n rv[prfx + prop] = b[prop];\n }\n });\n keys(b).forEach((prop) => {\n if (!hasOwn(a, prop)) {\n rv[prfx + prop] = b[prop];\n }\n });\n return rv;\n}\n\nfunction getEffectiveKeys(primaryKey, req) {\n if (req.type === 'delete')\n return req.keys;\n return req.keys || req.values.map(primaryKey.extractKey);\n}\n\nconst hooksMiddleware = {\n stack: \"dbcore\",\n name: \"HooksMiddleware\",\n level: 2,\n create: (downCore) => ({\n ...downCore,\n table(tableName) {\n const downTable = downCore.table(tableName);\n const { primaryKey } = downTable.schema;\n const tableMiddleware = {\n ...downTable,\n mutate(req) {\n const dxTrans = PSD.trans;\n const { deleting, creating, updating } = dxTrans.table(tableName).hook;\n switch (req.type) {\n case 'add':\n if (creating.fire === nop)\n break;\n return dxTrans._promise('readwrite', () => addPutOrDelete(req), true);\n case 'put':\n if (creating.fire === nop && updating.fire === nop)\n break;\n return dxTrans._promise('readwrite', () => addPutOrDelete(req), true);\n case 'delete':\n if (deleting.fire === nop)\n break;\n return dxTrans._promise('readwrite', () => addPutOrDelete(req), true);\n case 'deleteRange':\n if (deleting.fire === nop)\n break;\n return dxTrans._promise('readwrite', () => deleteRange(req), true);\n }\n return downTable.mutate(req);\n function addPutOrDelete(req) {\n const dxTrans = PSD.trans;\n const keys = req.keys || getEffectiveKeys(primaryKey, req);\n if (!keys)\n throw new Error(\"Keys missing\");\n req = req.type === 'add' || req.type === 'put' ?\n { ...req, keys } :\n { ...req };\n if (req.type !== 'delete')\n req.values = [...req.values];\n if (req.keys)\n req.keys = [...req.keys];\n return getExistingValues(downTable, req, keys).then(existingValues => {\n const contexts = keys.map((key, i) => {\n const existingValue = existingValues[i];\n const ctx = { onerror: null, onsuccess: null };\n if (req.type === 'delete') {\n deleting.fire.call(ctx, key, existingValue, dxTrans);\n }\n else if (req.type === 'add' || existingValue === undefined) {\n const generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans);\n if (key == null && generatedPrimaryKey != null) {\n key = generatedPrimaryKey;\n req.keys[i] = key;\n if (!primaryKey.outbound) {\n setByKeyPath(req.values[i], primaryKey.keyPath, key);\n }\n }\n }\n else {\n const objectDiff = getObjectDiff(existingValue, req.values[i]);\n const additionalChanges = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans);\n if (additionalChanges) {\n const requestedValue = req.values[i];\n Object.keys(additionalChanges).forEach(keyPath => {\n if (hasOwn(requestedValue, keyPath)) {\n requestedValue[keyPath] = additionalChanges[keyPath];\n }\n else {\n setByKeyPath(requestedValue, keyPath, additionalChanges[keyPath]);\n }\n });\n }\n }\n return ctx;\n });\n return downTable.mutate(req).then(({ failures, results, numFailures, lastResult }) => {\n for (let i = 0; i < keys.length; ++i) {\n const primKey = results ? results[i] : keys[i];\n const ctx = contexts[i];\n if (primKey == null) {\n ctx.onerror && ctx.onerror(failures[i]);\n }\n else {\n ctx.onsuccess && ctx.onsuccess(req.type === 'put' && existingValues[i] ?\n req.values[i] :\n primKey\n );\n }\n }\n return { failures, results, numFailures, lastResult };\n }).catch(error => {\n contexts.forEach(ctx => ctx.onerror && ctx.onerror(error));\n return Promise.reject(error);\n });\n });\n }\n function deleteRange(req) {\n return deleteNextChunk(req.trans, req.range, 10000);\n }\n function deleteNextChunk(trans, range, limit) {\n return downTable.query({ trans, values: false, query: { index: primaryKey, range }, limit })\n .then(({ result }) => {\n return addPutOrDelete({ type: 'delete', keys: result, trans }).then(res => {\n if (res.numFailures > 0)\n return Promise.reject(res.failures[0]);\n if (result.length < limit) {\n return { failures: [], numFailures: 0, lastResult: undefined };\n }\n else {\n return deleteNextChunk(trans, { ...range, lower: result[result.length - 1], lowerOpen: true }, limit);\n }\n });\n });\n }\n }\n };\n return tableMiddleware;\n },\n })\n};\nfunction getExistingValues(table, req, effectiveKeys) {\n return req.type === \"add\"\n ? Promise.resolve([])\n : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: \"immutable\" });\n}\n\nfunction getFromTransactionCache(keys, cache, clone) {\n try {\n if (!cache)\n return null;\n if (cache.keys.length < keys.length)\n return null;\n const result = [];\n for (let i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) {\n if (cmp(cache.keys[i], keys[j]) !== 0)\n continue;\n result.push(clone ? deepClone(cache.values[i]) : cache.values[i]);\n ++j;\n }\n return result.length === keys.length ? result : null;\n }\n catch (_a) {\n return null;\n }\n}\nconst cacheExistingValuesMiddleware = {\n stack: \"dbcore\",\n level: -1,\n create: (core) => {\n return {\n table: (tableName) => {\n const table = core.table(tableName);\n return {\n ...table,\n getMany: (req) => {\n if (!req.cache) {\n return table.getMany(req);\n }\n const cachedResult = getFromTransactionCache(req.keys, req.trans[\"_cache\"], req.cache === \"clone\");\n if (cachedResult) {\n return DexiePromise.resolve(cachedResult);\n }\n return table.getMany(req).then((res) => {\n req.trans[\"_cache\"] = {\n keys: req.keys,\n values: req.cache === \"clone\" ? deepClone(res) : res,\n };\n return res;\n });\n },\n mutate: (req) => {\n if (req.type !== \"add\")\n req.trans[\"_cache\"] = null;\n return table.mutate(req);\n },\n };\n },\n };\n },\n};\n\nfunction isEmptyRange(node) {\n return !(\"from\" in node);\n}\nconst RangeSet = function (fromOrTree, to) {\n if (this) {\n extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 });\n }\n else {\n const rv = new RangeSet();\n if (fromOrTree && (\"d\" in fromOrTree)) {\n extend(rv, fromOrTree);\n }\n return rv;\n }\n};\nprops(RangeSet.prototype, {\n add(rangeSet) {\n mergeRanges(this, rangeSet);\n return this;\n },\n addKey(key) {\n addRange(this, key, key);\n return this;\n },\n addKeys(keys) {\n keys.forEach(key => addRange(this, key, key));\n return this;\n },\n [iteratorSymbol]() {\n return getRangeSetIterator(this);\n }\n});\nfunction addRange(target, from, to) {\n const diff = cmp(from, to);\n if (isNaN(diff))\n return;\n if (diff > 0)\n throw RangeError();\n if (isEmptyRange(target))\n return extend(target, { from, to, d: 1 });\n const left = target.l;\n const right = target.r;\n if (cmp(to, target.from) < 0) {\n left\n ? addRange(left, from, to)\n : (target.l = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.to) > 0) {\n right\n ? addRange(right, from, to)\n : (target.r = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.from) < 0) {\n target.from = from;\n target.l = null;\n target.d = right ? right.d + 1 : 1;\n }\n if (cmp(to, target.to) > 0) {\n target.to = to;\n target.r = null;\n target.d = target.l ? target.l.d + 1 : 1;\n }\n const rightWasCutOff = !target.r;\n if (left && !target.l) {\n mergeRanges(target, left);\n }\n if (right && rightWasCutOff) {\n mergeRanges(target, right);\n }\n}\nfunction mergeRanges(target, newSet) {\n function _addRangeSet(target, { from, to, l, r }) {\n addRange(target, from, to);\n if (l)\n _addRangeSet(target, l);\n if (r)\n _addRangeSet(target, r);\n }\n if (!isEmptyRange(newSet))\n _addRangeSet(target, newSet);\n}\nfunction rangesOverlap(rangeSet1, rangeSet2) {\n const i1 = getRangeSetIterator(rangeSet2);\n let nextResult1 = i1.next();\n if (nextResult1.done)\n return false;\n let a = nextResult1.value;\n const i2 = getRangeSetIterator(rangeSet1);\n let nextResult2 = i2.next(a.from);\n let b = nextResult2.value;\n while (!nextResult1.done && !nextResult2.done) {\n if (cmp(b.from, a.to) <= 0 && cmp(b.to, a.from) >= 0)\n return true;\n cmp(a.from, b.from) < 0\n ? (a = (nextResult1 = i1.next(b.from)).value)\n : (b = (nextResult2 = i2.next(a.from)).value);\n }\n return false;\n}\nfunction getRangeSetIterator(node) {\n let state = isEmptyRange(node) ? null : { s: 0, n: node };\n return {\n next(key) {\n const keyProvided = arguments.length > 0;\n while (state) {\n switch (state.s) {\n case 0:\n state.s = 1;\n if (keyProvided) {\n while (state.n.l && cmp(key, state.n.from) < 0)\n state = { up: state, n: state.n.l, s: 1 };\n }\n else {\n while (state.n.l)\n state = { up: state, n: state.n.l, s: 1 };\n }\n case 1:\n state.s = 2;\n if (!keyProvided || cmp(key, state.n.to) <= 0)\n return { value: state.n, done: false };\n case 2:\n if (state.n.r) {\n state.s = 3;\n state = { up: state, n: state.n.r, s: 0 };\n continue;\n }\n case 3:\n state = state.up;\n }\n }\n return { done: true };\n },\n };\n}\nfunction rebalance(target) {\n var _a, _b;\n const diff = (((_a = target.r) === null || _a === void 0 ? void 0 : _a.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0);\n const r = diff > 1 ? \"r\" : diff < -1 ? \"l\" : \"\";\n if (r) {\n const l = r === \"r\" ? \"l\" : \"r\";\n const rootClone = { ...target };\n const oldRootRight = target[r];\n target.from = oldRootRight.from;\n target.to = oldRootRight.to;\n target[r] = oldRootRight[r];\n rootClone[r] = oldRootRight[l];\n target[l] = rootClone;\n rootClone.d = computeDepth(rootClone);\n }\n target.d = computeDepth(target);\n}\nfunction computeDepth({ r, l }) {\n return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1;\n}\n\nconst observabilityMiddleware = {\n stack: \"dbcore\",\n level: 0,\n create: (core) => {\n const dbName = core.schema.name;\n const FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY);\n return {\n ...core,\n table: (tableName) => {\n const table = core.table(tableName);\n const { schema } = table;\n const { primaryKey } = schema;\n const { extractKey, outbound } = primaryKey;\n const tableClone = {\n ...table,\n mutate: (req) => {\n const trans = req.trans;\n const mutatedParts = trans.mutatedParts || (trans.mutatedParts = {});\n const getRangeSet = (indexName) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (mutatedParts[part] ||\n (mutatedParts[part] = new RangeSet()));\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n const { type } = req;\n let [keys, newObjs] = req.type === \"deleteRange\"\n ? [req.range]\n : req.type === \"delete\"\n ? [req.keys]\n : req.values.length < 50\n ? [[], req.values]\n : [];\n const oldCache = req.trans[\"_cache\"];\n return table.mutate(req).then((res) => {\n if (isArray(keys)) {\n if (type !== \"delete\")\n keys = res.results;\n pkRangeSet.addKeys(keys);\n const oldObjs = getFromTransactionCache(keys, oldCache);\n if (!oldObjs && type !== \"add\") {\n delsRangeSet.addKeys(keys);\n }\n if (oldObjs || newObjs) {\n trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs);\n }\n }\n else if (keys) {\n const range = { from: keys.lower, to: keys.upper };\n delsRangeSet.add(range);\n pkRangeSet.add(range);\n }\n else {\n pkRangeSet.add(FULL_RANGE);\n delsRangeSet.add(FULL_RANGE);\n schema.indexes.forEach(idx => getRangeSet(idx.name).add(FULL_RANGE));\n }\n return res;\n });\n },\n };\n const getRange = ({ query: { index, range }, }) => {\n var _a, _b;\n return [\n index,\n new RangeSet((_a = range.lower) !== null && _a !== void 0 ? _a : core.MIN_KEY, (_b = range.upper) !== null && _b !== void 0 ? _b : core.MAX_KEY),\n ];\n };\n const readSubscribers = {\n get: (req) => [primaryKey, new RangeSet(req.key)],\n getMany: (req) => [primaryKey, new RangeSet().addKeys(req.keys)],\n count: getRange,\n query: getRange,\n openCursor: getRange,\n };\n keys(readSubscribers).forEach(method => {\n tableClone[method] = function (req) {\n const { subscr } = PSD;\n if (subscr) {\n const getRangeSet = (indexName) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (subscr[part] ||\n (subscr[part] = new RangeSet()));\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n const [queriedIndex, queriedRanges] = readSubscribers[method](req);\n getRangeSet(queriedIndex.name || \"\").add(queriedRanges);\n if (!queriedIndex.isPrimaryKey) {\n if (method === \"count\") {\n delsRangeSet.add(FULL_RANGE);\n }\n else {\n const keysPromise = method === \"query\" &&\n outbound &&\n req.values &&\n table.query({\n ...req,\n values: false,\n });\n return table[method].apply(this, arguments).then((res) => {\n if (method === \"query\") {\n if (outbound && req.values) {\n return keysPromise.then(({ result: resultingKeys }) => {\n pkRangeSet.addKeys(resultingKeys);\n return res;\n });\n }\n const pKeys = req.values\n ? res.result.map(extractKey)\n : res.result;\n if (req.values) {\n pkRangeSet.addKeys(pKeys);\n }\n else {\n delsRangeSet.addKeys(pKeys);\n }\n }\n else if (method === \"openCursor\") {\n const cursor = res;\n const wantValues = req.values;\n return (cursor &&\n Object.create(cursor, {\n key: {\n get() {\n delsRangeSet.addKey(cursor.primaryKey);\n return cursor.key;\n },\n },\n primaryKey: {\n get() {\n const pkey = cursor.primaryKey;\n delsRangeSet.addKey(pkey);\n return pkey;\n },\n },\n value: {\n get() {\n wantValues && pkRangeSet.addKey(cursor.primaryKey);\n return cursor.value;\n },\n },\n }));\n }\n return res;\n });\n }\n }\n }\n return table[method].apply(this, arguments);\n };\n });\n return tableClone;\n },\n };\n },\n};\nfunction trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) {\n function addAffectedIndex(ix) {\n const rangeSet = getRangeSet(ix.name || \"\");\n function extractKey(obj) {\n return obj != null ? ix.extractKey(obj) : null;\n }\n const addKeyOrKeys = (key) => ix.multiEntry && isArray(key)\n ? key.forEach(key => rangeSet.addKey(key))\n : rangeSet.addKey(key);\n (oldObjs || newObjs).forEach((_, i) => {\n const oldKey = oldObjs && extractKey(oldObjs[i]);\n const newKey = newObjs && extractKey(newObjs[i]);\n if (cmp(oldKey, newKey) !== 0) {\n if (oldKey != null)\n addKeyOrKeys(oldKey);\n if (newKey != null)\n addKeyOrKeys(newKey);\n }\n });\n }\n schema.indexes.forEach(addAffectedIndex);\n}\n\nclass Dexie$1 {\n constructor(name, options) {\n this._middlewares = {};\n this.verno = 0;\n const deps = Dexie$1.dependencies;\n this._options = options = {\n addons: Dexie$1.addons,\n autoOpen: true,\n indexedDB: deps.indexedDB,\n IDBKeyRange: deps.IDBKeyRange,\n ...options\n };\n this._deps = {\n indexedDB: options.indexedDB,\n IDBKeyRange: options.IDBKeyRange\n };\n const { addons, } = options;\n this._dbSchema = {};\n this._versions = [];\n this._storeNames = [];\n this._allTables = {};\n this.idbdb = null;\n this._novip = this;\n const state = {\n dbOpenError: null,\n isBeingOpened: false,\n onReadyBeingFired: null,\n openComplete: false,\n dbReadyResolve: nop,\n dbReadyPromise: null,\n cancelOpen: nop,\n openCanceller: null,\n autoSchema: true,\n PR1398_maxLoop: 3\n };\n state.dbReadyPromise = new DexiePromise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new DexiePromise((_, reject) => {\n state.cancelOpen = reject;\n });\n this._state = state;\n this.name = name;\n this.on = Events(this, \"populate\", \"blocked\", \"versionchange\", \"close\", { ready: [promisableChain, nop] });\n this.on.ready.subscribe = override(this.on.ready.subscribe, subscribe => {\n return (subscriber, bSticky) => {\n Dexie$1.vip(() => {\n const state = this._state;\n if (state.openComplete) {\n if (!state.dbOpenError)\n DexiePromise.resolve().then(subscriber);\n if (bSticky)\n subscribe(subscriber);\n }\n else if (state.onReadyBeingFired) {\n state.onReadyBeingFired.push(subscriber);\n if (bSticky)\n subscribe(subscriber);\n }\n else {\n subscribe(subscriber);\n const db = this;\n if (!bSticky)\n subscribe(function unsubscribe() {\n db.on.ready.unsubscribe(subscriber);\n db.on.ready.unsubscribe(unsubscribe);\n });\n }\n });\n };\n });\n this.Collection = createCollectionConstructor(this);\n this.Table = createTableConstructor(this);\n this.Transaction = createTransactionConstructor(this);\n this.Version = createVersionConstructor(this);\n this.WhereClause = createWhereClauseConstructor(this);\n this.on(\"versionchange\", ev => {\n if (ev.newVersion > 0)\n console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`);\n else\n console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`);\n this.close();\n });\n this.on(\"blocked\", ev => {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\n console.warn(`Dexie.delete('${this.name}') was blocked`);\n else\n console.warn(`Upgrade '${this.name}' blocked by other connection holding version ${ev.oldVersion / 10}`);\n });\n this._maxKey = getMaxKey(options.IDBKeyRange);\n this._createTransaction = (mode, storeNames, dbschema, parentTransaction) => new this.Transaction(mode, storeNames, dbschema, this._options.chromeTransactionDurability, parentTransaction);\n this._fireOnBlocked = ev => {\n this.on(\"blocked\").fire(ev);\n connections\n .filter(c => c.name === this.name && c !== this && !c._state.vcFired)\n .map(c => c.on(\"versionchange\").fire(ev));\n };\n this.use(virtualIndexMiddleware);\n this.use(hooksMiddleware);\n this.use(observabilityMiddleware);\n this.use(cacheExistingValuesMiddleware);\n this.vip = Object.create(this, { _vip: { value: true } });\n addons.forEach(addon => addon(this));\n }\n version(versionNumber) {\n if (isNaN(versionNumber) || versionNumber < 0.1)\n throw new exceptions.Type(`Given version is not a positive number`);\n versionNumber = Math.round(versionNumber * 10) / 10;\n if (this.idbdb || this._state.isBeingOpened)\n throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n const versions = this._versions;\n var versionInstance = versions.filter(v => v._cfg.version === versionNumber)[0];\n if (versionInstance)\n return versionInstance;\n versionInstance = new this.Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n versionInstance.stores({});\n this._state.autoSchema = false;\n return versionInstance;\n }\n _whenReady(fn) {\n return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new DexiePromise((resolve, reject) => {\n if (this._state.openComplete) {\n return reject(new exceptions.DatabaseClosed(this._state.dbOpenError));\n }\n if (!this._state.isBeingOpened) {\n if (!this._options.autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n this.open().catch(nop);\n }\n this._state.dbReadyPromise.then(resolve, reject);\n }).then(fn);\n }\n use({ stack, create, level, name }) {\n if (name)\n this.unuse({ stack, name });\n const middlewares = this._middlewares[stack] || (this._middlewares[stack] = []);\n middlewares.push({ stack, create, level: level == null ? 10 : level, name });\n middlewares.sort((a, b) => a.level - b.level);\n return this;\n }\n unuse({ stack, name, create }) {\n if (stack && this._middlewares[stack]) {\n this._middlewares[stack] = this._middlewares[stack].filter(mw => create ? mw.create !== create :\n name ? mw.name !== name :\n false);\n }\n return this;\n }\n open() {\n return dexieOpen(this);\n }\n _close() {\n const state = this._state;\n const idx = connections.indexOf(this);\n if (idx >= 0)\n connections.splice(idx, 1);\n if (this.idbdb) {\n try {\n this.idbdb.close();\n }\n catch (e) { }\n this._novip.idbdb = null;\n }\n state.dbReadyPromise = new DexiePromise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new DexiePromise((_, reject) => {\n state.cancelOpen = reject;\n });\n }\n close() {\n this._close();\n const state = this._state;\n this._options.autoOpen = false;\n state.dbOpenError = new exceptions.DatabaseClosed();\n if (state.isBeingOpened)\n state.cancelOpen(state.dbOpenError);\n }\n delete() {\n const hasArguments = arguments.length > 0;\n const state = this._state;\n return new DexiePromise((resolve, reject) => {\n const doDelete = () => {\n this.close();\n var req = this._deps.indexedDB.deleteDatabase(this.name);\n req.onsuccess = wrap(() => {\n _onDatabaseDeleted(this._deps, this.name);\n resolve();\n });\n req.onerror = eventRejectHandler(reject);\n req.onblocked = this._fireOnBlocked;\n };\n if (hasArguments)\n throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\n if (state.isBeingOpened) {\n state.dbReadyPromise.then(doDelete);\n }\n else {\n doDelete();\n }\n });\n }\n backendDB() {\n return this.idbdb;\n }\n isOpen() {\n return this.idbdb !== null;\n }\n hasBeenClosed() {\n const dbOpenError = this._state.dbOpenError;\n return dbOpenError && (dbOpenError.name === 'DatabaseClosed');\n }\n hasFailed() {\n return this._state.dbOpenError !== null;\n }\n dynamicallyOpened() {\n return this._state.autoSchema;\n }\n get tables() {\n return keys(this._allTables).map(name => this._allTables[name]);\n }\n transaction() {\n const args = extractTransactionArgs.apply(this, arguments);\n return this._transaction.apply(this, args);\n }\n _transaction(mode, tables, scopeFunc) {\n let parentTransaction = PSD.trans;\n if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1)\n parentTransaction = null;\n const onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', '');\n let idbMode, storeNames;\n try {\n storeNames = tables.map(table => {\n var storeName = table instanceof this.Table ? table.name : table;\n if (typeof storeName !== 'string')\n throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\n return storeName;\n });\n if (mode == \"r\" || mode === READONLY)\n idbMode = READONLY;\n else if (mode == \"rw\" || mode == READWRITE)\n idbMode = READWRITE;\n else\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n if (parentTransaction) {\n if (parentTransaction.mode === READONLY && idbMode === READWRITE) {\n if (onlyIfCompatible) {\n parentTransaction = null;\n }\n else\n throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\n }\n if (parentTransaction) {\n storeNames.forEach(storeName => {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n parentTransaction = null;\n }\n else\n throw new exceptions.SubTransaction(\"Table \" + storeName +\n \" not included in parent transaction.\");\n }\n });\n }\n if (onlyIfCompatible && parentTransaction && !parentTransaction.active) {\n parentTransaction = null;\n }\n }\n }\n catch (e) {\n return parentTransaction ?\n parentTransaction._promise(null, (_, reject) => { reject(e); }) :\n rejection(e);\n }\n const enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc);\n return (parentTransaction ?\n parentTransaction._promise(idbMode, enterTransaction, \"lock\") :\n PSD.trans ?\n usePSD(PSD.transless, () => this._whenReady(enterTransaction)) :\n this._whenReady(enterTransaction));\n }\n table(tableName) {\n if (!hasOwn(this._allTables, tableName)) {\n throw new exceptions.InvalidTable(`Table ${tableName} does not exist`);\n }\n return this._allTables[tableName];\n }\n}\n\nconst symbolObservable = typeof Symbol !== \"undefined\" && \"observable\" in Symbol\n ? Symbol.observable\n : \"@@observable\";\nclass Observable {\n constructor(subscribe) {\n this._subscribe = subscribe;\n }\n subscribe(x, error, complete) {\n return this._subscribe(!x || typeof x === \"function\" ? { next: x, error, complete } : x);\n }\n [symbolObservable]() {\n return this;\n }\n}\n\nfunction extendObservabilitySet(target, newSet) {\n keys(newSet).forEach(part => {\n const rangeSet = target[part] || (target[part] = new RangeSet());\n mergeRanges(rangeSet, newSet[part]);\n });\n return target;\n}\n\nfunction liveQuery(querier) {\n return new Observable((observer) => {\n const scopeFuncIsAsync = isAsyncFunction(querier);\n function execute(subscr) {\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n const exec = () => newScope(querier, { subscr, trans: null });\n const rv = PSD.trans\n ?\n usePSD(PSD.transless, exec)\n : exec();\n if (scopeFuncIsAsync) {\n rv.then(decrementExpectedAwaits, decrementExpectedAwaits);\n }\n return rv;\n }\n let closed = false;\n let accumMuts = {};\n let currentObs = {};\n const subscription = {\n get closed() {\n return closed;\n },\n unsubscribe: () => {\n closed = true;\n globalEvents.storagemutated.unsubscribe(mutationListener);\n },\n };\n observer.start && observer.start(subscription);\n let querying = false, startedListening = false;\n function shouldNotify() {\n return keys(currentObs).some((key) => accumMuts[key] && rangesOverlap(accumMuts[key], currentObs[key]));\n }\n const mutationListener = (parts) => {\n extendObservabilitySet(accumMuts, parts);\n if (shouldNotify()) {\n doQuery();\n }\n };\n const doQuery = () => {\n if (querying || closed)\n return;\n accumMuts = {};\n const subscr = {};\n const ret = execute(subscr);\n if (!startedListening) {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener);\n startedListening = true;\n }\n querying = true;\n Promise.resolve(ret).then((result) => {\n querying = false;\n if (closed)\n return;\n if (shouldNotify()) {\n doQuery();\n }\n else {\n accumMuts = {};\n currentObs = subscr;\n observer.next && observer.next(result);\n }\n }, (err) => {\n querying = false;\n observer.error && observer.error(err);\n subscription.unsubscribe();\n });\n };\n doQuery();\n return subscription;\n });\n}\n\nlet domDeps;\ntry {\n domDeps = {\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n };\n}\ncatch (e) {\n domDeps = { indexedDB: null, IDBKeyRange: null };\n}\n\nconst Dexie = Dexie$1;\nprops(Dexie, {\n ...fullNameExceptions,\n delete(databaseName) {\n const db = new Dexie(databaseName, { addons: [] });\n return db.delete();\n },\n exists(name) {\n return new Dexie(name, { addons: [] }).open().then(db => {\n db.close();\n return true;\n }).catch('NoSuchDatabaseError', () => false);\n },\n getDatabaseNames(cb) {\n try {\n return getDatabaseNames(Dexie.dependencies).then(cb);\n }\n catch (_a) {\n return rejection(new exceptions.MissingAPI());\n }\n },\n defineClass() {\n function Class(content) {\n extend(this, content);\n }\n return Class;\n },\n ignoreTransaction(scopeFunc) {\n return PSD.trans ?\n usePSD(PSD.transless, scopeFunc) :\n scopeFunc();\n },\n vip,\n async: function (generatorFn) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function')\n return DexiePromise.resolve(rv);\n return rv;\n }\n catch (e) {\n return rejection(e);\n }\n };\n },\n spawn: function (generatorFn, args, thiz) {\n try {\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\n if (!rv || typeof rv.then !== 'function')\n return DexiePromise.resolve(rv);\n return rv;\n }\n catch (e) {\n return rejection(e);\n }\n },\n currentTransaction: {\n get: () => PSD.trans || null\n },\n waitFor: function (promiseOrFunction, optionalTimeout) {\n const promise = DexiePromise.resolve(typeof promiseOrFunction === 'function' ?\n Dexie.ignoreTransaction(promiseOrFunction) :\n promiseOrFunction)\n .timeout(optionalTimeout || 60000);\n return PSD.trans ?\n PSD.trans.waitFor(promise) :\n promise;\n },\n Promise: DexiePromise,\n debug: {\n get: () => debug,\n set: value => {\n setDebug(value, value === 'dexie' ? () => true : dexieStackFrameFilter);\n }\n },\n derive: derive,\n extend: extend,\n props: props,\n override: override,\n Events: Events,\n on: globalEvents,\n liveQuery,\n extendObservabilitySet,\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n cmp,\n asap: asap$1,\n minKey: minKey,\n addons: [],\n connections: connections,\n errnames: errnames,\n dependencies: domDeps,\n semVer: DEXIE_VERSION,\n version: DEXIE_VERSION.split('.')\n .map(n => parseInt(n))\n .reduce((p, c, i) => p + (c / Math.pow(10, i * 2))),\n});\nDexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange);\n\nif (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, updatedParts => {\n if (!propagatingLocally) {\n let event;\n if (isIEOrEdge) {\n event = document.createEvent('CustomEvent');\n event.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts);\n }\n else {\n event = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, {\n detail: updatedParts\n });\n }\n propagatingLocally = true;\n dispatchEvent(event);\n propagatingLocally = false;\n }\n });\n addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, ({ detail }) => {\n if (!propagatingLocally) {\n propagateLocally(detail);\n }\n });\n}\nfunction propagateLocally(updateParts) {\n let wasMe = propagatingLocally;\n try {\n propagatingLocally = true;\n globalEvents.storagemutated.fire(updateParts);\n }\n finally {\n propagatingLocally = wasMe;\n }\n}\nlet propagatingLocally = false;\n\nif (typeof BroadcastChannel !== 'undefined') {\n const bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME);\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n if (!propagatingLocally) {\n bc.postMessage(changedParts);\n }\n });\n bc.onmessage = (ev) => {\n if (ev.data)\n propagateLocally(ev.data);\n };\n}\nelse if (typeof self !== 'undefined' && typeof navigator !== 'undefined') {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n try {\n if (!propagatingLocally) {\n if (typeof localStorage !== 'undefined') {\n localStorage.setItem(STORAGE_MUTATED_DOM_EVENT_NAME, JSON.stringify({\n trig: Math.random(),\n changedParts,\n }));\n }\n if (typeof self['clients'] === 'object') {\n [...self['clients'].matchAll({ includeUncontrolled: true })].forEach((client) => client.postMessage({\n type: STORAGE_MUTATED_DOM_EVENT_NAME,\n changedParts,\n }));\n }\n }\n }\n catch (_a) { }\n });\n if (typeof addEventListener !== 'undefined') {\n addEventListener('storage', (ev) => {\n if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) {\n const data = JSON.parse(ev.newValue);\n if (data)\n propagateLocally(data.changedParts);\n }\n });\n }\n const swContainer = self.document && navigator.serviceWorker;\n if (swContainer) {\n swContainer.addEventListener('message', propagateMessageLocally);\n }\n}\nfunction propagateMessageLocally({ data }) {\n if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) {\n propagateLocally(data.changedParts);\n }\n}\n\nDexiePromise.rejectionMapper = mapError;\nsetDebug(debug, dexieStackFrameFilter);\n\n\n//# sourceMappingURL=dexie.mjs.map\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/dexie/dist/modern/dexie.mjs?");
2327
+ eval("/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ Dexie$1)\n/* harmony export */ });\n/* unused harmony exports Dexie, RangeSet, liveQuery, mergeRanges, rangesOverlap */\n/*\n * Dexie.js - a minimalistic wrapper for IndexedDB\n * ===============================================\n *\n * By David Fahlander, david.fahlander@gmail.com\n *\n * Version 3.2.4, Tue May 30 2023\n *\n * https://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n */\n \nconst _global = typeof globalThis !== 'undefined' ? globalThis :\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\n\nconst keys = Object.keys;\nconst isArray = Array.isArray;\nif (typeof Promise !== 'undefined' && !_global.Promise) {\n _global.Promise = Promise;\n}\nfunction extend(obj, extension) {\n if (typeof extension !== 'object')\n return obj;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj;\n}\nconst getProto = Object.getPrototypeOf;\nconst _hasOwn = {}.hasOwnProperty;\nfunction hasOwn(obj, prop) {\n return _hasOwn.call(obj, prop);\n}\nfunction props(proto, extension) {\n if (typeof extension === 'function')\n extension = extension(getProto(proto));\n (typeof Reflect === \"undefined\" ? keys : Reflect.ownKeys)(extension).forEach(key => {\n setProp(proto, key, extension[key]);\n });\n}\nconst defineProperty = Object.defineProperty;\nfunction setProp(obj, prop, functionOrGetSet, options) {\n defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\n { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } :\n { value: functionOrGetSet, configurable: true, writable: true }, options));\n}\nfunction derive(Child) {\n return {\n from: function (Parent) {\n Child.prototype = Object.create(Parent.prototype);\n setProp(Child.prototype, \"constructor\", Child);\n return {\n extend: props.bind(null, Child.prototype)\n };\n }\n };\n}\nconst getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nfunction getPropertyDescriptor(obj, prop) {\n const pd = getOwnPropertyDescriptor(obj, prop);\n let proto;\n return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop);\n}\nconst _slice = [].slice;\nfunction slice(args, start, end) {\n return _slice.call(args, start, end);\n}\nfunction override(origFunc, overridedFactory) {\n return overridedFactory(origFunc);\n}\nfunction assert(b) {\n if (!b)\n throw new Error(\"Assertion Failed\");\n}\nfunction asap$1(fn) {\n if (_global.setImmediate)\n setImmediate(fn);\n else\n setTimeout(fn, 0);\n}\nfunction arrayToObject(array, extractor) {\n return array.reduce((result, item, i) => {\n var nameAndValue = extractor(item, i);\n if (nameAndValue)\n result[nameAndValue[0]] = nameAndValue[1];\n return result;\n }, {});\n}\nfunction tryCatch(fn, onerror, args) {\n try {\n fn.apply(null, args);\n }\n catch (ex) {\n onerror && onerror(ex);\n }\n}\nfunction getByKeyPath(obj, keyPath) {\n if (hasOwn(obj, keyPath))\n return obj[keyPath];\n if (!keyPath)\n return obj;\n if (typeof keyPath !== 'string') {\n var rv = [];\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n var val = getByKeyPath(obj, keyPath[i]);\n rv.push(val);\n }\n return rv;\n }\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var innerObj = obj[keyPath.substr(0, period)];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return undefined;\n}\nfunction setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined)\n return;\n if ('isFrozen' in Object && Object.isFrozen(obj))\n return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n }\n else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === \"\")\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(currentKeyPath)))\n obj.splice(currentKeyPath, 1);\n else\n delete obj[currentKeyPath];\n }\n else\n obj[currentKeyPath] = value;\n else {\n var innerObj = obj[currentKeyPath];\n if (!innerObj || !hasOwn(obj, currentKeyPath))\n innerObj = (obj[currentKeyPath] = {});\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n }\n else {\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(keyPath)))\n obj.splice(keyPath, 1);\n else\n delete obj[keyPath];\n }\n else\n obj[keyPath] = value;\n }\n }\n}\nfunction delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string')\n setByKeyPath(obj, keyPath, undefined);\n else if ('length' in keyPath)\n [].map.call(keyPath, function (kp) {\n setByKeyPath(obj, kp, undefined);\n });\n}\nfunction shallowClone(obj) {\n var rv = {};\n for (var m in obj) {\n if (hasOwn(obj, m))\n rv[m] = obj[m];\n }\n return rv;\n}\nconst concat = [].concat;\nfunction flatten(a) {\n return concat.apply([], a);\n}\nconst intrinsicTypeNames = \"Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey\"\n .split(',').concat(flatten([8, 16, 32, 64].map(num => [\"Int\", \"Uint\", \"Float\"].map(t => t + num + \"Array\")))).filter(t => _global[t]);\nconst intrinsicTypes = intrinsicTypeNames.map(t => _global[t]);\narrayToObject(intrinsicTypeNames, x => [x, true]);\nlet circularRefs = null;\nfunction deepClone(any) {\n circularRefs = typeof WeakMap !== 'undefined' && new WeakMap();\n const rv = innerDeepClone(any);\n circularRefs = null;\n return rv;\n}\nfunction innerDeepClone(any) {\n if (!any || typeof any !== 'object')\n return any;\n let rv = circularRefs && circularRefs.get(any);\n if (rv)\n return rv;\n if (isArray(any)) {\n rv = [];\n circularRefs && circularRefs.set(any, rv);\n for (var i = 0, l = any.length; i < l; ++i) {\n rv.push(innerDeepClone(any[i]));\n }\n }\n else if (intrinsicTypes.indexOf(any.constructor) >= 0) {\n rv = any;\n }\n else {\n const proto = getProto(any);\n rv = proto === Object.prototype ? {} : Object.create(proto);\n circularRefs && circularRefs.set(any, rv);\n for (var prop in any) {\n if (hasOwn(any, prop)) {\n rv[prop] = innerDeepClone(any[prop]);\n }\n }\n }\n return rv;\n}\nconst { toString } = {};\nfunction toStringTag(o) {\n return toString.call(o).slice(8, -1);\n}\nconst iteratorSymbol = typeof Symbol !== 'undefined' ?\n Symbol.iterator :\n '@@iterator';\nconst getIteratorOf = typeof iteratorSymbol === \"symbol\" ? function (x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\nconst NO_CHAR_ARRAY = {};\nfunction getArrayOf(arrayLike) {\n var i, a, x, it;\n if (arguments.length === 1) {\n if (isArray(arrayLike))\n return arrayLike.slice();\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string')\n return [arrayLike];\n if ((it = getIteratorOf(arrayLike))) {\n a = [];\n while ((x = it.next()), !x.done)\n a.push(x.value);\n return a;\n }\n if (arrayLike == null)\n return [arrayLike];\n i = arrayLike.length;\n if (typeof i === 'number') {\n a = new Array(i);\n while (i--)\n a[i] = arrayLike[i];\n return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--)\n a[i] = arguments[i];\n return a;\n}\nconst isAsyncFunction = typeof Symbol !== 'undefined'\n ? (fn) => fn[Symbol.toStringTag] === 'AsyncFunction'\n : () => false;\n\nvar debug = typeof location !== 'undefined' &&\n /^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\nfunction setDebug(value, filter) {\n debug = value;\n libraryFilter = filter;\n}\nvar libraryFilter = () => true;\nconst NEEDS_THROW_FOR_STACK = !new Error(\"\").stack;\nfunction getErrorWithStack() {\n if (NEEDS_THROW_FOR_STACK)\n try {\n getErrorWithStack.arguments;\n throw new Error();\n }\n catch (e) {\n return e;\n }\n return new Error();\n}\nfunction prettyStack(exception, numIgnoredFrames) {\n var stack = exception.stack;\n if (!stack)\n return \"\";\n numIgnoredFrames = (numIgnoredFrames || 0);\n if (stack.indexOf(exception.name) === 0)\n numIgnoredFrames += (exception.name + exception.message).split('\\n').length;\n return stack.split('\\n')\n .slice(numIgnoredFrames)\n .filter(libraryFilter)\n .map(frame => \"\\n\" + frame)\n .join('');\n}\n\nvar dexieErrorNames = [\n 'Modify',\n 'Bulk',\n 'OpenFailed',\n 'VersionChange',\n 'Schema',\n 'Upgrade',\n 'InvalidTable',\n 'MissingAPI',\n 'NoSuchDatabase',\n 'InvalidArgument',\n 'SubTransaction',\n 'Unsupported',\n 'Internal',\n 'DatabaseClosed',\n 'PrematureCommit',\n 'ForeignAwait'\n];\nvar idbDomErrorNames = [\n 'Unknown',\n 'Constraint',\n 'Data',\n 'TransactionInactive',\n 'ReadOnly',\n 'Version',\n 'NotFound',\n 'InvalidState',\n 'InvalidAccess',\n 'Abort',\n 'Timeout',\n 'QuotaExceeded',\n 'Syntax',\n 'DataClone'\n];\nvar errorList = dexieErrorNames.concat(idbDomErrorNames);\nvar defaultTexts = {\n VersionChanged: \"Database version changed by other database connection\",\n DatabaseClosed: \"Database has been closed\",\n Abort: \"Transaction aborted\",\n TransactionInactive: \"Transaction has already completed or failed\",\n MissingAPI: \"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb\"\n};\nfunction DexieError(name, msg) {\n this._e = getErrorWithStack();\n this.name = name;\n this.message = msg;\n}\nderive(DexieError).from(Error).extend({\n stack: {\n get: function () {\n return this._stack ||\n (this._stack = this.name + \": \" + this.message + prettyStack(this._e, 2));\n }\n },\n toString: function () { return this.name + \": \" + this.message; }\n});\nfunction getMultiErrorMessage(msg, failures) {\n return msg + \". Errors: \" + Object.keys(failures)\n .map(key => failures[key].toString())\n .filter((v, i, s) => s.indexOf(v) === i)\n .join('\\n');\n}\nfunction ModifyError(msg, failures, successCount, failedKeys) {\n this._e = getErrorWithStack();\n this.failures = failures;\n this.failedKeys = failedKeys;\n this.successCount = successCount;\n this.message = getMultiErrorMessage(msg, failures);\n}\nderive(ModifyError).from(DexieError);\nfunction BulkError(msg, failures) {\n this._e = getErrorWithStack();\n this.name = \"BulkError\";\n this.failures = Object.keys(failures).map(pos => failures[pos]);\n this.failuresByPos = failures;\n this.message = getMultiErrorMessage(msg, failures);\n}\nderive(BulkError).from(DexieError);\nvar errnames = errorList.reduce((obj, name) => (obj[name] = name + \"Error\", obj), {});\nconst BaseException = DexieError;\nvar exceptions = errorList.reduce((obj, name) => {\n var fullName = name + \"Error\";\n function DexieError(msgOrInner, inner) {\n this._e = getErrorWithStack();\n this.name = fullName;\n if (!msgOrInner) {\n this.message = defaultTexts[name] || fullName;\n this.inner = null;\n }\n else if (typeof msgOrInner === 'string') {\n this.message = `${msgOrInner}${!inner ? '' : '\\n ' + inner}`;\n this.inner = inner || null;\n }\n else if (typeof msgOrInner === 'object') {\n this.message = `${msgOrInner.name} ${msgOrInner.message}`;\n this.inner = msgOrInner;\n }\n }\n derive(DexieError).from(BaseException);\n obj[name] = DexieError;\n return obj;\n}, {});\nexceptions.Syntax = SyntaxError;\nexceptions.Type = TypeError;\nexceptions.Range = RangeError;\nvar exceptionMap = idbDomErrorNames.reduce((obj, name) => {\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\nfunction mapError(domError, message) {\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name])\n return domError;\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\n if (\"stack\" in domError) {\n setProp(rv, \"stack\", { get: function () {\n return this.inner.stack;\n } });\n }\n return rv;\n}\nvar fullNameExceptions = errorList.reduce((obj, name) => {\n if ([\"Syntax\", \"Type\", \"Range\"].indexOf(name) === -1)\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;\n\nfunction nop() { }\nfunction mirror(val) { return val; }\nfunction pureFunctionChain(f1, f2) {\n if (f1 == null || f1 === mirror)\n return f2;\n return function (val) {\n return f2(f1(val));\n };\n}\nfunction callBoth(on1, on2) {\n return function () {\n on1.apply(this, arguments);\n on2.apply(this, arguments);\n };\n}\nfunction hookCreatingChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res !== undefined)\n arguments[0] = res;\n var onsuccess = this.onsuccess,\n onerror = this.onerror;\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess)\n this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror)\n this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res2 !== undefined ? res2 : res;\n };\n}\nfunction hookDeletingChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function () {\n f1.apply(this, arguments);\n var onsuccess = this.onsuccess,\n onerror = this.onerror;\n this.onsuccess = this.onerror = null;\n f2.apply(this, arguments);\n if (onsuccess)\n this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror)\n this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n };\n}\nfunction hookUpdatingChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function (modifications) {\n var res = f1.apply(this, arguments);\n extend(modifications, res);\n var onsuccess = this.onsuccess,\n onerror = this.onerror;\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess)\n this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror)\n this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res === undefined ?\n (res2 === undefined ? undefined : res2) :\n (extend(res, res2));\n };\n}\nfunction reverseStoppableEventChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function () {\n if (f2.apply(this, arguments) === false)\n return false;\n return f1.apply(this, arguments);\n };\n}\nfunction promisableChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this, i = arguments.length, args = new Array(i);\n while (i--)\n args[i] = arguments[i];\n return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n\nvar INTERNAL = {};\nconst LONG_STACKS_CLIP_LIMIT = 100,\nMAX_LONG_STACKS = 20, ZONE_ECHO_LIMIT = 100, [resolvedNativePromise, nativePromiseProto, resolvedGlobalPromise] = typeof Promise === 'undefined' ?\n [] :\n (() => {\n let globalP = Promise.resolve();\n if (typeof crypto === 'undefined' || !crypto.subtle)\n return [globalP, getProto(globalP), globalP];\n const nativeP = crypto.subtle.digest(\"SHA-512\", new Uint8Array([0]));\n return [\n nativeP,\n getProto(nativeP),\n globalP\n ];\n })(), nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\nconst NativePromise = resolvedNativePromise && resolvedNativePromise.constructor;\nconst patchGlobalPromise = !!resolvedGlobalPromise;\nvar stack_being_generated = false;\nvar schedulePhysicalTick = resolvedGlobalPromise ?\n () => { resolvedGlobalPromise.then(physicalTick); }\n :\n _global.setImmediate ?\n setImmediate.bind(null, physicalTick) :\n _global.MutationObserver ?\n () => {\n var hiddenDiv = document.createElement(\"div\");\n (new MutationObserver(() => {\n physicalTick();\n hiddenDiv = null;\n })).observe(hiddenDiv, { attributes: true });\n hiddenDiv.setAttribute('i', '1');\n } :\n () => { setTimeout(physicalTick, 0); };\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\nvar isOutsideMicroTick = true,\nneedsNewPhysicalTick = true,\nunhandledErrors = [],\nrejectingErrors = [],\ncurrentFulfiller = null, rejectionMapper = mirror;\nvar globalPSD = {\n id: 'global',\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: globalError,\n pgp: false,\n env: {},\n finalize: function () {\n this.unhandleds.forEach(uh => {\n try {\n globalError(uh[0], uh[1]);\n }\n catch (e) { }\n });\n }\n};\nvar PSD = globalPSD;\nvar microtickQueue = [];\nvar numScheduledCalls = 0;\nvar tickFinalizers = [];\nfunction DexiePromise(fn) {\n if (typeof this !== 'object')\n throw new TypeError('Promises must be constructed via new');\n this._listeners = [];\n this.onuncatched = nop;\n this._lib = false;\n var psd = (this._PSD = PSD);\n if (debug) {\n this._stackHolder = getErrorWithStack();\n this._prev = null;\n this._numPrev = 0;\n }\n if (typeof fn !== 'function') {\n if (fn !== INTERNAL)\n throw new TypeError('Not a function');\n this._state = arguments[1];\n this._value = arguments[2];\n if (this._state === false)\n handleRejection(this, this._value);\n return;\n }\n this._state = null;\n this._value = null;\n ++psd.ref;\n executePromiseTask(this, fn);\n}\nconst thenProp = {\n get: function () {\n var psd = PSD, microTaskId = totalEchoes;\n function then(onFulfilled, onRejected) {\n var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\n const cleanup = possibleAwait && !decrementExpectedAwaits();\n var rv = new DexiePromise((resolve, reject) => {\n propagateToListener(this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), resolve, reject, psd));\n });\n debug && linkToPreviousPromise(rv, this);\n return rv;\n }\n then.prototype = INTERNAL;\n return then;\n },\n set: function (value) {\n setProp(this, 'then', value && value.prototype === INTERNAL ?\n thenProp :\n {\n get: function () {\n return value;\n },\n set: thenProp.set\n });\n }\n};\nprops(DexiePromise.prototype, {\n then: thenProp,\n _then: function (onFulfilled, onRejected) {\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD));\n },\n catch: function (onRejected) {\n if (arguments.length === 1)\n return this.then(null, onRejected);\n var type = arguments[0], handler = arguments[1];\n return typeof type === 'function' ? this.then(null, err =>\n err instanceof type ? handler(err) : PromiseReject(err))\n : this.then(null, err =>\n err && err.name === type ? handler(err) : PromiseReject(err));\n },\n finally: function (onFinally) {\n return this.then(value => {\n onFinally();\n return value;\n }, err => {\n onFinally();\n return PromiseReject(err);\n });\n },\n stack: {\n get: function () {\n if (this._stack)\n return this._stack;\n try {\n stack_being_generated = true;\n var stacks = getStack(this, [], MAX_LONG_STACKS);\n var stack = stacks.join(\"\\nFrom previous: \");\n if (this._state !== null)\n this._stack = stack;\n return stack;\n }\n finally {\n stack_being_generated = false;\n }\n }\n },\n timeout: function (ms, msg) {\n return ms < Infinity ?\n new DexiePromise((resolve, reject) => {\n var handle = setTimeout(() => reject(new exceptions.Timeout(msg)), ms);\n this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\n }) : this;\n }\n});\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag)\n setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise');\nglobalPSD.env = snapShot();\nfunction Listener(onFulfilled, onRejected, resolve, reject, zone) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.resolve = resolve;\n this.reject = reject;\n this.psd = zone;\n}\nprops(DexiePromise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments)\n .map(onPossibleParallellAsync);\n return new DexiePromise(function (resolve, reject) {\n if (values.length === 0)\n resolve([]);\n var remaining = values.length;\n values.forEach((a, i) => DexiePromise.resolve(a).then(x => {\n values[i] = x;\n if (!--remaining)\n resolve(values);\n }, reject));\n });\n },\n resolve: value => {\n if (value instanceof DexiePromise)\n return value;\n if (value && typeof value.then === 'function')\n return new DexiePromise((resolve, reject) => {\n value.then(resolve, reject);\n });\n var rv = new DexiePromise(INTERNAL, true, value);\n linkToPreviousPromise(rv, currentFulfiller);\n return rv;\n },\n reject: PromiseReject,\n race: function () {\n var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n values.map(value => DexiePromise.resolve(value).then(resolve, reject));\n });\n },\n PSD: {\n get: () => PSD,\n set: value => PSD = value\n },\n totalEchoes: { get: () => totalEchoes },\n newPSD: newScope,\n usePSD: usePSD,\n scheduler: {\n get: () => asap,\n set: value => { asap = value; }\n },\n rejectionMapper: {\n get: () => rejectionMapper,\n set: value => { rejectionMapper = value; }\n },\n follow: (fn, zoneProps) => {\n return new DexiePromise((resolve, reject) => {\n return newScope((resolve, reject) => {\n var psd = PSD;\n psd.unhandleds = [];\n psd.onunhandled = reject;\n psd.finalize = callBoth(function () {\n run_at_end_of_this_or_next_physical_tick(() => {\n this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, zoneProps, resolve, reject);\n });\n }\n});\nif (NativePromise) {\n if (NativePromise.allSettled)\n setProp(DexiePromise, \"allSettled\", function () {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise(resolve => {\n if (possiblePromises.length === 0)\n resolve([]);\n let remaining = possiblePromises.length;\n const results = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(value => results[i] = { status: \"fulfilled\", value }, reason => results[i] = { status: \"rejected\", reason })\n .then(() => --remaining || resolve(results)));\n });\n });\n if (NativePromise.any && typeof AggregateError !== 'undefined')\n setProp(DexiePromise, \"any\", function () {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n if (possiblePromises.length === 0)\n reject(new AggregateError([]));\n let remaining = possiblePromises.length;\n const failures = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(value => resolve(value), failure => {\n failures[i] = failure;\n if (!--remaining)\n reject(new AggregateError(failures));\n }));\n });\n });\n}\nfunction executePromiseTask(promise, fn) {\n try {\n fn(value => {\n if (promise._state !== null)\n return;\n if (value === promise)\n throw new TypeError('A promise cannot be resolved with itself.');\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n if (value && typeof value.then === 'function') {\n executePromiseTask(promise, (resolve, reject) => {\n value instanceof DexiePromise ?\n value._then(resolve, reject) :\n value.then(resolve, reject);\n });\n }\n else {\n promise._state = true;\n promise._value = value;\n propagateAllListeners(promise);\n }\n if (shouldExecuteTick)\n endMicroTickScope();\n }, handleRejection.bind(null, promise));\n }\n catch (ex) {\n handleRejection(promise, ex);\n }\n}\nfunction handleRejection(promise, reason) {\n rejectingErrors.push(reason);\n if (promise._state !== null)\n return;\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n reason = rejectionMapper(reason);\n promise._state = false;\n promise._value = reason;\n debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(() => {\n var origProp = getPropertyDescriptor(reason, \"stack\");\n reason._promise = promise;\n setProp(reason, \"stack\", {\n get: () => stack_being_generated ?\n origProp && (origProp.get ?\n origProp.get.apply(reason) :\n origProp.value) :\n promise.stack\n });\n });\n addPossiblyUnhandledError(promise);\n propagateAllListeners(promise);\n if (shouldExecuteTick)\n endMicroTickScope();\n}\nfunction propagateAllListeners(promise) {\n var listeners = promise._listeners;\n promise._listeners = [];\n for (var i = 0, len = listeners.length; i < len; ++i) {\n propagateToListener(promise, listeners[i]);\n }\n var psd = promise._PSD;\n --psd.ref || psd.finalize();\n if (numScheduledCalls === 0) {\n ++numScheduledCalls;\n asap(() => {\n if (--numScheduledCalls === 0)\n finalizePhysicalTick();\n }, []);\n }\n}\nfunction propagateToListener(promise, listener) {\n if (promise._state === null) {\n promise._listeners.push(listener);\n return;\n }\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\n if (cb === null) {\n return (promise._state ? listener.resolve : listener.reject)(promise._value);\n }\n ++listener.psd.ref;\n ++numScheduledCalls;\n asap(callListener, [cb, promise, listener]);\n}\nfunction callListener(cb, promise, listener) {\n try {\n currentFulfiller = promise;\n var ret, value = promise._value;\n if (promise._state) {\n ret = cb(value);\n }\n else {\n if (rejectingErrors.length)\n rejectingErrors = [];\n ret = cb(value);\n if (rejectingErrors.indexOf(value) === -1)\n markErrorAsHandled(promise);\n }\n listener.resolve(ret);\n }\n catch (e) {\n listener.reject(e);\n }\n finally {\n currentFulfiller = null;\n if (--numScheduledCalls === 0)\n finalizePhysicalTick();\n --listener.psd.ref || listener.psd.finalize();\n }\n}\nfunction getStack(promise, stacks, limit) {\n if (stacks.length === limit)\n return stacks;\n var stack = \"\";\n if (promise._state === false) {\n var failure = promise._value, errorName, message;\n if (failure != null) {\n errorName = failure.name || \"Error\";\n message = failure.message || failure;\n stack = prettyStack(failure, 0);\n }\n else {\n errorName = failure;\n message = \"\";\n }\n stacks.push(errorName + (message ? \": \" + message : \"\") + stack);\n }\n if (debug) {\n stack = prettyStack(promise._stackHolder, 2);\n if (stack && stacks.indexOf(stack) === -1)\n stacks.push(stack);\n if (promise._prev)\n getStack(promise._prev, stacks, limit);\n }\n return stacks;\n}\nfunction linkToPreviousPromise(promise, prev) {\n var numPrev = prev ? prev._numPrev + 1 : 0;\n if (numPrev < LONG_STACKS_CLIP_LIMIT) {\n promise._prev = prev;\n promise._numPrev = numPrev;\n }\n}\nfunction physicalTick() {\n beginMicroTickScope() && endMicroTickScope();\n}\nfunction beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\nfunction endMicroTickScope() {\n var callbacks, i, l;\n do {\n while (microtickQueue.length > 0) {\n callbacks = microtickQueue;\n microtickQueue = [];\n l = callbacks.length;\n for (i = 0; i < l; ++i) {\n var item = callbacks[i];\n item[0].apply(null, item[1]);\n }\n }\n } while (microtickQueue.length > 0);\n isOutsideMicroTick = true;\n needsNewPhysicalTick = true;\n}\nfunction finalizePhysicalTick() {\n var unhandledErrs = unhandledErrors;\n unhandledErrors = [];\n unhandledErrs.forEach(p => {\n p._PSD.onunhandled.call(null, p._value, p);\n });\n var finalizers = tickFinalizers.slice(0);\n var i = finalizers.length;\n while (i)\n finalizers[--i]();\n}\nfunction run_at_end_of_this_or_next_physical_tick(fn) {\n function finalizer() {\n fn();\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\n }\n tickFinalizers.push(finalizer);\n ++numScheduledCalls;\n asap(() => {\n if (--numScheduledCalls === 0)\n finalizePhysicalTick();\n }, []);\n}\nfunction addPossiblyUnhandledError(promise) {\n if (!unhandledErrors.some(p => p._value === promise._value))\n unhandledErrors.push(promise);\n}\nfunction markErrorAsHandled(promise) {\n var i = unhandledErrors.length;\n while (i)\n if (unhandledErrors[--i]._value === promise._value) {\n unhandledErrors.splice(i, 1);\n return;\n }\n}\nfunction PromiseReject(reason) {\n return new DexiePromise(INTERNAL, false, reason);\n}\nfunction wrap(fn, errorCatcher) {\n var psd = PSD;\n return function () {\n var wasRootExec = beginMicroTickScope(), outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn.apply(this, arguments);\n }\n catch (e) {\n errorCatcher && errorCatcher(e);\n }\n finally {\n switchToZone(outerScope, false);\n if (wasRootExec)\n endMicroTickScope();\n }\n };\n}\nconst task = { awaits: 0, echoes: 0, id: 0 };\nvar taskCounter = 0;\nvar zoneStack = [];\nvar zoneEchoes = 0;\nvar totalEchoes = 0;\nvar zone_id_counter = 0;\nfunction newScope(fn, props, a1, a2) {\n var parent = PSD, psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n psd.id = ++zone_id_counter;\n var globalEnv = globalPSD.env;\n psd.env = patchGlobalPromise ? {\n Promise: DexiePromise,\n PromiseProp: { value: DexiePromise, configurable: true, writable: true },\n all: DexiePromise.all,\n race: DexiePromise.race,\n allSettled: DexiePromise.allSettled,\n any: DexiePromise.any,\n resolve: DexiePromise.resolve,\n reject: DexiePromise.reject,\n nthen: getPatchedPromiseThen(globalEnv.nthen, psd),\n gthen: getPatchedPromiseThen(globalEnv.gthen, psd)\n } : {};\n if (props)\n extend(psd, props);\n ++parent.ref;\n psd.finalize = function () {\n --this.parent.ref || this.parent.finalize();\n };\n var rv = usePSD(psd, fn, a1, a2);\n if (psd.ref === 0)\n psd.finalize();\n return rv;\n}\nfunction incrementExpectedAwaits() {\n if (!task.id)\n task.id = ++taskCounter;\n ++task.awaits;\n task.echoes += ZONE_ECHO_LIMIT;\n return task.id;\n}\nfunction decrementExpectedAwaits() {\n if (!task.awaits)\n return false;\n if (--task.awaits === 0)\n task.id = 0;\n task.echoes = task.awaits * ZONE_ECHO_LIMIT;\n return true;\n}\nif (('' + nativePromiseThen).indexOf('[native code]') === -1) {\n incrementExpectedAwaits = decrementExpectedAwaits = nop;\n}\nfunction onPossibleParallellAsync(possiblePromise) {\n if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) {\n incrementExpectedAwaits();\n return possiblePromise.then(x => {\n decrementExpectedAwaits();\n return x;\n }, e => {\n decrementExpectedAwaits();\n return rejection(e);\n });\n }\n return possiblePromise;\n}\nfunction zoneEnterEcho(targetZone) {\n ++totalEchoes;\n if (!task.echoes || --task.echoes === 0) {\n task.echoes = task.id = 0;\n }\n zoneStack.push(PSD);\n switchToZone(targetZone, true);\n}\nfunction zoneLeaveEcho() {\n var zone = zoneStack[zoneStack.length - 1];\n zoneStack.pop();\n switchToZone(zone, false);\n}\nfunction switchToZone(targetZone, bEnteringZone) {\n var currentZone = PSD;\n if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) {\n enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho);\n }\n if (targetZone === PSD)\n return;\n PSD = targetZone;\n if (currentZone === globalPSD)\n globalPSD.env = snapShot();\n if (patchGlobalPromise) {\n var GlobalPromise = globalPSD.env.Promise;\n var targetEnv = targetZone.env;\n nativePromiseProto.then = targetEnv.nthen;\n GlobalPromise.prototype.then = targetEnv.gthen;\n if (currentZone.global || targetZone.global) {\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\n GlobalPromise.all = targetEnv.all;\n GlobalPromise.race = targetEnv.race;\n GlobalPromise.resolve = targetEnv.resolve;\n GlobalPromise.reject = targetEnv.reject;\n if (targetEnv.allSettled)\n GlobalPromise.allSettled = targetEnv.allSettled;\n if (targetEnv.any)\n GlobalPromise.any = targetEnv.any;\n }\n }\n}\nfunction snapShot() {\n var GlobalPromise = _global.Promise;\n return patchGlobalPromise ? {\n Promise: GlobalPromise,\n PromiseProp: Object.getOwnPropertyDescriptor(_global, \"Promise\"),\n all: GlobalPromise.all,\n race: GlobalPromise.race,\n allSettled: GlobalPromise.allSettled,\n any: GlobalPromise.any,\n resolve: GlobalPromise.resolve,\n reject: GlobalPromise.reject,\n nthen: nativePromiseProto.then,\n gthen: GlobalPromise.prototype.then\n } : {};\n}\nfunction usePSD(psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn(a1, a2, a3);\n }\n finally {\n switchToZone(outerScope, false);\n }\n}\nfunction enqueueNativeMicroTask(job) {\n nativePromiseThen.call(resolvedNativePromise, job);\n}\nfunction nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) {\n return typeof fn !== 'function' ? fn : function () {\n var outerZone = PSD;\n if (possibleAwait)\n incrementExpectedAwaits();\n switchToZone(zone, true);\n try {\n return fn.apply(this, arguments);\n }\n finally {\n switchToZone(outerZone, false);\n if (cleanup)\n enqueueNativeMicroTask(decrementExpectedAwaits);\n }\n };\n}\nfunction getPatchedPromiseThen(origThen, zone) {\n return function (onResolved, onRejected) {\n return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone), nativeAwaitCompatibleWrap(onRejected, zone));\n };\n}\nconst UNHANDLEDREJECTION = \"unhandledrejection\";\nfunction globalError(err, promise) {\n var rv;\n try {\n rv = promise.onuncatched(err);\n }\n catch (e) { }\n if (rv !== false)\n try {\n var event, eventData = { promise: promise, reason: err };\n if (_global.document && document.createEvent) {\n event = document.createEvent('Event');\n event.initEvent(UNHANDLEDREJECTION, true, true);\n extend(event, eventData);\n }\n else if (_global.CustomEvent) {\n event = new CustomEvent(UNHANDLEDREJECTION, { detail: eventData });\n extend(event, eventData);\n }\n if (event && _global.dispatchEvent) {\n dispatchEvent(event);\n if (!_global.PromiseRejectionEvent && _global.onunhandledrejection)\n try {\n _global.onunhandledrejection(event);\n }\n catch (_) { }\n }\n if (debug && event && !event.defaultPrevented) {\n console.warn(`Unhandled rejection: ${err.stack || err}`);\n }\n }\n catch (e) { }\n}\nvar rejection = DexiePromise.reject;\n\nfunction tempTransaction(db, mode, storeNames, fn) {\n if (!db.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) {\n if (db._state.openComplete) {\n return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError));\n }\n if (!db._state.isBeingOpened) {\n if (!db._options.autoOpen)\n return rejection(new exceptions.DatabaseClosed());\n db.open().catch(nop);\n }\n return db._state.dbReadyPromise.then(() => tempTransaction(db, mode, storeNames, fn));\n }\n else {\n var trans = db._createTransaction(mode, storeNames, db._dbSchema);\n try {\n trans.create();\n db._state.PR1398_maxLoop = 3;\n }\n catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(() => tempTransaction(db, mode, storeNames, fn));\n }\n return rejection(ex);\n }\n return trans._promise(mode, (resolve, reject) => {\n return newScope(() => {\n PSD.trans = trans;\n return fn(resolve, reject, trans);\n });\n }).then(result => {\n return trans._completion.then(() => result);\n });\n }\n}\n\nconst DEXIE_VERSION = '3.2.4';\nconst maxString = String.fromCharCode(65535);\nconst minKey = -Infinity;\nconst INVALID_KEY_ARGUMENT = \"Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.\";\nconst STRING_EXPECTED = \"String expected.\";\nconst connections = [];\nconst isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent);\nconst hasIEDeleteObjectStoreBug = isIEOrEdge;\nconst hangsOnDeleteLargeKeyRange = isIEOrEdge;\nconst dexieStackFrameFilter = frame => !/(dexie\\.js|dexie\\.min\\.js)/.test(frame);\nconst DBNAMES_DB = '__dbnames';\nconst READONLY = 'readonly';\nconst READWRITE = 'readwrite';\n\nfunction combine(filter1, filter2) {\n return filter1 ?\n filter2 ?\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\n filter1 :\n filter2;\n}\n\nconst AnyRange = {\n type: 3 ,\n lower: -Infinity,\n lowerOpen: false,\n upper: [[]],\n upperOpen: false\n};\n\nfunction workaroundForUndefinedPrimKey(keyPath) {\n return typeof keyPath === \"string\" && !/\\./.test(keyPath)\n ? (obj) => {\n if (obj[keyPath] === undefined && (keyPath in obj)) {\n obj = deepClone(obj);\n delete obj[keyPath];\n }\n return obj;\n }\n : (obj) => obj;\n}\n\nclass Table {\n _trans(mode, fn, writeLocked) {\n const trans = this._tx || PSD.trans;\n const tableName = this.name;\n function checkTableInTransaction(resolve, reject, trans) {\n if (!trans.schema[tableName])\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\");\n return fn(trans.idbtrans, trans);\n }\n const wasRootExec = beginMicroTickScope();\n try {\n return trans && trans.db === this.db ?\n trans === PSD.trans ?\n trans._promise(mode, checkTableInTransaction, writeLocked) :\n newScope(() => trans._promise(mode, checkTableInTransaction, writeLocked), { trans: trans, transless: PSD.transless || PSD }) :\n tempTransaction(this.db, mode, [this.name], checkTableInTransaction);\n }\n finally {\n if (wasRootExec)\n endMicroTickScope();\n }\n }\n get(keyOrCrit, cb) {\n if (keyOrCrit && keyOrCrit.constructor === Object)\n return this.where(keyOrCrit).first(cb);\n return this._trans('readonly', (trans) => {\n return this.core.get({ trans, key: keyOrCrit })\n .then(res => this.hook.reading.fire(res));\n }).then(cb);\n }\n where(indexOrCrit) {\n if (typeof indexOrCrit === 'string')\n return new this.db.WhereClause(this, indexOrCrit);\n if (isArray(indexOrCrit))\n return new this.db.WhereClause(this, `[${indexOrCrit.join('+')}]`);\n const keyPaths = keys(indexOrCrit);\n if (keyPaths.length === 1)\n return this\n .where(keyPaths[0])\n .equals(indexOrCrit[keyPaths[0]]);\n const compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix => ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0) &&\n ix.keyPath.every(keyPath => keyPaths.indexOf(keyPath) >= 0))[0];\n if (compoundIndex && this.db._maxKey !== maxString)\n return this\n .where(compoundIndex.name)\n .equals(compoundIndex.keyPath.map(kp => indexOrCrit[kp]));\n if (!compoundIndex && debug)\n console.warn(`The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit of a ` +\n `compound index [${keyPaths.join('+')}]`);\n const { idxByName } = this.schema;\n const idb = this.db._deps.indexedDB;\n function equals(a, b) {\n try {\n return idb.cmp(a, b) === 0;\n }\n catch (e) {\n return false;\n }\n }\n const [idx, filterFunction] = keyPaths.reduce(([prevIndex, prevFilterFn], keyPath) => {\n const index = idxByName[keyPath];\n const value = indexOrCrit[keyPath];\n return [\n prevIndex || index,\n prevIndex || !index ?\n combine(prevFilterFn, index && index.multi ?\n x => {\n const prop = getByKeyPath(x, keyPath);\n return isArray(prop) && prop.some(item => equals(value, item));\n } : x => equals(value, getByKeyPath(x, keyPath)))\n : prevFilterFn\n ];\n }, [null, null]);\n return idx ?\n this.where(idx.name).equals(indexOrCrit[idx.keyPath])\n .filter(filterFunction) :\n compoundIndex ?\n this.filter(filterFunction) :\n this.where(keyPaths).equals('');\n }\n filter(filterFunction) {\n return this.toCollection().and(filterFunction);\n }\n count(thenShortcut) {\n return this.toCollection().count(thenShortcut);\n }\n offset(offset) {\n return this.toCollection().offset(offset);\n }\n limit(numRows) {\n return this.toCollection().limit(numRows);\n }\n each(callback) {\n return this.toCollection().each(callback);\n }\n toArray(thenShortcut) {\n return this.toCollection().toArray(thenShortcut);\n }\n toCollection() {\n return new this.db.Collection(new this.db.WhereClause(this));\n }\n orderBy(index) {\n return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ?\n `[${index.join('+')}]` :\n index));\n }\n reverse() {\n return this.toCollection().reverse();\n }\n mapToClass(constructor) {\n this.schema.mappedClass = constructor;\n const readHook = obj => {\n if (!obj)\n return obj;\n const res = Object.create(constructor.prototype);\n for (var m in obj)\n if (hasOwn(obj, m))\n try {\n res[m] = obj[m];\n }\n catch (_) { }\n return res;\n };\n if (this.schema.readHook) {\n this.hook.reading.unsubscribe(this.schema.readHook);\n }\n this.schema.readHook = readHook;\n this.hook(\"reading\", readHook);\n return constructor;\n }\n defineClass() {\n function Class(content) {\n extend(this, content);\n }\n return this.mapToClass(Class);\n }\n add(obj, key) {\n const { auto, keyPath } = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', trans => {\n return this.core.mutate({ trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd] });\n }).then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n try {\n setByKeyPath(obj, keyPath, lastResult);\n }\n catch (_) { }\n }\n return lastResult;\n });\n }\n update(keyOrObject, modifications) {\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\n const key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined)\n return rejection(new exceptions.InvalidArgument(\"Given object does not contain its primary key\"));\n try {\n if (typeof modifications !== \"function\") {\n keys(modifications).forEach(keyPath => {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n }\n else {\n modifications(keyOrObject, { value: keyOrObject, primKey: key });\n }\n }\n catch (_a) {\n }\n return this.where(\":id\").equals(key).modify(modifications);\n }\n else {\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\n }\n }\n put(obj, key) {\n const { auto, keyPath } = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', trans => this.core.mutate({ trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null }))\n .then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n try {\n setByKeyPath(obj, keyPath, lastResult);\n }\n catch (_) { }\n }\n return lastResult;\n });\n }\n delete(key) {\n return this._trans('readwrite', trans => this.core.mutate({ trans, type: 'delete', keys: [key] }))\n .then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined);\n }\n clear() {\n return this._trans('readwrite', trans => this.core.mutate({ trans, type: 'deleteRange', range: AnyRange }))\n .then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined);\n }\n bulkGet(keys) {\n return this._trans('readonly', trans => {\n return this.core.getMany({\n keys,\n trans\n }).then(result => result.map(res => this.hook.reading.fire(res)));\n });\n }\n bulkAdd(objects, keysOrOptions, options) {\n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions);\n const wantResults = options ? options.allKeys : undefined;\n return this._trans('readwrite', trans => {\n const { auto, keyPath } = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n const numObjects = objects.length;\n let objectsToAdd = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n return this.core.mutate({ trans, type: 'add', keys: keys, values: objectsToAdd, wantResults })\n .then(({ numFailures, results, lastResult, failures }) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0)\n return result;\n throw new BulkError(`${this.name}.bulkAdd(): ${numFailures} of ${numObjects} operations failed`, failures);\n });\n });\n }\n bulkPut(objects, keysOrOptions, options) {\n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions);\n const wantResults = options ? options.allKeys : undefined;\n return this._trans('readwrite', trans => {\n const { auto, keyPath } = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n const numObjects = objects.length;\n let objectsToPut = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n return this.core.mutate({ trans, type: 'put', keys: keys, values: objectsToPut, wantResults })\n .then(({ numFailures, results, lastResult, failures }) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0)\n return result;\n throw new BulkError(`${this.name}.bulkPut(): ${numFailures} of ${numObjects} operations failed`, failures);\n });\n });\n }\n bulkDelete(keys) {\n const numKeys = keys.length;\n return this._trans('readwrite', trans => {\n return this.core.mutate({ trans, type: 'delete', keys: keys });\n }).then(({ numFailures, lastResult, failures }) => {\n if (numFailures === 0)\n return lastResult;\n throw new BulkError(`${this.name}.bulkDelete(): ${numFailures} of ${numKeys} operations failed`, failures);\n });\n }\n}\n\nfunction Events(ctx) {\n var evs = {};\n var rv = function (eventName, subscriber) {\n if (subscriber) {\n var i = arguments.length, args = new Array(i - 1);\n while (--i)\n args[i - 1] = arguments[i];\n evs[eventName].subscribe.apply(null, args);\n return ctx;\n }\n else if (typeof (eventName) === 'string') {\n return evs[eventName];\n }\n };\n rv.addEventType = add;\n for (var i = 1, l = arguments.length; i < l; ++i) {\n add(arguments[i]);\n }\n return rv;\n function add(eventName, chainFunction, defaultFunction) {\n if (typeof eventName === 'object')\n return addConfiguredEvents(eventName);\n if (!chainFunction)\n chainFunction = reverseStoppableEventChain;\n if (!defaultFunction)\n defaultFunction = nop;\n var context = {\n subscribers: [],\n fire: defaultFunction,\n subscribe: function (cb) {\n if (context.subscribers.indexOf(cb) === -1) {\n context.subscribers.push(cb);\n context.fire = chainFunction(context.fire, cb);\n }\n },\n unsubscribe: function (cb) {\n context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; });\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\n }\n };\n evs[eventName] = rv[eventName] = context;\n return context;\n }\n function addConfiguredEvents(cfg) {\n keys(cfg).forEach(function (eventName) {\n var args = cfg[eventName];\n if (isArray(args)) {\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\n }\n else if (args === 'asap') {\n var context = add(eventName, mirror, function fire() {\n var i = arguments.length, args = new Array(i);\n while (i--)\n args[i] = arguments[i];\n context.subscribers.forEach(function (fn) {\n asap$1(function fireEvent() {\n fn.apply(null, args);\n });\n });\n });\n }\n else\n throw new exceptions.InvalidArgument(\"Invalid event config\");\n });\n }\n}\n\nfunction makeClassConstructor(prototype, constructor) {\n derive(constructor).from({ prototype });\n return constructor;\n}\n\nfunction createTableConstructor(db) {\n return makeClassConstructor(Table.prototype, function Table(name, tableSchema, trans) {\n this.db = db;\n this._tx = trans;\n this.name = name;\n this.schema = tableSchema;\n this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n });\n });\n}\n\nfunction isPlainKeyRange(ctx, ignoreLimitFilter) {\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n}\nfunction addFilter(ctx, fn) {\n ctx.filter = combine(ctx.filter, fn);\n}\nfunction addReplayFilter(ctx, factory, isLimitFilter) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? () => combine(curr(), factory()) : factory;\n ctx.justLimit = isLimitFilter && !curr;\n}\nfunction addMatchFilter(ctx, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n}\nfunction getIndexOrStore(ctx, coreSchema) {\n if (ctx.isPrimKey)\n return coreSchema.primaryKey;\n const index = coreSchema.getIndexByKeyPath(ctx.index);\n if (!index)\n throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + coreSchema.name + \" is not indexed\");\n return index;\n}\nfunction openCursor(ctx, coreTable, trans) {\n const index = getIndexOrStore(ctx, coreTable.schema);\n return coreTable.openCursor({\n trans,\n values: !ctx.keysOnly,\n reverse: ctx.dir === 'prev',\n unique: !!ctx.unique,\n query: {\n index,\n range: ctx.range\n }\n });\n}\nfunction iter(ctx, fn, coreTrans, coreTable) {\n const filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n return iterate(openCursor(ctx, coreTable, coreTrans), combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper);\n }\n else {\n const set = {};\n const union = (item, cursor, advance) => {\n if (!filter || filter(cursor, advance, result => cursor.stop(result), err => cursor.fail(err))) {\n var primaryKey = cursor.primaryKey;\n var key = '' + primaryKey;\n if (key === '[object ArrayBuffer]')\n key = '' + new Uint8Array(primaryKey);\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n };\n return Promise.all([\n ctx.or._iterate(union, coreTrans),\n iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper)\n ]);\n }\n}\nfunction iterate(cursorPromise, filter, fn, valueMapper) {\n var mappedFn = valueMapper ? (x, c, a) => fn(valueMapper(x), c, a) : fn;\n var wrappedFn = wrap(mappedFn);\n return cursorPromise.then(cursor => {\n if (cursor) {\n return cursor.start(() => {\n var c = () => cursor.continue();\n if (!filter || filter(cursor, advancer => c = advancer, val => { cursor.stop(val); c = nop; }, e => { cursor.fail(e); c = nop; }))\n wrappedFn(cursor.value, cursor, advancer => c = advancer);\n c();\n });\n }\n });\n}\n\nfunction cmp(a, b) {\n try {\n const ta = type(a);\n const tb = type(b);\n if (ta !== tb) {\n if (ta === 'Array')\n return 1;\n if (tb === 'Array')\n return -1;\n if (ta === 'binary')\n return 1;\n if (tb === 'binary')\n return -1;\n if (ta === 'string')\n return 1;\n if (tb === 'string')\n return -1;\n if (ta === 'Date')\n return 1;\n if (tb !== 'Date')\n return NaN;\n return -1;\n }\n switch (ta) {\n case 'number':\n case 'Date':\n case 'string':\n return a > b ? 1 : a < b ? -1 : 0;\n case 'binary': {\n return compareUint8Arrays(getUint8Array(a), getUint8Array(b));\n }\n case 'Array':\n return compareArrays(a, b);\n }\n }\n catch (_a) { }\n return NaN;\n}\nfunction compareArrays(a, b) {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n const res = cmp(a[i], b[i]);\n if (res !== 0)\n return res;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\nfunction compareUint8Arrays(a, b) {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n if (a[i] !== b[i])\n return a[i] < b[i] ? -1 : 1;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\nfunction type(x) {\n const t = typeof x;\n if (t !== 'object')\n return t;\n if (ArrayBuffer.isView(x))\n return 'binary';\n const tsTag = toStringTag(x);\n return tsTag === 'ArrayBuffer' ? 'binary' : tsTag;\n}\nfunction getUint8Array(a) {\n if (a instanceof Uint8Array)\n return a;\n if (ArrayBuffer.isView(a))\n return new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n return new Uint8Array(a);\n}\n\nclass Collection {\n _read(fn, cb) {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readonly', fn).then(cb);\n }\n _write(fn) {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readwrite', fn, \"locked\");\n }\n _addAlgorithm(fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n }\n _iterate(fn, coreTrans) {\n return iter(this._ctx, fn, coreTrans, this._ctx.table.core);\n }\n clone(props) {\n var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx);\n if (props)\n extend(ctx, props);\n rv._ctx = ctx;\n return rv;\n }\n raw() {\n this._ctx.valueMapper = null;\n return this;\n }\n each(fn) {\n var ctx = this._ctx;\n return this._read(trans => iter(ctx, fn, trans, ctx.table.core));\n }\n count(cb) {\n return this._read(trans => {\n const ctx = this._ctx;\n const coreTable = ctx.table.core;\n if (isPlainKeyRange(ctx, true)) {\n return coreTable.count({\n trans,\n query: {\n index: getIndexOrStore(ctx, coreTable.schema),\n range: ctx.range\n }\n }).then(count => Math.min(count, ctx.limit));\n }\n else {\n var count = 0;\n return iter(ctx, () => { ++count; return false; }, trans, coreTable)\n .then(() => count);\n }\n }).then(cb);\n }\n sortBy(keyPath, cb) {\n const parts = keyPath.split('.').reverse(), lastPart = parts[0], lastIndex = parts.length - 1;\n function getval(obj, i) {\n if (i)\n return getval(obj[parts[i]], i - 1);\n return obj[lastPart];\n }\n var order = this._ctx.dir === \"next\" ? 1 : -1;\n function sorter(a, b) {\n var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex);\n return aVal < bVal ? -order : aVal > bVal ? order : 0;\n }\n return this.toArray(function (a) {\n return a.sort(sorter);\n }).then(cb);\n }\n toArray(cb) {\n return this._read(trans => {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n const { valueMapper } = ctx;\n const index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n limit: ctx.limit,\n values: true,\n query: {\n index,\n range: ctx.range\n }\n }).then(({ result }) => valueMapper ? result.map(valueMapper) : result);\n }\n else {\n const a = [];\n return iter(ctx, item => a.push(item), trans, ctx.table.core).then(() => a);\n }\n }, cb);\n }\n offset(offset) {\n var ctx = this._ctx;\n if (offset <= 0)\n return this;\n ctx.offset += offset;\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return (cursor, advance) => {\n if (offsetLeft === 0)\n return true;\n if (offsetLeft === 1) {\n --offsetLeft;\n return false;\n }\n advance(() => {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n }\n else {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return () => (--offsetLeft < 0);\n });\n }\n return this;\n }\n limit(numRows) {\n this._ctx.limit = Math.min(this._ctx.limit, numRows);\n addReplayFilter(this._ctx, () => {\n var rowsLeft = numRows;\n return function (cursor, advance, resolve) {\n if (--rowsLeft <= 0)\n advance(resolve);\n return rowsLeft >= 0;\n };\n }, true);\n return this;\n }\n until(filterFunction, bIncludeStopEntry) {\n addFilter(this._ctx, function (cursor, advance, resolve) {\n if (filterFunction(cursor.value)) {\n advance(resolve);\n return bIncludeStopEntry;\n }\n else {\n return true;\n }\n });\n return this;\n }\n first(cb) {\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\n }\n last(cb) {\n return this.reverse().first(cb);\n }\n filter(filterFunction) {\n addFilter(this._ctx, function (cursor) {\n return filterFunction(cursor.value);\n });\n addMatchFilter(this._ctx, filterFunction);\n return this;\n }\n and(filter) {\n return this.filter(filter);\n }\n or(indexName) {\n return new this.db.WhereClause(this._ctx.table, indexName, this);\n }\n reverse() {\n this._ctx.dir = (this._ctx.dir === \"prev\" ? \"next\" : \"prev\");\n if (this._ondirectionchange)\n this._ondirectionchange(this._ctx.dir);\n return this;\n }\n desc() {\n return this.reverse();\n }\n eachKey(cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\n }\n eachUniqueKey(cb) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n }\n eachPrimaryKey(cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\n }\n keys(cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.key);\n }).then(function () {\n return a;\n }).then(cb);\n }\n primaryKeys(cb) {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n return this._read(trans => {\n var index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n values: false,\n limit: ctx.limit,\n query: {\n index,\n range: ctx.range\n }\n });\n }).then(({ result }) => result).then(cb);\n }\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.primaryKey);\n }).then(function () {\n return a;\n }).then(cb);\n }\n uniqueKeys(cb) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n }\n firstKey(cb) {\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\n }\n lastKey(cb) {\n return this.reverse().firstKey(cb);\n }\n distinct() {\n var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\n if (!idx || !idx.multi)\n return this;\n var set = {};\n addFilter(this._ctx, function (cursor) {\n var strKey = cursor.primaryKey.toString();\n var found = hasOwn(set, strKey);\n set[strKey] = true;\n return !found;\n });\n return this;\n }\n modify(changes) {\n var ctx = this._ctx;\n return this._write(trans => {\n var modifyer;\n if (typeof changes === 'function') {\n modifyer = changes;\n }\n else {\n var keyPaths = keys(changes);\n var numKeys = keyPaths.length;\n modifyer = function (item) {\n var anythingModified = false;\n for (var i = 0; i < numKeys; ++i) {\n var keyPath = keyPaths[i], val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val);\n anythingModified = true;\n }\n }\n return anythingModified;\n };\n }\n const coreTable = ctx.table.core;\n const { outbound, extractKey } = coreTable.schema.primaryKey;\n const limit = this.db._options.modifyChunkSize || 200;\n const totalFailures = [];\n let successCount = 0;\n const failedKeys = [];\n const applyMutateResult = (expectedCount, res) => {\n const { failures, numFailures } = res;\n successCount += expectedCount - numFailures;\n for (let pos of keys(failures)) {\n totalFailures.push(failures[pos]);\n }\n };\n return this.clone().primaryKeys().then(keys => {\n const nextChunk = (offset) => {\n const count = Math.min(limit, keys.length - offset);\n return coreTable.getMany({\n trans,\n keys: keys.slice(offset, offset + count),\n cache: \"immutable\"\n }).then(values => {\n const addValues = [];\n const putValues = [];\n const putKeys = outbound ? [] : null;\n const deleteKeys = [];\n for (let i = 0; i < count; ++i) {\n const origValue = values[i];\n const ctx = {\n value: deepClone(origValue),\n primKey: keys[offset + i]\n };\n if (modifyer.call(ctx, ctx.value, ctx) !== false) {\n if (ctx.value == null) {\n deleteKeys.push(keys[offset + i]);\n }\n else if (!outbound && cmp(extractKey(origValue), extractKey(ctx.value)) !== 0) {\n deleteKeys.push(keys[offset + i]);\n addValues.push(ctx.value);\n }\n else {\n putValues.push(ctx.value);\n if (outbound)\n putKeys.push(keys[offset + i]);\n }\n }\n }\n const criteria = isPlainKeyRange(ctx) &&\n ctx.limit === Infinity &&\n (typeof changes !== 'function' || changes === deleteCallback) && {\n index: ctx.index,\n range: ctx.range\n };\n return Promise.resolve(addValues.length > 0 &&\n coreTable.mutate({ trans, type: 'add', values: addValues })\n .then(res => {\n for (let pos in res.failures) {\n deleteKeys.splice(parseInt(pos), 1);\n }\n applyMutateResult(addValues.length, res);\n })).then(() => (putValues.length > 0 || (criteria && typeof changes === 'object')) &&\n coreTable.mutate({\n trans,\n type: 'put',\n keys: putKeys,\n values: putValues,\n criteria,\n changeSpec: typeof changes !== 'function'\n && changes\n }).then(res => applyMutateResult(putValues.length, res))).then(() => (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) &&\n coreTable.mutate({\n trans,\n type: 'delete',\n keys: deleteKeys,\n criteria\n }).then(res => applyMutateResult(deleteKeys.length, res))).then(() => {\n return keys.length > offset + count && nextChunk(offset + limit);\n });\n });\n };\n return nextChunk(0).then(() => {\n if (totalFailures.length > 0)\n throw new ModifyError(\"Error modifying one or more objects\", totalFailures, successCount, failedKeys);\n return keys.length;\n });\n });\n });\n }\n delete() {\n var ctx = this._ctx, range = ctx.range;\n if (isPlainKeyRange(ctx) &&\n ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || range.type === 3 ))\n {\n return this._write(trans => {\n const { primaryKey } = ctx.table.core.schema;\n const coreRange = range;\n return ctx.table.core.count({ trans, query: { index: primaryKey, range: coreRange } }).then(count => {\n return ctx.table.core.mutate({ trans, type: 'deleteRange', range: coreRange })\n .then(({ failures, lastResult, results, numFailures }) => {\n if (numFailures)\n throw new ModifyError(\"Could not delete some values\", Object.keys(failures).map(pos => failures[pos]), count - numFailures);\n return count - numFailures;\n });\n });\n });\n }\n return this.modify(deleteCallback);\n }\n}\nconst deleteCallback = (value, ctx) => ctx.value = null;\n\nfunction createCollectionConstructor(db) {\n return makeClassConstructor(Collection.prototype, function Collection(whereClause, keyRangeGenerator) {\n this.db = db;\n let keyRange = AnyRange, error = null;\n if (keyRangeGenerator)\n try {\n keyRange = keyRangeGenerator();\n }\n catch (ex) {\n error = ex;\n }\n const whereCtx = whereClause._ctx;\n const table = whereCtx.table;\n const readingHook = table.hook.reading.fire;\n this._ctx = {\n table: table,\n index: whereCtx.index,\n isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)),\n range: keyRange,\n keysOnly: false,\n dir: \"next\",\n unique: \"\",\n algorithm: null,\n filter: null,\n replayFilter: null,\n justLimit: true,\n isMatch: null,\n offset: 0,\n limit: Infinity,\n error: error,\n or: whereCtx.or,\n valueMapper: readingHook !== mirror ? readingHook : null\n };\n });\n}\n\nfunction simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n}\nfunction simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n}\n\nfunction fail(collectionOrWhereClause, err, T) {\n var collection = collectionOrWhereClause instanceof WhereClause ?\n new collectionOrWhereClause.Collection(collectionOrWhereClause) :\n collectionOrWhereClause;\n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n}\nfunction emptyCollection(whereClause) {\n return new whereClause.Collection(whereClause, () => rangeEqual(\"\")).limit(0);\n}\nfunction upperFactory(dir) {\n return dir === \"next\" ?\n (s) => s.toUpperCase() :\n (s) => s.toLowerCase();\n}\nfunction lowerFactory(dir) {\n return dir === \"next\" ?\n (s) => s.toLowerCase() :\n (s) => s.toUpperCase();\n}\nfunction nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\n var length = Math.min(key.length, lowerNeedle.length);\n var llp = -1;\n for (var i = 0; i < length; ++i) {\n var lwrKeyChar = lowerKey[i];\n if (lwrKeyChar !== lowerNeedle[i]) {\n if (cmp(key[i], upperNeedle[i]) < 0)\n return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\n if (cmp(key[i], lowerNeedle[i]) < 0)\n return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\n if (llp >= 0)\n return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\n return null;\n }\n if (cmp(key[i], lwrKeyChar) < 0)\n llp = i;\n }\n if (length < lowerNeedle.length && dir === \"next\")\n return key + upperNeedle.substr(key.length);\n if (length < key.length && dir === \"prev\")\n return key.substr(0, upperNeedle.length);\n return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1));\n}\nfunction addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) {\n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length;\n if (!needles.every(s => typeof s === 'string')) {\n return fail(whereClause, STRING_EXPECTED);\n }\n function initDirection(dir) {\n upper = upperFactory(dir);\n lower = lowerFactory(dir);\n compare = (dir === \"next\" ? simpleCompare : simpleCompareReverse);\n var needleBounds = needles.map(function (needle) {\n return { lower: lower(needle), upper: upper(needle) };\n }).sort(function (a, b) {\n return compare(a.lower, b.lower);\n });\n upperNeedles = needleBounds.map(function (nb) { return nb.upper; });\n lowerNeedles = needleBounds.map(function (nb) { return nb.lower; });\n direction = dir;\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\n }\n initDirection(\"next\");\n var c = new whereClause.Collection(whereClause, () => createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix));\n c._ondirectionchange = function (direction) {\n initDirection(direction);\n };\n var firstPossibleNeedle = 0;\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n if (typeof key !== 'string')\n return false;\n var lowerKey = lower(key);\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\n return true;\n }\n else {\n var lowestPossibleCasing = null;\n for (var i = firstPossibleNeedle; i < needlesLen; ++i) {\n var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction);\n if (casing === null && lowestPossibleCasing === null)\n firstPossibleNeedle = i + 1;\n else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\n }\n else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n}\nfunction createRange(lower, upper, lowerOpen, upperOpen) {\n return {\n type: 2 ,\n lower,\n upper,\n lowerOpen,\n upperOpen\n };\n}\nfunction rangeEqual(value) {\n return {\n type: 1 ,\n lower: value,\n upper: value\n };\n}\n\nclass WhereClause {\n get Collection() {\n return this._ctx.table.db.Collection;\n }\n between(lower, upper, includeLower, includeUpper) {\n includeLower = includeLower !== false;\n includeUpper = includeUpper === true;\n try {\n if ((this._cmp(lower, upper) > 0) ||\n (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\n return emptyCollection(this);\n return new this.Collection(this, () => createRange(lower, upper, !includeLower, !includeUpper));\n }\n catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n }\n equals(value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => rangeEqual(value));\n }\n above(value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, true));\n }\n aboveOrEqual(value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, false));\n }\n below(value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value, false, true));\n }\n belowOrEqual(value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value));\n }\n startsWith(str) {\n if (typeof str !== 'string')\n return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n }\n startsWithIgnoreCase(str) {\n if (str === \"\")\n return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, (x, a) => x.indexOf(a[0]) === 0, [str], maxString);\n }\n equalsIgnoreCase(str) {\n return addIgnoreCaseAlgorithm(this, (x, a) => x === a[0], [str], \"\");\n }\n anyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0)\n return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.indexOf(x) !== -1, set, \"\");\n }\n startsWithAnyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0)\n return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.some(n => x.indexOf(n) === 0), set, maxString);\n }\n anyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n let compare = this._cmp;\n try {\n set.sort(compare);\n }\n catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n if (set.length === 0)\n return emptyCollection(this);\n const c = new this.Collection(this, () => createRange(set[0], set[set.length - 1]));\n c._ondirectionchange = direction => {\n compare = (direction === \"next\" ?\n this._ascending :\n this._descending);\n set.sort(compare);\n };\n let i = 0;\n c._addAlgorithm((cursor, advance, resolve) => {\n const key = cursor.key;\n while (compare(key, set[i]) > 0) {\n ++i;\n if (i === set.length) {\n advance(resolve);\n return false;\n }\n }\n if (compare(key, set[i]) === 0) {\n return true;\n }\n else {\n advance(() => { cursor.continue(set[i]); });\n return false;\n }\n });\n return c;\n }\n notEqual(value) {\n return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false });\n }\n noneOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0)\n return new this.Collection(this);\n try {\n set.sort(this._ascending);\n }\n catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n const ranges = set.reduce((res, val) => res ?\n res.concat([[res[res.length - 1][1], val]]) :\n [[minKey, val]], null);\n ranges.push([set[set.length - 1], this.db._maxKey]);\n return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false });\n }\n inAnyRange(ranges, options) {\n const cmp = this._cmp, ascending = this._ascending, descending = this._descending, min = this._min, max = this._max;\n if (ranges.length === 0)\n return emptyCollection(this);\n if (!ranges.every(range => range[0] !== undefined &&\n range[1] !== undefined &&\n ascending(range[0], range[1]) <= 0)) {\n return fail(this, \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\", exceptions.InvalidArgument);\n }\n const includeLowers = !options || options.includeLowers !== false;\n const includeUppers = options && options.includeUppers === true;\n function addRange(ranges, newRange) {\n let i = 0, l = ranges.length;\n for (; i < l; ++i) {\n const range = ranges[i];\n if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) {\n range[0] = min(range[0], newRange[0]);\n range[1] = max(range[1], newRange[1]);\n break;\n }\n }\n if (i === l)\n ranges.push(newRange);\n return ranges;\n }\n let sortDirection = ascending;\n function rangeSorter(a, b) { return sortDirection(a[0], b[0]); }\n let set;\n try {\n set = ranges.reduce(addRange, []);\n set.sort(rangeSorter);\n }\n catch (ex) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n let rangePos = 0;\n const keyIsBeyondCurrentEntry = includeUppers ?\n key => ascending(key, set[rangePos][1]) > 0 :\n key => ascending(key, set[rangePos][1]) >= 0;\n const keyIsBeforeCurrentEntry = includeLowers ?\n key => descending(key, set[rangePos][0]) > 0 :\n key => descending(key, set[rangePos][0]) >= 0;\n function keyWithinCurrentRange(key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n let checkKey = keyIsBeyondCurrentEntry;\n const c = new this.Collection(this, () => createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers));\n c._ondirectionchange = direction => {\n if (direction === \"next\") {\n checkKey = keyIsBeyondCurrentEntry;\n sortDirection = ascending;\n }\n else {\n checkKey = keyIsBeforeCurrentEntry;\n sortDirection = descending;\n }\n set.sort(rangeSorter);\n };\n c._addAlgorithm((cursor, advance, resolve) => {\n var key = cursor.key;\n while (checkKey(key)) {\n ++rangePos;\n if (rangePos === set.length) {\n advance(resolve);\n return false;\n }\n }\n if (keyWithinCurrentRange(key)) {\n return true;\n }\n else if (this._cmp(key, set[rangePos][1]) === 0 || this._cmp(key, set[rangePos][0]) === 0) {\n return false;\n }\n else {\n advance(() => {\n if (sortDirection === ascending)\n cursor.continue(set[rangePos][0]);\n else\n cursor.continue(set[rangePos][1]);\n });\n return false;\n }\n });\n return c;\n }\n startsWithAnyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (!set.every(s => typeof s === 'string')) {\n return fail(this, \"startsWithAnyOf() only works with strings\");\n }\n if (set.length === 0)\n return emptyCollection(this);\n return this.inAnyRange(set.map((str) => [str, str + maxString]));\n }\n}\n\nfunction createWhereClauseConstructor(db) {\n return makeClassConstructor(WhereClause.prototype, function WhereClause(table, index, orCollection) {\n this.db = db;\n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n or: orCollection\n };\n const indexedDB = db._deps.indexedDB;\n if (!indexedDB)\n throw new exceptions.MissingAPI();\n this._cmp = this._ascending = indexedDB.cmp.bind(indexedDB);\n this._descending = (a, b) => indexedDB.cmp(b, a);\n this._max = (a, b) => indexedDB.cmp(a, b) > 0 ? a : b;\n this._min = (a, b) => indexedDB.cmp(a, b) < 0 ? a : b;\n this._IDBKeyRange = db._deps.IDBKeyRange;\n });\n}\n\nfunction eventRejectHandler(reject) {\n return wrap(function (event) {\n preventDefault(event);\n reject(event.target.error);\n return false;\n });\n}\nfunction preventDefault(event) {\n if (event.stopPropagation)\n event.stopPropagation();\n if (event.preventDefault)\n event.preventDefault();\n}\n\nconst DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated';\nconst STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1';\nconst globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME);\n\nclass Transaction {\n _lock() {\n assert(!PSD.global);\n ++this._reculock;\n if (this._reculock === 1 && !PSD.global)\n PSD.lockOwnerFor = this;\n return this;\n }\n _unlock() {\n assert(!PSD.global);\n if (--this._reculock === 0) {\n if (!PSD.global)\n PSD.lockOwnerFor = null;\n while (this._blockedFuncs.length > 0 && !this._locked()) {\n var fnAndPSD = this._blockedFuncs.shift();\n try {\n usePSD(fnAndPSD[1], fnAndPSD[0]);\n }\n catch (e) { }\n }\n }\n return this;\n }\n _locked() {\n return this._reculock && PSD.lockOwnerFor !== this;\n }\n create(idbtrans) {\n if (!this.mode)\n return this;\n const idbdb = this.db.idbdb;\n const dbOpenError = this.db._state.dbOpenError;\n assert(!this.idbtrans);\n if (!idbtrans && !idbdb) {\n switch (dbOpenError && dbOpenError.name) {\n case \"DatabaseClosedError\":\n throw new exceptions.DatabaseClosed(dbOpenError);\n case \"MissingAPIError\":\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\n default:\n throw new exceptions.OpenFailed(dbOpenError);\n }\n }\n if (!this.active)\n throw new exceptions.TransactionInactive();\n assert(this._completion._state === null);\n idbtrans = this.idbtrans = idbtrans ||\n (this.db.core\n ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })\n : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }));\n idbtrans.onerror = wrap(ev => {\n preventDefault(ev);\n this._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(ev => {\n preventDefault(ev);\n this.active && this._reject(new exceptions.Abort(idbtrans.error));\n this.active = false;\n this.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(() => {\n this.active = false;\n this._resolve();\n if ('mutatedParts' in idbtrans) {\n globalEvents.storagemutated.fire(idbtrans[\"mutatedParts\"]);\n }\n });\n return this;\n }\n _promise(mode, fn, bWriteLock) {\n if (mode === 'readwrite' && this.mode !== 'readwrite')\n return rejection(new exceptions.ReadOnly(\"Transaction is readonly\"));\n if (!this.active)\n return rejection(new exceptions.TransactionInactive());\n if (this._locked()) {\n return new DexiePromise((resolve, reject) => {\n this._blockedFuncs.push([() => {\n this._promise(mode, fn, bWriteLock).then(resolve, reject);\n }, PSD]);\n });\n }\n else if (bWriteLock) {\n return newScope(() => {\n var p = new DexiePromise((resolve, reject) => {\n this._lock();\n const rv = fn(resolve, reject, this);\n if (rv && rv.then)\n rv.then(resolve, reject);\n });\n p.finally(() => this._unlock());\n p._lib = true;\n return p;\n });\n }\n else {\n var p = new DexiePromise((resolve, reject) => {\n var rv = fn(resolve, reject, this);\n if (rv && rv.then)\n rv.then(resolve, reject);\n });\n p._lib = true;\n return p;\n }\n }\n _root() {\n return this.parent ? this.parent._root() : this;\n }\n waitFor(promiseLike) {\n var root = this._root();\n const promise = DexiePromise.resolve(promiseLike);\n if (root._waitingFor) {\n root._waitingFor = root._waitingFor.then(() => promise);\n }\n else {\n root._waitingFor = promise;\n root._waitingQueue = [];\n var store = root.idbtrans.objectStore(root.storeNames[0]);\n (function spin() {\n ++root._spinCount;\n while (root._waitingQueue.length)\n (root._waitingQueue.shift())();\n if (root._waitingFor)\n store.get(-Infinity).onsuccess = spin;\n }());\n }\n var currentWaitPromise = root._waitingFor;\n return new DexiePromise((resolve, reject) => {\n promise.then(res => root._waitingQueue.push(wrap(resolve.bind(null, res))), err => root._waitingQueue.push(wrap(reject.bind(null, err)))).finally(() => {\n if (root._waitingFor === currentWaitPromise) {\n root._waitingFor = null;\n }\n });\n });\n }\n abort() {\n if (this.active) {\n this.active = false;\n if (this.idbtrans)\n this.idbtrans.abort();\n this._reject(new exceptions.Abort());\n }\n }\n table(tableName) {\n const memoizedTables = (this._memoizedTables || (this._memoizedTables = {}));\n if (hasOwn(memoizedTables, tableName))\n return memoizedTables[tableName];\n const tableSchema = this.schema[tableName];\n if (!tableSchema) {\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\");\n }\n const transactionBoundTable = new this.db.Table(tableName, tableSchema, this);\n transactionBoundTable.core = this.db.core.table(tableName);\n memoizedTables[tableName] = transactionBoundTable;\n return transactionBoundTable;\n }\n}\n\nfunction createTransactionConstructor(db) {\n return makeClassConstructor(Transaction.prototype, function Transaction(mode, storeNames, dbschema, chromeTransactionDurability, parent) {\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.schema = dbschema;\n this.chromeTransactionDurability = chromeTransactionDurability;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._resolve = null;\n this._reject = null;\n this._waitingFor = null;\n this._waitingQueue = null;\n this._spinCount = 0;\n this._completion = new DexiePromise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n this._completion.then(() => {\n this.active = false;\n this.on.complete.fire();\n }, e => {\n var wasActive = this.active;\n this.active = false;\n this.on.error.fire(e);\n this.parent ?\n this.parent._reject(e) :\n wasActive && this.idbtrans && this.idbtrans.abort();\n return rejection(e);\n });\n });\n}\n\nfunction createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey) {\n return {\n name,\n keyPath,\n unique,\n multi,\n auto,\n compound,\n src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + nameFromKeyPath(keyPath)\n };\n}\nfunction nameFromKeyPath(keyPath) {\n return typeof keyPath === 'string' ?\n keyPath :\n keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : \"\";\n}\n\nfunction createTableSchema(name, primKey, indexes) {\n return {\n name,\n primKey,\n indexes,\n mappedClass: null,\n idxByName: arrayToObject(indexes, index => [index.name, index])\n };\n}\n\nfunction safariMultiStoreFix(storeNames) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\nlet getMaxKey = (IdbKeyRange) => {\n try {\n IdbKeyRange.only([[]]);\n getMaxKey = () => [[]];\n return [[]];\n }\n catch (e) {\n getMaxKey = () => maxString;\n return maxString;\n }\n};\n\nfunction getKeyExtractor(keyPath) {\n if (keyPath == null) {\n return () => undefined;\n }\n else if (typeof keyPath === 'string') {\n return getSinglePathKeyExtractor(keyPath);\n }\n else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\nfunction getSinglePathKeyExtractor(keyPath) {\n const split = keyPath.split('.');\n if (split.length === 1) {\n return obj => obj[keyPath];\n }\n else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n\nfunction arrayify(arrayLike) {\n return [].slice.call(arrayLike);\n}\nlet _id_counter = 0;\nfunction getKeyPathAlias(keyPath) {\n return keyPath == null ?\n \":id\" :\n typeof keyPath === 'string' ?\n keyPath :\n `[${keyPath.join('+')}]`;\n}\nfunction createDBCore(db, IdbKeyRange, tmpTrans) {\n function extractSchema(db, trans) {\n const tables = arrayify(db.objectStoreNames);\n return {\n schema: {\n name: db.name,\n tables: tables.map(table => trans.objectStore(table)).map(store => {\n const { keyPath, autoIncrement } = store;\n const compound = isArray(keyPath);\n const outbound = keyPath == null;\n const indexByKeyPath = {};\n const result = {\n name: store.name,\n primaryKey: {\n name: null,\n isPrimaryKey: true,\n outbound,\n compound,\n keyPath,\n autoIncrement,\n unique: true,\n extractKey: getKeyExtractor(keyPath)\n },\n indexes: arrayify(store.indexNames).map(indexName => store.index(indexName))\n .map(index => {\n const { name, unique, multiEntry, keyPath } = index;\n const compound = isArray(keyPath);\n const result = {\n name,\n compound,\n keyPath,\n unique,\n multiEntry,\n extractKey: getKeyExtractor(keyPath)\n };\n indexByKeyPath[getKeyPathAlias(keyPath)] = result;\n return result;\n }),\n getIndexByKeyPath: (keyPath) => indexByKeyPath[getKeyPathAlias(keyPath)]\n };\n indexByKeyPath[\":id\"] = result.primaryKey;\n if (keyPath != null) {\n indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey;\n }\n return result;\n })\n },\n hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) &&\n !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604)\n };\n }\n function makeIDBKeyRange(range) {\n if (range.type === 3 )\n return null;\n if (range.type === 4 )\n throw new Error(\"Cannot convert never type to IDBKeyRange\");\n const { lower, upper, lowerOpen, upperOpen } = range;\n const idbRange = lower === undefined ?\n upper === undefined ?\n null :\n IdbKeyRange.upperBound(upper, !!upperOpen) :\n upper === undefined ?\n IdbKeyRange.lowerBound(lower, !!lowerOpen) :\n IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen);\n return idbRange;\n }\n function createDbCoreTable(tableSchema) {\n const tableName = tableSchema.name;\n function mutate({ trans, type, keys, values, range }) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = trans.objectStore(tableName);\n const outbound = store.keyPath == null;\n const isAddOrPut = type === \"put\" || type === \"add\";\n if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange')\n throw new Error(\"Invalid operation type: \" + type);\n const { length } = keys || values || { length: 1 };\n if (keys && values && keys.length !== values.length) {\n throw new Error(\"Given keys array must have same length as given values array.\");\n }\n if (length === 0)\n return resolve({ numFailures: 0, failures: {}, results: [], lastResult: undefined });\n let req;\n const reqs = [];\n const failures = [];\n let numFailures = 0;\n const errorHandler = event => {\n ++numFailures;\n preventDefault(event);\n };\n if (type === 'deleteRange') {\n if (range.type === 4 )\n return resolve({ numFailures, failures, results: [], lastResult: undefined });\n if (range.type === 3 )\n reqs.push(req = store.clear());\n else\n reqs.push(req = store.delete(makeIDBKeyRange(range)));\n }\n else {\n const [args1, args2] = isAddOrPut ?\n outbound ?\n [values, keys] :\n [values, null] :\n [keys, null];\n if (isAddOrPut) {\n for (let i = 0; i < length; ++i) {\n reqs.push(req = (args2 && args2[i] !== undefined ?\n store[type](args1[i], args2[i]) :\n store[type](args1[i])));\n req.onerror = errorHandler;\n }\n }\n else {\n for (let i = 0; i < length; ++i) {\n reqs.push(req = store[type](args1[i]));\n req.onerror = errorHandler;\n }\n }\n }\n const done = event => {\n const lastResult = event.target.result;\n reqs.forEach((req, i) => req.error != null && (failures[i] = req.error));\n resolve({\n numFailures,\n failures,\n results: type === \"delete\" ? keys : reqs.map(req => req.result),\n lastResult\n });\n };\n req.onerror = event => {\n errorHandler(event);\n done(event);\n };\n req.onsuccess = done;\n });\n }\n function openCursor({ trans, values, query, reverse, unique }) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const { index, range } = query;\n const store = trans.objectStore(tableName);\n const source = index.isPrimaryKey ?\n store :\n store.index(index.name);\n const direction = reverse ?\n unique ?\n \"prevunique\" :\n \"prev\" :\n unique ?\n \"nextunique\" :\n \"next\";\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(makeIDBKeyRange(range), direction) :\n source.openKeyCursor(makeIDBKeyRange(range), direction);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(ev => {\n const cursor = req.result;\n if (!cursor) {\n resolve(null);\n return;\n }\n cursor.___id = ++_id_counter;\n cursor.done = false;\n const _cursorContinue = cursor.continue.bind(cursor);\n let _cursorContinuePrimaryKey = cursor.continuePrimaryKey;\n if (_cursorContinuePrimaryKey)\n _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor);\n const _cursorAdvance = cursor.advance.bind(cursor);\n const doThrowCursorIsNotStarted = () => { throw new Error(\"Cursor not started\"); };\n const doThrowCursorIsStopped = () => { throw new Error(\"Cursor not stopped\"); };\n cursor.trans = trans;\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted;\n cursor.fail = wrap(reject);\n cursor.next = function () {\n let gotOne = 1;\n return this.start(() => gotOne-- ? this.continue() : this.stop()).then(() => this);\n };\n cursor.start = (callback) => {\n const iterationPromise = new Promise((resolveIteration, rejectIteration) => {\n resolveIteration = wrap(resolveIteration);\n req.onerror = eventRejectHandler(rejectIteration);\n cursor.fail = rejectIteration;\n cursor.stop = value => {\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped;\n resolveIteration(value);\n };\n });\n const guardedCallback = () => {\n if (req.result) {\n try {\n callback();\n }\n catch (err) {\n cursor.fail(err);\n }\n }\n else {\n cursor.done = true;\n cursor.start = () => { throw new Error(\"Cursor behind last entry\"); };\n cursor.stop();\n }\n };\n req.onsuccess = wrap(ev => {\n req.onsuccess = guardedCallback;\n guardedCallback();\n });\n cursor.continue = _cursorContinue;\n cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n cursor.advance = _cursorAdvance;\n guardedCallback();\n return iterationPromise;\n };\n resolve(cursor);\n }, reject);\n });\n }\n function query(hasGetAll) {\n return (request) => {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const { trans, values, limit, query } = request;\n const nonInfinitLimit = limit === Infinity ? undefined : limit;\n const { index, range } = query;\n const store = trans.objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n if (limit === 0)\n return resolve({ result: [] });\n if (hasGetAll) {\n const req = values ?\n source.getAll(idbKeyRange, nonInfinitLimit) :\n source.getAllKeys(idbKeyRange, nonInfinitLimit);\n req.onsuccess = event => resolve({ result: event.target.result });\n req.onerror = eventRejectHandler(reject);\n }\n else {\n let count = 0;\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(idbKeyRange) :\n source.openKeyCursor(idbKeyRange);\n const result = [];\n req.onsuccess = event => {\n const cursor = req.result;\n if (!cursor)\n return resolve({ result });\n result.push(values ? cursor.value : cursor.primaryKey);\n if (++count === limit)\n return resolve({ result });\n cursor.continue();\n };\n req.onerror = eventRejectHandler(reject);\n }\n });\n };\n }\n return {\n name: tableName,\n schema: tableSchema,\n mutate,\n getMany({ trans, keys }) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = trans.objectStore(tableName);\n const length = keys.length;\n const result = new Array(length);\n let keyCount = 0;\n let callbackCount = 0;\n let req;\n const successHandler = event => {\n const req = event.target;\n if ((result[req._pos] = req.result) != null)\n ;\n if (++callbackCount === keyCount)\n resolve(result);\n };\n const errorHandler = eventRejectHandler(reject);\n for (let i = 0; i < length; ++i) {\n const key = keys[i];\n if (key != null) {\n req = store.get(keys[i]);\n req._pos = i;\n req.onsuccess = successHandler;\n req.onerror = errorHandler;\n ++keyCount;\n }\n }\n if (keyCount === 0)\n resolve(result);\n });\n },\n get({ trans, key }) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = trans.objectStore(tableName);\n const req = store.get(key);\n req.onsuccess = event => resolve(event.target.result);\n req.onerror = eventRejectHandler(reject);\n });\n },\n query: query(hasGetAll),\n openCursor,\n count({ query, trans }) {\n const { index, range } = query;\n return new Promise((resolve, reject) => {\n const store = trans.objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n const req = idbKeyRange ? source.count(idbKeyRange) : source.count();\n req.onsuccess = wrap(ev => resolve(ev.target.result));\n req.onerror = eventRejectHandler(reject);\n });\n }\n };\n }\n const { schema, hasGetAll } = extractSchema(db, tmpTrans);\n const tables = schema.tables.map(tableSchema => createDbCoreTable(tableSchema));\n const tableMap = {};\n tables.forEach(table => tableMap[table.name] = table);\n return {\n stack: \"dbcore\",\n transaction: db.transaction.bind(db),\n table(name) {\n const result = tableMap[name];\n if (!result)\n throw new Error(`Table '${name}' not found`);\n return tableMap[name];\n },\n MIN_KEY: -Infinity,\n MAX_KEY: getMaxKey(IdbKeyRange),\n schema\n };\n}\n\nfunction createMiddlewareStack(stackImpl, middlewares) {\n return middlewares.reduce((down, { create }) => ({ ...down, ...create(down) }), stackImpl);\n}\nfunction createMiddlewareStacks(middlewares, idbdb, { IDBKeyRange, indexedDB }, tmpTrans) {\n const dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore);\n return {\n dbcore\n };\n}\nfunction generateMiddlewareStacks({ _novip: db }, tmpTrans) {\n const idbdb = tmpTrans.db;\n const stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans);\n db.core = stacks.dbcore;\n db.tables.forEach(table => {\n const tableName = table.name;\n if (db.core.schema.tables.some(tbl => tbl.name === tableName)) {\n table.core = db.core.table(tableName);\n if (db[tableName] instanceof db.Table) {\n db[tableName].core = table.core;\n }\n }\n });\n}\n\nfunction setApiOnPlace({ _novip: db }, objs, tableNames, dbschema) {\n tableNames.forEach(tableName => {\n const schema = dbschema[tableName];\n objs.forEach(obj => {\n const propDesc = getPropertyDescriptor(obj, tableName);\n if (!propDesc || (\"value\" in propDesc && propDesc.value === undefined)) {\n if (obj === db.Transaction.prototype || obj instanceof db.Transaction) {\n setProp(obj, tableName, {\n get() { return this.table(tableName); },\n set(value) {\n defineProperty(this, tableName, { value, writable: true, configurable: true, enumerable: true });\n }\n });\n }\n else {\n obj[tableName] = new db.Table(tableName, schema);\n }\n }\n });\n });\n}\nfunction removeTablesApi({ _novip: db }, objs) {\n objs.forEach(obj => {\n for (let key in obj) {\n if (obj[key] instanceof db.Table)\n delete obj[key];\n }\n });\n}\nfunction lowerVersionFirst(a, b) {\n return a._cfg.version - b._cfg.version;\n}\nfunction runUpgraders(db, oldVersion, idbUpgradeTrans, reject) {\n const globalSchema = db._dbSchema;\n const trans = db._createTransaction('readwrite', db._storeNames, globalSchema);\n trans.create(idbUpgradeTrans);\n trans._completion.catch(reject);\n const rejectTransaction = trans._reject.bind(trans);\n const transless = PSD.transless || PSD;\n newScope(() => {\n PSD.trans = trans;\n PSD.transless = transless;\n if (oldVersion === 0) {\n keys(globalSchema).forEach(tableName => {\n createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n generateMiddlewareStacks(db, idbUpgradeTrans);\n DexiePromise.follow(() => db.on.populate.fire(trans)).catch(rejectTransaction);\n }\n else\n updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans).catch(rejectTransaction);\n });\n}\nfunction updateTablesAndIndexes({ _novip: db }, oldVersion, trans, idbUpgradeTrans) {\n const queue = [];\n const versions = db._versions;\n let globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans);\n let anyContentUpgraderHasRun = false;\n const versToRun = versions.filter(v => v._cfg.version >= oldVersion);\n versToRun.forEach(version => {\n queue.push(() => {\n const oldSchema = globalSchema;\n const newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans);\n adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans);\n globalSchema = db._dbSchema = newSchema;\n const diff = getSchemaDiff(oldSchema, newSchema);\n diff.add.forEach(tuple => {\n createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n diff.change.forEach(change => {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n }\n else {\n const store = idbUpgradeTrans.objectStore(change.name);\n change.add.forEach(idx => addIndex(store, idx));\n change.change.forEach(idx => {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n change.del.forEach(idxName => store.deleteIndex(idxName));\n }\n });\n const contentUpgrade = version._cfg.contentUpgrade;\n if (contentUpgrade && version._cfg.version > oldVersion) {\n generateMiddlewareStacks(db, idbUpgradeTrans);\n trans._memoizedTables = {};\n anyContentUpgraderHasRun = true;\n let upgradeSchema = shallowClone(newSchema);\n diff.del.forEach(table => {\n upgradeSchema[table] = oldSchema[table];\n });\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema), upgradeSchema);\n trans.schema = upgradeSchema;\n const contentUpgradeIsAsync = isAsyncFunction(contentUpgrade);\n if (contentUpgradeIsAsync) {\n incrementExpectedAwaits();\n }\n let returnValue;\n const promiseFollowed = DexiePromise.follow(() => {\n returnValue = contentUpgrade(trans);\n if (returnValue) {\n if (contentUpgradeIsAsync) {\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n }\n }\n });\n return (returnValue && typeof returnValue.then === 'function' ?\n DexiePromise.resolve(returnValue) : promiseFollowed.then(() => returnValue));\n }\n });\n queue.push(idbtrans => {\n if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) {\n const newSchema = version._cfg.dbschema;\n deleteRemovedTables(newSchema, idbtrans);\n }\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema);\n trans.schema = db._dbSchema;\n });\n });\n function runQueue() {\n return queue.length ? DexiePromise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) :\n DexiePromise.resolve();\n }\n return runQueue().then(() => {\n createMissingTables(globalSchema, idbUpgradeTrans);\n });\n}\nfunction getSchemaDiff(oldSchema, newSchema) {\n const diff = {\n del: [],\n add: [],\n change: []\n };\n let table;\n for (table in oldSchema) {\n if (!newSchema[table])\n diff.del.push(table);\n }\n for (table in newSchema) {\n const oldDef = oldSchema[table], newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n }\n else {\n const change = {\n name: table,\n def: newDef,\n recreate: false,\n del: [],\n add: [],\n change: []\n };\n if ((\n '' + (oldDef.primKey.keyPath || '')) !== ('' + (newDef.primKey.keyPath || '')) ||\n (oldDef.primKey.auto !== newDef.primKey.auto && !isIEOrEdge))\n {\n change.recreate = true;\n diff.change.push(change);\n }\n else {\n const oldIndexes = oldDef.idxByName;\n const newIndexes = newDef.idxByName;\n let idxName;\n for (idxName in oldIndexes) {\n if (!newIndexes[idxName])\n change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n const oldIdx = oldIndexes[idxName], newIdx = newIndexes[idxName];\n if (!oldIdx)\n change.add.push(newIdx);\n else if (oldIdx.src !== newIdx.src)\n change.change.push(newIdx);\n }\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\n diff.change.push(change);\n }\n }\n }\n }\n return diff;\n}\nfunction createTable(idbtrans, tableName, primKey, indexes) {\n const store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ?\n { keyPath: primKey.keyPath, autoIncrement: primKey.auto } :\n { autoIncrement: primKey.auto });\n indexes.forEach(idx => addIndex(store, idx));\n return store;\n}\nfunction createMissingTables(newSchema, idbtrans) {\n keys(newSchema).forEach(tableName => {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n}\nfunction deleteRemovedTables(newSchema, idbtrans) {\n [].slice.call(idbtrans.db.objectStoreNames).forEach(storeName => newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName));\n}\nfunction addIndex(store, idx) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n}\nfunction buildGlobalSchema(db, idbdb, tmpTrans) {\n const globalSchema = {};\n const dbStoreNames = slice(idbdb.objectStoreNames, 0);\n dbStoreNames.forEach(storeName => {\n const store = tmpTrans.objectStore(storeName);\n let keyPath = store.keyPath;\n const primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || \"\", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== \"string\", true);\n const indexes = [];\n for (let j = 0; j < store.indexNames.length; ++j) {\n const idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n var index = createIndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== \"string\", false);\n indexes.push(index);\n }\n globalSchema[storeName] = createTableSchema(storeName, primKey, indexes);\n });\n return globalSchema;\n}\nfunction readGlobalSchema({ _novip: db }, idbdb, tmpTrans) {\n db.verno = idbdb.version / 10;\n const globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans);\n db._storeNames = slice(idbdb.objectStoreNames, 0);\n setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema);\n}\nfunction verifyInstalledSchema(db, tmpTrans) {\n const installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans);\n const diff = getSchemaDiff(installedSchema, db._dbSchema);\n return !(diff.add.length || diff.change.some(ch => ch.add.length || ch.change.length));\n}\nfunction adjustToExistingIndexNames({ _novip: db }, schema, idbtrans) {\n const storeNames = idbtrans.db.objectStoreNames;\n for (let i = 0; i < storeNames.length; ++i) {\n const storeName = storeNames[i];\n const store = idbtrans.objectStore(storeName);\n db._hasGetAll = 'getAll' in store;\n for (let j = 0; j < store.indexNames.length; ++j) {\n const indexName = store.indexNames[j];\n const keyPath = store.index(indexName).keyPath;\n const dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n const indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) {\n indexSpec.name = indexName;\n delete schema[storeName].idxByName[dexieName];\n schema[storeName].idxByName[indexName] = indexSpec;\n }\n }\n }\n }\n if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604) {\n db._hasGetAll = false;\n }\n}\nfunction parseIndexSyntax(primKeyAndIndexes) {\n return primKeyAndIndexes.split(',').map((index, indexNum) => {\n index = index.trim();\n const name = index.replace(/([&*]|\\+\\+)/g, \"\");\n const keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n return createIndexSpec(name, keyPath || null, /\\&/.test(index), /\\*/.test(index), /\\+\\+/.test(index), isArray(keyPath), indexNum === 0);\n });\n}\n\nclass Version {\n _parseStoresSpec(stores, outSchema) {\n keys(stores).forEach(tableName => {\n if (stores[tableName] !== null) {\n var indexes = parseIndexSyntax(stores[tableName]);\n var primKey = indexes.shift();\n if (primKey.multi)\n throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\n indexes.forEach(idx => {\n if (idx.auto)\n throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\n if (!idx.keyPath)\n throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\n });\n outSchema[tableName] = createTableSchema(tableName, primKey, indexes);\n }\n });\n }\n stores(stores) {\n const db = this.db;\n this._cfg.storesSource = this._cfg.storesSource ?\n extend(this._cfg.storesSource, stores) :\n stores;\n const versions = db._versions;\n const storesSpec = {};\n let dbschema = {};\n versions.forEach(version => {\n extend(storesSpec, version._cfg.storesSource);\n dbschema = (version._cfg.dbschema = {});\n version._parseStoresSpec(storesSpec, dbschema);\n });\n db._dbSchema = dbschema;\n removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]);\n setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);\n db._storeNames = keys(dbschema);\n return this;\n }\n upgrade(upgradeFunction) {\n this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction);\n return this;\n }\n}\n\nfunction createVersionConstructor(db) {\n return makeClassConstructor(Version.prototype, function Version(versionNumber) {\n this.db = db;\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n });\n}\n\nfunction getDbNamesTable(indexedDB, IDBKeyRange) {\n let dbNamesDB = indexedDB[\"_dbNamesDB\"];\n if (!dbNamesDB) {\n dbNamesDB = indexedDB[\"_dbNamesDB\"] = new Dexie$1(DBNAMES_DB, {\n addons: [],\n indexedDB,\n IDBKeyRange,\n });\n dbNamesDB.version(1).stores({ dbnames: \"name\" });\n }\n return dbNamesDB.table(\"dbnames\");\n}\nfunction hasDatabasesNative(indexedDB) {\n return indexedDB && typeof indexedDB.databases === \"function\";\n}\nfunction getDatabaseNames({ indexedDB, IDBKeyRange, }) {\n return hasDatabasesNative(indexedDB)\n ? Promise.resolve(indexedDB.databases()).then((infos) => infos\n .map((info) => info.name)\n .filter((name) => name !== DBNAMES_DB))\n : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys();\n}\nfunction _onDatabaseCreated({ indexedDB, IDBKeyRange }, name) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).put({ name }).catch(nop);\n}\nfunction _onDatabaseDeleted({ indexedDB, IDBKeyRange }, name) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop);\n}\n\nfunction vip(fn) {\n return newScope(function () {\n PSD.letThrough = true;\n return fn();\n });\n}\n\nfunction idbReady() {\n var isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return clearInterval(intervalId); });\n}\n\nfunction dexieOpen(db) {\n const state = db._state;\n const { indexedDB } = db._deps;\n if (state.isBeingOpened || db.idbdb)\n return state.dbReadyPromise.then(() => state.dbOpenError ?\n rejection(state.dbOpenError) :\n db);\n debug && (state.openCanceller._stackHolder = getErrorWithStack());\n state.isBeingOpened = true;\n state.dbOpenError = null;\n state.openComplete = false;\n const openCanceller = state.openCanceller;\n function throwIfCancelled() {\n if (state.openCanceller !== openCanceller)\n throw new exceptions.DatabaseClosed('db.open() was cancelled');\n }\n let resolveDbReady = state.dbReadyResolve,\n upgradeTransaction = null, wasCreated = false;\n return DexiePromise.race([openCanceller, (typeof navigator === 'undefined' ? DexiePromise.resolve() : idbReady()).then(() => new DexiePromise((resolve, reject) => {\n throwIfCancelled();\n if (!indexedDB)\n throw new exceptions.MissingAPI();\n const dbName = db.name;\n const req = state.autoSchema ?\n indexedDB.open(dbName) :\n indexedDB.open(dbName, Math.round(db.verno * 10));\n if (!req)\n throw new exceptions.MissingAPI();\n req.onerror = eventRejectHandler(reject);\n req.onblocked = wrap(db._fireOnBlocked);\n req.onupgradeneeded = wrap(e => {\n upgradeTransaction = req.transaction;\n if (state.autoSchema && !db._options.allowEmptyDB) {\n req.onerror = preventDefault;\n upgradeTransaction.abort();\n req.result.close();\n const delreq = indexedDB.deleteDatabase(dbName);\n delreq.onsuccess = delreq.onerror = wrap(() => {\n reject(new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`));\n });\n }\n else {\n upgradeTransaction.onerror = eventRejectHandler(reject);\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion;\n wasCreated = oldVer < 1;\n db._novip.idbdb = req.result;\n runUpgraders(db, oldVer / 10, upgradeTransaction, reject);\n }\n }, reject);\n req.onsuccess = wrap(() => {\n upgradeTransaction = null;\n const idbdb = db._novip.idbdb = req.result;\n const objectStoreNames = slice(idbdb.objectStoreNames);\n if (objectStoreNames.length > 0)\n try {\n const tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly');\n if (state.autoSchema)\n readGlobalSchema(db, idbdb, tmpTrans);\n else {\n adjustToExistingIndexNames(db, db._dbSchema, tmpTrans);\n if (!verifyInstalledSchema(db, tmpTrans)) {\n console.warn(`Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.`);\n }\n }\n generateMiddlewareStacks(db, tmpTrans);\n }\n catch (e) {\n }\n connections.push(db);\n idbdb.onversionchange = wrap(ev => {\n state.vcFired = true;\n db.on(\"versionchange\").fire(ev);\n });\n idbdb.onclose = wrap(ev => {\n db.on(\"close\").fire(ev);\n });\n if (wasCreated)\n _onDatabaseCreated(db._deps, dbName);\n resolve();\n }, reject);\n }))]).then(() => {\n throwIfCancelled();\n state.onReadyBeingFired = [];\n return DexiePromise.resolve(vip(() => db.on.ready.fire(db.vip))).then(function fireRemainders() {\n if (state.onReadyBeingFired.length > 0) {\n let remainders = state.onReadyBeingFired.reduce(promisableChain, nop);\n state.onReadyBeingFired = [];\n return DexiePromise.resolve(vip(() => remainders(db.vip))).then(fireRemainders);\n }\n });\n }).finally(() => {\n state.onReadyBeingFired = null;\n state.isBeingOpened = false;\n }).then(() => {\n return db;\n }).catch(err => {\n state.dbOpenError = err;\n try {\n upgradeTransaction && upgradeTransaction.abort();\n }\n catch (_a) { }\n if (openCanceller === state.openCanceller) {\n db._close();\n }\n return rejection(err);\n }).finally(() => {\n state.openComplete = true;\n resolveDbReady();\n });\n}\n\nfunction awaitIterator(iterator) {\n var callNext = result => iterator.next(result), doThrow = error => iterator.throw(error), onSuccess = step(callNext), onError = step(doThrow);\n function step(getNext) {\n return (val) => {\n var next = getNext(val), value = next.value;\n return next.done ? value :\n (!value || typeof value.then !== 'function' ?\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\n value.then(onSuccess, onError));\n };\n }\n return step(callNext)();\n}\n\nfunction extractTransactionArgs(mode, _tableArgs_, scopeFunc) {\n var i = arguments.length;\n if (i < 2)\n throw new exceptions.InvalidArgument(\"Too few arguments\");\n var args = new Array(i - 1);\n while (--i)\n args[i - 1] = arguments[i];\n scopeFunc = args.pop();\n var tables = flatten(args);\n return [mode, tables, scopeFunc];\n}\nfunction enterTransactionScope(db, mode, storeNames, parentTransaction, scopeFunc) {\n return DexiePromise.resolve().then(() => {\n const transless = PSD.transless || PSD;\n const trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction);\n const zoneProps = {\n trans: trans,\n transless: transless\n };\n if (parentTransaction) {\n trans.idbtrans = parentTransaction.idbtrans;\n }\n else {\n try {\n trans.create();\n db._state.PR1398_maxLoop = 3;\n }\n catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(() => enterTransactionScope(db, mode, storeNames, null, scopeFunc));\n }\n return rejection(ex);\n }\n }\n const scopeFuncIsAsync = isAsyncFunction(scopeFunc);\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n let returnValue;\n const promiseFollowed = DexiePromise.follow(() => {\n returnValue = scopeFunc.call(trans, trans);\n if (returnValue) {\n if (scopeFuncIsAsync) {\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n }\n else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\n returnValue = awaitIterator(returnValue);\n }\n }\n }, zoneProps);\n return (returnValue && typeof returnValue.then === 'function' ?\n DexiePromise.resolve(returnValue).then(x => trans.active ?\n x\n : rejection(new exceptions.PrematureCommit(\"Transaction committed too early. See http://bit.ly/2kdckMn\")))\n : promiseFollowed.then(() => returnValue)).then(x => {\n if (parentTransaction)\n trans._resolve();\n return trans._completion.then(() => x);\n }).catch(e => {\n trans._reject(e);\n return rejection(e);\n });\n });\n}\n\nfunction pad(a, value, count) {\n const result = isArray(a) ? a.slice() : [a];\n for (let i = 0; i < count; ++i)\n result.push(value);\n return result;\n}\nfunction createVirtualIndexMiddleware(down) {\n return {\n ...down,\n table(tableName) {\n const table = down.table(tableName);\n const { schema } = table;\n const indexLookup = {};\n const allVirtualIndexes = [];\n function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) {\n const keyPathAlias = getKeyPathAlias(keyPath);\n const indexList = (indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []);\n const keyLength = keyPath == null ? 0 : typeof keyPath === 'string' ? 1 : keyPath.length;\n const isVirtual = keyTail > 0;\n const virtualIndex = {\n ...lowLevelIndex,\n isVirtual,\n keyTail,\n keyLength,\n extractKey: getKeyExtractor(keyPath),\n unique: !isVirtual && lowLevelIndex.unique\n };\n indexList.push(virtualIndex);\n if (!virtualIndex.isPrimaryKey) {\n allVirtualIndexes.push(virtualIndex);\n }\n if (keyLength > 1) {\n const virtualKeyPath = keyLength === 2 ?\n keyPath[0] :\n keyPath.slice(0, keyLength - 1);\n addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex);\n }\n indexList.sort((a, b) => a.keyTail - b.keyTail);\n return virtualIndex;\n }\n const primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey);\n indexLookup[\":id\"] = [primaryKey];\n for (const index of schema.indexes) {\n addVirtualIndexes(index.keyPath, 0, index);\n }\n function findBestIndex(keyPath) {\n const result = indexLookup[getKeyPathAlias(keyPath)];\n return result && result[0];\n }\n function translateRange(range, keyTail) {\n return {\n type: range.type === 1 ?\n 2 :\n range.type,\n lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail),\n lowerOpen: true,\n upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail),\n upperOpen: true\n };\n }\n function translateRequest(req) {\n const index = req.query.index;\n return index.isVirtual ? {\n ...req,\n query: {\n index,\n range: translateRange(req.query.range, index.keyTail)\n }\n } : req;\n }\n const result = {\n ...table,\n schema: {\n ...schema,\n primaryKey,\n indexes: allVirtualIndexes,\n getIndexByKeyPath: findBestIndex\n },\n count(req) {\n return table.count(translateRequest(req));\n },\n query(req) {\n return table.query(translateRequest(req));\n },\n openCursor(req) {\n const { keyTail, isVirtual, keyLength } = req.query.index;\n if (!isVirtual)\n return table.openCursor(req);\n function createVirtualCursor(cursor) {\n function _continue(key) {\n key != null ?\n cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) :\n req.unique ?\n cursor.continue(cursor.key.slice(0, keyLength)\n .concat(req.reverse\n ? down.MIN_KEY\n : down.MAX_KEY, keyTail)) :\n cursor.continue();\n }\n const virtualCursor = Object.create(cursor, {\n continue: { value: _continue },\n continuePrimaryKey: {\n value(key, primaryKey) {\n cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey);\n }\n },\n primaryKey: {\n get() {\n return cursor.primaryKey;\n }\n },\n key: {\n get() {\n const key = cursor.key;\n return keyLength === 1 ?\n key[0] :\n key.slice(0, keyLength);\n }\n },\n value: {\n get() {\n return cursor.value;\n }\n }\n });\n return virtualCursor;\n }\n return table.openCursor(translateRequest(req))\n .then(cursor => cursor && createVirtualCursor(cursor));\n }\n };\n return result;\n }\n };\n}\nconst virtualIndexMiddleware = {\n stack: \"dbcore\",\n name: \"VirtualIndexMiddleware\",\n level: 1,\n create: createVirtualIndexMiddleware\n};\n\nfunction getObjectDiff(a, b, rv, prfx) {\n rv = rv || {};\n prfx = prfx || '';\n keys(a).forEach((prop) => {\n if (!hasOwn(b, prop)) {\n rv[prfx + prop] = undefined;\n }\n else {\n var ap = a[prop], bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) {\n const apTypeName = toStringTag(ap);\n const bpTypeName = toStringTag(bp);\n if (apTypeName !== bpTypeName) {\n rv[prfx + prop] = b[prop];\n }\n else if (apTypeName === 'Object') {\n getObjectDiff(ap, bp, rv, prfx + prop + '.');\n }\n else if (ap !== bp) {\n rv[prfx + prop] = b[prop];\n }\n }\n else if (ap !== bp)\n rv[prfx + prop] = b[prop];\n }\n });\n keys(b).forEach((prop) => {\n if (!hasOwn(a, prop)) {\n rv[prfx + prop] = b[prop];\n }\n });\n return rv;\n}\n\nfunction getEffectiveKeys(primaryKey, req) {\n if (req.type === 'delete')\n return req.keys;\n return req.keys || req.values.map(primaryKey.extractKey);\n}\n\nconst hooksMiddleware = {\n stack: \"dbcore\",\n name: \"HooksMiddleware\",\n level: 2,\n create: (downCore) => ({\n ...downCore,\n table(tableName) {\n const downTable = downCore.table(tableName);\n const { primaryKey } = downTable.schema;\n const tableMiddleware = {\n ...downTable,\n mutate(req) {\n const dxTrans = PSD.trans;\n const { deleting, creating, updating } = dxTrans.table(tableName).hook;\n switch (req.type) {\n case 'add':\n if (creating.fire === nop)\n break;\n return dxTrans._promise('readwrite', () => addPutOrDelete(req), true);\n case 'put':\n if (creating.fire === nop && updating.fire === nop)\n break;\n return dxTrans._promise('readwrite', () => addPutOrDelete(req), true);\n case 'delete':\n if (deleting.fire === nop)\n break;\n return dxTrans._promise('readwrite', () => addPutOrDelete(req), true);\n case 'deleteRange':\n if (deleting.fire === nop)\n break;\n return dxTrans._promise('readwrite', () => deleteRange(req), true);\n }\n return downTable.mutate(req);\n function addPutOrDelete(req) {\n const dxTrans = PSD.trans;\n const keys = req.keys || getEffectiveKeys(primaryKey, req);\n if (!keys)\n throw new Error(\"Keys missing\");\n req = req.type === 'add' || req.type === 'put' ?\n { ...req, keys } :\n { ...req };\n if (req.type !== 'delete')\n req.values = [...req.values];\n if (req.keys)\n req.keys = [...req.keys];\n return getExistingValues(downTable, req, keys).then(existingValues => {\n const contexts = keys.map((key, i) => {\n const existingValue = existingValues[i];\n const ctx = { onerror: null, onsuccess: null };\n if (req.type === 'delete') {\n deleting.fire.call(ctx, key, existingValue, dxTrans);\n }\n else if (req.type === 'add' || existingValue === undefined) {\n const generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans);\n if (key == null && generatedPrimaryKey != null) {\n key = generatedPrimaryKey;\n req.keys[i] = key;\n if (!primaryKey.outbound) {\n setByKeyPath(req.values[i], primaryKey.keyPath, key);\n }\n }\n }\n else {\n const objectDiff = getObjectDiff(existingValue, req.values[i]);\n const additionalChanges = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans);\n if (additionalChanges) {\n const requestedValue = req.values[i];\n Object.keys(additionalChanges).forEach(keyPath => {\n if (hasOwn(requestedValue, keyPath)) {\n requestedValue[keyPath] = additionalChanges[keyPath];\n }\n else {\n setByKeyPath(requestedValue, keyPath, additionalChanges[keyPath]);\n }\n });\n }\n }\n return ctx;\n });\n return downTable.mutate(req).then(({ failures, results, numFailures, lastResult }) => {\n for (let i = 0; i < keys.length; ++i) {\n const primKey = results ? results[i] : keys[i];\n const ctx = contexts[i];\n if (primKey == null) {\n ctx.onerror && ctx.onerror(failures[i]);\n }\n else {\n ctx.onsuccess && ctx.onsuccess(req.type === 'put' && existingValues[i] ?\n req.values[i] :\n primKey\n );\n }\n }\n return { failures, results, numFailures, lastResult };\n }).catch(error => {\n contexts.forEach(ctx => ctx.onerror && ctx.onerror(error));\n return Promise.reject(error);\n });\n });\n }\n function deleteRange(req) {\n return deleteNextChunk(req.trans, req.range, 10000);\n }\n function deleteNextChunk(trans, range, limit) {\n return downTable.query({ trans, values: false, query: { index: primaryKey, range }, limit })\n .then(({ result }) => {\n return addPutOrDelete({ type: 'delete', keys: result, trans }).then(res => {\n if (res.numFailures > 0)\n return Promise.reject(res.failures[0]);\n if (result.length < limit) {\n return { failures: [], numFailures: 0, lastResult: undefined };\n }\n else {\n return deleteNextChunk(trans, { ...range, lower: result[result.length - 1], lowerOpen: true }, limit);\n }\n });\n });\n }\n }\n };\n return tableMiddleware;\n },\n })\n};\nfunction getExistingValues(table, req, effectiveKeys) {\n return req.type === \"add\"\n ? Promise.resolve([])\n : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: \"immutable\" });\n}\n\nfunction getFromTransactionCache(keys, cache, clone) {\n try {\n if (!cache)\n return null;\n if (cache.keys.length < keys.length)\n return null;\n const result = [];\n for (let i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) {\n if (cmp(cache.keys[i], keys[j]) !== 0)\n continue;\n result.push(clone ? deepClone(cache.values[i]) : cache.values[i]);\n ++j;\n }\n return result.length === keys.length ? result : null;\n }\n catch (_a) {\n return null;\n }\n}\nconst cacheExistingValuesMiddleware = {\n stack: \"dbcore\",\n level: -1,\n create: (core) => {\n return {\n table: (tableName) => {\n const table = core.table(tableName);\n return {\n ...table,\n getMany: (req) => {\n if (!req.cache) {\n return table.getMany(req);\n }\n const cachedResult = getFromTransactionCache(req.keys, req.trans[\"_cache\"], req.cache === \"clone\");\n if (cachedResult) {\n return DexiePromise.resolve(cachedResult);\n }\n return table.getMany(req).then((res) => {\n req.trans[\"_cache\"] = {\n keys: req.keys,\n values: req.cache === \"clone\" ? deepClone(res) : res,\n };\n return res;\n });\n },\n mutate: (req) => {\n if (req.type !== \"add\")\n req.trans[\"_cache\"] = null;\n return table.mutate(req);\n },\n };\n },\n };\n },\n};\n\nfunction isEmptyRange(node) {\n return !(\"from\" in node);\n}\nconst RangeSet = function (fromOrTree, to) {\n if (this) {\n extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 });\n }\n else {\n const rv = new RangeSet();\n if (fromOrTree && (\"d\" in fromOrTree)) {\n extend(rv, fromOrTree);\n }\n return rv;\n }\n};\nprops(RangeSet.prototype, {\n add(rangeSet) {\n mergeRanges(this, rangeSet);\n return this;\n },\n addKey(key) {\n addRange(this, key, key);\n return this;\n },\n addKeys(keys) {\n keys.forEach(key => addRange(this, key, key));\n return this;\n },\n [iteratorSymbol]() {\n return getRangeSetIterator(this);\n }\n});\nfunction addRange(target, from, to) {\n const diff = cmp(from, to);\n if (isNaN(diff))\n return;\n if (diff > 0)\n throw RangeError();\n if (isEmptyRange(target))\n return extend(target, { from, to, d: 1 });\n const left = target.l;\n const right = target.r;\n if (cmp(to, target.from) < 0) {\n left\n ? addRange(left, from, to)\n : (target.l = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.to) > 0) {\n right\n ? addRange(right, from, to)\n : (target.r = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.from) < 0) {\n target.from = from;\n target.l = null;\n target.d = right ? right.d + 1 : 1;\n }\n if (cmp(to, target.to) > 0) {\n target.to = to;\n target.r = null;\n target.d = target.l ? target.l.d + 1 : 1;\n }\n const rightWasCutOff = !target.r;\n if (left && !target.l) {\n mergeRanges(target, left);\n }\n if (right && rightWasCutOff) {\n mergeRanges(target, right);\n }\n}\nfunction mergeRanges(target, newSet) {\n function _addRangeSet(target, { from, to, l, r }) {\n addRange(target, from, to);\n if (l)\n _addRangeSet(target, l);\n if (r)\n _addRangeSet(target, r);\n }\n if (!isEmptyRange(newSet))\n _addRangeSet(target, newSet);\n}\nfunction rangesOverlap(rangeSet1, rangeSet2) {\n const i1 = getRangeSetIterator(rangeSet2);\n let nextResult1 = i1.next();\n if (nextResult1.done)\n return false;\n let a = nextResult1.value;\n const i2 = getRangeSetIterator(rangeSet1);\n let nextResult2 = i2.next(a.from);\n let b = nextResult2.value;\n while (!nextResult1.done && !nextResult2.done) {\n if (cmp(b.from, a.to) <= 0 && cmp(b.to, a.from) >= 0)\n return true;\n cmp(a.from, b.from) < 0\n ? (a = (nextResult1 = i1.next(b.from)).value)\n : (b = (nextResult2 = i2.next(a.from)).value);\n }\n return false;\n}\nfunction getRangeSetIterator(node) {\n let state = isEmptyRange(node) ? null : { s: 0, n: node };\n return {\n next(key) {\n const keyProvided = arguments.length > 0;\n while (state) {\n switch (state.s) {\n case 0:\n state.s = 1;\n if (keyProvided) {\n while (state.n.l && cmp(key, state.n.from) < 0)\n state = { up: state, n: state.n.l, s: 1 };\n }\n else {\n while (state.n.l)\n state = { up: state, n: state.n.l, s: 1 };\n }\n case 1:\n state.s = 2;\n if (!keyProvided || cmp(key, state.n.to) <= 0)\n return { value: state.n, done: false };\n case 2:\n if (state.n.r) {\n state.s = 3;\n state = { up: state, n: state.n.r, s: 0 };\n continue;\n }\n case 3:\n state = state.up;\n }\n }\n return { done: true };\n },\n };\n}\nfunction rebalance(target) {\n var _a, _b;\n const diff = (((_a = target.r) === null || _a === void 0 ? void 0 : _a.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0);\n const r = diff > 1 ? \"r\" : diff < -1 ? \"l\" : \"\";\n if (r) {\n const l = r === \"r\" ? \"l\" : \"r\";\n const rootClone = { ...target };\n const oldRootRight = target[r];\n target.from = oldRootRight.from;\n target.to = oldRootRight.to;\n target[r] = oldRootRight[r];\n rootClone[r] = oldRootRight[l];\n target[l] = rootClone;\n rootClone.d = computeDepth(rootClone);\n }\n target.d = computeDepth(target);\n}\nfunction computeDepth({ r, l }) {\n return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1;\n}\n\nconst observabilityMiddleware = {\n stack: \"dbcore\",\n level: 0,\n create: (core) => {\n const dbName = core.schema.name;\n const FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY);\n return {\n ...core,\n table: (tableName) => {\n const table = core.table(tableName);\n const { schema } = table;\n const { primaryKey } = schema;\n const { extractKey, outbound } = primaryKey;\n const tableClone = {\n ...table,\n mutate: (req) => {\n const trans = req.trans;\n const mutatedParts = trans.mutatedParts || (trans.mutatedParts = {});\n const getRangeSet = (indexName) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (mutatedParts[part] ||\n (mutatedParts[part] = new RangeSet()));\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n const { type } = req;\n let [keys, newObjs] = req.type === \"deleteRange\"\n ? [req.range]\n : req.type === \"delete\"\n ? [req.keys]\n : req.values.length < 50\n ? [[], req.values]\n : [];\n const oldCache = req.trans[\"_cache\"];\n return table.mutate(req).then((res) => {\n if (isArray(keys)) {\n if (type !== \"delete\")\n keys = res.results;\n pkRangeSet.addKeys(keys);\n const oldObjs = getFromTransactionCache(keys, oldCache);\n if (!oldObjs && type !== \"add\") {\n delsRangeSet.addKeys(keys);\n }\n if (oldObjs || newObjs) {\n trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs);\n }\n }\n else if (keys) {\n const range = { from: keys.lower, to: keys.upper };\n delsRangeSet.add(range);\n pkRangeSet.add(range);\n }\n else {\n pkRangeSet.add(FULL_RANGE);\n delsRangeSet.add(FULL_RANGE);\n schema.indexes.forEach(idx => getRangeSet(idx.name).add(FULL_RANGE));\n }\n return res;\n });\n },\n };\n const getRange = ({ query: { index, range }, }) => {\n var _a, _b;\n return [\n index,\n new RangeSet((_a = range.lower) !== null && _a !== void 0 ? _a : core.MIN_KEY, (_b = range.upper) !== null && _b !== void 0 ? _b : core.MAX_KEY),\n ];\n };\n const readSubscribers = {\n get: (req) => [primaryKey, new RangeSet(req.key)],\n getMany: (req) => [primaryKey, new RangeSet().addKeys(req.keys)],\n count: getRange,\n query: getRange,\n openCursor: getRange,\n };\n keys(readSubscribers).forEach(method => {\n tableClone[method] = function (req) {\n const { subscr } = PSD;\n if (subscr) {\n const getRangeSet = (indexName) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (subscr[part] ||\n (subscr[part] = new RangeSet()));\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n const [queriedIndex, queriedRanges] = readSubscribers[method](req);\n getRangeSet(queriedIndex.name || \"\").add(queriedRanges);\n if (!queriedIndex.isPrimaryKey) {\n if (method === \"count\") {\n delsRangeSet.add(FULL_RANGE);\n }\n else {\n const keysPromise = method === \"query\" &&\n outbound &&\n req.values &&\n table.query({\n ...req,\n values: false,\n });\n return table[method].apply(this, arguments).then((res) => {\n if (method === \"query\") {\n if (outbound && req.values) {\n return keysPromise.then(({ result: resultingKeys }) => {\n pkRangeSet.addKeys(resultingKeys);\n return res;\n });\n }\n const pKeys = req.values\n ? res.result.map(extractKey)\n : res.result;\n if (req.values) {\n pkRangeSet.addKeys(pKeys);\n }\n else {\n delsRangeSet.addKeys(pKeys);\n }\n }\n else if (method === \"openCursor\") {\n const cursor = res;\n const wantValues = req.values;\n return (cursor &&\n Object.create(cursor, {\n key: {\n get() {\n delsRangeSet.addKey(cursor.primaryKey);\n return cursor.key;\n },\n },\n primaryKey: {\n get() {\n const pkey = cursor.primaryKey;\n delsRangeSet.addKey(pkey);\n return pkey;\n },\n },\n value: {\n get() {\n wantValues && pkRangeSet.addKey(cursor.primaryKey);\n return cursor.value;\n },\n },\n }));\n }\n return res;\n });\n }\n }\n }\n return table[method].apply(this, arguments);\n };\n });\n return tableClone;\n },\n };\n },\n};\nfunction trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) {\n function addAffectedIndex(ix) {\n const rangeSet = getRangeSet(ix.name || \"\");\n function extractKey(obj) {\n return obj != null ? ix.extractKey(obj) : null;\n }\n const addKeyOrKeys = (key) => ix.multiEntry && isArray(key)\n ? key.forEach(key => rangeSet.addKey(key))\n : rangeSet.addKey(key);\n (oldObjs || newObjs).forEach((_, i) => {\n const oldKey = oldObjs && extractKey(oldObjs[i]);\n const newKey = newObjs && extractKey(newObjs[i]);\n if (cmp(oldKey, newKey) !== 0) {\n if (oldKey != null)\n addKeyOrKeys(oldKey);\n if (newKey != null)\n addKeyOrKeys(newKey);\n }\n });\n }\n schema.indexes.forEach(addAffectedIndex);\n}\n\nclass Dexie$1 {\n constructor(name, options) {\n this._middlewares = {};\n this.verno = 0;\n const deps = Dexie$1.dependencies;\n this._options = options = {\n addons: Dexie$1.addons,\n autoOpen: true,\n indexedDB: deps.indexedDB,\n IDBKeyRange: deps.IDBKeyRange,\n ...options\n };\n this._deps = {\n indexedDB: options.indexedDB,\n IDBKeyRange: options.IDBKeyRange\n };\n const { addons, } = options;\n this._dbSchema = {};\n this._versions = [];\n this._storeNames = [];\n this._allTables = {};\n this.idbdb = null;\n this._novip = this;\n const state = {\n dbOpenError: null,\n isBeingOpened: false,\n onReadyBeingFired: null,\n openComplete: false,\n dbReadyResolve: nop,\n dbReadyPromise: null,\n cancelOpen: nop,\n openCanceller: null,\n autoSchema: true,\n PR1398_maxLoop: 3\n };\n state.dbReadyPromise = new DexiePromise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new DexiePromise((_, reject) => {\n state.cancelOpen = reject;\n });\n this._state = state;\n this.name = name;\n this.on = Events(this, \"populate\", \"blocked\", \"versionchange\", \"close\", { ready: [promisableChain, nop] });\n this.on.ready.subscribe = override(this.on.ready.subscribe, subscribe => {\n return (subscriber, bSticky) => {\n Dexie$1.vip(() => {\n const state = this._state;\n if (state.openComplete) {\n if (!state.dbOpenError)\n DexiePromise.resolve().then(subscriber);\n if (bSticky)\n subscribe(subscriber);\n }\n else if (state.onReadyBeingFired) {\n state.onReadyBeingFired.push(subscriber);\n if (bSticky)\n subscribe(subscriber);\n }\n else {\n subscribe(subscriber);\n const db = this;\n if (!bSticky)\n subscribe(function unsubscribe() {\n db.on.ready.unsubscribe(subscriber);\n db.on.ready.unsubscribe(unsubscribe);\n });\n }\n });\n };\n });\n this.Collection = createCollectionConstructor(this);\n this.Table = createTableConstructor(this);\n this.Transaction = createTransactionConstructor(this);\n this.Version = createVersionConstructor(this);\n this.WhereClause = createWhereClauseConstructor(this);\n this.on(\"versionchange\", ev => {\n if (ev.newVersion > 0)\n console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`);\n else\n console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`);\n this.close();\n });\n this.on(\"blocked\", ev => {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\n console.warn(`Dexie.delete('${this.name}') was blocked`);\n else\n console.warn(`Upgrade '${this.name}' blocked by other connection holding version ${ev.oldVersion / 10}`);\n });\n this._maxKey = getMaxKey(options.IDBKeyRange);\n this._createTransaction = (mode, storeNames, dbschema, parentTransaction) => new this.Transaction(mode, storeNames, dbschema, this._options.chromeTransactionDurability, parentTransaction);\n this._fireOnBlocked = ev => {\n this.on(\"blocked\").fire(ev);\n connections\n .filter(c => c.name === this.name && c !== this && !c._state.vcFired)\n .map(c => c.on(\"versionchange\").fire(ev));\n };\n this.use(virtualIndexMiddleware);\n this.use(hooksMiddleware);\n this.use(observabilityMiddleware);\n this.use(cacheExistingValuesMiddleware);\n this.vip = Object.create(this, { _vip: { value: true } });\n addons.forEach(addon => addon(this));\n }\n version(versionNumber) {\n if (isNaN(versionNumber) || versionNumber < 0.1)\n throw new exceptions.Type(`Given version is not a positive number`);\n versionNumber = Math.round(versionNumber * 10) / 10;\n if (this.idbdb || this._state.isBeingOpened)\n throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n const versions = this._versions;\n var versionInstance = versions.filter(v => v._cfg.version === versionNumber)[0];\n if (versionInstance)\n return versionInstance;\n versionInstance = new this.Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n versionInstance.stores({});\n this._state.autoSchema = false;\n return versionInstance;\n }\n _whenReady(fn) {\n return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new DexiePromise((resolve, reject) => {\n if (this._state.openComplete) {\n return reject(new exceptions.DatabaseClosed(this._state.dbOpenError));\n }\n if (!this._state.isBeingOpened) {\n if (!this._options.autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n this.open().catch(nop);\n }\n this._state.dbReadyPromise.then(resolve, reject);\n }).then(fn);\n }\n use({ stack, create, level, name }) {\n if (name)\n this.unuse({ stack, name });\n const middlewares = this._middlewares[stack] || (this._middlewares[stack] = []);\n middlewares.push({ stack, create, level: level == null ? 10 : level, name });\n middlewares.sort((a, b) => a.level - b.level);\n return this;\n }\n unuse({ stack, name, create }) {\n if (stack && this._middlewares[stack]) {\n this._middlewares[stack] = this._middlewares[stack].filter(mw => create ? mw.create !== create :\n name ? mw.name !== name :\n false);\n }\n return this;\n }\n open() {\n return dexieOpen(this);\n }\n _close() {\n const state = this._state;\n const idx = connections.indexOf(this);\n if (idx >= 0)\n connections.splice(idx, 1);\n if (this.idbdb) {\n try {\n this.idbdb.close();\n }\n catch (e) { }\n this._novip.idbdb = null;\n }\n state.dbReadyPromise = new DexiePromise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new DexiePromise((_, reject) => {\n state.cancelOpen = reject;\n });\n }\n close() {\n this._close();\n const state = this._state;\n this._options.autoOpen = false;\n state.dbOpenError = new exceptions.DatabaseClosed();\n if (state.isBeingOpened)\n state.cancelOpen(state.dbOpenError);\n }\n delete() {\n const hasArguments = arguments.length > 0;\n const state = this._state;\n return new DexiePromise((resolve, reject) => {\n const doDelete = () => {\n this.close();\n var req = this._deps.indexedDB.deleteDatabase(this.name);\n req.onsuccess = wrap(() => {\n _onDatabaseDeleted(this._deps, this.name);\n resolve();\n });\n req.onerror = eventRejectHandler(reject);\n req.onblocked = this._fireOnBlocked;\n };\n if (hasArguments)\n throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\n if (state.isBeingOpened) {\n state.dbReadyPromise.then(doDelete);\n }\n else {\n doDelete();\n }\n });\n }\n backendDB() {\n return this.idbdb;\n }\n isOpen() {\n return this.idbdb !== null;\n }\n hasBeenClosed() {\n const dbOpenError = this._state.dbOpenError;\n return dbOpenError && (dbOpenError.name === 'DatabaseClosed');\n }\n hasFailed() {\n return this._state.dbOpenError !== null;\n }\n dynamicallyOpened() {\n return this._state.autoSchema;\n }\n get tables() {\n return keys(this._allTables).map(name => this._allTables[name]);\n }\n transaction() {\n const args = extractTransactionArgs.apply(this, arguments);\n return this._transaction.apply(this, args);\n }\n _transaction(mode, tables, scopeFunc) {\n let parentTransaction = PSD.trans;\n if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1)\n parentTransaction = null;\n const onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', '');\n let idbMode, storeNames;\n try {\n storeNames = tables.map(table => {\n var storeName = table instanceof this.Table ? table.name : table;\n if (typeof storeName !== 'string')\n throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\n return storeName;\n });\n if (mode == \"r\" || mode === READONLY)\n idbMode = READONLY;\n else if (mode == \"rw\" || mode == READWRITE)\n idbMode = READWRITE;\n else\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n if (parentTransaction) {\n if (parentTransaction.mode === READONLY && idbMode === READWRITE) {\n if (onlyIfCompatible) {\n parentTransaction = null;\n }\n else\n throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\n }\n if (parentTransaction) {\n storeNames.forEach(storeName => {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n parentTransaction = null;\n }\n else\n throw new exceptions.SubTransaction(\"Table \" + storeName +\n \" not included in parent transaction.\");\n }\n });\n }\n if (onlyIfCompatible && parentTransaction && !parentTransaction.active) {\n parentTransaction = null;\n }\n }\n }\n catch (e) {\n return parentTransaction ?\n parentTransaction._promise(null, (_, reject) => { reject(e); }) :\n rejection(e);\n }\n const enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc);\n return (parentTransaction ?\n parentTransaction._promise(idbMode, enterTransaction, \"lock\") :\n PSD.trans ?\n usePSD(PSD.transless, () => this._whenReady(enterTransaction)) :\n this._whenReady(enterTransaction));\n }\n table(tableName) {\n if (!hasOwn(this._allTables, tableName)) {\n throw new exceptions.InvalidTable(`Table ${tableName} does not exist`);\n }\n return this._allTables[tableName];\n }\n}\n\nconst symbolObservable = typeof Symbol !== \"undefined\" && \"observable\" in Symbol\n ? Symbol.observable\n : \"@@observable\";\nclass Observable {\n constructor(subscribe) {\n this._subscribe = subscribe;\n }\n subscribe(x, error, complete) {\n return this._subscribe(!x || typeof x === \"function\" ? { next: x, error, complete } : x);\n }\n [symbolObservable]() {\n return this;\n }\n}\n\nfunction extendObservabilitySet(target, newSet) {\n keys(newSet).forEach(part => {\n const rangeSet = target[part] || (target[part] = new RangeSet());\n mergeRanges(rangeSet, newSet[part]);\n });\n return target;\n}\n\nfunction liveQuery(querier) {\n let hasValue = false;\n let currentValue = undefined;\n const observable = new Observable((observer) => {\n const scopeFuncIsAsync = isAsyncFunction(querier);\n function execute(subscr) {\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n const exec = () => newScope(querier, { subscr, trans: null });\n const rv = PSD.trans\n ?\n usePSD(PSD.transless, exec)\n : exec();\n if (scopeFuncIsAsync) {\n rv.then(decrementExpectedAwaits, decrementExpectedAwaits);\n }\n return rv;\n }\n let closed = false;\n let accumMuts = {};\n let currentObs = {};\n const subscription = {\n get closed() {\n return closed;\n },\n unsubscribe: () => {\n closed = true;\n globalEvents.storagemutated.unsubscribe(mutationListener);\n },\n };\n observer.start && observer.start(subscription);\n let querying = false, startedListening = false;\n function shouldNotify() {\n return keys(currentObs).some((key) => accumMuts[key] && rangesOverlap(accumMuts[key], currentObs[key]));\n }\n const mutationListener = (parts) => {\n extendObservabilitySet(accumMuts, parts);\n if (shouldNotify()) {\n doQuery();\n }\n };\n const doQuery = () => {\n if (querying || closed)\n return;\n accumMuts = {};\n const subscr = {};\n const ret = execute(subscr);\n if (!startedListening) {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener);\n startedListening = true;\n }\n querying = true;\n Promise.resolve(ret).then((result) => {\n hasValue = true;\n currentValue = result;\n querying = false;\n if (closed)\n return;\n if (shouldNotify()) {\n doQuery();\n }\n else {\n accumMuts = {};\n currentObs = subscr;\n observer.next && observer.next(result);\n }\n }, (err) => {\n querying = false;\n hasValue = false;\n observer.error && observer.error(err);\n subscription.unsubscribe();\n });\n };\n doQuery();\n return subscription;\n });\n observable.hasValue = () => hasValue;\n observable.getValue = () => currentValue;\n return observable;\n}\n\nlet domDeps;\ntry {\n domDeps = {\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n };\n}\ncatch (e) {\n domDeps = { indexedDB: null, IDBKeyRange: null };\n}\n\nconst Dexie = Dexie$1;\nprops(Dexie, {\n ...fullNameExceptions,\n delete(databaseName) {\n const db = new Dexie(databaseName, { addons: [] });\n return db.delete();\n },\n exists(name) {\n return new Dexie(name, { addons: [] }).open().then(db => {\n db.close();\n return true;\n }).catch('NoSuchDatabaseError', () => false);\n },\n getDatabaseNames(cb) {\n try {\n return getDatabaseNames(Dexie.dependencies).then(cb);\n }\n catch (_a) {\n return rejection(new exceptions.MissingAPI());\n }\n },\n defineClass() {\n function Class(content) {\n extend(this, content);\n }\n return Class;\n },\n ignoreTransaction(scopeFunc) {\n return PSD.trans ?\n usePSD(PSD.transless, scopeFunc) :\n scopeFunc();\n },\n vip,\n async: function (generatorFn) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function')\n return DexiePromise.resolve(rv);\n return rv;\n }\n catch (e) {\n return rejection(e);\n }\n };\n },\n spawn: function (generatorFn, args, thiz) {\n try {\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\n if (!rv || typeof rv.then !== 'function')\n return DexiePromise.resolve(rv);\n return rv;\n }\n catch (e) {\n return rejection(e);\n }\n },\n currentTransaction: {\n get: () => PSD.trans || null\n },\n waitFor: function (promiseOrFunction, optionalTimeout) {\n const promise = DexiePromise.resolve(typeof promiseOrFunction === 'function' ?\n Dexie.ignoreTransaction(promiseOrFunction) :\n promiseOrFunction)\n .timeout(optionalTimeout || 60000);\n return PSD.trans ?\n PSD.trans.waitFor(promise) :\n promise;\n },\n Promise: DexiePromise,\n debug: {\n get: () => debug,\n set: value => {\n setDebug(value, value === 'dexie' ? () => true : dexieStackFrameFilter);\n }\n },\n derive: derive,\n extend: extend,\n props: props,\n override: override,\n Events: Events,\n on: globalEvents,\n liveQuery,\n extendObservabilitySet,\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n cmp,\n asap: asap$1,\n minKey: minKey,\n addons: [],\n connections: connections,\n errnames: errnames,\n dependencies: domDeps,\n semVer: DEXIE_VERSION,\n version: DEXIE_VERSION.split('.')\n .map(n => parseInt(n))\n .reduce((p, c, i) => p + (c / Math.pow(10, i * 2))),\n});\nDexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange);\n\nif (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, updatedParts => {\n if (!propagatingLocally) {\n let event;\n if (isIEOrEdge) {\n event = document.createEvent('CustomEvent');\n event.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts);\n }\n else {\n event = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, {\n detail: updatedParts\n });\n }\n propagatingLocally = true;\n dispatchEvent(event);\n propagatingLocally = false;\n }\n });\n addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, ({ detail }) => {\n if (!propagatingLocally) {\n propagateLocally(detail);\n }\n });\n}\nfunction propagateLocally(updateParts) {\n let wasMe = propagatingLocally;\n try {\n propagatingLocally = true;\n globalEvents.storagemutated.fire(updateParts);\n }\n finally {\n propagatingLocally = wasMe;\n }\n}\nlet propagatingLocally = false;\n\nif (typeof BroadcastChannel !== 'undefined') {\n const bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME);\n if (typeof bc.unref === 'function') {\n bc.unref();\n }\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n if (!propagatingLocally) {\n bc.postMessage(changedParts);\n }\n });\n bc.onmessage = (ev) => {\n if (ev.data)\n propagateLocally(ev.data);\n };\n}\nelse if (typeof self !== 'undefined' && typeof navigator !== 'undefined') {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n try {\n if (!propagatingLocally) {\n if (typeof localStorage !== 'undefined') {\n localStorage.setItem(STORAGE_MUTATED_DOM_EVENT_NAME, JSON.stringify({\n trig: Math.random(),\n changedParts,\n }));\n }\n if (typeof self['clients'] === 'object') {\n [...self['clients'].matchAll({ includeUncontrolled: true })].forEach((client) => client.postMessage({\n type: STORAGE_MUTATED_DOM_EVENT_NAME,\n changedParts,\n }));\n }\n }\n }\n catch (_a) { }\n });\n if (typeof addEventListener !== 'undefined') {\n addEventListener('storage', (ev) => {\n if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) {\n const data = JSON.parse(ev.newValue);\n if (data)\n propagateLocally(data.changedParts);\n }\n });\n }\n const swContainer = self.document && navigator.serviceWorker;\n if (swContainer) {\n swContainer.addEventListener('message', propagateMessageLocally);\n }\n}\nfunction propagateMessageLocally({ data }) {\n if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) {\n propagateLocally(data.changedParts);\n }\n}\n\nDexiePromise.rejectionMapper = mapError;\nsetDebug(debug, dexieStackFrameFilter);\n\n\n//# sourceMappingURL=dexie.mjs.map\n\n\n//# sourceURL=webpack://mainnet-js/../../node_modules/dexie/dist/modern/dexie.mjs?");
2368
2328
 
2369
2329
  /***/ }),
2370
2330