diff --git a/README.md b/README.md index a6da68cf..5ae7e04a 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,8 @@ ```javascript const getData = function(err, myIndex) { - readStreamOfDocuments // <- a stream of documents to be indexed - .pipe(myIndex.defaultPipeline()) // <- an extentable document processing pipeline - .pipe(myIndex.add()) // <- myIndex is a search index that can now be queried + readStreamOfDocuments // <- a stream of documents to be indexed + .pipe(myIndex.feed()) // <- an extendable document processing pipeline (do objectMode: true for a stream of objects) } require('search-index')(options, getData) // <- make a new index ``` diff --git a/dist/search-index.js b/dist/search-index.js index dd9daa2d..c93a23b0 100644 --- a/dist/search-index.js +++ b/dist/search-index.js @@ -38,6 +38,7 @@ const getAdder = function (SearchIndex, done) { SearchIndex.defaultPipeline = searchIndexAdder.defaultPipeline SearchIndex.del = searchIndexAdder.deleter SearchIndex.deleteStream = searchIndexAdder.deleteStream + SearchIndex.feed = searchIndexAdder.feed SearchIndex.flush = searchIndexAdder.flush done(err, SearchIndex) }) @@ -83,7 +84,7 @@ const getOptions = function (options, done) { } } -},{"./siUtil.js":2,"bunyan":9,"leveldown":57,"levelup":70,"search-index-adder":103,"search-index-searcher":107}],2:[function(require,module,exports){ +},{"./siUtil.js":2,"bunyan":10,"leveldown":59,"levelup":72,"search-index-adder":105,"search-index-searcher":109}],2:[function(require,module,exports){ module.exports = function(siOptions) { var siUtil = {} @@ -120,6 +121,263 @@ module.exports = function(siOptions) { } },{}],3:[function(require,module,exports){ +(function (process,Buffer){ + + +'use strict' + +var Parser = require('jsonparse') + , through = require('through') + +/* + + the value of this.stack that creationix's jsonparse has is weird. + + it makes this code ugly, but his problem is way harder that mine, + so i'll forgive him. + +*/ + +exports.parse = function (path, map) { + var header, footer + var parser = new Parser() + var stream = through(function (chunk) { + if('string' === typeof chunk) + chunk = new Buffer(chunk) + parser.write(chunk) + }, + function (data) { + if(data) + stream.write(data) + if (header) + stream.emit('header', header) + if (footer) + stream.emit('footer', footer) + stream.queue(null) + }) + + if('string' === typeof path) + path = path.split('.').map(function (e) { + if (e === '$*') + return {emitKey: true} + else if (e === '*') + return true + else if (e === '') // '..'.split('.') returns an empty string + return {recurse: true} + else + return e + }) + + + var count = 0, _key + if(!path || !path.length) + path = null + + parser.onValue = function (value) { + if (!this.root) + stream.root = value + + if(! path) return + + var i = 0 // iterates on path + var j = 0 // iterates on stack + var emitKey = false; + var emitPath = false; + while (i < path.length) { + var key = path[i] + var c + j++ + + if (key && !key.recurse) { + c = (j === this.stack.length) ? this : this.stack[j] + if (!c) return + if (! check(key, c.key)) { + setHeaderFooter(c.key, value) + return + } + emitKey = !!key.emitKey; + emitPath = !!key.emitPath; + i++ + } else { + i++ + var nextKey = path[i] + if (! nextKey) return + while (true) { + c = (j === this.stack.length) ? this : this.stack[j] + if (!c) return + if (check(nextKey, c.key)) { + i++; + if (!Object.isFrozen(this.stack[j])) + this.stack[j].value = null + break + } else { + setHeaderFooter(c.key, value) + } + j++ + } + } + + } + + // emit header + if (header) { + stream.emit('header', header); + header = false; + } + if (j !== this.stack.length) return + + count ++ + var actualPath = this.stack.slice(1).map(function(element) { return element.key }).concat([this.key]) + var data = this.value[this.key] + if(null != data) + if(null != (data = map ? map(data, actualPath) : data)) { + if (emitKey || emitPath) { + data = { value: data }; + if (emitKey) + data["key"] = this.key; + if (emitPath) + data["path"] = actualPath; + } + + stream.queue(data) + } + delete this.value[this.key] + for(var k in this.stack) + if (!Object.isFrozen(this.stack[k])) + this.stack[k].value = null + } + parser._onToken = parser.onToken; + + parser.onToken = function (token, value) { + parser._onToken(token, value); + if (this.stack.length === 0) { + if (stream.root) { + if(!path) + stream.queue(stream.root) + count = 0; + stream.root = null; + } + } + } + + parser.onError = function (err) { + if(err.message.indexOf("at position") > -1) + err.message = "Invalid JSON (" + err.message + ")"; + stream.emit('error', err) + } + + return stream + + function setHeaderFooter(key, value) { + // header has not been emitted yet + if (header !== false) { + header = header || {} + header[key] = value + } + + // footer has not been emitted yet but header has + if (footer !== false && header === false) { + footer = footer || {} + footer[key] = value + } + } +} + +function check (x, y) { + if ('string' === typeof x) + return y == x + else if (x && 'function' === typeof x.exec) + return x.exec(y) + else if ('boolean' === typeof x || 'object' === typeof x) + return x + else if ('function' === typeof x) + return x(y) + return false +} + +exports.stringify = function (op, sep, cl, indent) { + indent = indent || 0 + if (op === false){ + op = '' + sep = '\n' + cl = '' + } else if (op == null) { + + op = '[\n' + sep = '\n,\n' + cl = '\n]\n' + + } + + //else, what ever you like + + var stream + , first = true + , anyData = false + stream = through(function (data) { + anyData = true + try { + var json = JSON.stringify(data, null, indent) + } catch (err) { + return stream.emit('error', err) + } + if(first) { first = false ; stream.queue(op + json)} + else stream.queue(sep + json) + }, + function (data) { + if(!anyData) + stream.queue(op) + stream.queue(cl) + stream.queue(null) + }) + + return stream +} + +exports.stringifyObject = function (op, sep, cl, indent) { + indent = indent || 0 + if (op === false){ + op = '' + sep = '\n' + cl = '' + } else if (op == null) { + + op = '{\n' + sep = '\n,\n' + cl = '\n}\n' + + } + + //else, what ever you like + + var first = true + var anyData = false + var stream = through(function (data) { + anyData = true + var json = JSON.stringify(data[0]) + ':' + JSON.stringify(data[1], null, indent) + if(first) { first = false ; this.queue(op + json)} + else this.queue(sep + json) + }, + function (data) { + if(!anyData) this.queue(op) + this.queue(cl) + + this.queue(null) + }) + + return stream +} + +if(!module.parent && process.title !== 'browser') { + process.stdin + .pipe(exports.parse(process.argv[2])) + .pipe(exports.stringify('[', ',\n', ']\n', 2)) + .pipe(process.stdout) +} + + +}).call(this,require('_process'),require("buffer").Buffer) +},{"_process":86,"buffer":9,"jsonparse":46,"through":132}],4:[function(require,module,exports){ (function (global){ 'use strict'; @@ -613,7 +871,7 @@ var objectKeys = Object.keys || function (obj) { }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"util/":134}],4:[function(require,module,exports){ +},{"util/":137}],5:[function(require,module,exports){ (function (process,global){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : @@ -6166,7 +6424,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":84}],5:[function(require,module,exports){ +},{"_process":86}],6:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength @@ -6282,11 +6540,11 @@ function fromByteArray (uint8) { return parts.join('') } -},{}],6:[function(require,module,exports){ - },{}],7:[function(require,module,exports){ -arguments[4][6][0].apply(exports,arguments) -},{"dup":6}],8:[function(require,module,exports){ + +},{}],8:[function(require,module,exports){ +arguments[4][7][0].apply(exports,arguments) +},{"dup":7}],9:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. @@ -8079,7 +8337,7 @@ function isnan (val) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"base64-js":5,"ieee754":39,"isarray":43}],9:[function(require,module,exports){ +},{"base64-js":6,"ieee754":40,"isarray":44}],10:[function(require,module,exports){ (function (Buffer,process){ /** * Copyright (c) 2017 Trent Mick. @@ -9710,7 +9968,7 @@ module.exports.RotatingFileStream = RotatingFileStream; module.exports.safeCycles = safeCycles; }).call(this,{"isBuffer":require("../../is-buffer/index.js")},require('_process')) -},{"../../is-buffer/index.js":42,"_process":84,"assert":3,"events":37,"fs":7,"os":82,"safe-json-stringify":102,"stream":125,"util":134}],10:[function(require,module,exports){ +},{"../../is-buffer/index.js":43,"_process":86,"assert":4,"events":38,"fs":8,"os":84,"safe-json-stringify":104,"stream":127,"util":137}],11:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // @@ -9821,7 +10079,7 @@ function objectToString(o) { } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":42}],11:[function(require,module,exports){ +},{"../../is-buffer/index.js":43}],12:[function(require,module,exports){ var util = require('util') , AbstractIterator = require('abstract-leveldown').AbstractIterator @@ -9857,7 +10115,7 @@ DeferredIterator.prototype._operation = function (method, args) { module.exports = DeferredIterator; -},{"abstract-leveldown":16,"util":134}],12:[function(require,module,exports){ +},{"abstract-leveldown":17,"util":137}],13:[function(require,module,exports){ (function (Buffer,process){ var util = require('util') , AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN @@ -9917,7 +10175,7 @@ module.exports = DeferredLevelDOWN module.exports.DeferredIterator = DeferredIterator }).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process')) -},{"../is-buffer/index.js":42,"./deferred-iterator":11,"_process":84,"abstract-leveldown":16,"util":134}],13:[function(require,module,exports){ +},{"../is-buffer/index.js":43,"./deferred-iterator":12,"_process":86,"abstract-leveldown":17,"util":137}],14:[function(require,module,exports){ (function (process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -10000,7 +10258,7 @@ AbstractChainedBatch.prototype.write = function (options, callback) { module.exports = AbstractChainedBatch }).call(this,require('_process')) -},{"_process":84}],14:[function(require,module,exports){ +},{"_process":86}],15:[function(require,module,exports){ (function (process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -10053,7 +10311,7 @@ AbstractIterator.prototype.end = function (callback) { module.exports = AbstractIterator }).call(this,require('_process')) -},{"_process":84}],15:[function(require,module,exports){ +},{"_process":86}],16:[function(require,module,exports){ (function (Buffer,process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -10329,13 +10587,13 @@ AbstractLevelDOWN.prototype._checkKey = function (obj, type) { module.exports = AbstractLevelDOWN }).call(this,{"isBuffer":require("../../../is-buffer/index.js")},require('_process')) -},{"../../../is-buffer/index.js":42,"./abstract-chained-batch":13,"./abstract-iterator":14,"_process":84,"xtend":136}],16:[function(require,module,exports){ +},{"../../../is-buffer/index.js":43,"./abstract-chained-batch":14,"./abstract-iterator":15,"_process":86,"xtend":139}],17:[function(require,module,exports){ exports.AbstractLevelDOWN = require('./abstract-leveldown') exports.AbstractIterator = require('./abstract-iterator') exports.AbstractChainedBatch = require('./abstract-chained-batch') exports.isLevelDOWN = require('./is-leveldown') -},{"./abstract-chained-batch":13,"./abstract-iterator":14,"./abstract-leveldown":15,"./is-leveldown":17}],17:[function(require,module,exports){ +},{"./abstract-chained-batch":14,"./abstract-iterator":15,"./abstract-leveldown":16,"./is-leveldown":18}],18:[function(require,module,exports){ var AbstractLevelDOWN = require('./abstract-leveldown') function isLevelDOWN (db) { @@ -10351,7 +10609,7 @@ function isLevelDOWN (db) { module.exports = isLevelDOWN -},{"./abstract-leveldown":15}],18:[function(require,module,exports){ +},{"./abstract-leveldown":16}],19:[function(require,module,exports){ const pumpify = require('pumpify') const stopwords = [] @@ -10417,7 +10675,7 @@ exports.customPipeline = function (pl) { return pumpify.obj.apply(this, pl) } -},{"./pipeline/CalculateTermFrequency.js":19,"./pipeline/CreateCompositeVector.js":20,"./pipeline/CreateSortVectors.js":21,"./pipeline/CreateStoredDocument.js":22,"./pipeline/FieldedSearch.js":23,"./pipeline/IngestDoc.js":24,"./pipeline/LowCase.js":25,"./pipeline/NormaliseFields.js":26,"./pipeline/RemoveStopWords.js":27,"./pipeline/Spy.js":28,"./pipeline/Tokeniser.js":29,"pumpify":87}],19:[function(require,module,exports){ +},{"./pipeline/CalculateTermFrequency.js":20,"./pipeline/CreateCompositeVector.js":21,"./pipeline/CreateSortVectors.js":22,"./pipeline/CreateStoredDocument.js":23,"./pipeline/FieldedSearch.js":24,"./pipeline/IngestDoc.js":25,"./pipeline/LowCase.js":26,"./pipeline/NormaliseFields.js":27,"./pipeline/RemoveStopWords.js":28,"./pipeline/Spy.js":29,"./pipeline/Tokeniser.js":30,"pumpify":89}],20:[function(require,module,exports){ const tv = require('term-vector') const tf = require('term-frequency') const Transform = require('stream').Transform @@ -10462,7 +10720,7 @@ CalculateTermFrequency.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":125,"term-frequency":128,"term-vector":129,"util":134}],20:[function(require,module,exports){ +},{"stream":127,"term-frequency":130,"term-vector":131,"util":137}],21:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -10493,7 +10751,7 @@ CreateCompositeVector.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":125,"util":134}],21:[function(require,module,exports){ +},{"stream":127,"util":137}],22:[function(require,module,exports){ const tf = require('term-frequency') const tv = require('term-vector') const Transform = require('stream').Transform @@ -10530,7 +10788,7 @@ CreateSortVectors.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":125,"term-frequency":128,"term-vector":129,"util":134}],22:[function(require,module,exports){ +},{"stream":127,"term-frequency":130,"term-vector":131,"util":137}],23:[function(require,module,exports){ // Creates the document that will be returned in the search // results. There may be cases where the document that is searchable // is not the same as the document that is returned @@ -10561,7 +10819,7 @@ CreateStoredDocument.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":125,"util":134}],23:[function(require,module,exports){ +},{"stream":127,"util":137}],24:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -10586,7 +10844,7 @@ FieldedSearch.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":125,"util":134}],24:[function(require,module,exports){ +},{"stream":127,"util":137}],25:[function(require,module,exports){ const util = require('util') const Transform = require('stream').Transform @@ -10623,7 +10881,7 @@ IngestDoc.prototype._transform = function (doc, encoding, end) { } -},{"stream":125,"util":134}],25:[function(require,module,exports){ +},{"stream":127,"util":137}],26:[function(require,module,exports){ // insert all search tokens in lower case const Transform = require('stream').Transform const util = require('util') @@ -10657,7 +10915,7 @@ LowCase.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":125,"util":134}],26:[function(require,module,exports){ +},{"stream":127,"util":137}],27:[function(require,module,exports){ const util = require('util') const Transform = require('stream').Transform @@ -10685,7 +10943,7 @@ NormaliseFields.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":125,"util":134}],27:[function(require,module,exports){ +},{"stream":127,"util":137}],28:[function(require,module,exports){ // removes stopwords from indexed docs const Transform = require('stream').Transform const util = require('util') @@ -10716,7 +10974,7 @@ RemoveStopWords.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":125,"util":134}],28:[function(require,module,exports){ +},{"stream":127,"util":137}],29:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -10731,7 +10989,7 @@ Spy.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":125,"util":134}],29:[function(require,module,exports){ +},{"stream":127,"util":137}],30:[function(require,module,exports){ // split up fields in to arrays of tokens const Transform = require('stream').Transform const util = require('util') @@ -10763,7 +11021,7 @@ Tokeniser.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":125,"util":134}],30:[function(require,module,exports){ +},{"stream":127,"util":137}],31:[function(require,module,exports){ (function (process,Buffer){ var stream = require('readable-stream') var eos = require('end-of-stream') @@ -10995,7 +11253,7 @@ Duplexify.prototype.end = function(data, enc, cb) { module.exports = Duplexify }).call(this,require('_process'),require("buffer").Buffer) -},{"_process":84,"buffer":8,"end-of-stream":31,"inherits":40,"readable-stream":98,"stream-shift":126}],31:[function(require,module,exports){ +},{"_process":86,"buffer":9,"end-of-stream":32,"inherits":41,"readable-stream":100,"stream-shift":128}],32:[function(require,module,exports){ var once = require('once'); var noop = function() {}; @@ -11068,7 +11326,7 @@ var eos = function(stream, opts, callback) { }; module.exports = eos; -},{"once":32}],32:[function(require,module,exports){ +},{"once":33}],33:[function(require,module,exports){ var wrappy = require('wrappy') module.exports = wrappy(once) @@ -11091,7 +11349,7 @@ function once (fn) { return f } -},{"wrappy":135}],33:[function(require,module,exports){ +},{"wrappy":138}],34:[function(require,module,exports){ var once = require('once'); var noop = function() {}; @@ -11176,7 +11434,7 @@ var eos = function(stream, opts, callback) { module.exports = eos; -},{"once":81}],34:[function(require,module,exports){ +},{"once":83}],35:[function(require,module,exports){ var prr = require('prr') function init (type, message, cause) { @@ -11233,7 +11491,7 @@ module.exports = function (errno) { } } -},{"prr":36}],35:[function(require,module,exports){ +},{"prr":37}],36:[function(require,module,exports){ var all = module.exports.all = [ { errno: -2, @@ -11548,7 +11806,7 @@ all.forEach(function (error) { module.exports.custom = require('./custom')(module.exports) module.exports.create = module.exports.custom.createError -},{"./custom":34}],36:[function(require,module,exports){ +},{"./custom":35}],37:[function(require,module,exports){ /*! * prr * (c) 2013 Rod Vagg @@ -11612,7 +11870,7 @@ module.exports.create = module.exports.custom.createError return prr }) -},{}],37:[function(require,module,exports){ +},{}],38:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -11916,7 +12174,7 @@ function isUndefined(arg) { return arg === void 0; } -},{}],38:[function(require,module,exports){ +},{}],39:[function(require,module,exports){ /*global window:false, self:false, define:false, module:false */ /** @@ -13323,7 +13581,7 @@ function isUndefined(arg) { }, this); -},{}],39:[function(require,module,exports){ +},{}],40:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 @@ -13409,7 +13667,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],40:[function(require,module,exports){ +},{}],41:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { @@ -13434,7 +13692,7 @@ if (typeof Object.create === 'function') { } } -},{}],41:[function(require,module,exports){ +},{}],42:[function(require,module,exports){ // This module takes an arbitrary number of sorted arrays, and returns // the intersection as a stream. Arrays need to be sorted in order for @@ -13500,7 +13758,7 @@ exports.getIntersectionStream = function(sortedSets) { return s } -},{"stream":125}],42:[function(require,module,exports){ +},{"stream":127}],43:[function(require,module,exports){ /*! * Determine if an object is a Buffer * @@ -13523,14 +13781,14 @@ function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } -},{}],43:[function(require,module,exports){ +},{}],44:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; -},{}],44:[function(require,module,exports){ +},{}],45:[function(require,module,exports){ var Buffer = require('buffer').Buffer; module.exports = isBuffer; @@ -13540,7 +13798,424 @@ function isBuffer (o) { || /\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o)); } -},{"buffer":8}],45:[function(require,module,exports){ +},{"buffer":9}],46:[function(require,module,exports){ +(function (Buffer){ +/*global Buffer*/ +// Named constants with unique integer values +var C = {}; +// Tokens +var LEFT_BRACE = C.LEFT_BRACE = 0x1; +var RIGHT_BRACE = C.RIGHT_BRACE = 0x2; +var LEFT_BRACKET = C.LEFT_BRACKET = 0x3; +var RIGHT_BRACKET = C.RIGHT_BRACKET = 0x4; +var COLON = C.COLON = 0x5; +var COMMA = C.COMMA = 0x6; +var TRUE = C.TRUE = 0x7; +var FALSE = C.FALSE = 0x8; +var NULL = C.NULL = 0x9; +var STRING = C.STRING = 0xa; +var NUMBER = C.NUMBER = 0xb; +// Tokenizer States +var START = C.START = 0x11; +var STOP = C.STOP = 0x12; +var TRUE1 = C.TRUE1 = 0x21; +var TRUE2 = C.TRUE2 = 0x22; +var TRUE3 = C.TRUE3 = 0x23; +var FALSE1 = C.FALSE1 = 0x31; +var FALSE2 = C.FALSE2 = 0x32; +var FALSE3 = C.FALSE3 = 0x33; +var FALSE4 = C.FALSE4 = 0x34; +var NULL1 = C.NULL1 = 0x41; +var NULL2 = C.NULL2 = 0x42; +var NULL3 = C.NULL3 = 0x43; +var NUMBER1 = C.NUMBER1 = 0x51; +var NUMBER3 = C.NUMBER3 = 0x53; +var STRING1 = C.STRING1 = 0x61; +var STRING2 = C.STRING2 = 0x62; +var STRING3 = C.STRING3 = 0x63; +var STRING4 = C.STRING4 = 0x64; +var STRING5 = C.STRING5 = 0x65; +var STRING6 = C.STRING6 = 0x66; +// Parser States +var VALUE = C.VALUE = 0x71; +var KEY = C.KEY = 0x72; +// Parser Modes +var OBJECT = C.OBJECT = 0x81; +var ARRAY = C.ARRAY = 0x82; +// Character constants +var BACK_SLASH = "\\".charCodeAt(0); +var FORWARD_SLASH = "\/".charCodeAt(0); +var BACKSPACE = "\b".charCodeAt(0); +var FORM_FEED = "\f".charCodeAt(0); +var NEWLINE = "\n".charCodeAt(0); +var CARRIAGE_RETURN = "\r".charCodeAt(0); +var TAB = "\t".charCodeAt(0); + +var STRING_BUFFER_SIZE = 64 * 1024; + +function Parser() { + this.tState = START; + this.value = undefined; + + this.string = undefined; // string data + this.stringBuffer = Buffer.alloc ? Buffer.alloc(STRING_BUFFER_SIZE) : new Buffer(STRING_BUFFER_SIZE); + this.stringBufferOffset = 0; + this.unicode = undefined; // unicode escapes + this.highSurrogate = undefined; + + this.key = undefined; + this.mode = undefined; + this.stack = []; + this.state = VALUE; + this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary + this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read + this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached + + // Stream offset + this.offset = -1; +} + +// Slow code to string converter (only used when throwing syntax errors) +Parser.toknam = function (code) { + var keys = Object.keys(C); + for (var i = 0, l = keys.length; i < l; i++) { + var key = keys[i]; + if (C[key] === code) { return key; } + } + return code && ("0x" + code.toString(16)); +}; + +var proto = Parser.prototype; +proto.onError = function (err) { throw err; }; +proto.charError = function (buffer, i) { + this.tState = STOP; + this.onError(new Error("Unexpected " + JSON.stringify(String.fromCharCode(buffer[i])) + " at position " + i + " in state " + Parser.toknam(this.tState))); +}; +proto.appendStringChar = function (char) { + if (this.stringBufferOffset >= STRING_BUFFER_SIZE) { + this.string += this.stringBuffer.toString('utf8'); + this.stringBufferOffset = 0; + } + + this.stringBuffer[this.stringBufferOffset++] = char; +}; +proto.appendStringBuf = function (buf, start, end) { + var size = buf.length; + if (typeof start === 'number') { + if (typeof end === 'number') { + if (end < 0) { + // adding a negative end decreeses the size + size = buf.length - start + end; + } else { + size = end - start; + } + } else { + size = buf.length - start; + } + } + + if (size < 0) { + size = 0; + } + + if (this.stringBufferOffset + size > STRING_BUFFER_SIZE) { + this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset); + this.stringBufferOffset = 0; + } + + buf.copy(this.stringBuffer, this.stringBufferOffset, start, end); + this.stringBufferOffset += size; +}; +proto.write = function (buffer) { + if (typeof buffer === "string") buffer = new Buffer(buffer); + var n; + for (var i = 0, l = buffer.length; i < l; i++) { + if (this.tState === START){ + n = buffer[i]; + this.offset++; + if(n === 0x7b){ this.onToken(LEFT_BRACE, "{"); // { + }else if(n === 0x7d){ this.onToken(RIGHT_BRACE, "}"); // } + }else if(n === 0x5b){ this.onToken(LEFT_BRACKET, "["); // [ + }else if(n === 0x5d){ this.onToken(RIGHT_BRACKET, "]"); // ] + }else if(n === 0x3a){ this.onToken(COLON, ":"); // : + }else if(n === 0x2c){ this.onToken(COMMA, ","); // , + }else if(n === 0x74){ this.tState = TRUE1; // t + }else if(n === 0x66){ this.tState = FALSE1; // f + }else if(n === 0x6e){ this.tState = NULL1; // n + }else if(n === 0x22){ // " + this.string = ""; + this.stringBufferOffset = 0; + this.tState = STRING1; + }else if(n === 0x2d){ this.string = "-"; this.tState = NUMBER1; // - + }else{ + if (n >= 0x30 && n < 0x40) { // 1-9 + this.string = String.fromCharCode(n); this.tState = NUMBER3; + } else if (n === 0x20 || n === 0x09 || n === 0x0a || n === 0x0d) { + // whitespace + } else { + return this.charError(buffer, i); + } + } + }else if (this.tState === STRING1){ // After open quote + n = buffer[i]; // get current byte from buffer + // check for carry over of a multi byte char split between data chunks + // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration + if (this.bytes_remaining > 0) { + for (var j = 0; j < this.bytes_remaining; j++) { + this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = buffer[j]; + } + + this.appendStringBuf(this.temp_buffs[this.bytes_in_sequence]); + this.bytes_in_sequence = this.bytes_remaining = 0; + i = i + j - 1; + } else if (this.bytes_remaining === 0 && n >= 128) { // else if no remainder bytes carried over, parse multi byte (>=128) chars one at a time + if (n <= 193 || n > 244) { + return this.onError(new Error("Invalid UTF-8 character at position " + i + " in state " + Parser.toknam(this.tState))); + } + if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2; + if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3; + if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4; + if ((this.bytes_in_sequence + i) > buffer.length) { // if bytes needed to complete char fall outside buffer length, we have a boundary split + for (var k = 0; k <= (buffer.length - 1 - i); k++) { + this.temp_buffs[this.bytes_in_sequence][k] = buffer[i + k]; // fill temp buffer of correct size with bytes available in this chunk + } + this.bytes_remaining = (i + this.bytes_in_sequence) - buffer.length; + i = buffer.length - 1; + } else { + this.appendStringBuf(buffer, i, i + this.bytes_in_sequence); + i = i + this.bytes_in_sequence - 1; + } + } else if (n === 0x22) { + this.tState = START; + this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset); + this.stringBufferOffset = 0; + this.onToken(STRING, this.string); + this.offset += Buffer.byteLength(this.string, 'utf8') + 1; + this.string = undefined; + } + else if (n === 0x5c) { + this.tState = STRING2; + } + else if (n >= 0x20) { this.appendStringChar(n); } + else { + return this.charError(buffer, i); + } + }else if (this.tState === STRING2){ // After backslash + n = buffer[i]; + if(n === 0x22){ this.appendStringChar(n); this.tState = STRING1; + }else if(n === 0x5c){ this.appendStringChar(BACK_SLASH); this.tState = STRING1; + }else if(n === 0x2f){ this.appendStringChar(FORWARD_SLASH); this.tState = STRING1; + }else if(n === 0x62){ this.appendStringChar(BACKSPACE); this.tState = STRING1; + }else if(n === 0x66){ this.appendStringChar(FORM_FEED); this.tState = STRING1; + }else if(n === 0x6e){ this.appendStringChar(NEWLINE); this.tState = STRING1; + }else if(n === 0x72){ this.appendStringChar(CARRIAGE_RETURN); this.tState = STRING1; + }else if(n === 0x74){ this.appendStringChar(TAB); this.tState = STRING1; + }else if(n === 0x75){ this.unicode = ""; this.tState = STRING3; + }else{ + return this.charError(buffer, i); + } + }else if (this.tState === STRING3 || this.tState === STRING4 || this.tState === STRING5 || this.tState === STRING6){ // unicode hex codes + n = buffer[i]; + // 0-9 A-F a-f + if ((n >= 0x30 && n < 0x40) || (n > 0x40 && n <= 0x46) || (n > 0x60 && n <= 0x66)) { + this.unicode += String.fromCharCode(n); + if (this.tState++ === STRING6) { + var intVal = parseInt(this.unicode, 16); + this.unicode = undefined; + if (this.highSurrogate !== undefined && intVal >= 0xDC00 && intVal < (0xDFFF + 1)) { //<56320,57343> - lowSurrogate + this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate, intVal))); + this.highSurrogate = undefined; + } else if (this.highSurrogate === undefined && intVal >= 0xD800 && intVal < (0xDBFF + 1)) { //<55296,56319> - highSurrogate + this.highSurrogate = intVal; + } else { + if (this.highSurrogate !== undefined) { + this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate))); + this.highSurrogate = undefined; + } + this.appendStringBuf(new Buffer(String.fromCharCode(intVal))); + } + this.tState = STRING1; + } + } else { + return this.charError(buffer, i); + } + } else if (this.tState === NUMBER1 || this.tState === NUMBER3) { + n = buffer[i]; + + switch (n) { + case 0x30: // 0 + case 0x31: // 1 + case 0x32: // 2 + case 0x33: // 3 + case 0x34: // 4 + case 0x35: // 5 + case 0x36: // 6 + case 0x37: // 7 + case 0x38: // 8 + case 0x39: // 9 + case 0x2e: // . + case 0x65: // e + case 0x45: // E + case 0x2b: // + + case 0x2d: // - + this.string += String.fromCharCode(n); + this.tState = NUMBER3; + break; + default: + this.tState = START; + var result = Number(this.string); + + if (isNaN(result)){ + return this.charError(buffer, i); + } + + if ((this.string.match(/[0-9]+/) == this.string) && (result.toString() != this.string)) { + // Long string of digits which is an ID string and not valid and/or safe JavaScript integer Number + this.onToken(STRING, this.string); + } else { + this.onToken(NUMBER, result); + } + + this.offset += this.string.length - 1; + this.string = undefined; + i--; + break; + } + }else if (this.tState === TRUE1){ // r + if (buffer[i] === 0x72) { this.tState = TRUE2; } + else { return this.charError(buffer, i); } + }else if (this.tState === TRUE2){ // u + if (buffer[i] === 0x75) { this.tState = TRUE3; } + else { return this.charError(buffer, i); } + }else if (this.tState === TRUE3){ // e + if (buffer[i] === 0x65) { this.tState = START; this.onToken(TRUE, true); this.offset+= 3; } + else { return this.charError(buffer, i); } + }else if (this.tState === FALSE1){ // a + if (buffer[i] === 0x61) { this.tState = FALSE2; } + else { return this.charError(buffer, i); } + }else if (this.tState === FALSE2){ // l + if (buffer[i] === 0x6c) { this.tState = FALSE3; } + else { return this.charError(buffer, i); } + }else if (this.tState === FALSE3){ // s + if (buffer[i] === 0x73) { this.tState = FALSE4; } + else { return this.charError(buffer, i); } + }else if (this.tState === FALSE4){ // e + if (buffer[i] === 0x65) { this.tState = START; this.onToken(FALSE, false); this.offset+= 4; } + else { return this.charError(buffer, i); } + }else if (this.tState === NULL1){ // u + if (buffer[i] === 0x75) { this.tState = NULL2; } + else { return this.charError(buffer, i); } + }else if (this.tState === NULL2){ // l + if (buffer[i] === 0x6c) { this.tState = NULL3; } + else { return this.charError(buffer, i); } + }else if (this.tState === NULL3){ // l + if (buffer[i] === 0x6c) { this.tState = START; this.onToken(NULL, null); this.offset += 3; } + else { return this.charError(buffer, i); } + } + } +}; +proto.onToken = function (token, value) { + // Override this to get events +}; + +proto.parseError = function (token, value) { + this.tState = STOP; + this.onError(new Error("Unexpected " + Parser.toknam(token) + (value ? ("(" + JSON.stringify(value) + ")") : "") + " in state " + Parser.toknam(this.state))); +}; +proto.push = function () { + this.stack.push({value: this.value, key: this.key, mode: this.mode}); +}; +proto.pop = function () { + var value = this.value; + var parent = this.stack.pop(); + this.value = parent.value; + this.key = parent.key; + this.mode = parent.mode; + this.emit(value); + if (!this.mode) { this.state = VALUE; } +}; +proto.emit = function (value) { + if (this.mode) { this.state = COMMA; } + this.onValue(value); +}; +proto.onValue = function (value) { + // Override me +}; +proto.onToken = function (token, value) { + if(this.state === VALUE){ + if(token === STRING || token === NUMBER || token === TRUE || token === FALSE || token === NULL){ + if (this.value) { + this.value[this.key] = value; + } + this.emit(value); + }else if(token === LEFT_BRACE){ + this.push(); + if (this.value) { + this.value = this.value[this.key] = {}; + } else { + this.value = {}; + } + this.key = undefined; + this.state = KEY; + this.mode = OBJECT; + }else if(token === LEFT_BRACKET){ + this.push(); + if (this.value) { + this.value = this.value[this.key] = []; + } else { + this.value = []; + } + this.key = 0; + this.mode = ARRAY; + this.state = VALUE; + }else if(token === RIGHT_BRACE){ + if (this.mode === OBJECT) { + this.pop(); + } else { + return this.parseError(token, value); + } + }else if(token === RIGHT_BRACKET){ + if (this.mode === ARRAY) { + this.pop(); + } else { + return this.parseError(token, value); + } + }else{ + return this.parseError(token, value); + } + }else if(this.state === KEY){ + if (token === STRING) { + this.key = value; + this.state = COLON; + } else if (token === RIGHT_BRACE) { + this.pop(); + } else { + return this.parseError(token, value); + } + }else if(this.state === COLON){ + if (token === COLON) { this.state = VALUE; } + else { return this.parseError(token, value); } + }else if(this.state === COMMA){ + if (token === COMMA) { + if (this.mode === ARRAY) { this.key++; this.state = VALUE; } + else if (this.mode === OBJECT) { this.state = KEY; } + + } else if (token === RIGHT_BRACKET && this.mode === ARRAY || token === RIGHT_BRACE && this.mode === OBJECT) { + this.pop(); + } else { + return this.parseError(token, value); + } + }else{ + return this.parseError(token, value); + } +}; + +Parser.C = C; + +module.exports = Parser; + +}).call(this,require("buffer").Buffer) +},{"buffer":9}],47:[function(require,module,exports){ var encodings = require('./lib/encodings'); module.exports = Codec; @@ -13648,7 +14323,7 @@ Codec.prototype.valueAsBuffer = function(opts){ }; -},{"./lib/encodings":46}],46:[function(require,module,exports){ +},{"./lib/encodings":48}],48:[function(require,module,exports){ (function (Buffer){ exports.utf8 = exports['utf-8'] = { @@ -13728,7 +14403,7 @@ function isBinary(data){ }).call(this,require("buffer").Buffer) -},{"buffer":8}],47:[function(require,module,exports){ +},{"buffer":9}],49:[function(require,module,exports){ /* Copyright (c) 2012-2015 LevelUP contributors * See list at * MIT License @@ -13752,7 +14427,7 @@ module.exports = { , EncodingError : createError('EncodingError', LevelUPError) } -},{"errno":35}],48:[function(require,module,exports){ +},{"errno":36}],50:[function(require,module,exports){ var inherits = require('inherits'); var Readable = require('readable-stream').Readable; var extend = require('xtend'); @@ -13810,12 +14485,12 @@ ReadStream.prototype._cleanup = function(){ }; -},{"inherits":40,"level-errors":47,"readable-stream":55,"xtend":136}],49:[function(require,module,exports){ +},{"inherits":41,"level-errors":49,"readable-stream":57,"xtend":139}],51:[function(require,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; -},{}],50:[function(require,module,exports){ +},{}],52:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -13908,7 +14583,7 @@ function forEach (xs, f) { } }).call(this,require('_process')) -},{"./_stream_readable":52,"./_stream_writable":54,"_process":84,"core-util-is":10,"inherits":40}],51:[function(require,module,exports){ +},{"./_stream_readable":54,"./_stream_writable":56,"_process":86,"core-util-is":11,"inherits":41}],53:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -13956,7 +14631,7 @@ PassThrough.prototype._transform = function(chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":53,"core-util-is":10,"inherits":40}],52:[function(require,module,exports){ +},{"./_stream_transform":55,"core-util-is":11,"inherits":41}],54:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -14911,7 +15586,7 @@ function indexOf (xs, x) { } }).call(this,require('_process')) -},{"./_stream_duplex":50,"_process":84,"buffer":8,"core-util-is":10,"events":37,"inherits":40,"isarray":49,"stream":125,"string_decoder/":56,"util":6}],53:[function(require,module,exports){ +},{"./_stream_duplex":52,"_process":86,"buffer":9,"core-util-is":11,"events":38,"inherits":41,"isarray":51,"stream":127,"string_decoder/":58,"util":7}],55:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -15122,7 +15797,7 @@ function done(stream, er) { return stream.push(null); } -},{"./_stream_duplex":50,"core-util-is":10,"inherits":40}],54:[function(require,module,exports){ +},{"./_stream_duplex":52,"core-util-is":11,"inherits":41}],56:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -15603,7 +16278,7 @@ function endWritable(stream, state, cb) { } }).call(this,require('_process')) -},{"./_stream_duplex":50,"_process":84,"buffer":8,"core-util-is":10,"inherits":40,"stream":125}],55:[function(require,module,exports){ +},{"./_stream_duplex":52,"_process":86,"buffer":9,"core-util-is":11,"inherits":41,"stream":127}],57:[function(require,module,exports){ (function (process){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = require('stream'); @@ -15617,7 +16292,7 @@ if (!process.browser && process.env.READABLE_STREAM === 'disable') { } }).call(this,require('_process')) -},{"./lib/_stream_duplex.js":50,"./lib/_stream_passthrough.js":51,"./lib/_stream_readable.js":52,"./lib/_stream_transform.js":53,"./lib/_stream_writable.js":54,"_process":84,"stream":125}],56:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":52,"./lib/_stream_passthrough.js":53,"./lib/_stream_readable.js":54,"./lib/_stream_transform.js":55,"./lib/_stream_writable.js":56,"_process":86,"stream":127}],58:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -15840,7 +16515,7 @@ function base64DetectIncompleteChar(buffer) { this.charLength = this.charReceived ? 3 : 0; } -},{"buffer":8}],57:[function(require,module,exports){ +},{"buffer":9}],59:[function(require,module,exports){ (function (Buffer){ module.exports = Level @@ -16018,7 +16693,7 @@ var checkKeyValue = Level.prototype._checkKeyValue = function (obj, type) { } }).call(this,require("buffer").Buffer) -},{"./iterator":58,"abstract-leveldown":61,"buffer":8,"idb-wrapper":38,"isbuffer":44,"typedarray-to-buffer":130,"util":134,"xtend":68}],58:[function(require,module,exports){ +},{"./iterator":60,"abstract-leveldown":63,"buffer":9,"idb-wrapper":39,"isbuffer":45,"typedarray-to-buffer":133,"util":137,"xtend":70}],60:[function(require,module,exports){ var util = require('util') var AbstractIterator = require('abstract-leveldown').AbstractIterator var ltgt = require('ltgt') @@ -16092,7 +16767,7 @@ Iterator.prototype._next = function (callback) { this.callback = callback } -},{"abstract-leveldown":61,"ltgt":79,"util":134}],59:[function(require,module,exports){ +},{"abstract-leveldown":63,"ltgt":81,"util":137}],61:[function(require,module,exports){ (function (process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -16176,9 +16851,9 @@ AbstractChainedBatch.prototype.write = function (options, callback) { module.exports = AbstractChainedBatch }).call(this,require('_process')) -},{"_process":84}],60:[function(require,module,exports){ -arguments[4][14][0].apply(exports,arguments) -},{"_process":84,"dup":14}],61:[function(require,module,exports){ +},{"_process":86}],62:[function(require,module,exports){ +arguments[4][15][0].apply(exports,arguments) +},{"_process":86,"dup":15}],63:[function(require,module,exports){ (function (Buffer,process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -16438,7 +17113,7 @@ module.exports.AbstractIterator = AbstractIterator module.exports.AbstractChainedBatch = AbstractChainedBatch }).call(this,{"isBuffer":require("../../../is-buffer/index.js")},require('_process')) -},{"../../../is-buffer/index.js":42,"./abstract-chained-batch":59,"./abstract-iterator":60,"_process":84,"xtend":62}],62:[function(require,module,exports){ +},{"../../../is-buffer/index.js":43,"./abstract-chained-batch":61,"./abstract-iterator":62,"_process":86,"xtend":64}],64:[function(require,module,exports){ module.exports = extend function extend() { @@ -16457,7 +17132,7 @@ function extend() { return target } -},{}],63:[function(require,module,exports){ +},{}],65:[function(require,module,exports){ var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; @@ -16499,11 +17174,11 @@ module.exports = function forEach(obj, fn) { }; -},{}],64:[function(require,module,exports){ +},{}],66:[function(require,module,exports){ module.exports = Object.keys || require('./shim'); -},{"./shim":66}],65:[function(require,module,exports){ +},{"./shim":68}],67:[function(require,module,exports){ var toString = Object.prototype.toString; module.exports = function isArguments(value) { @@ -16521,7 +17196,7 @@ module.exports = function isArguments(value) { }; -},{}],66:[function(require,module,exports){ +},{}],68:[function(require,module,exports){ (function () { "use strict"; @@ -16585,7 +17260,7 @@ module.exports = function isArguments(value) { }()); -},{"./foreach":63,"./isArguments":65}],67:[function(require,module,exports){ +},{"./foreach":65,"./isArguments":67}],69:[function(require,module,exports){ module.exports = hasKeys function hasKeys(source) { @@ -16594,7 +17269,7 @@ function hasKeys(source) { typeof source === "function") } -},{}],68:[function(require,module,exports){ +},{}],70:[function(require,module,exports){ var Keys = require("object-keys") var hasKeys = require("./has-keys") @@ -16621,7 +17296,7 @@ function extend() { return target } -},{"./has-keys":67,"object-keys":64}],69:[function(require,module,exports){ +},{"./has-keys":69,"object-keys":66}],71:[function(require,module,exports){ /* Copyright (c) 2012-2016 LevelUP contributors * See list at * MIT License @@ -16706,7 +17381,7 @@ Batch.prototype.write = function (callback) { module.exports = Batch -},{"./util":71,"level-errors":47}],70:[function(require,module,exports){ +},{"./util":73,"level-errors":49}],72:[function(require,module,exports){ (function (process){ /* Copyright (c) 2012-2016 LevelUP contributors * See list at @@ -17115,7 +17790,7 @@ module.exports.repair = deprecate( }).call(this,require('_process')) -},{"./batch":69,"./leveldown":6,"./util":71,"_process":84,"deferred-leveldown":12,"events":37,"level-codec":45,"level-errors":47,"level-iterator-stream":48,"prr":85,"util":134,"xtend":136}],71:[function(require,module,exports){ +},{"./batch":71,"./leveldown":7,"./util":73,"_process":86,"deferred-leveldown":13,"events":38,"level-codec":47,"level-errors":49,"level-iterator-stream":50,"prr":87,"util":137,"xtend":139}],73:[function(require,module,exports){ /* Copyright (c) 2012-2016 LevelUP contributors * See list at * MIT License @@ -17154,7 +17829,7 @@ module.exports = { , isDefined : isDefined } -},{"xtend":136}],72:[function(require,module,exports){ +},{"xtend":139}],74:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -18328,7 +19003,7 @@ function isObjectLike(value) { module.exports = difference; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],73:[function(require,module,exports){ +},{}],75:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -19397,7 +20072,7 @@ function isObjectLike(value) { module.exports = intersection; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],74:[function(require,module,exports){ +},{}],76:[function(require,module,exports){ (function (global){ /** * Lodash (Custom Build) @@ -21249,7 +21924,7 @@ function stubFalse() { module.exports = isEqual; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],75:[function(require,module,exports){ +},{}],77:[function(require,module,exports){ /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` @@ -21502,7 +22177,7 @@ function identity(value) { module.exports = sortedIndexOf; -},{}],76:[function(require,module,exports){ +},{}],78:[function(require,module,exports){ /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` @@ -21908,7 +22583,7 @@ function toNumber(value) { module.exports = spread; -},{}],77:[function(require,module,exports){ +},{}],79:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -23093,7 +23768,7 @@ function noop() { module.exports = union; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],78:[function(require,module,exports){ +},{}],80:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -23993,7 +24668,7 @@ function noop() { module.exports = uniq; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],79:[function(require,module,exports){ +},{}],81:[function(require,module,exports){ (function (Buffer){ exports.compare = function (a, b) { @@ -24166,7 +24841,7 @@ exports.filter = function (range, compare) { }).call(this,{"isBuffer":require("../is-buffer/index.js")}) -},{"../is-buffer/index.js":42}],80:[function(require,module,exports){ +},{"../is-buffer/index.js":43}],82:[function(require,module,exports){ // nGramLengths is of the form [ 9, 10 ] const getNGramsOfMultipleLengths = function (inputArray, nGramLengths) { @@ -24201,7 +24876,7 @@ exports.ngram = function (inputArray, nGramLength) { } } -},{}],81:[function(require,module,exports){ +},{}],83:[function(require,module,exports){ var wrappy = require('wrappy') module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) @@ -24245,7 +24920,7 @@ function onceStrict (fn) { return f } -},{"wrappy":135}],82:[function(require,module,exports){ +},{"wrappy":138}],84:[function(require,module,exports){ exports.endianness = function () { return 'LE' }; exports.hostname = function () { @@ -24292,7 +24967,7 @@ exports.tmpdir = exports.tmpDir = function () { exports.EOL = '\n'; -},{}],83:[function(require,module,exports){ +},{}],85:[function(require,module,exports){ (function (process){ 'use strict'; @@ -24339,7 +25014,7 @@ function nextTick(fn, arg1, arg2, arg3) { } }).call(this,require('_process')) -},{"_process":84}],84:[function(require,module,exports){ +},{"_process":86}],86:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -24525,9 +25200,9 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],85:[function(require,module,exports){ -arguments[4][36][0].apply(exports,arguments) -},{"dup":36}],86:[function(require,module,exports){ +},{}],87:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"dup":37}],88:[function(require,module,exports){ var once = require('once') var eos = require('end-of-stream') var fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes @@ -24609,7 +25284,7 @@ var pump = function () { module.exports = pump -},{"end-of-stream":33,"fs":6,"once":81}],87:[function(require,module,exports){ +},{"end-of-stream":34,"fs":7,"once":83}],89:[function(require,module,exports){ var pump = require('pump') var inherits = require('inherits') var Duplexify = require('duplexify') @@ -24666,10 +25341,10 @@ var define = function(opts) { module.exports = define({destroy:false}) module.exports.obj = define({destroy:false, objectMode:true, highWaterMark:16}) -},{"duplexify":30,"inherits":40,"pump":86}],88:[function(require,module,exports){ +},{"duplexify":31,"inherits":41,"pump":88}],90:[function(require,module,exports){ module.exports = require('./lib/_stream_duplex.js'); -},{"./lib/_stream_duplex.js":89}],89:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":91}],91:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -24794,7 +25469,7 @@ function forEach(xs, f) { f(xs[i], i); } } -},{"./_stream_readable":91,"./_stream_writable":93,"core-util-is":10,"inherits":40,"process-nextick-args":83}],90:[function(require,module,exports){ +},{"./_stream_readable":93,"./_stream_writable":95,"core-util-is":11,"inherits":41,"process-nextick-args":85}],92:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -24842,7 +25517,7 @@ function PassThrough(options) { PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":92,"core-util-is":10,"inherits":40}],91:[function(require,module,exports){ +},{"./_stream_transform":94,"core-util-is":11,"inherits":41}],93:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -25851,7 +26526,7 @@ function indexOf(xs, x) { return -1; } }).call(this,require('_process')) -},{"./_stream_duplex":89,"./internal/streams/BufferList":94,"./internal/streams/destroy":95,"./internal/streams/stream":96,"_process":84,"core-util-is":10,"events":37,"inherits":40,"isarray":43,"process-nextick-args":83,"safe-buffer":101,"string_decoder/":127,"util":6}],92:[function(require,module,exports){ +},{"./_stream_duplex":91,"./internal/streams/BufferList":96,"./internal/streams/destroy":97,"./internal/streams/stream":98,"_process":86,"core-util-is":11,"events":38,"inherits":41,"isarray":44,"process-nextick-args":85,"safe-buffer":103,"string_decoder/":129,"util":7}],94:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -26066,7 +26741,7 @@ function done(stream, er, data) { return stream.push(null); } -},{"./_stream_duplex":89,"core-util-is":10,"inherits":40}],93:[function(require,module,exports){ +},{"./_stream_duplex":91,"core-util-is":11,"inherits":41}],95:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -26733,7 +27408,7 @@ Writable.prototype._destroy = function (err, cb) { }; }).call(this,require('_process')) -},{"./_stream_duplex":89,"./internal/streams/destroy":95,"./internal/streams/stream":96,"_process":84,"core-util-is":10,"inherits":40,"process-nextick-args":83,"safe-buffer":101,"util-deprecate":131}],94:[function(require,module,exports){ +},{"./_stream_duplex":91,"./internal/streams/destroy":97,"./internal/streams/stream":98,"_process":86,"core-util-is":11,"inherits":41,"process-nextick-args":85,"safe-buffer":103,"util-deprecate":134}],96:[function(require,module,exports){ 'use strict'; /**/ @@ -26808,7 +27483,7 @@ module.exports = function () { return BufferList; }(); -},{"safe-buffer":101}],95:[function(require,module,exports){ +},{"safe-buffer":103}],97:[function(require,module,exports){ 'use strict'; /**/ @@ -26881,13 +27556,13 @@ module.exports = { destroy: destroy, undestroy: undestroy }; -},{"process-nextick-args":83}],96:[function(require,module,exports){ +},{"process-nextick-args":85}],98:[function(require,module,exports){ module.exports = require('events').EventEmitter; -},{"events":37}],97:[function(require,module,exports){ +},{"events":38}],99:[function(require,module,exports){ module.exports = require('./readable').PassThrough -},{"./readable":98}],98:[function(require,module,exports){ +},{"./readable":100}],100:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; @@ -26896,13 +27571,13 @@ exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); -},{"./lib/_stream_duplex.js":89,"./lib/_stream_passthrough.js":90,"./lib/_stream_readable.js":91,"./lib/_stream_transform.js":92,"./lib/_stream_writable.js":93}],99:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":91,"./lib/_stream_passthrough.js":92,"./lib/_stream_readable.js":93,"./lib/_stream_transform.js":94,"./lib/_stream_writable.js":95}],101:[function(require,module,exports){ module.exports = require('./readable').Transform -},{"./readable":98}],100:[function(require,module,exports){ +},{"./readable":100}],102:[function(require,module,exports){ module.exports = require('./lib/_stream_writable.js'); -},{"./lib/_stream_writable.js":93}],101:[function(require,module,exports){ +},{"./lib/_stream_writable.js":95}],103:[function(require,module,exports){ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') var Buffer = buffer.Buffer @@ -26966,7 +27641,7 @@ SafeBuffer.allocUnsafeSlow = function (size) { return buffer.SlowBuffer(size) } -},{"buffer":8}],102:[function(require,module,exports){ +},{"buffer":9}],104:[function(require,module,exports){ var hasProp = Object.prototype.hasOwnProperty; function throwsMessage(err) { @@ -27027,7 +27702,7 @@ module.exports = function(data) { module.exports.ensureProperties = ensureProperties; -},{}],103:[function(require,module,exports){ +},{}],105:[function(require,module,exports){ /* search-index-adder @@ -27041,6 +27716,7 @@ const DBWriteCleanStream = require('./lib/replicate.js').DBWriteCleanStream const DBWriteMergeStream = require('./lib/replicate.js').DBWriteMergeStream const DocVector = require('./lib/delete.js').DocVector const IndexBatch = require('./lib/add.js').IndexBatch +const JSONStream = require('JSONStream') const Readable = require('stream').Readable const RecalibrateDB = require('./lib/delete.js').RecalibrateDB const bunyan = require('bunyan') @@ -27066,7 +27742,6 @@ module.exports = function (givenOptions, callback) { s.push(null) s.pipe(Indexer.defaultPipeline(batch.batchOps)) .pipe(Indexer.add()) - // .on('data', function (data) {}) .on('finish', function () { return done() }) @@ -27164,6 +27839,23 @@ module.exports = function (givenOptions, callback) { }) } + Indexer.feed = function (ops) { + if (ops && ops.objectMode) { + // feed from stream of objects + return pumpify.obj( + Indexer.defaultPipeline(ops), + Indexer.add(ops) + ) + } else { + // feed from stream of strings + return pumpify( + JSONStream.parse(), + Indexer.defaultPipeline(ops), + Indexer.add(ops) + ) + } + } + Indexer.flush = function (APICallback) { del.flush(options, function (err) { return APICallback(err) @@ -27211,7 +27903,7 @@ const getOptions = function (options, done) { } } -},{"./lib/add.js":104,"./lib/delete.js":105,"./lib/replicate.js":106,"async":4,"bunyan":9,"docproc":18,"leveldown":57,"levelup":70,"pumpify":87,"stream":125}],104:[function(require,module,exports){ +},{"./lib/add.js":106,"./lib/delete.js":107,"./lib/replicate.js":108,"JSONStream":3,"async":5,"bunyan":10,"docproc":19,"leveldown":59,"levelup":72,"pumpify":89,"stream":127}],106:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -27271,7 +27963,7 @@ IndexBatch.prototype._flush = function (end) { return end() } -},{"stream":125,"util":134}],105:[function(require,module,exports){ +},{"stream":127,"util":137}],107:[function(require,module,exports){ // deletes all references to a document from the search index const util = require('util') @@ -27392,7 +28084,7 @@ RecalibrateDB.prototype._transform = function (dbEntry, encoding, end) { }) } -},{"stream":125,"util":134}],106:[function(require,module,exports){ +},{"stream":127,"util":137}],108:[function(require,module,exports){ const Transform = require('stream').Transform const Writable = require('stream').Writable const util = require('util') @@ -27470,7 +28162,7 @@ DBWriteCleanStream.prototype._flush = function (end) { } exports.DBWriteCleanStream = DBWriteCleanStream -},{"stream":125,"util":134}],107:[function(require,module,exports){ +},{"stream":127,"util":137}],109:[function(require,module,exports){ const AvailableFields = require('./lib/AvailableFields.js').AvailableFields const CalculateBuckets = require('./lib/CalculateBuckets.js').CalculateBuckets const CalculateCategories = require('./lib/CalculateCategories.js').CalculateCategories @@ -27663,7 +28355,7 @@ module.exports = function (givenOptions, moduleReady) { }) } -},{"./lib/AvailableFields.js":108,"./lib/CalculateBuckets.js":109,"./lib/CalculateCategories.js":110,"./lib/CalculateEntireResultSet.js":111,"./lib/CalculateResultSetPerClause.js":112,"./lib/CalculateTopScoringDocs.js":113,"./lib/CalculateTotalHits.js":114,"./lib/Classify.js":115,"./lib/FetchDocsFromDB.js":116,"./lib/FetchStoredDoc.js":117,"./lib/GetIntersectionStream.js":118,"./lib/MergeOrConditions.js":119,"./lib/ScoreDocsOnField.js":120,"./lib/ScoreTopScoringDocsTFIDF.js":121,"./lib/SortTopScoringDocs.js":122,"./lib/matcher.js":123,"./lib/siUtil.js":124,"bunyan":9,"levelup":70,"stream":125}],108:[function(require,module,exports){ +},{"./lib/AvailableFields.js":110,"./lib/CalculateBuckets.js":111,"./lib/CalculateCategories.js":112,"./lib/CalculateEntireResultSet.js":113,"./lib/CalculateResultSetPerClause.js":114,"./lib/CalculateTopScoringDocs.js":115,"./lib/CalculateTotalHits.js":116,"./lib/Classify.js":117,"./lib/FetchDocsFromDB.js":118,"./lib/FetchStoredDoc.js":119,"./lib/GetIntersectionStream.js":120,"./lib/MergeOrConditions.js":121,"./lib/ScoreDocsOnField.js":122,"./lib/ScoreTopScoringDocsTFIDF.js":123,"./lib/SortTopScoringDocs.js":124,"./lib/matcher.js":125,"./lib/siUtil.js":126,"bunyan":10,"levelup":72,"stream":127}],110:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -27678,7 +28370,7 @@ AvailableFields.prototype._transform = function (field, encoding, end) { return end() } -},{"stream":125,"util":134}],109:[function(require,module,exports){ +},{"stream":127,"util":137}],111:[function(require,module,exports){ const _intersection = require('lodash.intersection') const _uniq = require('lodash.uniq') const Transform = require('stream').Transform @@ -27719,7 +28411,7 @@ CalculateBuckets.prototype._transform = function (mergedQueryClauses, encoding, }) } -},{"lodash.intersection":73,"lodash.uniq":78,"stream":125,"util":134}],110:[function(require,module,exports){ +},{"lodash.intersection":75,"lodash.uniq":80,"stream":127,"util":137}],112:[function(require,module,exports){ const _intersection = require('lodash.intersection') const Transform = require('stream').Transform const util = require('util') @@ -27782,7 +28474,7 @@ CalculateCategories.prototype._transform = function (mergedQueryClauses, encodin }) } -},{"lodash.intersection":73,"stream":125,"util":134}],111:[function(require,module,exports){ +},{"lodash.intersection":75,"stream":127,"util":137}],113:[function(require,module,exports){ const Transform = require('stream').Transform const _union = require('lodash.union') const util = require('util') @@ -27805,7 +28497,7 @@ CalculateEntireResultSet.prototype._flush = function (end) { return end() } -},{"lodash.union":77,"stream":125,"util":134}],112:[function(require,module,exports){ +},{"lodash.union":79,"stream":127,"util":137}],114:[function(require,module,exports){ const Transform = require('stream').Transform const _difference = require('lodash.difference') const _intersection = require('lodash.intersection') @@ -27900,7 +28592,7 @@ CalculateResultSetPerClause.prototype._transform = function (queryClause, encodi }) } -},{"./siUtil.js":124,"lodash.difference":72,"lodash.intersection":73,"lodash.spread":76,"stream":125,"util":134}],113:[function(require,module,exports){ +},{"./siUtil.js":126,"lodash.difference":74,"lodash.intersection":75,"lodash.spread":78,"stream":127,"util":137}],115:[function(require,module,exports){ const Transform = require('stream').Transform const _sortedIndexOf = require('lodash.sortedindexof') const util = require('util') @@ -27953,7 +28645,7 @@ CalculateTopScoringDocs.prototype._transform = function (clauseSet, encoding, en }) } -},{"lodash.sortedindexof":75,"stream":125,"util":134}],114:[function(require,module,exports){ +},{"lodash.sortedindexof":77,"stream":127,"util":137}],116:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -27970,7 +28662,7 @@ CalculateTotalHits.prototype._transform = function (mergedQueryClauses, encoding end() } -},{"stream":125,"util":134}],115:[function(require,module,exports){ +},{"stream":127,"util":137}],117:[function(require,module,exports){ const Transform = require('stream').Transform const ngraminator = require('ngraminator') const util = require('util') @@ -28041,7 +28733,7 @@ Classify.prototype._flush = function (end) { }) } -},{"ngraminator":80,"stream":125,"util":134}],116:[function(require,module,exports){ +},{"ngraminator":82,"stream":127,"util":137}],118:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -28062,7 +28754,7 @@ FetchDocsFromDB.prototype._transform = function (line, encoding, end) { }) } -},{"stream":125,"util":134}],117:[function(require,module,exports){ +},{"stream":127,"util":137}],119:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -28086,7 +28778,7 @@ FetchStoredDoc.prototype._transform = function (doc, encoding, end) { }) } -},{"stream":125,"util":134}],118:[function(require,module,exports){ +},{"stream":127,"util":137}],120:[function(require,module,exports){ const Transform = require('stream').Transform const iats = require('intersect-arrays-to-stream') const util = require('util') @@ -28121,7 +28813,7 @@ GetIntersectionStream.prototype._transform = function (line, encoding, end) { }) } -},{"intersect-arrays-to-stream":41,"stream":125,"util":134}],119:[function(require,module,exports){ +},{"intersect-arrays-to-stream":42,"stream":127,"util":137}],121:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -28184,7 +28876,7 @@ MergeOrConditions.prototype._flush = function (end) { return end() } -},{"stream":125,"util":134}],120:[function(require,module,exports){ +},{"stream":127,"util":137}],122:[function(require,module,exports){ const Transform = require('stream').Transform const _sortedIndexOf = require('lodash.sortedindexof') const util = require('util') @@ -28223,7 +28915,7 @@ ScoreDocsOnField.prototype._transform = function (clauseSet, encoding, end) { }) } -},{"lodash.sortedindexof":75,"stream":125,"util":134}],121:[function(require,module,exports){ +},{"lodash.sortedindexof":77,"stream":127,"util":137}],123:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -28301,7 +28993,7 @@ ScoreTopScoringDocsTFIDF.prototype._transform = function (clause, encoding, end) }) } -},{"stream":125,"util":134}],122:[function(require,module,exports){ +},{"stream":127,"util":137}],124:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -28347,7 +29039,7 @@ SortTopScoringDocs.prototype._flush = function (end) { return end() } -},{"stream":125,"util":134}],123:[function(require,module,exports){ +},{"stream":127,"util":137}],125:[function(require,module,exports){ const Readable = require('stream').Readable const Transform = require('stream').Transform const util = require('util') @@ -28415,7 +29107,7 @@ exports.match = function (q, options) { return s.pipe(new MatcherStream(q, options)) } -},{"stream":125,"util":134}],124:[function(require,module,exports){ +},{"stream":127,"util":137}],126:[function(require,module,exports){ exports.getKeySet = function (clause, sep) { var keySet = [] for (var fieldName in clause) { @@ -28464,7 +29156,7 @@ exports.getQueryDefaults = function (q) { }, q) } -},{}],125:[function(require,module,exports){ +},{}],127:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -28593,7 +29285,7 @@ Stream.prototype.pipe = function(dest, options) { return dest; }; -},{"events":37,"inherits":40,"readable-stream/duplex.js":88,"readable-stream/passthrough.js":97,"readable-stream/readable.js":98,"readable-stream/transform.js":99,"readable-stream/writable.js":100}],126:[function(require,module,exports){ +},{"events":38,"inherits":41,"readable-stream/duplex.js":90,"readable-stream/passthrough.js":99,"readable-stream/readable.js":100,"readable-stream/transform.js":101,"readable-stream/writable.js":102}],128:[function(require,module,exports){ module.exports = shift function shift (stream) { @@ -28615,7 +29307,7 @@ function getStateLength (state) { return state.length } -},{}],127:[function(require,module,exports){ +},{}],129:[function(require,module,exports){ 'use strict'; var Buffer = require('safe-buffer').Buffer; @@ -28888,7 +29580,7 @@ function simpleWrite(buf) { function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } -},{"safe-buffer":101}],128:[function(require,module,exports){ +},{"safe-buffer":103}],130:[function(require,module,exports){ exports.doubleNormalization0point5 = 'doubleNormalization0point5' exports.logNormalization = 'logNormalization' exports.raw = 'raw' @@ -28938,7 +29630,7 @@ exports.getTermFrequency = function (docVector, options) { } } -},{}],129:[function(require,module,exports){ +},{}],131:[function(require,module,exports){ /** * search-index module. * @module term-vector @@ -29004,7 +29696,119 @@ var getTermVectorForNgramLength = function (tokens, nGramLength) { return vector } -},{"lodash.isequal":74}],130:[function(require,module,exports){ +},{"lodash.isequal":76}],132:[function(require,module,exports){ +(function (process){ +var Stream = require('stream') + +// through +// +// a stream that does nothing but re-emit the input. +// useful for aggregating a series of changing but not ending streams into one stream) + +exports = module.exports = through +through.through = through + +//create a readable writable stream. + +function through (write, end, opts) { + write = write || function (data) { this.queue(data) } + end = end || function () { this.queue(null) } + + var ended = false, destroyed = false, buffer = [], _ended = false + var stream = new Stream() + stream.readable = stream.writable = true + stream.paused = false + +// stream.autoPause = !(opts && opts.autoPause === false) + stream.autoDestroy = !(opts && opts.autoDestroy === false) + + stream.write = function (data) { + write.call(this, data) + return !stream.paused + } + + function drain() { + while(buffer.length && !stream.paused) { + var data = buffer.shift() + if(null === data) + return stream.emit('end') + else + stream.emit('data', data) + } + } + + stream.queue = stream.push = function (data) { +// console.error(ended) + if(_ended) return stream + if(data === null) _ended = true + buffer.push(data) + drain() + return stream + } + + //this will be registered as the first 'end' listener + //must call destroy next tick, to make sure we're after any + //stream piped from here. + //this is only a problem if end is not emitted synchronously. + //a nicer way to do this is to make sure this is the last listener for 'end' + + stream.on('end', function () { + stream.readable = false + if(!stream.writable && stream.autoDestroy) + process.nextTick(function () { + stream.destroy() + }) + }) + + function _end () { + stream.writable = false + end.call(stream) + if(!stream.readable && stream.autoDestroy) + stream.destroy() + } + + stream.end = function (data) { + if(ended) return + ended = true + if(arguments.length) stream.write(data) + _end() // will emit or queue + return stream + } + + stream.destroy = function () { + if(destroyed) return + destroyed = true + ended = true + buffer.length = 0 + stream.writable = stream.readable = false + stream.emit('close') + return stream + } + + stream.pause = function () { + if(stream.paused) return + stream.paused = true + return stream + } + + stream.resume = function () { + if(stream.paused) { + stream.paused = false + stream.emit('resume') + } + drain() + //may have become paused again, + //as drain emits 'data'. + if(!stream.paused) + stream.emit('drain') + return stream + } + return stream +} + + +}).call(this,require('_process')) +},{"_process":86,"stream":127}],133:[function(require,module,exports){ (function (Buffer){ /** * Convert a typed array to a Buffer without a copy @@ -29027,7 +29831,7 @@ module.exports = function (arr) { } }).call(this,require("buffer").Buffer) -},{"buffer":8}],131:[function(require,module,exports){ +},{"buffer":9}],134:[function(require,module,exports){ (function (global){ /** @@ -29098,16 +29902,16 @@ function config (name) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],132:[function(require,module,exports){ -arguments[4][40][0].apply(exports,arguments) -},{"dup":40}],133:[function(require,module,exports){ +},{}],135:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"dup":41}],136:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } -},{}],134:[function(require,module,exports){ +},{}],137:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -29697,7 +30501,7 @@ function hasOwnProperty(obj, prop) { } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":133,"_process":84,"inherits":132}],135:[function(require,module,exports){ +},{"./support/isBuffer":136,"_process":86,"inherits":135}],138:[function(require,module,exports){ // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. @@ -29732,7 +30536,7 @@ function wrappy (fn, cb) { } } -},{}],136:[function(require,module,exports){ +},{}],139:[function(require,module,exports){ module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; diff --git a/dist/search-index.min.js b/dist/search-index.min.js index 9126d5ef..f508a7f5 100644 --- a/dist/search-index.min.js +++ b/dist/search-index.min.js @@ -1,13 +1,13 @@ -!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,g.SearchIndex=f()}}(function(){var define;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n||e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o=0;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return!Error.isPrototypeOf(expected)&&!0===expected.call({},actual)}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError('"block" argument must be a function');"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}var util=require("util/"),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames=function(){return"foo"===function(){}.name}(),assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert.throws=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":134}],4:[function(require,module,exports){(function(process,global){!function(global,factory){"object"==typeof exports&&void 0!==module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory(global.async=global.async||{})}(this,function(exports){"use strict";function slice(arrayLike,start){start|=0;for(var newLen=Math.max(arrayLike.length-start,0),newArr=Array(newLen),idx=0;idx-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function noop(){}function once(fn){return function(){if(null!==fn){var callFn=fn;fn=null,callFn.apply(this,arguments)}}}function baseTimes(n,iteratee){for(var index=-1,result=Array(n);++index-1&&value%1==0&&valuelength?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=length?array:baseSlice(array,start,end)}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function charsStartIndex(strSymbols,chrSymbols){for(var index=-1,length=strSymbols.length;++index-1;);return index}function asciiToArray(string){return string.split("")}function hasUnicode(string){return reHasUnicode.test(string)}function unicodeToArray(string){return string.match(reUnicode)||[]}function stringToArray(string){return hasUnicode(string)?unicodeToArray(string):asciiToArray(string)}function toString(value){return null==value?"":baseToString(value)}function trim(string,chars,guard){if((string=toString(string))&&(guard||void 0===chars))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars);return castSlice(strSymbols,charsStartIndex(strSymbols,chrSymbols),charsEndIndex(strSymbols,chrSymbols)+1).join("")}function parseParams(func){return func=func.toString().replace(STRIP_COMMENTS,""),func=func.match(FN_ARGS)[2].replace(" ",""),func=func?func.split(FN_ARG_SPLIT):[],func=func.map(function(arg){return trim(arg.replace(FN_ARG,""))})}function autoInject(tasks,callback){var newTasks={};baseForOwn(tasks,function(taskFn,key){function newTask(results,taskCb){var newArgs=arrayMap(params,function(name){return results[name]});newArgs.push(taskCb),wrapAsync(taskFn).apply(null,newArgs)}var params,fnIsAsync=isAsync(taskFn),hasNoDeps=!fnIsAsync&&1===taskFn.length||fnIsAsync&&0===taskFn.length;if(isArray(taskFn))params=taskFn.slice(0,-1),taskFn=taskFn[taskFn.length-1],newTasks[key]=params.concat(params.length>0?newTask:taskFn);else if(hasNoDeps)newTasks[key]=taskFn;else{if(params=parseParams(taskFn),0===taskFn.length&&!fnIsAsync&&0===params.length)throw new Error("autoInject task functions require explicit parameters.");fnIsAsync||params.pop(),newTasks[key]=params.concat(newTask)}}),auto(newTasks,callback)}function DLL(){this.head=this.tail=null,this.length=0}function setInitial(dll,node){dll.length=1,dll.head=dll.tail=node}function queue(worker,concurrency,payload){function _insert(data,insertAtFront,callback){if(null!=callback&&"function"!=typeof callback)throw new Error("task callback must be a function");if(q.started=!0,isArray(data)||(data=[data]),0===data.length&&q.idle())return setImmediate$1(function(){q.drain()});for(var i=0,l=data.length;i=0&&workersList.splice(index),task.callback.apply(task,arguments),null!=err&&q.error(err,task.data)}numRunning<=q.concurrency-q.buffer&&q.unsaturated(),q.idle()&&q.drain(),q.process()}}if(null==concurrency)concurrency=1;else if(0===concurrency)throw new Error("Concurrency must not be zero");var _worker=wrapAsync(worker),numRunning=0,workersList=[],isProcessing=!1,q={_tasks:new DLL,concurrency:concurrency,payload:payload,saturated:noop,unsaturated:noop,buffer:concurrency/4,empty:noop,drain:noop,error:noop,started:!1,paused:!1,push:function(data,callback){_insert(data,!1,callback)},kill:function(){q.drain=noop,q._tasks.empty()},unshift:function(data,callback){_insert(data,!0,callback)},remove:function(testFn){q._tasks.remove(testFn)},process:function(){if(!isProcessing){for(isProcessing=!0;!q.paused&&numRunning2&&(result=slice(arguments,1)),results[key]=result,callback(err)})},function(err){callback(err,results)})}function parallelLimit(tasks,callback){_parallel(eachOf,tasks,callback)}function parallelLimit$1(tasks,limit,callback){_parallel(_eachOfLimit(limit),tasks,callback)}function race(tasks,callback){if(callback=once(callback||noop),!isArray(tasks))return callback(new TypeError("First argument to race must be an array of functions"));if(!tasks.length)return callback();for(var i=0,l=tasks.length;ib?1:0}var _iteratee=wrapAsync(iteratee);map(coll,function(x,callback){_iteratee(x,function(err,criteria){ -if(err)return callback(err);callback(null,{value:x,criteria:criteria})})},function(err,results){if(err)return callback(err);callback(null,arrayMap(results.sort(comparator),baseProperty("value")))})}function timeout(asyncFn,milliseconds,info){var fn=wrapAsync(asyncFn);return initialParams(function(args,callback){function timeoutCallback(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,callback(error)}var timer,timedOut=!1;args.push(function(){timedOut||(callback.apply(null,arguments),clearTimeout(timer))}),timer=setTimeout(timeoutCallback,milliseconds),fn.apply(null,args)})}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function timeLimit(count,limit,iteratee,callback){var _iteratee=wrapAsync(iteratee);mapLimit(baseRange(0,count,1),limit,_iteratee,callback)}function transform(coll,accumulator,iteratee,callback){arguments.length<=3&&(callback=iteratee,iteratee=accumulator,accumulator=isArray(coll)?[]:{}),callback=once(callback||noop);var _iteratee=wrapAsync(iteratee);eachOf(coll,function(v,k,cb){_iteratee(accumulator,v,k,cb)},function(err){callback(err,accumulator)})}function tryEach(tasks,callback){var result,error=null;callback=callback||noop,eachSeries(tasks,function(task,callback){wrapAsync(task)(function(err,res){result=arguments.length>2?slice(arguments,1):res,error=err,callback(!err)})},function(){callback(error,result)})}function unmemoize(fn){return function(){return(fn.unmemoized||fn).apply(null,arguments)}}function whilst(test,iteratee,callback){callback=onlyOnce(callback||noop);var _iteratee=wrapAsync(iteratee);if(!test())return callback(null);var next=function(err){if(err)return callback(err);if(test())return _iteratee(next);var args=slice(arguments,1);callback.apply(null,[null].concat(args))};_iteratee(next)}function until(test,iteratee,callback){whilst(function(){return!test.apply(this,arguments)},iteratee,callback)}var _defer,initialParams=function(fn){return function(){var args=slice(arguments),callback=args.pop();fn.call(this,args,callback)}},hasSetImmediate="function"==typeof setImmediate&&setImmediate,hasNextTick="object"==typeof process&&"function"==typeof process.nextTick;_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback;var setImmediate$1=wrap(_defer),supportsSymbol="function"==typeof Symbol,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol$1=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag$1=Symbol$1?Symbol$1.toStringTag:void 0,objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString,nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol$1?Symbol$1.toStringTag:void 0,asyncTag="[object AsyncFunction]",funcTag="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]",MAX_SAFE_INTEGER=9007199254740991,breakLoop={},iteratorSymbol="function"==typeof Symbol&&Symbol.iterator,getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()},argsTag="[object Arguments]",objectProto$3=Object.prototype,hasOwnProperty$2=objectProto$3.hasOwnProperty,propertyIsEnumerable=objectProto$3.propertyIsEnumerable,isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty$2.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,Buffer=moduleExports?root.Buffer:void 0,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,MAX_SAFE_INTEGER$1=9007199254740991,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags["[object Float32Array]"]=typedArrayTags["[object Float64Array]"]=typedArrayTags["[object Int8Array]"]=typedArrayTags["[object Int16Array]"]=typedArrayTags["[object Int32Array]"]=typedArrayTags["[object Uint8Array]"]=typedArrayTags["[object Uint8ClampedArray]"]=typedArrayTags["[object Uint16Array]"]=typedArrayTags["[object Uint32Array]"]=!0,typedArrayTags["[object Arguments]"]=typedArrayTags["[object Array]"]=typedArrayTags["[object ArrayBuffer]"]=typedArrayTags["[object Boolean]"]=typedArrayTags["[object DataView]"]=typedArrayTags["[object Date]"]=typedArrayTags["[object Error]"]=typedArrayTags["[object Function]"]=typedArrayTags["[object Map]"]=typedArrayTags["[object Number]"]=typedArrayTags["[object Object]"]=typedArrayTags["[object RegExp]"]=typedArrayTags["[object Set]"]=typedArrayTags["[object String]"]=typedArrayTags["[object WeakMap]"]=!1;var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,freeProcess=moduleExports$1&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?function(func){return function(value){return func(value)}}(nodeIsTypedArray):baseIsTypedArray,objectProto$2=Object.prototype,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),objectProto$4=Object.prototype,hasOwnProperty$3=objectProto$4.hasOwnProperty,eachOfGeneric=doLimit(eachOfLimit,1/0),eachOf=function(coll,iteratee,callback){(isArrayLike(coll)?eachOfArrayLike:eachOfGeneric)(coll,wrapAsync(iteratee),callback)},map=doParallel(_asyncMap),applyEach=applyEach$1(map),mapLimit=doParallelLimit(_asyncMap),mapSeries=doLimit(mapLimit,1),applyEachSeries=applyEach$1(mapSeries),apply=function(fn){var args=slice(arguments,1);return function(){var callArgs=slice(arguments);return fn.apply(null,args.concat(callArgs))}},baseFor=function(fromRight){return function(object,iteratee,keysFunc){for(var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length;length--;){var key=props[fromRight?length:++index];if(!1===iteratee(iterable[key],key,iterable))break}return object}}(),auto=function(tasks,concurrency,callback){function enqueueTask(key,task){readyTasks.push(function(){runTask(key,task)})}function processQueue(){if(0===readyTasks.length&&0===runningTasks)return callback(null,results);for(;readyTasks.length&&runningTasks2&&(result=slice(arguments,1)),err){var safeResults={};baseForOwn(results,function(val,rkey){safeResults[rkey]=val}),safeResults[key]=result,hasError=!0,listeners=Object.create(null),callback(err,safeResults)}else results[key]=result,taskComplete(key)});runningTasks++;var taskFn=wrapAsync(task[task.length-1]);task.length>1?taskFn(results,taskCallback):taskFn(taskCallback)}}function getDependents(taskName){var result=[];return baseForOwn(tasks,function(task,key){isArray(task)&&baseIndexOf(task,taskName,0)>=0&&result.push(key)}),result}"function"==typeof concurrency&&(callback=concurrency,concurrency=null),callback=once(callback||noop);var keys$$1=keys(tasks),numTasks=keys$$1.length;if(!numTasks)return callback(null);concurrency||(concurrency=numTasks);var results={},runningTasks=0,hasError=!1,listeners=Object.create(null),readyTasks=[],readyToCheck=[],uncheckedDependencies={};baseForOwn(tasks,function(task,key){if(!isArray(task))return enqueueTask(key,[task]),void readyToCheck.push(key);var dependencies=task.slice(0,task.length-1),remainingDependencies=dependencies.length;if(0===remainingDependencies)return enqueueTask(key,task),void readyToCheck.push(key);uncheckedDependencies[key]=remainingDependencies,arrayEach(dependencies,function(dependencyName){if(!tasks[dependencyName])throw new Error("async.auto task `"+key+"` has a non-existent dependency `"+dependencyName+"` in "+dependencies.join(", "));addListener(dependencyName,function(){0===--remainingDependencies&&enqueueTask(key,task)})})}),function(){for(var currentTask,counter=0;readyToCheck.length;)currentTask=readyToCheck.pop(),counter++,arrayEach(getDependents(currentTask),function(dependent){0==--uncheckedDependencies[dependent]&&readyToCheck.push(dependent)});if(counter!==numTasks)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),processQueue()},symbolTag="[object Symbol]",INFINITY=1/0,symbolProto=Symbol$1?Symbol$1.prototype:void 0,symbolToString=symbolProto?symbolProto.toString:void 0,reHasUnicode=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0\\ufe0e\\ufe0f]"),rsCombo="[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",reOptMod="(?:[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]|\\ud83c[\\udffb-\\udfff])?",rsOptJoin="(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*",rsSeq="[\\ufe0e\\ufe0f]?"+reOptMod+rsOptJoin,rsSymbol="(?:"+["[^\\ud800-\\udfff]"+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,"[\\ud800-\\udfff]"].join("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reTrim=/^\s+|\s+$/g,FN_ARGS=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,FN_ARG_SPLIT=/,/,FN_ARG=/(=.+)?(\s*)$/,STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;DLL.prototype.removeLink=function(node){return node.prev?node.prev.next=node.next:this.head=node.next,node.next?node.next.prev=node.prev:this.tail=node.prev,node.prev=node.next=null,this.length-=1,node},DLL.prototype.empty=function(){for(;this.head;)this.shift();return this},DLL.prototype.insertAfter=function(node,newNode){newNode.prev=node,newNode.next=node.next,node.next?node.next.prev=newNode:this.tail=newNode,node.next=newNode,this.length+=1},DLL.prototype.insertBefore=function(node,newNode){newNode.prev=node.prev,newNode.next=node,node.prev?node.prev.next=newNode:this.head=newNode,node.prev=newNode,this.length+=1},DLL.prototype.unshift=function(node){this.head?this.insertBefore(this.head,node):setInitial(this,node)},DLL.prototype.push=function(node){this.tail?this.insertAfter(this.tail,node):setInitial(this,node)},DLL.prototype.shift=function(){return this.head&&this.removeLink(this.head)},DLL.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},DLL.prototype.toArray=function(){for(var arr=Array(this.length),curr=this.head,idx=0;idx=nextNode.priority;)nextNode=nextNode.next;for(var i=0,l=data.length;i0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===b64[len-2]?2:"="===b64[len-1]?1:0}function byteLength(b64){return 3*b64.length/4-placeHoldersCount(b64)}function toByteArray(b64){var i,l,tmp,placeHolders,arr,len=b64.length;placeHolders=placeHoldersCount(b64),arr=new Arr(3*len/4-placeHolders),l=placeHolders>0?len-4:len;var L=0;for(i=0;i>16&255,arr[L++]=tmp>>8&255,arr[L++]=255&tmp;return 2===placeHolders?(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[L++]=255&tmp):1===placeHolders&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[L++]=tmp>>8&255,arr[L++]=255&tmp),arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i=start;ilen2?len2:i+16383));return 1===extraBytes?(tmp=uint8[len-1],output+=lookup[tmp>>2],output+=lookup[tmp<<4&63],output+="=="):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],output+=lookup[tmp>>10],output+=lookup[tmp>>4&63],output+=lookup[tmp<<2&63],output+="="),parts.push(output),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer))return string.byteLength;"string"!=typeof string&&(string=""+string);var len=string.length;if(0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":case void 0:return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),byteOffset=+byteOffset,isNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&("ucs2"===(encoding=String(encoding).toLowerCase())||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;jremaining&&(length=remaining):length=remaining;var strLen=string.length;if(strLen%2!=0)throw new TypeError("Invalid hex string");length>strLen/2&&(length=strLen/2);for(var i=0;i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:secondByte=buf[i+1],128==(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte)>127&&(codePoint=tempCodePoint);break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128==(192&secondByte)&&128==(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte)>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint);break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128==(192&secondByte)&&128==(192&thirdByte)&&128==(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte)>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint)}}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;ilen)&&(end=len);for(var out="",i=start;ilength)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function objectWriteUInt16(buf,value,offset,littleEndian){value<0&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);i>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){value<0&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);i>>8*(littleEndian?i:3-i)&255}function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=stringtrim(str).replace(INVALID_BASE64_RE,""),str.length<2)return"";for(;str.length%4!=0;)str+="=";return str}function stringtrim(str){return str.trim?str.trim():str.replace(/^\s+|\s+$/g,"")}function toHex(n){return n<16?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var codePoint,length=string.length,leadSurrogate=null,bytes=[],i=0;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=65536+(leadSurrogate-55296<<10|codePoint-56320)}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isnan(val){return val!==val}var base64=require("base64-js"),ieee754=require("ieee754"),isArray=require("isarray");exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50,Buffer.TYPED_ARRAY_SUPPORT=void 0!==global.TYPED_ARRAY_SUPPORT?global.TYPED_ARRAY_SUPPORT:function(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}(),exports.kMaxLength=kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(arr){return arr.__proto__=Buffer.prototype,arr},Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0})),Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)},Buffer.isBuffer=function(b){return!(null==b||!b._isBuffer)},Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i0&&(str=this.toString("hex",0,max).match(/.{2}/g).join(" "),this.length>max&&(str+=" ... ")),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target))throw new TypeError("Argument must be a Buffer");if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),start<0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;iremaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,start<0?(start+=len)<0&&(start=0):start>len&&(start=len),end<0?(end+=len)<0&&(end=0):end>len&&(end=len),end0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,byteLength|=0,!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0)}var mul=1,i=0;for(this[offset]=255&value;++i=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++i>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart=0;--i)target[i+targetStart]=this[i+start];else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,end=void 0===end?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":return fastAndSafeJsonStringify(args[i++]);case"%%":return"%";default:return x}}),x=args[i];i=0,format('rotating-file stream "count" is not >= 0: %j in %j',this.count,this)),options.period){var period={hourly:"1h",daily:"1d",weekly:"1w",monthly:"1m",yearly:"1y"}[options.period]||options.period,m=/^([1-9][0-9]*)([hdwmy]|ms)$/.exec(period);if(!m)throw new Error(format('invalid period: "%s"',options.period));this.periodNum=Number(m[1]),this.periodScope=m[2]}else this.periodNum=1,this.periodScope="d";var lastModified=null;try{lastModified=fs.statSync(this.path).mtime.getTime()}catch(err){}var rotateAfterOpen=!1;if(lastModified){lastModified call rotate()"),this.rotate()):this._setupNextRot()},util.inherits(RotatingFileStream,EventEmitter),RotatingFileStream.prototype._debug=function(){return!1},RotatingFileStream.prototype._setupNextRot=function(){this.rotAt=this._calcRotTime(1),this._setRotationTimer()},RotatingFileStream.prototype._setRotationTimer=function(){var self=this,delay=this.rotAt-Date.now();delay>2147483647&&(delay=2147483647),this.timeout=setTimeout(function(){self._debug("_setRotationTimer timeout -> call rotate()"),self.rotate()},delay),"function"==typeof this.timeout.unref&&this.timeout.unref()},RotatingFileStream.prototype._calcRotTime=function(periodOffset){this._debug("_calcRotTime: %s%s",this.periodNum,this.periodScope);var d=new Date;this._debug(" now local: %s",d),this._debug(" now utc: %s",d.toISOString());var rotAt;switch(this.periodScope){case"ms":rotAt=this.rotAt?this.rotAt+this.periodNum*periodOffset:Date.now()+this.periodNum*periodOffset;break;case"h":rotAt=this.rotAt?this.rotAt+60*this.periodNum*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),d.getUTCHours()+periodOffset);break;case"d":rotAt=this.rotAt?this.rotAt+24*this.periodNum*60*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+periodOffset);break;case"w":if(this.rotAt)rotAt=this.rotAt+7*this.periodNum*24*60*60*1e3*periodOffset;else{var dayOffset=7-d.getUTCDay();periodOffset<1&&(dayOffset=-d.getUTCDay()),(periodOffset>1||periodOffset<-1)&&(dayOffset+=7*periodOffset),rotAt=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+dayOffset)}break;case"m":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+this.periodNum*periodOffset,1):Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+periodOffset,1);break;case"y":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear()+this.periodNum*periodOffset,0,1):Date.UTC(d.getUTCFullYear()+periodOffset,0,1);break;default:assert.fail(format('invalid period scope: "%s"',this.periodScope))}if(this._debug()){this._debug(" **rotAt**: %s (utc: %s)",rotAt,new Date(rotAt).toUTCString());var now=Date.now();this._debug(" now: %s (%sms == %smin == %sh to go)",now,rotAt-now,(rotAt-now)/1e3/60,(rotAt-now)/1e3/60/60)}return rotAt},RotatingFileStream.prototype.rotate=function(){function moves(){if(0===self.count||n<0)return finish();var before=self.path,after=self.path+"."+String(n);n>0&&(before+="."+String(n-1)),n-=1,fs.exists(before,function(exists){exists?(self._debug(" mv %s %s",before,after),mv(before,after,function(mvErr){mvErr?(self.emit("error",mvErr),finish()):moves()})):moves()})}function finish(){self._debug(" open %s",self.path),self.stream=fs.createWriteStream(self.path,{flags:"a",encoding:"utf8"});for(var q=self.rotQueue,len=q.length,i=0;iDate.now())return self._setRotationTimer();if(this._debug("rotate"),self.rotating)throw new TypeError("cannot start a rotation when already rotating");self.rotating=!0,self.stream.end();var n=this.count;!function(){var toDel=self.path+"."+String(n-1);0===n&&(toDel=self.path),n-=1,self._debug(" rm %s",toDel),fs.unlink(toDel,function(delErr){moves()})}()},RotatingFileStream.prototype.write=function(s){return this.rotating?(this.rotQueue.push(s),!1):this.stream.write(s)},RotatingFileStream.prototype.end=function(s){this.stream.end()},RotatingFileStream.prototype.destroy=function(s){this.stream.destroy()},RotatingFileStream.prototype.destroySoon=function(s){this.stream.destroySoon()}),util.inherits(RingBuffer,EventEmitter),RingBuffer.prototype.write=function(record){if(!this.writable)throw new Error("RingBuffer has been ended already");return this.records.push(record),this.records.length>this.limit&&this.records.shift(),!0},RingBuffer.prototype.end=function(){arguments.length>0&&this.write.apply(this,Array.prototype.slice.call(arguments)),this.writable=!1},RingBuffer.prototype.destroy=function(){this.writable=!1,this.emit("close")},RingBuffer.prototype.destroySoon=function(){this.destroy()},module.exports=Logger,module.exports.TRACE=10,module.exports.DEBUG=20,module.exports.INFO=INFO,module.exports.WARN=WARN,module.exports.ERROR=ERROR,module.exports.FATAL=60,module.exports.resolveLevel=resolveLevel,module.exports.levelFromName=levelFromName,module.exports.nameFromLevel=nameFromLevel,module.exports.VERSION="1.8.10",module.exports.LOG_VERSION=LOG_VERSION,module.exports.createLogger=function(options){return new Logger(options)},module.exports.RingBuffer=RingBuffer,module.exports.RotatingFileStream=RotatingFileStream,module.exports.safeCycles=safeCycles}).call(this,{isBuffer:require("../../is-buffer/index.js")},require("_process"))},{"../../is-buffer/index.js":42,_process:84,assert:3,events:37,fs:7,os:82,"safe-json-stringify":102,stream:125,util:134}],10:[function(require,module,exports){(function(Buffer){function isArray(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return"[object Date]"===objectToString(d)}function isError(e){return"[object Error]"===objectToString(e)||e instanceof Error}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg}function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=Buffer.isBuffer}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":42}],11:[function(require,module,exports){function DeferredIterator(options){AbstractIterator.call(this,options),this._options=options,this._iterator=null,this._operations=[]}var util=require("util"),AbstractIterator=require("abstract-leveldown").AbstractIterator;util.inherits(DeferredIterator,AbstractIterator),DeferredIterator.prototype.setDb=function(db){var it=this._iterator=db.iterator(this._options);this._operations.forEach(function(op){it[op.method].apply(it,op.args)})},DeferredIterator.prototype._operation=function(method,args){if(this._iterator)return this._iterator[method].apply(this._iterator,args);this._operations.push({method:method,args:args})},"next end".split(" ").forEach(function(m){DeferredIterator.prototype["_"+m]=function(){this._operation(m,arguments)}}),module.exports=DeferredIterator},{"abstract-leveldown":16,util:134}],12:[function(require,module,exports){(function(Buffer,process){function DeferredLevelDOWN(location){AbstractLevelDOWN.call(this,"string"==typeof location?location:""),this._db=void 0,this._operations=[],this._iterators=[]}var util=require("util"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,DeferredIterator=require("./deferred-iterator");util.inherits(DeferredLevelDOWN,AbstractLevelDOWN),DeferredLevelDOWN.prototype.setDb=function(db){this._db=db,this._operations.forEach(function(op){db[op.method].apply(db,op.args)}),this._iterators.forEach(function(it){it.setDb(db)})},DeferredLevelDOWN.prototype._open=function(options,callback){return process.nextTick(callback)},DeferredLevelDOWN.prototype._operation=function(method,args){if(this._db)return this._db[method].apply(this._db,args);this._operations.push({method:method,args:args})},"put get del batch approximateSize".split(" ").forEach(function(m){DeferredLevelDOWN.prototype["_"+m]=function(){this._operation(m,arguments)}}),DeferredLevelDOWN.prototype._isBuffer=function(obj){return Buffer.isBuffer(obj)},DeferredLevelDOWN.prototype._iterator=function(options){if(this._db)return this._db.iterator.apply(this._db,arguments);var it=new DeferredIterator(options);return this._iterators.push(it),it},module.exports=DeferredLevelDOWN,module.exports.DeferredIterator=DeferredIterator}).call(this,{isBuffer:require("../is-buffer/index.js")},require("_process"))},{"../is-buffer/index.js":42,"./deferred-iterator":11,_process:84,"abstract-leveldown":16,util:134}],13:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:84}],14:[function(require,module,exports){(function(process){function AbstractIterator(db){this.db=db,this._ended=!1,this._nexting=!1}AbstractIterator.prototype.next=function(callback){var self=this;if("function"!=typeof callback)throw new Error("next() requires a callback argument");return self._ended?callback(new Error("cannot call next() after end()")):self._nexting?callback(new Error("cannot call next() before previous next() has completed")):(self._nexting=!0,"function"==typeof self._next?self._next(function(){self._nexting=!1,callback.apply(null,arguments)}):void process.nextTick(function(){self._nexting=!1,callback()}))},AbstractIterator.prototype.end=function(callback){if("function"!=typeof callback)throw new Error("end() requires a callback argument");return this._ended?callback(new Error("end() already called on iterator")):(this._ended=!0,"function"==typeof this._end?this._end(callback):void process.nextTick(callback))},module.exports=AbstractIterator}).call(this,require("_process"))},{_process:84}],15:[function(require,module,exports){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location,this.status="new"}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){var self=this,oldStatus=this.status;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");"object"!=typeof options&&(options={}),options.createIfMissing=0!=options.createIfMissing,options.errorIfExists=!!options.errorIfExists,"function"==typeof this._open?(this.status="opening",this._open(options,function(err){if(err)return self.status=oldStatus,callback(err);self.status="open",callback()})):(this.status="open",process.nextTick(callback))},AbstractLevelDOWN.prototype.close=function(callback){var self=this,oldStatus=this.status;if("function"!=typeof callback)throw new Error("close() requires a callback argument");"function"==typeof this._close?(this.status="closing",this._close(function(err){if(err)return self.status=oldStatus,callback(err);self.status="closed",callback()})):(this.status="closed",process.nextTick(callback))},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),options.asBuffer=0!=options.asBuffer,"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),null==value||this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"==typeof array&&(callback=array),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));options&&"object"==typeof options||(options={});for(var e,err,i=0,l=array.length;i<.,\-|]+|\\u0003/},doc.options||{});for(var fieldName in doc.normalised){var fieldOptions=Object.assign({},{separator:options.separator},options.fieldOptions[fieldName]);"[object Array]"===Object.prototype.toString.call(doc.normalised[fieldName])?doc.tokenised[fieldName]=doc.normalised[fieldName]:doc.tokenised[fieldName]=doc.normalised[fieldName].split(fieldOptions.separator)}return this.push(doc),end()}},{stream:125,util:134}],30:[function(require,module,exports){(function(process,Buffer){var stream=require("readable-stream"),eos=require("end-of-stream"),inherits=require("inherits"),shift=require("stream-shift"),SIGNAL_FLUSH=new Buffer([0]),onuncork=function(self,fn){self._corked?self.once("uncork",fn):fn() -},destroyer=function(self,end){return function(err){err?self.destroy("premature close"===err.message?null:err):end&&!self._ended&&self.end()}},end=function(ws,fn){return ws?ws._writableState&&ws._writableState.finished?fn():ws._writableState?ws.end(fn):(ws.end(),void fn()):fn()},toStreams2=function(rs){return new stream.Readable({objectMode:!0,highWaterMark:16}).wrap(rs)},Duplexify=function(writable,readable,opts){if(!(this instanceof Duplexify))return new Duplexify(writable,readable,opts);stream.Duplex.call(this,opts),this._writable=null,this._readable=null,this._readable2=null,this._forwardDestroy=!opts||!1!==opts.destroy,this._forwardEnd=!opts||!1!==opts.end,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,writable&&this.setWritable(writable),readable&&this.setReadable(readable)};inherits(Duplexify,stream.Duplex),Duplexify.obj=function(writable,readable,opts){return opts||(opts={}),opts.objectMode=!0,opts.highWaterMark=16,new Duplexify(writable,readable,opts)},Duplexify.prototype.cork=function(){1==++this._corked&&this.emit("cork")},Duplexify.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},Duplexify.prototype.setWritable=function(writable){if(this._unwrite&&this._unwrite(),this.destroyed)return void(writable&&writable.destroy&&writable.destroy());if(null===writable||!1===writable)return void this.end();var self=this,unend=eos(writable,{writable:!0,readable:!1},destroyer(this,this._forwardEnd)),ondrain=function(){var ondrain=self._ondrain;self._ondrain=null,ondrain&&ondrain()},clear=function(){self._writable.removeListener("drain",ondrain),unend()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=clear,this.uncork()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)return void(readable&&readable.destroy&&readable.destroy());if(null===readable||!1===readable)return this.push(null),void this.resume();var self=this,unend=eos(readable,{writable:!1,readable:!0},destroyer(this)),onreadable=function(){self._forward()},onend=function(){self.push(null)},clear=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()};this._drained=!0,this._readable=readable,this._readable2=readable._readableState?readable:toStreams2(readable),this._readable2.on("readable",onreadable),this._readable2.on("end",onend),this._unread=clear,this._forward()},Duplexify.prototype._read=function(){this._drained=!0,this._forward()},Duplexify.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){this._forwarding=!0;for(var data;this._drained&&null!==(data=shift(this._readable2));)this.destroyed||(this._drained=this.push(data));this._forwarding=!1}},Duplexify.prototype.destroy=function(err){if(!this.destroyed){this.destroyed=!0;var self=this;process.nextTick(function(){self._destroy(err)})}},Duplexify.prototype._destroy=function(err){if(err){var ondrain=this._ondrain;this._ondrain=null,ondrain?ondrain(err):this.emit("error",err)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},Duplexify.prototype._write=function(data,enc,cb){return this.destroyed?cb():this._corked?onuncork(this,this._write.bind(this,data,enc,cb)):data===SIGNAL_FLUSH?this._finish(cb):this._writable?void(!1===this._writable.write(data)?this._ondrain=cb:cb()):cb()},Duplexify.prototype._finish=function(cb){var self=this;this.emit("preend"),onuncork(this,function(){end(self._forwardEnd&&self._writable,function(){!1===self._writableState.prefinished&&(self._writableState.prefinished=!0),self.emit("prefinish"),onuncork(self,cb)})})},Duplexify.prototype.end=function(data,enc,cb){return"function"==typeof data?this.end(null,null,data):"function"==typeof enc?this.end(data,null,enc):(this._ended=!0,data&&this.write(data),this._writableState.ending||this.write(SIGNAL_FLUSH),stream.Writable.prototype.end.call(this,cb))},module.exports=Duplexify}).call(this,require("_process"),require("buffer").Buffer)},{_process:84,buffer:8,"end-of-stream":31,inherits:40,"readable-stream":98,"stream-shift":126}],31:[function(require,module,exports){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback()},onend=function(){readable=!1,writable||callback()},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback(new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:32}],32:[function(require,module,exports){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0})})},{wrappy:135}],33:[function(require,module,exports){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},isChildProcess=function(stream){return stream.stdio&&Array.isArray(stream.stdio)&&3===stream.stdio.length},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback.call(stream)},onend=function(){readable=!1,writable||callback.call(stream)},onexit=function(exitCode){callback.call(stream,exitCode?new Error("exited with error code: "+exitCode):null)},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback.call(stream,new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),isChildProcess(stream)&&stream.on("exit",onexit),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("exit",onexit),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:81}],34:[function(require,module,exports){function init(type,message,cause){prr(this,{type:type,name:type,cause:"string"!=typeof message?message:cause,message:message&&"string"!=typeof message?message.message:message},"ewr")}function CustomError(message,cause){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),init.call(this,"CustomError",message,cause)}function createError(errno,type,proto){var err=function(message,cause){init.call(this,type,message,cause),"FilesystemError"==type&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(errno.errno[this.cause.errno]?errno.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return err.prototype=proto?new proto:new CustomError,err}var prr=require("prr");CustomError.prototype=new Error,module.exports=function(errno){var ce=function(type,proto){return createError(errno,type,proto)};return{CustomError:CustomError,FilesystemError:ce("FilesystemError"),createError:ce}}},{prr:36}],35:[function(require,module,exports){var all=module.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];module.exports.errno={},module.exports.code={},all.forEach(function(error){module.exports.errno[error.errno]=error,module.exports.code[error.code]=error}),module.exports.custom=require("./custom")(module.exports),module.exports.create=module.exports.custom.createError},{"./custom":34}],36:[function(require,module,exports){!function(name,context,definition){void 0!==module&&module.exports?module.exports=definition():context.prr=definition()}(0,this,function(){var setProperty="function"==typeof Object.defineProperty?function(obj,key,options){return Object.defineProperty(obj,key,options),obj}:function(obj,key,options){return obj[key]=options.value,obj},makeOptions=function(value,options){var oo="object"==typeof options,os=!oo&&"string"==typeof options,op=function(p){return oo?!!options[p]:!!os&&options.indexOf(p[0])>-1};return{enumerable:op("enumerable"),configurable:op("configurable"),writable:op("writable"),value:value}};return function(obj,key,value,options){var k;if(options=makeOptions(value,options),"object"==typeof key){for(k in key)Object.hasOwnProperty.call(key,k)&&(options.value=key[k],setProperty(obj,k,options));return obj}return setProperty(obj,key,options)}})},{}],37:[function(require,module,exports){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if((er=arguments[1])instanceof Error)throw er;var err=new Error('Uncaught, unspecified "error" event. ('+er+")");throw err.context=er,err}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args)}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;i0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace()),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-- >0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(position<0)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){return this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},{}],38:[function(require,module,exports){!function(name,definition,global){"use strict";"function"==typeof define?define(definition):void 0!==module&&module.exports?module.exports=definition():global.IDBStore=definition()}(0,function(){"use strict";function mixin(target,source){var name,s;for(name in source)(s=source[name])!==empty[name]&&s!==target[name]&&(target[name]=s);return target}function hasVersionError(errorEvent){return"error"in errorEvent.target?"VersionError"==errorEvent.target.error.name:"errorCode"in errorEvent.target&&12==errorEvent.target.errorCode}var defaultErrorHandler=function(error){throw error},defaultSuccessHandler=function(){},defaults={storeName:"Store",storePrefix:"IDBWrapper-",dbVersion:1,keyPath:"id",autoIncrement:!0,onStoreReady:function(){},onError:defaultErrorHandler,indexes:[],implementationPreference:["indexedDB","webkitIndexedDB","mozIndexedDB","shimIndexedDB"]},IDBStore=function(kwArgs,onStoreReady){void 0===onStoreReady&&"function"==typeof kwArgs&&(onStoreReady=kwArgs),"[object Object]"!=Object.prototype.toString.call(kwArgs)&&(kwArgs={});for(var key in defaults)this[key]=void 0!==kwArgs[key]?kwArgs[key]:defaults[key];this.dbName=this.storePrefix+this.storeName,this.dbVersion=parseInt(this.dbVersion,10)||1,onStoreReady&&(this.onStoreReady=onStoreReady);var env="object"==typeof window?window:self,availableImplementations=this.implementationPreference.filter(function(implName){return implName in env});this.implementation=availableImplementations[0],this.idb=env[this.implementation],this.keyRange=env.IDBKeyRange||env.webkitIDBKeyRange||env.mozIDBKeyRange,this.consts={READ_ONLY:"readonly",READ_WRITE:"readwrite",VERSION_CHANGE:"versionchange",NEXT:"next",NEXT_NO_DUPLICATE:"nextunique",PREV:"prev",PREV_NO_DUPLICATE:"prevunique"},this.openDB()},proto={constructor:IDBStore,version:"1.7.1",db:null,dbName:null,dbVersion:null,store:null,storeName:null,storePrefix:null,keyPath:null,autoIncrement:null,indexes:null,implementationPreference:null,implementation:"",onStoreReady:null,onError:null,_insertIdCount:0,openDB:function(){var openRequest=this.idb.open(this.dbName,this.dbVersion),preventSuccessCallback=!1;openRequest.onerror=function(errorEvent){if(hasVersionError(errorEvent))this.onError(new Error("The version number provided is lower than the existing one."));else{var error;if(errorEvent.target.error)error=errorEvent.target.error;else{var errorMessage="IndexedDB unknown error occurred when opening DB "+this.dbName+" version "+this.dbVersion;"errorCode"in errorEvent.target&&(errorMessage+=" with error code "+errorEvent.target.errorCode),error=new Error(errorMessage)}this.onError(error)}}.bind(this),openRequest.onsuccess=function(event){if(!preventSuccessCallback){if(this.db)return void this.onStoreReady();if(this.db=event.target.result,"string"==typeof this.db.version)return void this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."));if(!this.db.objectStoreNames.contains(this.storeName))return void this.onError(new Error("Object store couldn't be created."));var emptyTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);this.store=emptyTransaction.objectStore(this.storeName);var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(!indexName)return preventSuccessCallback=!0,void this.onError(new Error("Cannot create index: No index name given."));if(this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);this.indexComplies(actualIndex,indexData)||(preventSuccessCallback=!0,this.onError(new Error('Cannot modify index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else preventSuccessCallback=!0,this.onError(new Error('Cannot create new index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))},this),existingIndexes.length&&(preventSuccessCallback=!0,this.onError(new Error('Cannot delete index(es) "'+existingIndexes.toString()+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),preventSuccessCallback||this.onStoreReady()}}.bind(this),openRequest.onupgradeneeded=function(event){if(this.db=event.target.result,this.db.objectStoreNames.contains(this.storeName))this.store=event.target.transaction.objectStore(this.storeName);else{var optionalParameters={autoIncrement:this.autoIncrement};null!==this.keyPath&&(optionalParameters.keyPath=this.keyPath),this.store=this.db.createObjectStore(this.storeName,optionalParameters)}var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(indexName||(preventSuccessCallback=!0,this.onError(new Error("Cannot create index: No index name given."))),this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);this.indexComplies(actualIndex,indexData)||(this.store.deleteIndex(indexName),this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})},this),existingIndexes.length&&existingIndexes.forEach(function(_indexName){this.store.deleteIndex(_indexName)},this)}.bind(this)},deleteDatabase:function(onSuccess,onError){if(this.idb.deleteDatabase){this.db.close();var deleteRequest=this.idb.deleteDatabase(this.dbName);deleteRequest.onsuccess=onSuccess,deleteRequest.onerror=onError}else onError(new Error("Browser does not support IndexedDB deleteDatabase!"))},put:function(key,value,onSuccess,onError){null!==this.keyPath&&(onError=onSuccess,onSuccess=value,value=key),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var putRequest,hasSuccess=!1,result=null,putTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);return putTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},putTransaction.onabort=onError,putTransaction.onerror=onError,null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=putTransaction.objectStore(this.storeName).put(value)):putRequest=putTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},putRequest.onerror=onError,putTransaction},get:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,getTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);getTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getTransaction.onabort=onError,getTransaction.onerror=onError;var getRequest=getTransaction.objectStore(this.storeName).get(key);return getRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getRequest.onerror=onError,getTransaction},remove:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,removeTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);removeTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},removeTransaction.onabort=onError,removeTransaction.onerror=onError;var deleteRequest=removeTransaction.objectStore(this.storeName).delete(key);return deleteRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},deleteRequest.onerror=onError,removeTransaction},batch:function(dataArray,onSuccess,onError){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),"[object Array]"!=Object.prototype.toString.call(dataArray))onError(new Error("dataArray argument must be of type Array."));else if(0===dataArray.length)return onSuccess(!0);var count=dataArray.length,called=!1,hasSuccess=!1,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(hasSuccess)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(){0!==--count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(operation){var type=operation.type,key=operation.key,value=operation.value,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err,type,key))};if("remove"==type){var deleteRequest=batchTransaction.objectStore(this.storeName).delete(key);deleteRequest.onsuccess=onItemSuccess,deleteRequest.onerror=onItemError}else if("put"==type){var putRequest;null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=batchTransaction.objectStore(this.storeName).put(value)):putRequest=batchTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError}},this),batchTransaction},putBatch:function(dataArray,onSuccess,onError){var batchData=dataArray.map(function(item){return{type:"put",value:item}});return this.batch(batchData,onSuccess,onError)},upsertBatch:function(dataArray,options,onSuccess,onError){"function"==typeof options&&(onSuccess=options,onError=onSuccess,options={}),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),options||(options={}),"[object Array]"!=Object.prototype.toString.call(dataArray)&&onError(new Error("dataArray argument must be of type Array."));var keyField=options.keyField||this.keyPath,count=dataArray.length,called=!1,hasSuccess=!1,index=0,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){hasSuccess?onSuccess(dataArray):onError(!1)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){dataArray[index++][keyField]=event.target.result,0!==--count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(record){var putRequest,key=record.key,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err))};null!==this.keyPath?(this._addIdPropertyIfNeeded(record),putRequest=batchTransaction.objectStore(this.storeName).put(record)):putRequest=batchTransaction.objectStore(this.storeName).put(record,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError},this),batchTransaction},removeBatch:function(keyArray,onSuccess,onError){var batchData=keyArray.map(function(key){return{type:"remove",key:key}});return this.batch(batchData,onSuccess,onError)},getBatch:function(keyArray,onSuccess,onError,arrayType){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),arrayType||(arrayType="sparse"),"[object Array]"!=Object.prototype.toString.call(keyArray))onError(new Error("keyArray argument must be of type Array."));else if(0===keyArray.length)return onSuccess([]);var data=[],count=keyArray.length,called=!1,hasSuccess=!1,result=null,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);batchTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){event.target.result||"dense"==arrayType?data.push(event.target.result):"sparse"==arrayType&&data.length++,0===--count&&(called=!0,hasSuccess=!0,result=data)};return keyArray.forEach(function(key){var onItemError=function(err){called=!0,result=err,onError(err),batchTransaction.abort()},getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=onItemError},this),batchTransaction},getAll:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var getAllTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY),store=getAllTransaction.objectStore(this.storeName);return store.getAll?this._getAllNative(getAllTransaction,store,onSuccess,onError):this._getAllCursor(getAllTransaction,store,onSuccess,onError),getAllTransaction},_getAllNative:function(getAllTransaction,store,onSuccess,onError){var hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var getAllRequest=store.getAll();getAllRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getAllRequest.onerror=onError},_getAllCursor:function(getAllTransaction,store,onSuccess,onError){var all=[],hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)}, -getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var cursorRequest=store.openCursor();cursorRequest.onsuccess=function(event){var cursor=event.target.result;cursor?(all.push(cursor.value),cursor.continue()):(hasSuccess=!0,result=all)},cursorRequest.onError=onError},clear:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,clearTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);clearTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},clearTransaction.onabort=onError,clearTransaction.onerror=onError;var clearRequest=clearTransaction.objectStore(this.storeName).clear();return clearRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},clearRequest.onerror=onError,clearTransaction},_addIdPropertyIfNeeded:function(dataObj){void 0===dataObj[this.keyPath]&&(dataObj[this.keyPath]=this._insertIdCount+++Date.now())},getIndexList:function(){return this.store.indexNames},hasIndex:function(indexName){return this.store.indexNames.contains(indexName)},normalizeIndexData:function(indexData){indexData.keyPath=indexData.keyPath||indexData.name,indexData.unique=!!indexData.unique,indexData.multiEntry=!!indexData.multiEntry},indexComplies:function(actual,expected){return["keyPath","unique","multiEntry"].every(function(key){if("multiEntry"==key&&void 0===actual[key]&&!1===expected[key])return!0;if("keyPath"==key&&"[object Array]"==Object.prototype.toString.call(expected[key])){var exp=expected.keyPath,act=actual.keyPath;if("string"==typeof act)return exp.toString()==act;if("function"!=typeof act.contains&&"function"!=typeof act.indexOf)return!1;if(act.length!==exp.length)return!1;for(var i=0,m=exp.length;i>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:1/0*(s?-1:1);m+=Math.pow(2,mLen),e-=eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias),value*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],40:[function(require,module,exports){"function"==typeof Object.create?module.exports=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],41:[function(require,module,exports){var Readable=require("stream").Readable;exports.getIntersectionStream=function(sortedSets){for(var s=new Readable,i=0,ii=[],k=0;ksortedSets[i+1][ii[i+1]])ii[i+1]++;else if(i+2=sortedSets[k].length&&(finished=!0);i=0}return s.push(null),s}},{stream:125}],42:[function(require,module,exports){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}module.exports=function(obj){return null!=obj&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)}},{}],43:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},{}],44:[function(require,module,exports){function isBuffer(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}var Buffer=require("buffer").Buffer;module.exports=isBuffer},{buffer:8}],45:[function(require,module,exports){function Codec(opts){this.opts=opts||{},this.encodings=encodings}var encodings=require("./lib/encodings");module.exports=Codec,Codec.prototype._encoding=function(encoding){return"string"==typeof encoding&&(encoding=encodings[encoding]),encoding||(encoding=encodings.id),encoding},Codec.prototype._keyEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&batchOpts.keyEncoding||opts&&opts.keyEncoding||this.opts.keyEncoding)},Codec.prototype._valueEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&(batchOpts.valueEncoding||batchOpts.encoding)||opts&&(opts.valueEncoding||opts.encoding)||this.opts.valueEncoding||this.opts.encoding)},Codec.prototype.encodeKey=function(key,opts,batchOpts){return this._keyEncoding(opts,batchOpts).encode(key)},Codec.prototype.encodeValue=function(value,opts,batchOpts){return this._valueEncoding(opts,batchOpts).encode(value)},Codec.prototype.decodeKey=function(key,opts){return this._keyEncoding(opts).decode(key)},Codec.prototype.decodeValue=function(value,opts){return this._valueEncoding(opts).decode(value)},Codec.prototype.encodeBatch=function(ops,opts){var self=this;return ops.map(function(_op){var op={type:_op.type,key:self.encodeKey(_op.key,opts,_op)};return self.keyAsBuffer(opts,_op)&&(op.keyEncoding="binary"),_op.prefix&&(op.prefix=_op.prefix),"value"in _op&&(op.value=self.encodeValue(_op.value,opts,_op),self.valueAsBuffer(opts,_op)&&(op.valueEncoding="binary")),op})};var ltgtKeys=["lt","gt","lte","gte","start","end"];Codec.prototype.encodeLtgt=function(ltgt){var self=this,ret={};return Object.keys(ltgt).forEach(function(key){ret[key]=ltgtKeys.indexOf(key)>-1?self.encodeKey(ltgt[key],ltgt):ltgt[key]}),ret},Codec.prototype.createStreamDecoder=function(opts){var self=this;return opts.keys&&opts.values?function(key,value){return{key:self.decodeKey(key,opts),value:self.decodeValue(value,opts)}}:opts.keys?function(key){return self.decodeKey(key,opts)}:opts.values?function(_,value){return self.decodeValue(value,opts)}:function(){}},Codec.prototype.keyAsBuffer=function(opts){return this._keyEncoding(opts).buffer},Codec.prototype.valueAsBuffer=function(opts){return this._valueEncoding(opts).buffer}},{"./lib/encodings":46}],46:[function(require,module,exports){(function(Buffer){function identity(value){return value}function isBinary(data){return void 0===data||null===data||Buffer.isBuffer(data)}exports.utf8=exports["utf-8"]={encode:function(data){return isBinary(data)?data:String(data)},decode:identity,buffer:!1,type:"utf8"},exports.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},exports.binary={encode:function(data){return isBinary(data)?data:new Buffer(data)},decode:identity,buffer:!0,type:"binary"},exports.id={encode:function(data){return data},decode:function(data){return data},buffer:!1,type:"id"},["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"].forEach(function(type){exports[type]={encode:function(data){return isBinary(data)?data:new Buffer(data,type)},decode:function(buffer){return buffer.toString(type)},buffer:!0,type:type}})}).call(this,require("buffer").Buffer)},{buffer:8}],47:[function(require,module,exports){var createError=require("errno").create,LevelUPError=createError("LevelUPError"),NotFoundError=createError("NotFoundError",LevelUPError);NotFoundError.prototype.notFound=!0,NotFoundError.prototype.status=404,module.exports={LevelUPError:LevelUPError,InitializationError:createError("InitializationError",LevelUPError),OpenError:createError("OpenError",LevelUPError),ReadError:createError("ReadError",LevelUPError),WriteError:createError("WriteError",LevelUPError),NotFoundError:NotFoundError,EncodingError:createError("EncodingError",LevelUPError)}},{errno:35}],48:[function(require,module,exports){function ReadStream(iterator,options){if(!(this instanceof ReadStream))return new ReadStream(iterator,options);Readable.call(this,extend(options,{objectMode:!0})),this._iterator=iterator,this._destroyed=!1,this._decoder=null,options&&options.decoder&&(this._decoder=options.decoder),this.on("end",this._cleanup.bind(this))}var inherits=require("inherits"),Readable=require("readable-stream").Readable,extend=require("xtend"),EncodingError=require("level-errors").EncodingError;module.exports=ReadStream,inherits(ReadStream,Readable),ReadStream.prototype._read=function(){var self=this;this._destroyed||this._iterator.next(function(err,key,value){if(!self._destroyed){if(err)return self.emit("error",err);if(void 0===key&&void 0===value)self.push(null);else{if(!self._decoder)return self.push({key:key,value:value});try{var value=self._decoder(key,value)}catch(err){return self.emit("error",new EncodingError(err)),void self.push(null)}self.push(value)}}})},ReadStream.prototype.destroy=ReadStream.prototype._cleanup=function(){var self=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(err){if(err)return self.emit("error",err);self.emit("close")}))}},{inherits:40,"level-errors":47,"readable-stream":55,xtend:136}],49:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],50:[function(require,module,exports){(function(process){function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),options&&!1===options.readable&&(this.readable=!1),options&&!1===options.writable&&(this.writable=!1),this.allowHalfOpen=!0,options&&!1===options.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",onend)}function onend(){this.allowHalfOpen||this._writableState.ended||process.nextTick(this.end.bind(this))}module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys},util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable),function(xs,f){for(var i=0,l=xs.length;i0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk)),addToFront||(state.reading=!1),state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state);else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM)n=MAX_HWM;else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:isNaN(n)||util.isNull(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:n<=0?0:(n>state.highWaterMark&&(state.highWaterMark=roundUpToNextPowerOf2(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return util.isBuffer(chunk)||util.isString(chunk)||util.isNullOrUndefined(chunk)||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?process.nextTick(function(){emitReadable_(stream)}):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(function(){maybeReadMore_(stream,state)}))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=length)ret=stringMode?list.join(""):Buffer.concat(list,length),list.length=0;else if(n0)throw new Error("endReadable called on non-empty stream");state.endEmitted||(state.ended=!0,process.nextTick(function(){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}))}function forEach(xs,f){for(var i=0,l=xs.length;i0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,util.isNull(ret)&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&0===state.length&&endReadable(this),util.isNull(ret)||this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",cleanup),src.removeListener("data",ondata),!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),!1===dest.write(chunk)&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EE.listenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);return dest.on("drain",ondrain),src.on("data",ondata),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i1){for(var cbs=[],c=0;c=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived=55296&&charCode<=56319)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},{buffer:8}],57:[function(require,module,exports){(function(Buffer){function Level(location){if(!(this instanceof Level))return new Level(location);if(!location)throw new Error("constructor requires at least a location argument");this.IDBOptions={},this.location=location}module.exports=Level;var IDB=require("idb-wrapper"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,util=require("util"),Iterator=require("./iterator"),isBuffer=require("isbuffer"),xtend=require("xtend"),toBuffer=require("typedarray-to-buffer");util.inherits(Level,AbstractLevelDOWN),Level.prototype._open=function(options,callback){var self=this,idbOpts={storeName:this.location,autoIncrement:!1,keyPath:null,onStoreReady:function(){callback&&callback(null,self.idb)},onError:function(err){callback&&callback(err)}};xtend(idbOpts,options),this.IDBOptions=idbOpts,this.idb=new IDB(idbOpts)},Level.prototype._get=function(key,options,callback){this.idb.get(key,function(value){if(void 0===value)return callback(new Error("NotFound"));var asBuffer=!0;return!1===options.asBuffer&&(asBuffer=!1),options.raw&&(asBuffer=!1),asBuffer&&(value=value instanceof Uint8Array?toBuffer(value):new Buffer(String(value))),callback(null,value,key)},callback)},Level.prototype._del=function(id,options,callback){this.idb.remove(id,callback,callback)},Level.prototype._put=function(key,value,options,callback){value instanceof ArrayBuffer&&(value=toBuffer(new Uint8Array(value)));var obj=this.convertEncoding(key,value,options);Buffer.isBuffer(obj.value)&&("function"==typeof value.toArrayBuffer?obj.value=new Uint8Array(value.toArrayBuffer()):obj.value=new Uint8Array(value)),this.idb.put(obj.key,obj.value,function(){callback()},callback)},Level.prototype.convertEncoding=function(key,value,options){if(options.raw)return{key:key,value:value};if(value){var stringed=value.toString();"NaN"===stringed&&(value="NaN")}var valEnc=options.valueEncoding,obj={key:key,value:value};return!value||valEnc&&"binary"===valEnc||"object"!=typeof obj.value&&(obj.value=stringed),obj},Level.prototype.iterator=function(options){return"object"!=typeof options&&(options={}),new Iterator(this.idb,options)},Level.prototype._batch=function(array,options,callback){var i,k,copiedOp,currentOp,modified=[];if(0===array.length)return setTimeout(callback,0);for(i=0;i0&&this._count++>=this._limit&&(shouldCall=!1),shouldCall&&this.callback(!1,cursor.key,cursor.value),cursor&&cursor.continue()},Iterator.prototype._next=function(callback){return callback?this._keyRangeError?callback():(this._started||(this.createIterator(),this._started=!0),void(this.callback=callback)):new Error("next() requires a callback argument")}},{"abstract-leveldown":61,ltgt:79,util:134}],59:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;if(err=this._db._checkKeyValue(value,"value",this._db._isBuffer))throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:84}],60:[function(require,module,exports){arguments[4][14][0].apply(exports,arguments)},{_process:84,dup:14}],61:[function(require,module,exports){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");if("object"!=typeof options&&(options={}),"function"==typeof this._open)return this._open(options,callback);process.nextTick(callback)},AbstractLevelDOWN.prototype.close=function(callback){if("function"!=typeof callback)throw new Error("close() requires a callback argument");if("function"==typeof this._close)return this._close(callback);process.nextTick(callback)},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(err=this._checkKeyValue(value,"value",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));"object"!=typeof options&&(options={});for(var e,err,i=0,l=array.length;i2?arguments[2]:null;if(l===+l)for(i=0;i=0&&"[object Function]"===toString.call(value.callee)),isArguments}},{}],66:[function(require,module,exports){!function(){"use strict";var keysShim,has=Object.prototype.hasOwnProperty,toString=Object.prototype.toString,forEach=require("./foreach"),isArgs=require("./isArguments"),hasDontEnumBug=!{toString:null}.propertyIsEnumerable("toString"),hasProtoEnumBug=function(){}.propertyIsEnumerable("prototype"),dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];keysShim=function(object){var isObject=null!==object&&"object"==typeof object,isFunction="[object Function]"===toString.call(object),isArguments=isArgs(object),theKeys=[];if(!isObject&&!isFunction&&!isArguments)throw new TypeError("Object.keys called on a non-object");if(isArguments)forEach(object,function(value){theKeys.push(value)});else{var name,skipProto=hasProtoEnumBug&&isFunction;for(name in object)skipProto&&"prototype"===name||!has.call(object,name)||theKeys.push(name)}if(hasDontEnumBug){var ctor=object.constructor,skipConstructor=ctor&&ctor.prototype===object;forEach(dontEnums,function(dontEnum){skipConstructor&&"constructor"===dontEnum||!has.call(object,dontEnum)||theKeys.push(dontEnum)})}return theKeys},module.exports=keysShim}()},{"./foreach":63,"./isArguments":65}],67:[function(require,module,exports){function hasKeys(source){return null!==source&&("object"==typeof source||"function"==typeof source)}module.exports=hasKeys},{}],68:[function(require,module,exports){function extend(){for(var target={},i=0;i-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){return!(!isObject(value)||isMasked(value))&&(isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor).test(toSource(value))}function getMapData(map,key){var data=map.__data__;return isKeyable(key)?data["string"==typeof key?"string":"hash"]:data.map}function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:void 0}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function toSource(func){if(null!=func){try{return funcToString.call(func)}catch(e){}try{return func+""}catch(e){}}return""}function eq(value,other){return value===other||value!==value&&other!==other}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var difference=function(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=120&&array.length>=120)?new SetCache(othIndex&&array):void 0}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}var HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),splice=arrayProto.splice,nativeMax=Math.max,nativeMin=Math.min,Map=getNative(root,"Map"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var intersection=function(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=null==entries?0:entries.length;for(this.clear();++indexarrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&COMPARE_UNORDERED_FLAG?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index-1&&value%1==0&&value-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function stubArray(){return[]}function stubFalse(){return!1}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2,MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",arrayTag="[object Array]",asyncTag="[object AsyncFunction]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",nullTag="[object Null]",objectTag="[object Object]",proxyTag="[object Proxy]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",undefinedTag="[object Undefined]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags["[object Float32Array]"]=typedArrayTags["[object Float64Array]"]=typedArrayTags["[object Int8Array]"]=typedArrayTags["[object Int16Array]"]=typedArrayTags["[object Int32Array]"]=typedArrayTags["[object Uint8Array]"]=typedArrayTags["[object Uint8ClampedArray]"]=typedArrayTags["[object Uint16Array]"]=typedArrayTags["[object Uint32Array]"]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags["[object WeakMap]"]=!1;var freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),nativeObjectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Buffer=moduleExports?root.Buffer:void 0,Symbol=root.Symbol,Uint8Array=root.Uint8Array,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,symToStringTag=Symbol?Symbol.toStringTag:void 0,nativeGetSymbols=Object.getOwnPropertySymbols,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),DataView=getNative(root,"DataView"),Map=getNative(root,"Map"),Promise=getNative(root,"Promise"),Set=getNative(root,"Set"),WeakMap=getNative(root,"WeakMap"),nativeCreate=getNative(Object,"create"),dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap),symbolProto=Symbol?Symbol.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0;Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas,Stack.prototype.clear=stackClear,Stack.prototype.delete=stackDelete,Stack.prototype.get=stackGet,Stack.prototype.has=stackHas,Stack.prototype.set=stackSet;var getSymbols=nativeGetSymbols?function(object){return null==object?[]:(object=Object(object),arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol)}))}:stubArray,getTag=baseGetTag;(DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag||Map&&getTag(new Map)!=mapTag||Promise&&"[object Promise]"!=getTag(Promise.resolve())||Set&&getTag(new Set)!=setTag||WeakMap&&"[object WeakMap]"!=getTag(new WeakMap))&&(getTag=function(value){var result=baseGetTag(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):"";if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return"[object Promise]";case setCtorString:return setTag;case weakMapCtorString:return"[object WeakMap]"}return result});var isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isBuffer=nativeIsBuffer||stubFalse,isTypedArray=nodeIsTypedArray?function(func){return function(value){return func(value)}}(nodeIsTypedArray):baseIsTypedArray;module.exports=isEqual}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],75:[function(require,module,exports){function baseSortedIndex(array,value,retHighest){var low=0,high=array?array.length:low;if("number"==typeof value&&value===value&&high<=HALF_MAX_ARRAY_LENGTH){for(;low>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computedlength?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=length?array:baseSlice(array,start,end)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=void 0===start?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toFinite(value){if(!value)return 0===value?value:0;if((value=toNumber(value))===INFINITY||value===-INFINITY){return(value<0?-1:1)*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}var FUNC_ERROR_TEXT="Expected a function",INFINITY=1/0,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,symbolTag="[object Symbol]",reTrim=/^\s+|\s+$/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt,objectProto=Object.prototype,objectToString=objectProto.toString,nativeMax=Math.max;module.exports=spread},{}],77:[function(require,module,exports){(function(global){function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayIncludes(array,value){return!!(array?array.length:0)&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){return!(!isObject(value)||isMasked(value))&&(isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor).test(toSource(value))}function baseUniq(array,iteratee,comparator){var index=-1,includes=arrayIncludes,length=array.length,isCommon=!0,result=[],seen=result;if(comparator)isCommon=!1,includes=arrayIncludesWith;else if(length>=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}function noop(){}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),Set=getNative(root,"Set"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:noop,union=function(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexb?1:0};var lowerBoundKey=exports.lowerBoundKey=function(range){return hasKey(range,"gt")||hasKey(range,"gte")||hasKey(range,"min")||(range.reverse?hasKey(range,"end"):hasKey(range,"start"))||void 0},lowerBound=exports.lowerBound=function(range,def){var k=lowerBoundKey(range);return k?range[k]:def},lowerBoundInclusive=exports.lowerBoundInclusive=function(range){return!has(range,"gt")},upperBoundInclusive=exports.upperBoundInclusive=function(range){return!has(range,"lt")},lowerBoundExclusive=exports.lowerBoundExclusive=function(range){return!lowerBoundInclusive(range)},upperBoundExclusive=exports.upperBoundExclusive=function(range){return!upperBoundInclusive(range)},upperBoundKey=exports.upperBoundKey=function(range){return hasKey(range,"lt")||hasKey(range,"lte")||hasKey(range,"max")||(range.reverse?hasKey(range,"start"):hasKey(range,"end"))||void 0},upperBound=exports.upperBound=function(range,def){var k=upperBoundKey(range);return k?range[k]:def};exports.start=function(range,def){return range.reverse?upperBound(range,def):lowerBound(range,def)},exports.end=function(range,def){return range.reverse?lowerBound(range,def):upperBound(range,def)},exports.startInclusive=function(range){return range.reverse?upperBoundInclusive(range):lowerBoundInclusive(range)},exports.endInclusive=function(range){return range.reverse?lowerBoundInclusive(range):upperBoundInclusive(range)},exports.toLtgt=function(range,_range,map,lower,upper){_range=_range||{},map=map||id;var defaults=arguments.length>3,lb=exports.lowerBoundKey(range),ub=exports.upperBoundKey(range);return lb?"gt"===lb?_range.gt=map(range.gt,!1):_range.gte=map(range[lb],!1):defaults&&(_range.gte=map(lower,!1)),ub?"lt"===ub?_range.lt=map(range.lt,!0):_range.lte=map(range[ub],!0):defaults&&(_range.lte=map(upper,!0)),null!=range.reverse&&(_range.reverse=!!range.reverse),has(_range,"max")&&delete _range.max,has(_range,"min")&&delete _range.min,has(_range,"start")&&delete _range.start,has(_range,"end")&&delete _range.end,_range},exports.contains=function(range,key,compare){compare=compare||exports.compare;var lb=lowerBound(range);if(isDef(lb)){var cmp=compare(key,lb);if(cmp<0||0===cmp&&lowerBoundExclusive(range))return!1}var ub=upperBound(range);if(isDef(ub)){var cmp=compare(key,ub);if(cmp>0||0===cmp&&upperBoundExclusive(range))return!1}return!0},exports.filter=function(range,compare){return function(key){return exports.contains(range,key,compare)}}}).call(this,{isBuffer:require("../is-buffer/index.js")})},{"../is-buffer/index.js":42}],80:[function(require,module,exports){const getNGramsOfMultipleLengths=function(inputArray,nGramLengths){var outputArray=[];return nGramLengths.forEach(function(len){outputArray=outputArray.concat(getNGramsOfSingleLength(inputArray,len))}),outputArray},getNGramsOfRangeOfLengths=function(inputArray,nGramLengths){for(var outputArray=[],i=nGramLengths.gte;i<=nGramLengths.lte;i++)outputArray=outputArray.concat(getNGramsOfSingleLength(inputArray,i));return outputArray},getNGramsOfSingleLength=function(inputArray,nGramLength){return inputArray.slice(nGramLength-1).map(function(item,i){return inputArray.slice(i,i+nGramLength)})};exports.ngram=function(inputArray,nGramLength){switch(nGramLength.constructor){case Array: -return getNGramsOfMultipleLengths(inputArray,nGramLength);case Number:return getNGramsOfSingleLength(inputArray,nGramLength);case Object:return getNGramsOfRangeOfLengths(inputArray,nGramLength)}}},{}],81:[function(require,module,exports){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}function onceStrict(fn){var f=function(){if(f.called)throw new Error(f.onceError);return f.called=!0,f.value=fn.apply(this,arguments)},name=fn.name||"Function wrapped with `once`";return f.onceError=name+" shouldn't be called more than once",f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),module.exports.strict=wrappy(onceStrict),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:!0})})},{wrappy:135}],82:[function(require,module,exports){exports.endianness=function(){return"LE"},exports.hostname=function(){return"undefined"!=typeof location?location.hostname:""},exports.loadavg=function(){return[]},exports.uptime=function(){return 0},exports.freemem=function(){return Number.MAX_VALUE},exports.totalmem=function(){return Number.MAX_VALUE},exports.cpus=function(){return[]},exports.type=function(){return"Browser"},exports.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},exports.networkInterfaces=exports.getNetworkInterfaces=function(){return{}},exports.arch=function(){return"javascript"},exports.platform=function(){return"browser"},exports.tmpdir=exports.tmpDir=function(){return"/tmp"},exports.EOL="\n"},{}],83:[function(require,module,exports){(function(process){"use strict";function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function(){fn.call(null,arg1)});case 3:return process.nextTick(function(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;i1)for(var i=1;i0,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})});return streams.reduce(pipe)};module.exports=pump},{"end-of-stream":33,fs:6,once:81}],87:[function(require,module,exports){var pump=require("pump"),inherits=require("inherits"),Duplexify=require("duplexify"),toArray=function(args){return args.length?Array.isArray(args[0])?args[0]:Array.prototype.slice.call(args):[]},define=function(opts){var Pumpify=function(){var streams=toArray(arguments);if(!(this instanceof Pumpify))return new Pumpify(streams);Duplexify.call(this,null,null,opts),streams.length&&this.setPipeline(streams)};return inherits(Pumpify,Duplexify),Pumpify.prototype.setPipeline=function(){var streams=toArray(arguments),self=this,ended=!1,w=streams[0],r=streams[streams.length-1];r=r.readable?r:null,w=w.writable?w:null;var onclose=function(){streams[0].emit("error",new Error("stream was destroyed"))};if(this.on("close",onclose),this.on("prefinish",function(){ended||self.cork()}),pump(streams,function(err){if(self.removeListener("close",onclose),err)return self.destroy(err);ended=!0,self.uncork()}),this.destroyed)return onclose();this.setWritable(w),this.setReadable(r)},Pumpify};module.exports=define({destroy:!1}),module.exports.obj=define({destroy:!1,objectMode:!0,highWaterMark:16})},{duplexify:30,inherits:40,pump:86}],88:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":89}],89:[function(require,module,exports){"use strict";function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),options&&!1===options.readable&&(this.readable=!1),options&&!1===options.writable&&(this.writable=!1),this.allowHalfOpen=!0,options&&!1===options.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",onend)}function onend(){this.allowHalfOpen||this._writableState.ended||processNextTick(onEndNT,this)}function onEndNT(self){self.end()}var processNextTick=require("process-nextick-args"),objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v0?("string"==typeof chunk||Object.getPrototypeOf(chunk)===Buffer.prototype||state.objectMode||(chunk=_uint8ArrayToBuffer(chunk)),addToFront?state.endEmitted?stream.emit("error",new Error("stream.unshift() after end event")):addChunk(stream,state,chunk,!0):state.ended?stream.emit("error",new Error("stream.push() after EOF")):(state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1))):addToFront||(state.reading=!1)}return needMoreData(state)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(nb===str.length?ret+=str:ret+=str.slice(0,n),0===(n-=nb)){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=Buffer.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),0===(n-=nb)){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1,!1!==dest.write(chunk)||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:unpipe;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("safe-buffer").Buffer,destroyImpl=require("./internal/streams/destroy");util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=_isUint8Array(chunk)&&!state.objectMode;return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)},Object.defineProperty(Writable.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){this.end(),cb(err)}}).call(this,require("_process"))},{"./_stream_duplex":89,"./internal/streams/destroy":95,"./internal/streams/stream":96,_process:84,"core-util-is":10,inherits:40,"process-nextick-args":83,"safe-buffer":101,"util-deprecate":131}],94:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function copyBuffer(src,target,offset){src.copy(target,offset)}var Buffer=require("safe-buffer").Buffer;module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return Buffer.alloc(0);if(1===this.length)return this.head.data;for(var ret=Buffer.allocUnsafe(n>>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret},BufferList}()},{"safe-buffer":101}],95:[function(require,module,exports){"use strict";function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;if(readableDestroyed||writableDestroyed)return void(cb?cb(err):!err||this._writableState&&this._writableState.errorEmitted||processNextTick(emitErrorNT,this,err));this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?(processNextTick(emitErrorNT,_this,err),_this._writableState&&(_this._writableState.errorEmitted=!0)):cb&&cb(err)})}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(self,err){self.emit("error",err)}var processNextTick=require("process-nextick-args");module.exports={destroy:destroy,undestroy:undestroy}},{"process-nextick-args":83}],96:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:37}],97:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":98}],98:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":89,"./lib/_stream_passthrough.js":90,"./lib/_stream_readable.js":91,"./lib/_stream_transform.js":92,"./lib/_stream_writable.js":93}],99:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":98}],100:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":93}],101:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0!==fill?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:8}],102:[function(require,module,exports){function throwsMessage(err){return"[Throws: "+(err?err.message:"?")+"]"}function safeGetValueFromPropertyOnObject(obj,property){if(hasProp.call(obj,property))try{return obj[property]}catch(err){return throwsMessage(err)}return obj[property]}function ensureProperties(obj){function visit(obj){if(null===obj||"object"!=typeof obj)return obj;if(-1!==seen.indexOf(obj))return"[Circular]";if(seen.push(obj),"function"==typeof obj.toJSON)try{return visit(obj.toJSON())}catch(err){return throwsMessage(err)}return Array.isArray(obj)?obj.map(visit):Object.keys(obj).reduce(function(result,prop){return result[prop]=visit(safeGetValueFromPropertyOnObject(obj,prop)),result},{})}var seen=[];return visit(obj)}var hasProp=Object.prototype.hasOwnProperty;module.exports=function(data){return JSON.stringify(ensureProperties(data))},module.exports.ensureProperties=ensureProperties},{}],103:[function(require,module,exports){const DBEntries=require("./lib/delete.js").DBEntries,DBWriteCleanStream=require("./lib/replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./lib/replicate.js").DBWriteMergeStream,DocVector=require("./lib/delete.js").DocVector,IndexBatch=require("./lib/add.js").IndexBatch,Readable=require("stream").Readable,RecalibrateDB=require("./lib/delete.js").RecalibrateDB,bunyan=require("bunyan"),del=require("./lib/delete.js"),docProc=require("docproc"),levelup=require("levelup"),pumpify=require("pumpify"),async=require("async");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){var Indexer={};Indexer.options=options;var q=async.queue(function(batch,done){var s;"add"===batch.operation?(s=new Readable({objectMode:!0}),batch.batch.forEach(function(doc){s.push(doc)}),s.push(null),s.pipe(Indexer.defaultPipeline(batch.batchOps)).pipe(Indexer.add()).on("finish",function(){return done()}).on("error",function(err){return done(err)})):"delete"===batch.operation&&(s=new Readable,batch.docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)}))},1);return Indexer.add=function(){return pumpify.obj(new IndexBatch(Indexer),new DBWriteMergeStream(options))},Indexer.concurrentAdd=function(batchOps,batch,done){q.push({batch:batch,batchOps:batchOps,operation:"add"},function(err){done(err)})},Indexer.concurrentDel=function(docIds,done){q.push({docIds:docIds,operation:"delete"},function(err){done(err)})},Indexer.close=function(callback){options.indexes.close(function(err){for(;!options.indexes.isClosed();)options.log.debug("closing...");options.indexes.isClosed()&&(options.log.debug("closed..."),callback(err))})},Indexer.dbWriteStream=function(streamOps){return streamOps=Object.assign({},{merge:!0},streamOps),streamOps.merge?new DBWriteMergeStream(options):new DBWriteCleanStream(options)},Indexer.defaultPipeline=function(batchOptions){return batchOptions=Object.assign({},options,batchOptions),docProc.pipeline(batchOptions)},Indexer.deleteStream=function(options){return pumpify.obj(new DocVector(options),new DBEntries(options),new RecalibrateDB(options))},Indexer.deleter=function(docIds,done){const s=new Readable;docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)})},Indexer.flush=function(APICallback){del.flush(options,function(err){return APICallback(err)})},callback(err,Indexer)})};const getOptions=function(options,done){if(options=Object.assign({},{deletable:!0,batchSize:1e3,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,searchable:!0,indexPath:"si",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/\s|\\n|\\u0003|[-.,<>]/,stopwords:[],weight:0},options),options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes)done(null,options);else{const leveldown=require("leveldown");levelup(options.indexPath||"si",{valueEncoding:"json",db:leveldown},function(err,db){options.indexes=db,done(err,options)})}}},{"./lib/add.js":104,"./lib/delete.js":105,"./lib/replicate.js":106,async:4,bunyan:9,docproc:18,leveldown:57,levelup:70,pumpify:87,stream:125}],104:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),emitIndexKeys=function(s){for(var key in s.deltaIndex)s.push({key:key,value:s.deltaIndex[key]});s.deltaIndex={}},IndexBatch=function(indexer){this.indexer=indexer,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.indexer.options.keySeparator;var that=this;this.indexer.deleter([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.indexer.options.log.info("processing doc "+ingestedDoc.id),that.deltaIndex["DOCUMENT"+sep+ingestedDoc.id+sep]=ingestedDoc.stored;for(var fieldName in ingestedDoc.vector){that.deltaIndex["FIELD"+sep+fieldName]=fieldName;for(var token in ingestedDoc.vector[fieldName]){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token,dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id]),that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.deltaIndex["DOCUMENT-VECTOR"+sep+ingestedDoc.id+sep+fieldName+sep]=ingestedDoc.vector[fieldName]}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.indexer.options.batchSize&&(that.push({totalKeys:totalKeys}),that.indexer.options.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:125,util:134}],105:[function(require,module,exports){const util=require("util"),Transform=require("stream").Transform;exports.flush=function(options,callback){const sep=options.keySeparator;var deleteOps=[];options.indexes.createKeyStream({gte:"0",lte:sep}).on("data",function(data){deleteOps.push({type:"del",key:data})}).on("error",function(err){return options.log.error(err," failed to empty index"),callback(err)}).on("end",function(){options.indexes.batch(deleteOps,callback)})};const DocVector=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DocVector=DocVector,util.inherits(DocVector,Transform),DocVector.prototype._transform=function(docId,encoding,end){docId=JSON.parse(docId);const sep=this.options.keySeparator;var that=this;this.options.indexes.createReadStream({gte:"DOCUMENT-VECTOR"+sep+docId+sep,lte:"DOCUMENT-VECTOR"+sep+docId+sep+sep}).on("data",function(data){that.push(data)}).on("close",function(){return end()})};const DBEntries=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DBEntries=DBEntries,util.inherits(DBEntries,Transform),DBEntries.prototype._transform=function(vector,encoding,end){const sep=this.options.keySeparator;var docId;for(var k in vector.value){docId=vector.key.split(sep)[1];var field=vector.key.split(sep)[2];this.push({key:"TF"+sep+field+sep+k,value:docId}),this.push({key:"DF"+sep+field+sep+k,value:docId})}return this.push({key:vector.key}),this.push({key:"DOCUMENT"+sep+docId+sep}),end()};const RecalibrateDB=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.RecalibrateDB=RecalibrateDB,util.inherits(RecalibrateDB,Transform),RecalibrateDB.prototype._transform=function(dbEntry,encoding,end){const sep=this.options.keySeparator;var that=this;this.options.indexes.get(dbEntry.key,function(err,value){err&&that.options.log.info(err),value||(value=[]);var docId=dbEntry.value,dbInstruction={};dbInstruction.key=dbEntry.key,dbEntry.key.substring(0,3)==="TF"+sep?(dbInstruction.value=value.filter(function(item){return item[1]!==docId}),0===dbInstruction.value.length?dbInstruction.type="del":dbInstruction.type="put"):dbEntry.key.substring(0,3)==="DF"+sep?(value.splice(value.indexOf(docId),1),dbInstruction.value=value,0===dbInstruction.value.length?dbInstruction.type="del":dbInstruction.type="put"):dbEntry.key.substring(0,9)==="DOCUMENT"+sep?dbInstruction.type="del":dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep&&(dbInstruction.type="del"),that.options.indexes.batch([dbInstruction],function(err){return end()})})}},{stream:125,util:134}],106:[function(require,module,exports){const Transform=require("stream").Transform,Writable=require("stream").Writable,util=require("util"),DBWriteMergeStream=function(options){this.options=options,Writable.call(this,{objectMode:!0})};exports.DBWriteMergeStream=DBWriteMergeStream,util.inherits(DBWriteMergeStream,Writable),DBWriteMergeStream.prototype._write=function(data,encoding,end){if(data.totalKeys)return end();const sep=this.options.keySeparator;var that=this;this.options.indexes.get(data.key,function(err,val){var newVal;newVal=data.key.substring(0,3)==="TF"+sep?data.value.concat(val||[]).sort(function(a,b){return a[0]b[0]?-1:a[1]b[1]?-1:0}):data.key.substring(0,3)==="DF"+sep?data.value.concat(val||[]).sort():"DOCUMENT-COUNT"===data.key?+val+(+data.value||0):data.value,that.options.indexes.put(data.key,newVal,function(err){end()})})};const DBWriteCleanStream=function(options){this.currentBatch=[],this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(DBWriteCleanStream,Transform),DBWriteCleanStream.prototype._transform=function(data,encoding,end){var that=this;this.currentBatch.push(data),this.currentBatch.length%this.options.batchSize==0?this.options.indexes.batch(this.currentBatch,function(err){that.push("indexing batch"),that.currentBatch=[],end()}):end()},DBWriteCleanStream.prototype._flush=function(end){var that=this;this.options.indexes.batch(this.currentBatch,function(err){that.push("remaining data indexed"),end()})},exports.DBWriteCleanStream=DBWriteCleanStream},{stream:125,util:134}],107:[function(require,module,exports){const AvailableFields=require("./lib/AvailableFields.js").AvailableFields,CalculateBuckets=require("./lib/CalculateBuckets.js").CalculateBuckets,CalculateCategories=require("./lib/CalculateCategories.js").CalculateCategories,CalculateEntireResultSet=require("./lib/CalculateEntireResultSet.js").CalculateEntireResultSet,CalculateResultSetPerClause=require("./lib/CalculateResultSetPerClause.js").CalculateResultSetPerClause,CalculateTopScoringDocs=require("./lib/CalculateTopScoringDocs.js").CalculateTopScoringDocs,CalculateTotalHits=require("./lib/CalculateTotalHits.js").CalculateTotalHits,Classify=require("./lib/Classify.js").Classify,FetchDocsFromDB=require("./lib/FetchDocsFromDB.js").FetchDocsFromDB,FetchStoredDoc=require("./lib/FetchStoredDoc.js").FetchStoredDoc,GetIntersectionStream=require("./lib/GetIntersectionStream.js").GetIntersectionStream,MergeOrConditions=require("./lib/MergeOrConditions.js").MergeOrConditions,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,SortTopScoringDocs=require("./lib/SortTopScoringDocs.js").SortTopScoringDocs,bunyan=require("bunyan"),levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),initModule=function(err,Searcher,moduleReady){return Searcher.bucketStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateBuckets(Searcher.options,q.filter||{},q.buckets))},Searcher.categoryStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateCategories(Searcher.options,q))},Searcher.classify=function(ops){return new Classify(Searcher,ops)},Searcher.close=function(callback){Searcher.options.indexes.close(function(err){for(;!Searcher.options.indexes.isClosed();)Searcher.options.log.debug("closing...");Searcher.options.indexes.isClosed()&&(Searcher.options.log.debug("closed..."),callback(err))})},Searcher.availableFields=function(){const sep=Searcher.options.keySeparator;return Searcher.options.indexes.createReadStream({gte:"FIELD"+sep,lte:"FIELD"+sep+sep}).pipe(new AvailableFields(Searcher.options))},Searcher.get=function(docIDs){var s=new Readable({objectMode:!0});return docIDs.forEach(function(id){s.push(id)}),s.push(null),s.pipe(new FetchDocsFromDB(Searcher.options))},Searcher.fieldNames=function(){return Searcher.options.indexes.createReadStream({gte:"FIELD",lte:"FIELD"})},Searcher.match=function(q){return matcher.match(q,Searcher.options)},Searcher.dbReadStream=function(){return Searcher.options.indexes.createReadStream()},Searcher.search=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),q.sort?s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options)):s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreTopScoringDocsTFIDF(Searcher.options)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options))},Searcher.scan=function(q){q=siUtil.getQueryDefaults(q);var s=new Readable({objectMode:!0});return s.push("init"),s.push(null),s.pipe(new GetIntersectionStream(Searcher.options,siUtil.getKeySet(q.query[0].AND,Searcher.options.keySeparator))).pipe(new FetchDocsFromDB(Searcher.options))},Searcher.totalHits=function(q,callback){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateTotalHits(Searcher.options)).on("data",function(totalHits){return callback(null,totalHits)})},moduleReady(err,Searcher)},getOptions=function(options,done){var Searcher={};if(Searcher.options=Object.assign({},{deletable:!0,fieldedSearch:!0,store:!0,indexPath:"si",keySeparator:"○",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/[|' .,\-|(\n)]+/,stopwords:[]},options),Searcher.options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes)return done(null,Searcher);levelup(Searcher.options.indexPath||"si",{valueEncoding:"json"},function(err,db){return Searcher.options.indexes=db,done(err,Searcher)})};module.exports=function(givenOptions,moduleReady){getOptions(givenOptions,function(err,Searcher){initModule(err,Searcher,moduleReady)})}},{"./lib/AvailableFields.js":108,"./lib/CalculateBuckets.js":109,"./lib/CalculateCategories.js":110,"./lib/CalculateEntireResultSet.js":111,"./lib/CalculateResultSetPerClause.js":112,"./lib/CalculateTopScoringDocs.js":113,"./lib/CalculateTotalHits.js":114,"./lib/Classify.js":115,"./lib/FetchDocsFromDB.js":116,"./lib/FetchStoredDoc.js":117,"./lib/GetIntersectionStream.js":118,"./lib/MergeOrConditions.js":119,"./lib/ScoreDocsOnField.js":120,"./lib/ScoreTopScoringDocsTFIDF.js":121,"./lib/SortTopScoringDocs.js":122,"./lib/matcher.js":123,"./lib/siUtil.js":124,bunyan:9,levelup:70,stream:125}],108:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),AvailableFields=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.AvailableFields=AvailableFields,util.inherits(AvailableFields,Transform),AvailableFields.prototype._transform=function(field,encoding,end){return this.push(field.key.split(this.options.keySeparator)[1]),end()}},{stream:125,util:134}],109:[function(require,module,exports){const _intersection=require("lodash.intersection"),_uniq=require("lodash.uniq"),Transform=require("stream").Transform,util=require("util"),CalculateBuckets=function(options,filter,requestedBuckets){this.buckets=requestedBuckets||[],this.filter=filter,this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateBuckets=CalculateBuckets,util.inherits(CalculateBuckets,Transform),CalculateBuckets.prototype._transform=function(mergedQueryClauses,encoding,end){const that=this,sep=this.options.keySeparator;var bucketsProcessed=0;that.buckets.forEach(function(bucket){const gte="DF"+sep+bucket.field+sep+bucket.gte,lte="DF"+sep+bucket.field+sep+bucket.lte+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){var IDSet=_intersection(data.value,mergedQueryClauses.set);IDSet.length>0&&(bucket.value=bucket.value||[],bucket.value=_uniq(bucket.value.concat(IDSet).sort()))}).on("close",function(){if(bucket.set||(bucket.value=bucket.value.length),that.push(bucket),++bucketsProcessed===that.buckets.length)return end()})})}},{"lodash.intersection":73,"lodash.uniq":78,stream:125,util:134}],110:[function(require,module,exports){const _intersection=require("lodash.intersection"),Transform=require("stream").Transform,util=require("util"),CalculateCategories=function(options,q){var category=q.category||[];category.values=[],this.offset=+q.offset,this.pageSize=+q.pageSize,this.category=category,this.options=options,this.query=q.query,Transform.call(this,{objectMode:!0})};exports.CalculateCategories=CalculateCategories,util.inherits(CalculateCategories,Transform),CalculateCategories.prototype._transform=function(mergedQueryClauses,encoding,end){if(!this.category.field)return end(new Error("you need to specify a category"));const sep=this.options.keySeparator,that=this,gte="DF"+sep+this.category.field+sep,lte="DF"+sep+this.category.field+sep+sep;this.category.values=this.category.values||[];var i=this.offset+this.pageSize,j=0;const rs=that.options.indexes.createReadStream({gte:gte,lte:lte});rs.on("data",function(data){if(!(that.offset>j++)){var IDSet=_intersection(data.value,mergedQueryClauses.set);if(IDSet.length>0){var key=data.key.split(sep)[2],value=IDSet.length;that.category.set&&(value=IDSet);var result={key:key,value:value};if(1===that.query.length)try{that.query[0].AND[that.category.field].indexOf(key)>-1&&(result.filter=!0)}catch(e){}i-- >that.offset?that.push(result):rs.destroy()}}}).on("close",function(){return end()})}},{"lodash.intersection":73,stream:125,util:134}],111:[function(require,module,exports){const Transform=require("stream").Transform,_union=require("lodash.union"),util=require("util"),CalculateEntireResultSet=function(options){this.options=options,this.setSoFar=[],Transform.call(this,{objectMode:!0})};exports.CalculateEntireResultSet=CalculateEntireResultSet,util.inherits(CalculateEntireResultSet,Transform),CalculateEntireResultSet.prototype._transform=function(queryClause,encoding,end){return this.setSoFar=_union(queryClause.set,this.setSoFar),end()},CalculateEntireResultSet.prototype._flush=function(end){return this.push({set:this.setSoFar}),end()}},{"lodash.union":77,stream:125,util:134}],112:[function(require,module,exports){const Transform=require("stream").Transform,_difference=require("lodash.difference"),_intersection=require("lodash.intersection"),_spread=require("lodash.spread"),siUtil=require("./siUtil.js"),util=require("util"),CalculateResultSetPerClause=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateResultSetPerClause=CalculateResultSetPerClause,util.inherits(CalculateResultSetPerClause,Transform),CalculateResultSetPerClause.prototype._transform=function(queryClause,encoding,end){const sep=this.options.keySeparator,that=this,frequencies=[];var NOT=function(includeResults){const bigIntersect=_spread(_intersection);var include=bigIntersect(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,termFrequencies:frequencies,BOOST:queryClause.BOOST||0}),end();var i=0,excludeResults=[];siUtil.getKeySet(queryClause.NOT,sep).forEach(function(item){var excludeSet={};that.options.indexes.createReadStream({gte:item[0],lte:item[1]+sep}).on("data",function(data){for(var i=0;ib.id?-1:0}).reduce(function(merged,cur){var lastDoc=merged[merged.length-1];return 0===merged.length||cur.id!==lastDoc.id?merged.push(cur):cur.id===lastDoc.id&&(lastDoc.scoringCriteria=lastDoc.scoringCriteria.concat(cur.scoringCriteria)),merged},[]);return mergedResultSet.map(function(item){return item.scoringCriteria&&(item.score=item.scoringCriteria.reduce(function(acc,val){return{score:+acc.score+ +val.score}},{score:0}).score,item.score=item.score/item.scoringCriteria.length),item}),mergedResultSet.forEach(function(item){that.push(item)}),end()}},{stream:125,util:134}],120:[function(require,module,exports){const Transform=require("stream").Transform,_sortedIndexOf=require("lodash.sortedindexof"),util=require("util"),ScoreDocsOnField=function(options,seekLimit,sort){this.options=options,this.seekLimit=seekLimit,this.sort=sort,Transform.call(this,{objectMode:!0})};exports.ScoreDocsOnField=ScoreDocsOnField,util.inherits(ScoreDocsOnField,Transform),ScoreDocsOnField.prototype._transform=function(clauseSet,encoding,end){const sep=this.options.keySeparator,that=this,gte="TF"+sep+this.sort.field+sep,lte="TF"+sep+this.sort.field+sep+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){for(var i=0;ib.score?-2:a.idb.id?-1:0}):this.resultSet=this.resultSet.sort(function(a,b){return a.score>b.score?2:a.scoreb.id?-1:0}),this.resultSet=this.resultSet.slice(this.q.offset,this.q.offset+this.q.pageSize),this.resultSet.forEach(function(hit){that.push(hit)}),end()}},{stream:125,util:134}],123:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatcherStream=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatcherStream,Transform),MatcherStream.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var results=[];this.options.indexes.createReadStream({start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep}).on("data",function(data){results.push(data)}).on("error",function(err){that.options.log.error("Oh my!",err)}).on("end",function(){return results.sort(function(a,b){return b.value.length-a.value.length}).slice(0,q.limit).forEach(function(item){var m={};switch(q.type){case"ID":m={token:item.key.split(sep)[2],documents:item.value};break;case"count":m={token:item.key.split(sep)[2],documentCount:item.value.length};break;default:m=item.key.split(sep)[2]}that.push(m)}),end()})},exports.match=function(q,options){var s=new Readable({objectMode:!0});return q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple"},q),q.beginsWith.length>5==6?2:byte>>4==14?3:byte>>3==30?4:-1}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j=0?(nb>0&&(self.lastNeed=nb-1),nb):--j=0?(nb>0&&(self.lastNeed=nb-2),nb):--j=0?(nb>0&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0)}function utf8CheckExtraBytes(self,buf,p){if(128!=(192&buf[0]))return self.lastNeed=0,"�".repeat(p);if(self.lastNeed>1&&buf.length>1){if(128!=(192&buf[1]))return self.lastNeed=1,"�".repeat(p+1);if(self.lastNeed>2&&buf.length>2&&128!=(192&buf[2]))return self.lastNeed=2,"�".repeat(p+2)}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0!==r?r:this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(buf.copy(this.lastChar,p,0,buf.length),void(this.lastNeed-=buf.length))}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"�".repeat(this.lastTotal-this.lastNeed):r}function utf16Text(buf,i){if((buf.length-i)%2==0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0===n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch((encoding=""+encoding)&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(void 0===(r=this.fillLast(buf)))return"";i=this.lastNeed,this.lastNeed=0}else i=0;return itokens.length)return[];for(var ngrams=[],i=0;i<=tokens.length-nGramLength;i++)ngrams.push(tokens.slice(i,i+nGramLength));if(ngrams=ngrams.sort(),1===ngrams.length)return[[ngrams[0],1]];for(var counter=1,lastToken=ngrams[0],vector=[],j=1;j=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){base=" [Function"+(value.name?": "+value.name:"")+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(recurseTimes<0)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;return output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}}),x=args[i];i-1&&(err.message="Invalid JSON ("+err.message+")"),stream.emit("error",err)},stream},exports.stringify=function(op,sep,cl,indent){indent=indent||0,!1===op?(op="",sep="\n",cl=""):null==op&&(op="[\n",sep="\n,\n",cl="\n]\n");var stream,first=!0,anyData=!1;return stream=through(function(data){anyData=!0;try{var json=JSON.stringify(data,null,indent)}catch(err){return stream.emit("error",err)}first?(first=!1,stream.queue(op+json)):stream.queue(sep+json)},function(data){anyData||stream.queue(op),stream.queue(cl),stream.queue(null)})},exports.stringifyObject=function(op,sep,cl,indent){indent=indent||0,!1===op?(op="",sep="\n",cl=""):null==op&&(op="{\n",sep="\n,\n",cl="\n}\n");var first=!0,anyData=!1;return through(function(data){anyData=!0;var json=JSON.stringify(data[0])+":"+JSON.stringify(data[1],null,indent);first?(first=!1,this.queue(op+json)):this.queue(sep+json)},function(data){anyData||this.queue(op),this.queue(cl),this.queue(null)})},module.parent||"browser"===process.title||process.stdin.pipe(exports.parse(process.argv[2])).pipe(exports.stringify("[",",\n","]\n",2)).pipe(process.stdout)}).call(this,require("_process"),require("buffer").Buffer)},{_process:86,buffer:9,jsonparse:46,through:132}],4:[function(require,module,exports){(function(global){"use strict";function compare(a,b){if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i=0;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return!Error.isPrototypeOf(expected)&&!0===expected.call({},actual)}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError('"block" argument must be a function');"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}var util=require("util/"),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames=function(){return"foo"===function(){}.name}(),assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert.throws=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":137}],5:[function(require,module,exports){(function(process,global){!function(global,factory){"object"==typeof exports&&void 0!==module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory(global.async=global.async||{})}(this,function(exports){"use strict";function slice(arrayLike,start){start|=0;for(var newLen=Math.max(arrayLike.length-start,0),newArr=Array(newLen),idx=0;idx-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function noop(){}function once(fn){return function(){if(null!==fn){var callFn=fn;fn=null,callFn.apply(this,arguments)}}}function baseTimes(n,iteratee){for(var index=-1,result=Array(n);++index-1&&value%1==0&&valuelength?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=length?array:baseSlice(array,start,end)}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function charsStartIndex(strSymbols,chrSymbols){for(var index=-1,length=strSymbols.length;++index-1;);return index}function asciiToArray(string){return string.split("")}function hasUnicode(string){return reHasUnicode.test(string)}function unicodeToArray(string){return string.match(reUnicode)||[]}function stringToArray(string){return hasUnicode(string)?unicodeToArray(string):asciiToArray(string)}function toString(value){return null==value?"":baseToString(value)}function trim(string,chars,guard){if((string=toString(string))&&(guard||void 0===chars))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars);return castSlice(strSymbols,charsStartIndex(strSymbols,chrSymbols),charsEndIndex(strSymbols,chrSymbols)+1).join("")}function parseParams(func){return func=func.toString().replace(STRIP_COMMENTS,""),func=func.match(FN_ARGS)[2].replace(" ",""),func=func?func.split(FN_ARG_SPLIT):[],func=func.map(function(arg){return trim(arg.replace(FN_ARG,""))})}function autoInject(tasks,callback){var newTasks={};baseForOwn(tasks,function(taskFn,key){function newTask(results,taskCb){var newArgs=arrayMap(params,function(name){return results[name]});newArgs.push(taskCb),wrapAsync(taskFn).apply(null,newArgs)}var params,fnIsAsync=isAsync(taskFn),hasNoDeps=!fnIsAsync&&1===taskFn.length||fnIsAsync&&0===taskFn.length;if(isArray(taskFn))params=taskFn.slice(0,-1),taskFn=taskFn[taskFn.length-1],newTasks[key]=params.concat(params.length>0?newTask:taskFn);else if(hasNoDeps)newTasks[key]=taskFn;else{if(params=parseParams(taskFn),0===taskFn.length&&!fnIsAsync&&0===params.length)throw new Error("autoInject task functions require explicit parameters.");fnIsAsync||params.pop(),newTasks[key]=params.concat(newTask)}}),auto(newTasks,callback)}function DLL(){this.head=this.tail=null,this.length=0}function setInitial(dll,node){dll.length=1,dll.head=dll.tail=node}function queue(worker,concurrency,payload){function _insert(data,insertAtFront,callback){if(null!=callback&&"function"!=typeof callback)throw new Error("task callback must be a function");if(q.started=!0,isArray(data)||(data=[data]),0===data.length&&q.idle())return setImmediate$1(function(){q.drain()});for(var i=0,l=data.length;i=0&&workersList.splice(index),task.callback.apply(task,arguments),null!=err&&q.error(err,task.data)}numRunning<=q.concurrency-q.buffer&&q.unsaturated(),q.idle()&&q.drain(),q.process()}}if(null==concurrency)concurrency=1;else if(0===concurrency)throw new Error("Concurrency must not be zero");var _worker=wrapAsync(worker),numRunning=0,workersList=[],isProcessing=!1,q={_tasks:new DLL,concurrency:concurrency,payload:payload,saturated:noop,unsaturated:noop,buffer:concurrency/4,empty:noop,drain:noop,error:noop,started:!1,paused:!1,push:function(data,callback){_insert(data,!1,callback)},kill:function(){q.drain=noop,q._tasks.empty()},unshift:function(data,callback){_insert(data,!0,callback)},remove:function(testFn){q._tasks.remove(testFn)},process:function(){if(!isProcessing){for(isProcessing=!0;!q.paused&&numRunning2&&(result=slice(arguments,1)),results[key]=result,callback(err)})},function(err){callback(err,results)})}function parallelLimit(tasks,callback){_parallel(eachOf,tasks,callback)}function parallelLimit$1(tasks,limit,callback){_parallel(_eachOfLimit(limit),tasks,callback)}function race(tasks,callback){if(callback=once(callback||noop),!isArray(tasks))return callback(new TypeError("First argument to race must be an array of functions"));if(!tasks.length)return callback();for(var i=0,l=tasks.length;ib?1:0}var _iteratee=wrapAsync(iteratee);map(coll,function(x,callback){_iteratee(x,function(err,criteria){if(err)return callback(err);callback(null,{value:x,criteria:criteria})})},function(err,results){if(err)return callback(err);callback(null,arrayMap(results.sort(comparator),baseProperty("value")))})}function timeout(asyncFn,milliseconds,info){var fn=wrapAsync(asyncFn);return initialParams(function(args,callback){function timeoutCallback(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,callback(error)}var timer,timedOut=!1;args.push(function(){timedOut||(callback.apply(null,arguments),clearTimeout(timer))}),timer=setTimeout(timeoutCallback,milliseconds),fn.apply(null,args)})}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function timeLimit(count,limit,iteratee,callback){var _iteratee=wrapAsync(iteratee);mapLimit(baseRange(0,count,1),limit,_iteratee,callback)}function transform(coll,accumulator,iteratee,callback){arguments.length<=3&&(callback=iteratee,iteratee=accumulator,accumulator=isArray(coll)?[]:{}),callback=once(callback||noop);var _iteratee=wrapAsync(iteratee);eachOf(coll,function(v,k,cb){_iteratee(accumulator,v,k,cb)},function(err){callback(err,accumulator)})}function tryEach(tasks,callback){var result,error=null;callback=callback||noop,eachSeries(tasks,function(task,callback){wrapAsync(task)(function(err,res){result=arguments.length>2?slice(arguments,1):res,error=err,callback(!err)})},function(){callback(error,result)})}function unmemoize(fn){return function(){return(fn.unmemoized||fn).apply(null,arguments)}}function whilst(test,iteratee,callback){callback=onlyOnce(callback||noop);var _iteratee=wrapAsync(iteratee);if(!test())return callback(null);var next=function(err){if(err)return callback(err);if(test())return _iteratee(next);var args=slice(arguments,1);callback.apply(null,[null].concat(args))};_iteratee(next)}function until(test,iteratee,callback){whilst(function(){return!test.apply(this,arguments)},iteratee,callback)}var _defer,initialParams=function(fn){return function(){var args=slice(arguments),callback=args.pop();fn.call(this,args,callback)}},hasSetImmediate="function"==typeof setImmediate&&setImmediate,hasNextTick="object"==typeof process&&"function"==typeof process.nextTick;_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback;var setImmediate$1=wrap(_defer),supportsSymbol="function"==typeof Symbol,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol$1=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag$1=Symbol$1?Symbol$1.toStringTag:void 0,objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString,nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol$1?Symbol$1.toStringTag:void 0,asyncTag="[object AsyncFunction]",funcTag="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]",MAX_SAFE_INTEGER=9007199254740991,breakLoop={},iteratorSymbol="function"==typeof Symbol&&Symbol.iterator,getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()},argsTag="[object Arguments]",objectProto$3=Object.prototype,hasOwnProperty$2=objectProto$3.hasOwnProperty,propertyIsEnumerable=objectProto$3.propertyIsEnumerable,isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty$2.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,Buffer=moduleExports?root.Buffer:void 0,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,MAX_SAFE_INTEGER$1=9007199254740991,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags["[object Float32Array]"]=typedArrayTags["[object Float64Array]"]=typedArrayTags["[object Int8Array]"]=typedArrayTags["[object Int16Array]"]=typedArrayTags["[object Int32Array]"]=typedArrayTags["[object Uint8Array]"]=typedArrayTags["[object Uint8ClampedArray]"]=typedArrayTags["[object Uint16Array]"]=typedArrayTags["[object Uint32Array]"]=!0,typedArrayTags["[object Arguments]"]=typedArrayTags["[object Array]"]=typedArrayTags["[object ArrayBuffer]"]=typedArrayTags["[object Boolean]"]=typedArrayTags["[object DataView]"]=typedArrayTags["[object Date]"]=typedArrayTags["[object Error]"]=typedArrayTags["[object Function]"]=typedArrayTags["[object Map]"]=typedArrayTags["[object Number]"]=typedArrayTags["[object Object]"]=typedArrayTags["[object RegExp]"]=typedArrayTags["[object Set]"]=typedArrayTags["[object String]"]=typedArrayTags["[object WeakMap]"]=!1;var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,freeProcess=moduleExports$1&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?function(func){return function(value){return func(value)}}(nodeIsTypedArray):baseIsTypedArray,objectProto$2=Object.prototype,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),objectProto$4=Object.prototype,hasOwnProperty$3=objectProto$4.hasOwnProperty,eachOfGeneric=doLimit(eachOfLimit,1/0),eachOf=function(coll,iteratee,callback){(isArrayLike(coll)?eachOfArrayLike:eachOfGeneric)(coll,wrapAsync(iteratee),callback)},map=doParallel(_asyncMap),applyEach=applyEach$1(map),mapLimit=doParallelLimit(_asyncMap),mapSeries=doLimit(mapLimit,1),applyEachSeries=applyEach$1(mapSeries),apply=function(fn){var args=slice(arguments,1);return function(){var callArgs=slice(arguments);return fn.apply(null,args.concat(callArgs))}},baseFor=function(fromRight){return function(object,iteratee,keysFunc){for(var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length;length--;){var key=props[fromRight?length:++index];if(!1===iteratee(iterable[key],key,iterable))break}return object}}(),auto=function(tasks,concurrency,callback){function enqueueTask(key,task){readyTasks.push(function(){runTask(key,task)})}function processQueue(){if(0===readyTasks.length&&0===runningTasks)return callback(null,results);for(;readyTasks.length&&runningTasks2&&(result=slice(arguments,1)),err){var safeResults={};baseForOwn(results,function(val,rkey){safeResults[rkey]=val}),safeResults[key]=result,hasError=!0,listeners=Object.create(null),callback(err,safeResults)}else results[key]=result,taskComplete(key)});runningTasks++;var taskFn=wrapAsync(task[task.length-1]);task.length>1?taskFn(results,taskCallback):taskFn(taskCallback)}}function getDependents(taskName){var result=[];return baseForOwn(tasks,function(task,key){isArray(task)&&baseIndexOf(task,taskName,0)>=0&&result.push(key)}),result}"function"==typeof concurrency&&(callback=concurrency,concurrency=null),callback=once(callback||noop);var keys$$1=keys(tasks),numTasks=keys$$1.length;if(!numTasks)return callback(null);concurrency||(concurrency=numTasks);var results={},runningTasks=0,hasError=!1,listeners=Object.create(null),readyTasks=[],readyToCheck=[],uncheckedDependencies={};baseForOwn(tasks,function(task,key){if(!isArray(task))return enqueueTask(key,[task]),void readyToCheck.push(key);var dependencies=task.slice(0,task.length-1),remainingDependencies=dependencies.length;if(0===remainingDependencies)return enqueueTask(key,task),void readyToCheck.push(key);uncheckedDependencies[key]=remainingDependencies,arrayEach(dependencies,function(dependencyName){if(!tasks[dependencyName])throw new Error("async.auto task `"+key+"` has a non-existent dependency `"+dependencyName+"` in "+dependencies.join(", "));addListener(dependencyName,function(){0===--remainingDependencies&&enqueueTask(key,task)})})}),function(){for(var currentTask,counter=0;readyToCheck.length;)currentTask=readyToCheck.pop(),counter++,arrayEach(getDependents(currentTask),function(dependent){0==--uncheckedDependencies[dependent]&&readyToCheck.push(dependent)});if(counter!==numTasks)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),processQueue()},symbolTag="[object Symbol]",INFINITY=1/0,symbolProto=Symbol$1?Symbol$1.prototype:void 0,symbolToString=symbolProto?symbolProto.toString:void 0,reHasUnicode=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0\\ufe0e\\ufe0f]"),rsCombo="[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",reOptMod="(?:[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]|\\ud83c[\\udffb-\\udfff])?",rsOptJoin="(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*",rsSeq="[\\ufe0e\\ufe0f]?"+reOptMod+rsOptJoin,rsSymbol="(?:"+["[^\\ud800-\\udfff]"+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,"[\\ud800-\\udfff]"].join("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reTrim=/^\s+|\s+$/g,FN_ARGS=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,FN_ARG_SPLIT=/,/,FN_ARG=/(=.+)?(\s*)$/,STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;DLL.prototype.removeLink=function(node){return node.prev?node.prev.next=node.next:this.head=node.next,node.next?node.next.prev=node.prev:this.tail=node.prev,node.prev=node.next=null,this.length-=1,node},DLL.prototype.empty=function(){for(;this.head;)this.shift();return this},DLL.prototype.insertAfter=function(node,newNode){newNode.prev=node,newNode.next=node.next,node.next?node.next.prev=newNode:this.tail=newNode,node.next=newNode,this.length+=1},DLL.prototype.insertBefore=function(node,newNode){newNode.prev=node.prev,newNode.next=node,node.prev?node.prev.next=newNode:this.head=newNode,node.prev=newNode,this.length+=1},DLL.prototype.unshift=function(node){this.head?this.insertBefore(this.head,node):setInitial(this,node)},DLL.prototype.push=function(node){this.tail?this.insertAfter(this.tail,node):setInitial(this,node)},DLL.prototype.shift=function(){return this.head&&this.removeLink(this.head)},DLL.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},DLL.prototype.toArray=function(){for(var arr=Array(this.length),curr=this.head,idx=0;idx=nextNode.priority;)nextNode=nextNode.next;for(var i=0,l=data.length;i0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===b64[len-2]?2:"="===b64[len-1]?1:0}function byteLength(b64){return 3*b64.length/4-placeHoldersCount(b64)}function toByteArray(b64){var i,l,tmp,placeHolders,arr,len=b64.length;placeHolders=placeHoldersCount(b64),arr=new Arr(3*len/4-placeHolders),l=placeHolders>0?len-4:len;var L=0;for(i=0;i>16&255,arr[L++]=tmp>>8&255,arr[L++]=255&tmp;return 2===placeHolders?(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[L++]=255&tmp):1===placeHolders&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[L++]=tmp>>8&255,arr[L++]=255&tmp),arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i=start;ilen2?len2:i+16383));return 1===extraBytes?(tmp=uint8[len-1],output+=lookup[tmp>>2],output+=lookup[tmp<<4&63],output+="=="):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],output+=lookup[tmp>>10],output+=lookup[tmp>>4&63],output+=lookup[tmp<<2&63],output+="="),parts.push(output),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer))return string.byteLength;"string"!=typeof string&&(string=""+string);var len=string.length;if(0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":case void 0:return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),byteOffset=+byteOffset,isNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&("ucs2"===(encoding=String(encoding).toLowerCase())||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2, +valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;jremaining&&(length=remaining):length=remaining;var strLen=string.length;if(strLen%2!=0)throw new TypeError("Invalid hex string");length>strLen/2&&(length=strLen/2);for(var i=0;i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:secondByte=buf[i+1],128==(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte)>127&&(codePoint=tempCodePoint);break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128==(192&secondByte)&&128==(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte)>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint);break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128==(192&secondByte)&&128==(192&thirdByte)&&128==(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte)>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint)}}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;ilen)&&(end=len);for(var out="",i=start;ilength)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function objectWriteUInt16(buf,value,offset,littleEndian){value<0&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);i>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){value<0&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);i>>8*(littleEndian?i:3-i)&255}function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=stringtrim(str).replace(INVALID_BASE64_RE,""),str.length<2)return"";for(;str.length%4!=0;)str+="=";return str}function stringtrim(str){return str.trim?str.trim():str.replace(/^\s+|\s+$/g,"")}function toHex(n){return n<16?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var codePoint,length=string.length,leadSurrogate=null,bytes=[],i=0;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=65536+(leadSurrogate-55296<<10|codePoint-56320)}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isnan(val){return val!==val}var base64=require("base64-js"),ieee754=require("ieee754"),isArray=require("isarray");exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50,Buffer.TYPED_ARRAY_SUPPORT=void 0!==global.TYPED_ARRAY_SUPPORT?global.TYPED_ARRAY_SUPPORT:function(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}(),exports.kMaxLength=kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(arr){return arr.__proto__=Buffer.prototype,arr},Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0})),Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)},Buffer.isBuffer=function(b){return!(null==b||!b._isBuffer)},Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i0&&(str=this.toString("hex",0,max).match(/.{2}/g).join(" "),this.length>max&&(str+=" ... ")),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target))throw new TypeError("Argument must be a Buffer");if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),start<0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;iremaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,start<0?(start+=len)<0&&(start=0):start>len&&(start=len),end<0?(end+=len)<0&&(end=0):end>len&&(end=len),end0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,byteLength|=0,!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0)}var mul=1,i=0;for(this[offset]=255&value;++i=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++i>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart=0;--i)target[i+targetStart]=this[i+start];else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,end=void 0===end?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":return fastAndSafeJsonStringify(args[i++]);case"%%":return"%";default:return x}}),x=args[i];i=0,format('rotating-file stream "count" is not >= 0: %j in %j',this.count,this)),options.period){var period={hourly:"1h",daily:"1d",weekly:"1w",monthly:"1m",yearly:"1y"}[options.period]||options.period,m=/^([1-9][0-9]*)([hdwmy]|ms)$/.exec(period);if(!m)throw new Error(format('invalid period: "%s"',options.period));this.periodNum=Number(m[1]),this.periodScope=m[2]}else this.periodNum=1,this.periodScope="d";var lastModified=null;try{lastModified=fs.statSync(this.path).mtime.getTime()}catch(err){}var rotateAfterOpen=!1;if(lastModified){lastModified call rotate()"),this.rotate()):this._setupNextRot()},util.inherits(RotatingFileStream,EventEmitter),RotatingFileStream.prototype._debug=function(){return!1},RotatingFileStream.prototype._setupNextRot=function(){this.rotAt=this._calcRotTime(1),this._setRotationTimer()},RotatingFileStream.prototype._setRotationTimer=function(){var self=this,delay=this.rotAt-Date.now();delay>2147483647&&(delay=2147483647),this.timeout=setTimeout(function(){self._debug("_setRotationTimer timeout -> call rotate()"),self.rotate()},delay),"function"==typeof this.timeout.unref&&this.timeout.unref()},RotatingFileStream.prototype._calcRotTime=function(periodOffset){this._debug("_calcRotTime: %s%s",this.periodNum,this.periodScope);var d=new Date;this._debug(" now local: %s",d),this._debug(" now utc: %s",d.toISOString());var rotAt;switch(this.periodScope){case"ms":rotAt=this.rotAt?this.rotAt+this.periodNum*periodOffset:Date.now()+this.periodNum*periodOffset;break;case"h":rotAt=this.rotAt?this.rotAt+60*this.periodNum*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),d.getUTCHours()+periodOffset);break;case"d":rotAt=this.rotAt?this.rotAt+24*this.periodNum*60*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+periodOffset);break;case"w":if(this.rotAt)rotAt=this.rotAt+7*this.periodNum*24*60*60*1e3*periodOffset;else{var dayOffset=7-d.getUTCDay();periodOffset<1&&(dayOffset=-d.getUTCDay()),(periodOffset>1||periodOffset<-1)&&(dayOffset+=7*periodOffset),rotAt=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+dayOffset)}break;case"m":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+this.periodNum*periodOffset,1):Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+periodOffset,1);break;case"y":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear()+this.periodNum*periodOffset,0,1):Date.UTC(d.getUTCFullYear()+periodOffset,0,1);break;default:assert.fail(format('invalid period scope: "%s"',this.periodScope))}if(this._debug()){this._debug(" **rotAt**: %s (utc: %s)",rotAt,new Date(rotAt).toUTCString());var now=Date.now();this._debug(" now: %s (%sms == %smin == %sh to go)",now,rotAt-now,(rotAt-now)/1e3/60,(rotAt-now)/1e3/60/60)}return rotAt},RotatingFileStream.prototype.rotate=function(){function moves(){if(0===self.count||n<0)return finish();var before=self.path,after=self.path+"."+String(n);n>0&&(before+="."+String(n-1)),n-=1,fs.exists(before,function(exists){exists?(self._debug(" mv %s %s",before,after),mv(before,after,function(mvErr){mvErr?(self.emit("error",mvErr),finish()):moves()})):moves()})}function finish(){self._debug(" open %s",self.path),self.stream=fs.createWriteStream(self.path,{flags:"a",encoding:"utf8"});for(var q=self.rotQueue,len=q.length,i=0;iDate.now())return self._setRotationTimer();if(this._debug("rotate"),self.rotating)throw new TypeError("cannot start a rotation when already rotating");self.rotating=!0,self.stream.end();var n=this.count;!function(){var toDel=self.path+"."+String(n-1);0===n&&(toDel=self.path),n-=1,self._debug(" rm %s",toDel),fs.unlink(toDel,function(delErr){moves()})}()},RotatingFileStream.prototype.write=function(s){return this.rotating?(this.rotQueue.push(s),!1):this.stream.write(s)},RotatingFileStream.prototype.end=function(s){this.stream.end()},RotatingFileStream.prototype.destroy=function(s){this.stream.destroy()},RotatingFileStream.prototype.destroySoon=function(s){this.stream.destroySoon()}),util.inherits(RingBuffer,EventEmitter),RingBuffer.prototype.write=function(record){if(!this.writable)throw new Error("RingBuffer has been ended already");return this.records.push(record),this.records.length>this.limit&&this.records.shift(),!0},RingBuffer.prototype.end=function(){arguments.length>0&&this.write.apply(this,Array.prototype.slice.call(arguments)),this.writable=!1},RingBuffer.prototype.destroy=function(){this.writable=!1,this.emit("close")},RingBuffer.prototype.destroySoon=function(){this.destroy()},module.exports=Logger,module.exports.TRACE=10,module.exports.DEBUG=20,module.exports.INFO=INFO,module.exports.WARN=WARN,module.exports.ERROR=ERROR,module.exports.FATAL=60,module.exports.resolveLevel=resolveLevel,module.exports.levelFromName=levelFromName,module.exports.nameFromLevel=nameFromLevel,module.exports.VERSION="1.8.10",module.exports.LOG_VERSION=LOG_VERSION,module.exports.createLogger=function(options){return new Logger(options)},module.exports.RingBuffer=RingBuffer,module.exports.RotatingFileStream=RotatingFileStream,module.exports.safeCycles=safeCycles}).call(this,{isBuffer:require("../../is-buffer/index.js")},require("_process"))},{"../../is-buffer/index.js":43,_process:86,assert:4,events:38,fs:8,os:84,"safe-json-stringify":104,stream:127,util:137}],11:[function(require,module,exports){(function(Buffer){function isArray(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return"[object Date]"===objectToString(d)}function isError(e){return"[object Error]"===objectToString(e)||e instanceof Error}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg}function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=Buffer.isBuffer}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":43}],12:[function(require,module,exports){function DeferredIterator(options){AbstractIterator.call(this,options),this._options=options,this._iterator=null,this._operations=[]}var util=require("util"),AbstractIterator=require("abstract-leveldown").AbstractIterator;util.inherits(DeferredIterator,AbstractIterator),DeferredIterator.prototype.setDb=function(db){var it=this._iterator=db.iterator(this._options);this._operations.forEach(function(op){it[op.method].apply(it,op.args)})},DeferredIterator.prototype._operation=function(method,args){if(this._iterator)return this._iterator[method].apply(this._iterator,args);this._operations.push({method:method,args:args})},"next end".split(" ").forEach(function(m){DeferredIterator.prototype["_"+m]=function(){this._operation(m,arguments)}}),module.exports=DeferredIterator},{"abstract-leveldown":17,util:137}],13:[function(require,module,exports){(function(Buffer,process){function DeferredLevelDOWN(location){AbstractLevelDOWN.call(this,"string"==typeof location?location:""),this._db=void 0,this._operations=[],this._iterators=[]}var util=require("util"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,DeferredIterator=require("./deferred-iterator");util.inherits(DeferredLevelDOWN,AbstractLevelDOWN),DeferredLevelDOWN.prototype.setDb=function(db){this._db=db,this._operations.forEach(function(op){db[op.method].apply(db,op.args)}),this._iterators.forEach(function(it){it.setDb(db)})},DeferredLevelDOWN.prototype._open=function(options,callback){return process.nextTick(callback)},DeferredLevelDOWN.prototype._operation=function(method,args){if(this._db)return this._db[method].apply(this._db,args);this._operations.push({method:method,args:args})},"put get del batch approximateSize".split(" ").forEach(function(m){DeferredLevelDOWN.prototype["_"+m]=function(){this._operation(m,arguments)}}),DeferredLevelDOWN.prototype._isBuffer=function(obj){return Buffer.isBuffer(obj)},DeferredLevelDOWN.prototype._iterator=function(options){if(this._db)return this._db.iterator.apply(this._db,arguments);var it=new DeferredIterator(options);return this._iterators.push(it),it},module.exports=DeferredLevelDOWN,module.exports.DeferredIterator=DeferredIterator}).call(this,{isBuffer:require("../is-buffer/index.js")},require("_process"))},{"../is-buffer/index.js":43,"./deferred-iterator":12,_process:86,"abstract-leveldown":17,util:137}],14:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:86}],15:[function(require,module,exports){(function(process){function AbstractIterator(db){this.db=db,this._ended=!1,this._nexting=!1}AbstractIterator.prototype.next=function(callback){var self=this;if("function"!=typeof callback)throw new Error("next() requires a callback argument");return self._ended?callback(new Error("cannot call next() after end()")):self._nexting?callback(new Error("cannot call next() before previous next() has completed")):(self._nexting=!0,"function"==typeof self._next?self._next(function(){self._nexting=!1,callback.apply(null,arguments)}):void process.nextTick(function(){self._nexting=!1,callback()}))},AbstractIterator.prototype.end=function(callback){if("function"!=typeof callback)throw new Error("end() requires a callback argument");return this._ended?callback(new Error("end() already called on iterator")):(this._ended=!0,"function"==typeof this._end?this._end(callback):void process.nextTick(callback))},module.exports=AbstractIterator}).call(this,require("_process"))},{_process:86}],16:[function(require,module,exports){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location,this.status="new"}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){var self=this,oldStatus=this.status;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");"object"!=typeof options&&(options={}),options.createIfMissing=0!=options.createIfMissing,options.errorIfExists=!!options.errorIfExists,"function"==typeof this._open?(this.status="opening",this._open(options,function(err){if(err)return self.status=oldStatus,callback(err);self.status="open",callback()})):(this.status="open",process.nextTick(callback))},AbstractLevelDOWN.prototype.close=function(callback){var self=this,oldStatus=this.status;if("function"!=typeof callback)throw new Error("close() requires a callback argument");"function"==typeof this._close?(this.status="closing",this._close(function(err){if(err)return self.status=oldStatus,callback(err);self.status="closed",callback()})):(this.status="closed",process.nextTick(callback))},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),options.asBuffer=0!=options.asBuffer,"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),null==value||this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"==typeof array&&(callback=array),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));options&&"object"==typeof options||(options={});for(var e,err,i=0,l=array.length;i<.,\-|]+|\\u0003/},doc.options||{});for(var fieldName in doc.normalised){var fieldOptions=Object.assign({},{separator:options.separator},options.fieldOptions[fieldName]);"[object Array]"===Object.prototype.toString.call(doc.normalised[fieldName])?doc.tokenised[fieldName]=doc.normalised[fieldName]:doc.tokenised[fieldName]=doc.normalised[fieldName].split(fieldOptions.separator)}return this.push(doc),end()}},{stream:127,util:137}],31:[function(require,module,exports){(function(process,Buffer){var stream=require("readable-stream"),eos=require("end-of-stream"),inherits=require("inherits"),shift=require("stream-shift"),SIGNAL_FLUSH=new Buffer([0]),onuncork=function(self,fn){self._corked?self.once("uncork",fn):fn()},destroyer=function(self,end){return function(err){err?self.destroy("premature close"===err.message?null:err):end&&!self._ended&&self.end()}},end=function(ws,fn){return ws?ws._writableState&&ws._writableState.finished?fn():ws._writableState?ws.end(fn):(ws.end(),void fn()):fn()},toStreams2=function(rs){return new stream.Readable({objectMode:!0,highWaterMark:16}).wrap(rs)},Duplexify=function(writable,readable,opts){if(!(this instanceof Duplexify))return new Duplexify(writable,readable,opts);stream.Duplex.call(this,opts),this._writable=null,this._readable=null,this._readable2=null,this._forwardDestroy=!opts||!1!==opts.destroy,this._forwardEnd=!opts||!1!==opts.end,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,writable&&this.setWritable(writable),readable&&this.setReadable(readable)};inherits(Duplexify,stream.Duplex),Duplexify.obj=function(writable,readable,opts){return opts||(opts={}),opts.objectMode=!0,opts.highWaterMark=16,new Duplexify(writable,readable,opts)},Duplexify.prototype.cork=function(){1==++this._corked&&this.emit("cork")},Duplexify.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},Duplexify.prototype.setWritable=function(writable){if(this._unwrite&&this._unwrite(),this.destroyed)return void(writable&&writable.destroy&&writable.destroy());if(null===writable||!1===writable)return void this.end();var self=this,unend=eos(writable,{writable:!0,readable:!1},destroyer(this,this._forwardEnd)),ondrain=function(){var ondrain=self._ondrain;self._ondrain=null,ondrain&&ondrain()},clear=function(){self._writable.removeListener("drain",ondrain),unend()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=clear,this.uncork()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)return void(readable&&readable.destroy&&readable.destroy());if(null===readable||!1===readable)return this.push(null),void this.resume();var self=this,unend=eos(readable,{writable:!1,readable:!0},destroyer(this)),onreadable=function(){self._forward()},onend=function(){self.push(null)},clear=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()};this._drained=!0,this._readable=readable,this._readable2=readable._readableState?readable:toStreams2(readable),this._readable2.on("readable",onreadable),this._readable2.on("end",onend),this._unread=clear,this._forward()},Duplexify.prototype._read=function(){this._drained=!0,this._forward()},Duplexify.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){this._forwarding=!0;for(var data;this._drained&&null!==(data=shift(this._readable2));)this.destroyed||(this._drained=this.push(data));this._forwarding=!1}},Duplexify.prototype.destroy=function(err){if(!this.destroyed){this.destroyed=!0;var self=this;process.nextTick(function(){self._destroy(err)})}},Duplexify.prototype._destroy=function(err){if(err){var ondrain=this._ondrain;this._ondrain=null,ondrain?ondrain(err):this.emit("error",err)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},Duplexify.prototype._write=function(data,enc,cb){return this.destroyed?cb():this._corked?onuncork(this,this._write.bind(this,data,enc,cb)):data===SIGNAL_FLUSH?this._finish(cb):this._writable?void(!1===this._writable.write(data)?this._ondrain=cb:cb()):cb()},Duplexify.prototype._finish=function(cb){var self=this;this.emit("preend"),onuncork(this,function(){end(self._forwardEnd&&self._writable,function(){!1===self._writableState.prefinished&&(self._writableState.prefinished=!0),self.emit("prefinish"),onuncork(self,cb)})})},Duplexify.prototype.end=function(data,enc,cb){return"function"==typeof data?this.end(null,null,data):"function"==typeof enc?this.end(data,null,enc):(this._ended=!0,data&&this.write(data),this._writableState.ending||this.write(SIGNAL_FLUSH),stream.Writable.prototype.end.call(this,cb))},module.exports=Duplexify}).call(this,require("_process"),require("buffer").Buffer)},{_process:86,buffer:9,"end-of-stream":32,inherits:41,"readable-stream":100,"stream-shift":128}],32:[function(require,module,exports){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback()},onend=function(){readable=!1,writable||callback()},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback(new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:33}],33:[function(require,module,exports){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0})})},{wrappy:138}],34:[function(require,module,exports){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},isChildProcess=function(stream){return stream.stdio&&Array.isArray(stream.stdio)&&3===stream.stdio.length},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback.call(stream)},onend=function(){readable=!1,writable||callback.call(stream)},onexit=function(exitCode){callback.call(stream,exitCode?new Error("exited with error code: "+exitCode):null)},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback.call(stream,new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),isChildProcess(stream)&&stream.on("exit",onexit),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("exit",onexit),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:83}],35:[function(require,module,exports){function init(type,message,cause){prr(this,{type:type,name:type,cause:"string"!=typeof message?message:cause,message:message&&"string"!=typeof message?message.message:message},"ewr")}function CustomError(message,cause){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),init.call(this,"CustomError",message,cause)}function createError(errno,type,proto){var err=function(message,cause){init.call(this,type,message,cause),"FilesystemError"==type&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(errno.errno[this.cause.errno]?errno.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return err.prototype=proto?new proto:new CustomError,err}var prr=require("prr");CustomError.prototype=new Error,module.exports=function(errno){var ce=function(type,proto){return createError(errno,type,proto)};return{CustomError:CustomError,FilesystemError:ce("FilesystemError"),createError:ce}}},{prr:37}],36:[function(require,module,exports){var all=module.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];module.exports.errno={},module.exports.code={},all.forEach(function(error){module.exports.errno[error.errno]=error,module.exports.code[error.code]=error}),module.exports.custom=require("./custom")(module.exports),module.exports.create=module.exports.custom.createError},{"./custom":35}],37:[function(require,module,exports){!function(name,context,definition){void 0!==module&&module.exports?module.exports=definition():context.prr=definition()}(0,this,function(){var setProperty="function"==typeof Object.defineProperty?function(obj,key,options){return Object.defineProperty(obj,key,options),obj}:function(obj,key,options){return obj[key]=options.value,obj},makeOptions=function(value,options){var oo="object"==typeof options,os=!oo&&"string"==typeof options,op=function(p){return oo?!!options[p]:!!os&&options.indexOf(p[0])>-1};return{enumerable:op("enumerable"),configurable:op("configurable"),writable:op("writable"),value:value}};return function(obj,key,value,options){var k;if(options=makeOptions(value,options),"object"==typeof key){for(k in key)Object.hasOwnProperty.call(key,k)&&(options.value=key[k],setProperty(obj,k,options));return obj}return setProperty(obj,key,options)}})},{}],38:[function(require,module,exports){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if((er=arguments[1])instanceof Error)throw er;var err=new Error('Uncaught, unspecified "error" event. ('+er+")");throw err.context=er,err}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args)}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;i0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace()),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-- >0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(position<0)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){return this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},{}],39:[function(require,module,exports){!function(name,definition,global){"use strict";"function"==typeof define?define(definition):void 0!==module&&module.exports?module.exports=definition():global.IDBStore=definition()}(0,function(){"use strict";function mixin(target,source){var name,s;for(name in source)(s=source[name])!==empty[name]&&s!==target[name]&&(target[name]=s);return target}function hasVersionError(errorEvent){return"error"in errorEvent.target?"VersionError"==errorEvent.target.error.name:"errorCode"in errorEvent.target&&12==errorEvent.target.errorCode}var defaultErrorHandler=function(error){throw error},defaultSuccessHandler=function(){},defaults={storeName:"Store",storePrefix:"IDBWrapper-",dbVersion:1,keyPath:"id",autoIncrement:!0,onStoreReady:function(){},onError:defaultErrorHandler,indexes:[],implementationPreference:["indexedDB","webkitIndexedDB","mozIndexedDB","shimIndexedDB"]},IDBStore=function(kwArgs,onStoreReady){void 0===onStoreReady&&"function"==typeof kwArgs&&(onStoreReady=kwArgs),"[object Object]"!=Object.prototype.toString.call(kwArgs)&&(kwArgs={});for(var key in defaults)this[key]=void 0!==kwArgs[key]?kwArgs[key]:defaults[key];this.dbName=this.storePrefix+this.storeName,this.dbVersion=parseInt(this.dbVersion,10)||1,onStoreReady&&(this.onStoreReady=onStoreReady);var env="object"==typeof window?window:self,availableImplementations=this.implementationPreference.filter(function(implName){return implName in env});this.implementation=availableImplementations[0],this.idb=env[this.implementation],this.keyRange=env.IDBKeyRange||env.webkitIDBKeyRange||env.mozIDBKeyRange,this.consts={READ_ONLY:"readonly",READ_WRITE:"readwrite",VERSION_CHANGE:"versionchange",NEXT:"next",NEXT_NO_DUPLICATE:"nextunique",PREV:"prev",PREV_NO_DUPLICATE:"prevunique"},this.openDB()},proto={constructor:IDBStore,version:"1.7.1",db:null,dbName:null,dbVersion:null,store:null,storeName:null,storePrefix:null,keyPath:null,autoIncrement:null,indexes:null,implementationPreference:null,implementation:"",onStoreReady:null,onError:null,_insertIdCount:0,openDB:function(){var openRequest=this.idb.open(this.dbName,this.dbVersion),preventSuccessCallback=!1;openRequest.onerror=function(errorEvent){if(hasVersionError(errorEvent))this.onError(new Error("The version number provided is lower than the existing one."));else{var error;if(errorEvent.target.error)error=errorEvent.target.error;else{var errorMessage="IndexedDB unknown error occurred when opening DB "+this.dbName+" version "+this.dbVersion;"errorCode"in errorEvent.target&&(errorMessage+=" with error code "+errorEvent.target.errorCode),error=new Error(errorMessage)}this.onError(error)}}.bind(this),openRequest.onsuccess=function(event){if(!preventSuccessCallback){if(this.db)return void this.onStoreReady();if(this.db=event.target.result,"string"==typeof this.db.version)return void this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."));if(!this.db.objectStoreNames.contains(this.storeName))return void this.onError(new Error("Object store couldn't be created."));var emptyTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);this.store=emptyTransaction.objectStore(this.storeName);var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(!indexName)return preventSuccessCallback=!0,void this.onError(new Error("Cannot create index: No index name given."));if(this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);this.indexComplies(actualIndex,indexData)||(preventSuccessCallback=!0,this.onError(new Error('Cannot modify index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else preventSuccessCallback=!0,this.onError(new Error('Cannot create new index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))},this),existingIndexes.length&&(preventSuccessCallback=!0,this.onError(new Error('Cannot delete index(es) "'+existingIndexes.toString()+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),preventSuccessCallback||this.onStoreReady()}}.bind(this),openRequest.onupgradeneeded=function(event){if(this.db=event.target.result,this.db.objectStoreNames.contains(this.storeName))this.store=event.target.transaction.objectStore(this.storeName);else{var optionalParameters={autoIncrement:this.autoIncrement};null!==this.keyPath&&(optionalParameters.keyPath=this.keyPath),this.store=this.db.createObjectStore(this.storeName,optionalParameters)}var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(indexName||(preventSuccessCallback=!0,this.onError(new Error("Cannot create index: No index name given."))),this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);this.indexComplies(actualIndex,indexData)||(this.store.deleteIndex(indexName),this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})},this),existingIndexes.length&&existingIndexes.forEach(function(_indexName){this.store.deleteIndex(_indexName)},this)}.bind(this)},deleteDatabase:function(onSuccess,onError){if(this.idb.deleteDatabase){this.db.close();var deleteRequest=this.idb.deleteDatabase(this.dbName);deleteRequest.onsuccess=onSuccess,deleteRequest.onerror=onError}else onError(new Error("Browser does not support IndexedDB deleteDatabase!"))},put:function(key,value,onSuccess,onError){null!==this.keyPath&&(onError=onSuccess,onSuccess=value,value=key),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var putRequest,hasSuccess=!1,result=null,putTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);return putTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},putTransaction.onabort=onError,putTransaction.onerror=onError,null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=putTransaction.objectStore(this.storeName).put(value)):putRequest=putTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},putRequest.onerror=onError,putTransaction},get:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,getTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);getTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getTransaction.onabort=onError,getTransaction.onerror=onError;var getRequest=getTransaction.objectStore(this.storeName).get(key);return getRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getRequest.onerror=onError,getTransaction},remove:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,removeTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);removeTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},removeTransaction.onabort=onError,removeTransaction.onerror=onError;var deleteRequest=removeTransaction.objectStore(this.storeName).delete(key);return deleteRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},deleteRequest.onerror=onError,removeTransaction},batch:function(dataArray,onSuccess,onError){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),"[object Array]"!=Object.prototype.toString.call(dataArray))onError(new Error("dataArray argument must be of type Array."));else if(0===dataArray.length)return onSuccess(!0);var count=dataArray.length,called=!1,hasSuccess=!1,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(hasSuccess)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(){0!==--count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(operation){var type=operation.type,key=operation.key,value=operation.value,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err,type,key))};if("remove"==type){var deleteRequest=batchTransaction.objectStore(this.storeName).delete(key);deleteRequest.onsuccess=onItemSuccess,deleteRequest.onerror=onItemError}else if("put"==type){var putRequest;null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=batchTransaction.objectStore(this.storeName).put(value)):putRequest=batchTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError}},this),batchTransaction},putBatch:function(dataArray,onSuccess,onError){var batchData=dataArray.map(function(item){return{type:"put",value:item}}) +;return this.batch(batchData,onSuccess,onError)},upsertBatch:function(dataArray,options,onSuccess,onError){"function"==typeof options&&(onSuccess=options,onError=onSuccess,options={}),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),options||(options={}),"[object Array]"!=Object.prototype.toString.call(dataArray)&&onError(new Error("dataArray argument must be of type Array."));var keyField=options.keyField||this.keyPath,count=dataArray.length,called=!1,hasSuccess=!1,index=0,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){hasSuccess?onSuccess(dataArray):onError(!1)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){dataArray[index++][keyField]=event.target.result,0!==--count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(record){var putRequest,key=record.key,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err))};null!==this.keyPath?(this._addIdPropertyIfNeeded(record),putRequest=batchTransaction.objectStore(this.storeName).put(record)):putRequest=batchTransaction.objectStore(this.storeName).put(record,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError},this),batchTransaction},removeBatch:function(keyArray,onSuccess,onError){var batchData=keyArray.map(function(key){return{type:"remove",key:key}});return this.batch(batchData,onSuccess,onError)},getBatch:function(keyArray,onSuccess,onError,arrayType){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),arrayType||(arrayType="sparse"),"[object Array]"!=Object.prototype.toString.call(keyArray))onError(new Error("keyArray argument must be of type Array."));else if(0===keyArray.length)return onSuccess([]);var data=[],count=keyArray.length,called=!1,hasSuccess=!1,result=null,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);batchTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){event.target.result||"dense"==arrayType?data.push(event.target.result):"sparse"==arrayType&&data.length++,0===--count&&(called=!0,hasSuccess=!0,result=data)};return keyArray.forEach(function(key){var onItemError=function(err){called=!0,result=err,onError(err),batchTransaction.abort()},getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=onItemError},this),batchTransaction},getAll:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var getAllTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY),store=getAllTransaction.objectStore(this.storeName);return store.getAll?this._getAllNative(getAllTransaction,store,onSuccess,onError):this._getAllCursor(getAllTransaction,store,onSuccess,onError),getAllTransaction},_getAllNative:function(getAllTransaction,store,onSuccess,onError){var hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var getAllRequest=store.getAll();getAllRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getAllRequest.onerror=onError},_getAllCursor:function(getAllTransaction,store,onSuccess,onError){var all=[],hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var cursorRequest=store.openCursor();cursorRequest.onsuccess=function(event){var cursor=event.target.result;cursor?(all.push(cursor.value),cursor.continue()):(hasSuccess=!0,result=all)},cursorRequest.onError=onError},clear:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,clearTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);clearTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},clearTransaction.onabort=onError,clearTransaction.onerror=onError;var clearRequest=clearTransaction.objectStore(this.storeName).clear();return clearRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},clearRequest.onerror=onError,clearTransaction},_addIdPropertyIfNeeded:function(dataObj){void 0===dataObj[this.keyPath]&&(dataObj[this.keyPath]=this._insertIdCount+++Date.now())},getIndexList:function(){return this.store.indexNames},hasIndex:function(indexName){return this.store.indexNames.contains(indexName)},normalizeIndexData:function(indexData){indexData.keyPath=indexData.keyPath||indexData.name,indexData.unique=!!indexData.unique,indexData.multiEntry=!!indexData.multiEntry},indexComplies:function(actual,expected){return["keyPath","unique","multiEntry"].every(function(key){if("multiEntry"==key&&void 0===actual[key]&&!1===expected[key])return!0;if("keyPath"==key&&"[object Array]"==Object.prototype.toString.call(expected[key])){var exp=expected.keyPath,act=actual.keyPath;if("string"==typeof act)return exp.toString()==act;if("function"!=typeof act.contains&&"function"!=typeof act.indexOf)return!1;if(act.length!==exp.length)return!1;for(var i=0,m=exp.length;i>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:1/0*(s?-1:1);m+=Math.pow(2,mLen),e-=eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias),value*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],41:[function(require,module,exports){"function"==typeof Object.create?module.exports=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],42:[function(require,module,exports){var Readable=require("stream").Readable;exports.getIntersectionStream=function(sortedSets){for(var s=new Readable,i=0,ii=[],k=0;ksortedSets[i+1][ii[i+1]])ii[i+1]++;else if(i+2=sortedSets[k].length&&(finished=!0);i=0}return s.push(null),s}},{stream:127}],43:[function(require,module,exports){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}module.exports=function(obj){return null!=obj&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)}},{}],44:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},{}],45:[function(require,module,exports){function isBuffer(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}var Buffer=require("buffer").Buffer;module.exports=isBuffer},{buffer:9}],46:[function(require,module,exports){(function(Buffer){function Parser(){this.tState=START,this.value=void 0,this.string=void 0,this.stringBuffer=Buffer.alloc?Buffer.alloc(STRING_BUFFER_SIZE):new Buffer(STRING_BUFFER_SIZE),this.stringBufferOffset=0,this.unicode=void 0,this.highSurrogate=void 0,this.key=void 0,this.mode=void 0,this.stack=[],this.state=VALUE,this.bytes_remaining=0,this.bytes_in_sequence=0,this.temp_buffs={2:new Buffer(2),3:new Buffer(3),4:new Buffer(4)},this.offset=-1}var C={},LEFT_BRACE=C.LEFT_BRACE=1,RIGHT_BRACE=C.RIGHT_BRACE=2,LEFT_BRACKET=C.LEFT_BRACKET=3,RIGHT_BRACKET=C.RIGHT_BRACKET=4,COLON=C.COLON=5,COMMA=C.COMMA=6,TRUE=C.TRUE=7,FALSE=C.FALSE=8,NULL=C.NULL=9,STRING=C.STRING=10,NUMBER=C.NUMBER=11,START=C.START=17,STOP=C.STOP=18,TRUE1=C.TRUE1=33,TRUE2=C.TRUE2=34,TRUE3=C.TRUE3=35,FALSE1=C.FALSE1=49,FALSE2=C.FALSE2=50,FALSE3=C.FALSE3=51,FALSE4=C.FALSE4=52,NULL1=C.NULL1=65,NULL2=C.NULL2=66,NULL3=C.NULL3=67,NUMBER1=C.NUMBER1=81,NUMBER3=C.NUMBER3=83,STRING1=C.STRING1=97,STRING2=C.STRING2=98,STRING3=C.STRING3=99,STRING4=C.STRING4=100,STRING5=C.STRING5=101,STRING6=C.STRING6=102,VALUE=C.VALUE=113,KEY=C.KEY=114,OBJECT=C.OBJECT=129,ARRAY=C.ARRAY=130,BACK_SLASH="\\".charCodeAt(0),FORWARD_SLASH="/".charCodeAt(0),BACKSPACE="\b".charCodeAt(0),FORM_FEED="\f".charCodeAt(0),NEWLINE="\n".charCodeAt(0),CARRIAGE_RETURN="\r".charCodeAt(0),TAB="\t".charCodeAt(0),STRING_BUFFER_SIZE=65536;Parser.toknam=function(code){for(var keys=Object.keys(C),i=0,l=keys.length;i=STRING_BUFFER_SIZE&&(this.string+=this.stringBuffer.toString("utf8"),this.stringBufferOffset=0),this.stringBuffer[this.stringBufferOffset++]=char},proto.appendStringBuf=function(buf,start,end){var size=buf.length;"number"==typeof start&&(size="number"==typeof end?end<0?buf.length-start+end:end-start:buf.length-start),size<0&&(size=0),this.stringBufferOffset+size>STRING_BUFFER_SIZE&&(this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0),buf.copy(this.stringBuffer,this.stringBufferOffset,start,end),this.stringBufferOffset+=size},proto.write=function(buffer){"string"==typeof buffer&&(buffer=new Buffer(buffer));for(var n,i=0,l=buffer.length;i=48&&n<64)this.string=String.fromCharCode(n),this.tState=NUMBER3;else if(32!==n&&9!==n&&10!==n&&13!==n)return this.charError(buffer,i)}else if(this.tState===STRING1)if(n=buffer[i],this.bytes_remaining>0){for(var j=0;j=128){if(n<=193||n>244)return this.onError(new Error("Invalid UTF-8 character at position "+i+" in state "+Parser.toknam(this.tState)));if(n>=194&&n<=223&&(this.bytes_in_sequence=2),n>=224&&n<=239&&(this.bytes_in_sequence=3),n>=240&&n<=244&&(this.bytes_in_sequence=4),this.bytes_in_sequence+i>buffer.length){for(var k=0;k<=buffer.length-1-i;k++)this.temp_buffs[this.bytes_in_sequence][k]=buffer[i+k];this.bytes_remaining=i+this.bytes_in_sequence-buffer.length,i=buffer.length-1}else this.appendStringBuf(buffer,i,i+this.bytes_in_sequence),i=i+this.bytes_in_sequence-1}else if(34===n)this.tState=START,this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0,this.onToken(STRING,this.string),this.offset+=Buffer.byteLength(this.string,"utf8")+1,this.string=void 0;else if(92===n)this.tState=STRING2;else{if(!(n>=32))return this.charError(buffer,i);this.appendStringChar(n)}else if(this.tState===STRING2)if(34===(n=buffer[i]))this.appendStringChar(n),this.tState=STRING1;else if(92===n)this.appendStringChar(BACK_SLASH),this.tState=STRING1;else if(47===n)this.appendStringChar(FORWARD_SLASH),this.tState=STRING1;else if(98===n)this.appendStringChar(BACKSPACE),this.tState=STRING1;else if(102===n)this.appendStringChar(FORM_FEED),this.tState=STRING1;else if(110===n)this.appendStringChar(NEWLINE),this.tState=STRING1;else if(114===n)this.appendStringChar(CARRIAGE_RETURN),this.tState=STRING1;else if(116===n)this.appendStringChar(TAB),this.tState=STRING1;else{if(117!==n)return this.charError(buffer,i);this.unicode="",this.tState=STRING3}else if(this.tState===STRING3||this.tState===STRING4||this.tState===STRING5||this.tState===STRING6){if(!((n=buffer[i])>=48&&n<64||n>64&&n<=70||n>96&&n<=102))return this.charError(buffer,i);if(this.unicode+=String.fromCharCode(n),this.tState++===STRING6){var intVal=parseInt(this.unicode,16);this.unicode=void 0,void 0!==this.highSurrogate&&intVal>=56320&&intVal<57344?(this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate,intVal))),this.highSurrogate=void 0):void 0===this.highSurrogate&&intVal>=55296&&intVal<56320?this.highSurrogate=intVal:(void 0!==this.highSurrogate&&(this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate))),this.highSurrogate=void 0),this.appendStringBuf(new Buffer(String.fromCharCode(intVal)))),this.tState=STRING1}}else if(this.tState===NUMBER1||this.tState===NUMBER3)switch(n=buffer[i]){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 46:case 101:case 69:case 43:case 45:this.string+=String.fromCharCode(n),this.tState=NUMBER3;break;default:this.tState=START;var result=Number(this.string);if(isNaN(result))return this.charError(buffer,i);this.string.match(/[0-9]+/)==this.string&&result.toString()!=this.string?this.onToken(STRING,this.string):this.onToken(NUMBER,result),this.offset+=this.string.length-1,this.string=void 0,i--}else if(this.tState===TRUE1){if(114!==buffer[i])return this.charError(buffer,i);this.tState=TRUE2}else if(this.tState===TRUE2){if(117!==buffer[i])return this.charError(buffer,i);this.tState=TRUE3}else if(this.tState===TRUE3){if(101!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(TRUE,!0),this.offset+=3}else if(this.tState===FALSE1){if(97!==buffer[i])return this.charError(buffer,i);this.tState=FALSE2}else if(this.tState===FALSE2){if(108!==buffer[i])return this.charError(buffer,i);this.tState=FALSE3}else if(this.tState===FALSE3){if(115!==buffer[i])return this.charError(buffer,i);this.tState=FALSE4}else if(this.tState===FALSE4){if(101!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(FALSE,!1),this.offset+=4}else if(this.tState===NULL1){if(117!==buffer[i])return this.charError(buffer,i);this.tState=NULL2}else if(this.tState===NULL2){if(108!==buffer[i])return this.charError(buffer,i);this.tState=NULL3}else if(this.tState===NULL3){if(108!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(NULL,null),this.offset+=3}},proto.onToken=function(token,value){},proto.parseError=function(token,value){this.tState=STOP,this.onError(new Error("Unexpected "+Parser.toknam(token)+(value?"("+JSON.stringify(value)+")":"")+" in state "+Parser.toknam(this.state)))},proto.push=function(){this.stack.push({value:this.value,key:this.key,mode:this.mode})},proto.pop=function(){var value=this.value,parent=this.stack.pop();this.value=parent.value,this.key=parent.key,this.mode=parent.mode,this.emit(value),this.mode||(this.state=VALUE)},proto.emit=function(value){this.mode&&(this.state=COMMA),this.onValue(value)},proto.onValue=function(value){},proto.onToken=function(token,value){if(this.state===VALUE)if(token===STRING||token===NUMBER||token===TRUE||token===FALSE||token===NULL)this.value&&(this.value[this.key]=value),this.emit(value);else if(token===LEFT_BRACE)this.push(),this.value?this.value=this.value[this.key]={}:this.value={},this.key=void 0,this.state=KEY,this.mode=OBJECT;else if(token===LEFT_BRACKET)this.push(),this.value?this.value=this.value[this.key]=[]:this.value=[],this.key=0,this.mode=ARRAY,this.state=VALUE;else if(token===RIGHT_BRACE){if(this.mode!==OBJECT)return this.parseError(token,value);this.pop()}else{if(token!==RIGHT_BRACKET)return this.parseError(token,value);if(this.mode!==ARRAY)return this.parseError(token,value);this.pop()}else if(this.state===KEY)if(token===STRING)this.key=value,this.state=COLON;else{if(token!==RIGHT_BRACE)return this.parseError(token,value);this.pop()}else if(this.state===COLON){if(token!==COLON)return this.parseError(token,value);this.state=VALUE}else{if(this.state!==COMMA)return this.parseError(token,value);if(token===COMMA)this.mode===ARRAY?(this.key++,this.state=VALUE):this.mode===OBJECT&&(this.state=KEY);else{if(!(token===RIGHT_BRACKET&&this.mode===ARRAY||token===RIGHT_BRACE&&this.mode===OBJECT))return this.parseError(token,value);this.pop()}}},Parser.C=C,module.exports=Parser}).call(this,require("buffer").Buffer)},{buffer:9}],47:[function(require,module,exports){function Codec(opts){this.opts=opts||{},this.encodings=encodings}var encodings=require("./lib/encodings");module.exports=Codec,Codec.prototype._encoding=function(encoding){return"string"==typeof encoding&&(encoding=encodings[encoding]),encoding||(encoding=encodings.id),encoding},Codec.prototype._keyEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&batchOpts.keyEncoding||opts&&opts.keyEncoding||this.opts.keyEncoding)},Codec.prototype._valueEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&(batchOpts.valueEncoding||batchOpts.encoding)||opts&&(opts.valueEncoding||opts.encoding)||this.opts.valueEncoding||this.opts.encoding)},Codec.prototype.encodeKey=function(key,opts,batchOpts){return this._keyEncoding(opts,batchOpts).encode(key)},Codec.prototype.encodeValue=function(value,opts,batchOpts){return this._valueEncoding(opts,batchOpts).encode(value)},Codec.prototype.decodeKey=function(key,opts){return this._keyEncoding(opts).decode(key)},Codec.prototype.decodeValue=function(value,opts){return this._valueEncoding(opts).decode(value)},Codec.prototype.encodeBatch=function(ops,opts){var self=this;return ops.map(function(_op){var op={type:_op.type,key:self.encodeKey(_op.key,opts,_op)};return self.keyAsBuffer(opts,_op)&&(op.keyEncoding="binary"),_op.prefix&&(op.prefix=_op.prefix),"value"in _op&&(op.value=self.encodeValue(_op.value,opts,_op),self.valueAsBuffer(opts,_op)&&(op.valueEncoding="binary")),op})};var ltgtKeys=["lt","gt","lte","gte","start","end"];Codec.prototype.encodeLtgt=function(ltgt){var self=this,ret={};return Object.keys(ltgt).forEach(function(key){ret[key]=ltgtKeys.indexOf(key)>-1?self.encodeKey(ltgt[key],ltgt):ltgt[key]}),ret},Codec.prototype.createStreamDecoder=function(opts){var self=this;return opts.keys&&opts.values?function(key,value){return{key:self.decodeKey(key,opts),value:self.decodeValue(value,opts)}}:opts.keys?function(key){return self.decodeKey(key,opts)}:opts.values?function(_,value){return self.decodeValue(value,opts)}:function(){}},Codec.prototype.keyAsBuffer=function(opts){return this._keyEncoding(opts).buffer},Codec.prototype.valueAsBuffer=function(opts){return this._valueEncoding(opts).buffer}},{"./lib/encodings":48}],48:[function(require,module,exports){(function(Buffer){function identity(value){return value}function isBinary(data){return void 0===data||null===data||Buffer.isBuffer(data)}exports.utf8=exports["utf-8"]={encode:function(data){return isBinary(data)?data:String(data)},decode:identity,buffer:!1,type:"utf8"},exports.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},exports.binary={encode:function(data){return isBinary(data)?data:new Buffer(data)},decode:identity,buffer:!0,type:"binary"},exports.id={encode:function(data){return data},decode:function(data){return data},buffer:!1,type:"id"},["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"].forEach(function(type){exports[type]={encode:function(data){return isBinary(data)?data:new Buffer(data,type)},decode:function(buffer){return buffer.toString(type)},buffer:!0,type:type}})}).call(this,require("buffer").Buffer)},{buffer:9}],49:[function(require,module,exports){var createError=require("errno").create,LevelUPError=createError("LevelUPError"),NotFoundError=createError("NotFoundError",LevelUPError);NotFoundError.prototype.notFound=!0,NotFoundError.prototype.status=404,module.exports={LevelUPError:LevelUPError,InitializationError:createError("InitializationError",LevelUPError),OpenError:createError("OpenError",LevelUPError),ReadError:createError("ReadError",LevelUPError),WriteError:createError("WriteError",LevelUPError),NotFoundError:NotFoundError,EncodingError:createError("EncodingError",LevelUPError)}},{errno:36}],50:[function(require,module,exports){function ReadStream(iterator,options){if(!(this instanceof ReadStream))return new ReadStream(iterator,options);Readable.call(this,extend(options,{objectMode:!0})),this._iterator=iterator,this._destroyed=!1,this._decoder=null,options&&options.decoder&&(this._decoder=options.decoder),this.on("end",this._cleanup.bind(this))}var inherits=require("inherits"),Readable=require("readable-stream").Readable,extend=require("xtend"),EncodingError=require("level-errors").EncodingError;module.exports=ReadStream,inherits(ReadStream,Readable),ReadStream.prototype._read=function(){var self=this;this._destroyed||this._iterator.next(function(err,key,value){if(!self._destroyed){if(err)return self.emit("error",err);if(void 0===key&&void 0===value)self.push(null);else{if(!self._decoder)return self.push({key:key,value:value});try{var value=self._decoder(key,value)}catch(err){return self.emit("error",new EncodingError(err)),void self.push(null)}self.push(value)}}})},ReadStream.prototype.destroy=ReadStream.prototype._cleanup=function(){var self=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(err){if(err)return self.emit("error",err);self.emit("close")}))}},{inherits:41,"level-errors":49,"readable-stream":57,xtend:139}],51:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],52:[function(require,module,exports){(function(process){function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),options&&!1===options.readable&&(this.readable=!1),options&&!1===options.writable&&(this.writable=!1),this.allowHalfOpen=!0,options&&!1===options.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",onend)}function onend(){this.allowHalfOpen||this._writableState.ended||process.nextTick(this.end.bind(this))}module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys},util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable),function(xs,f){for(var i=0,l=xs.length;i0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk)),addToFront||(state.reading=!1),state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state);else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM)n=MAX_HWM;else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:isNaN(n)||util.isNull(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:n<=0?0:(n>state.highWaterMark&&(state.highWaterMark=roundUpToNextPowerOf2(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return util.isBuffer(chunk)||util.isString(chunk)||util.isNullOrUndefined(chunk)||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?process.nextTick(function(){emitReadable_(stream)}):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(function(){maybeReadMore_(stream,state)}))}function maybeReadMore_(stream,state){ +for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=length)ret=stringMode?list.join(""):Buffer.concat(list,length),list.length=0;else if(n0)throw new Error("endReadable called on non-empty stream");state.endEmitted||(state.ended=!0,process.nextTick(function(){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}))}function forEach(xs,f){for(var i=0,l=xs.length;i0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,util.isNull(ret)&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&0===state.length&&endReadable(this),util.isNull(ret)||this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",cleanup),src.removeListener("data",ondata),!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),!1===dest.write(chunk)&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EE.listenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);return dest.on("drain",ondrain),src.on("data",ondata),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i1){for(var cbs=[],c=0;c=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived=55296&&charCode<=56319)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},{buffer:9}],59:[function(require,module,exports){(function(Buffer){function Level(location){if(!(this instanceof Level))return new Level(location);if(!location)throw new Error("constructor requires at least a location argument");this.IDBOptions={},this.location=location}module.exports=Level;var IDB=require("idb-wrapper"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,util=require("util"),Iterator=require("./iterator"),isBuffer=require("isbuffer"),xtend=require("xtend"),toBuffer=require("typedarray-to-buffer");util.inherits(Level,AbstractLevelDOWN),Level.prototype._open=function(options,callback){var self=this,idbOpts={storeName:this.location,autoIncrement:!1,keyPath:null,onStoreReady:function(){callback&&callback(null,self.idb)},onError:function(err){callback&&callback(err)}};xtend(idbOpts,options),this.IDBOptions=idbOpts,this.idb=new IDB(idbOpts)},Level.prototype._get=function(key,options,callback){this.idb.get(key,function(value){if(void 0===value)return callback(new Error("NotFound"));var asBuffer=!0;return!1===options.asBuffer&&(asBuffer=!1),options.raw&&(asBuffer=!1),asBuffer&&(value=value instanceof Uint8Array?toBuffer(value):new Buffer(String(value))),callback(null,value,key)},callback)},Level.prototype._del=function(id,options,callback){this.idb.remove(id,callback,callback)},Level.prototype._put=function(key,value,options,callback){value instanceof ArrayBuffer&&(value=toBuffer(new Uint8Array(value)));var obj=this.convertEncoding(key,value,options);Buffer.isBuffer(obj.value)&&("function"==typeof value.toArrayBuffer?obj.value=new Uint8Array(value.toArrayBuffer()):obj.value=new Uint8Array(value)),this.idb.put(obj.key,obj.value,function(){callback()},callback)},Level.prototype.convertEncoding=function(key,value,options){if(options.raw)return{key:key,value:value};if(value){var stringed=value.toString();"NaN"===stringed&&(value="NaN")}var valEnc=options.valueEncoding,obj={key:key,value:value};return!value||valEnc&&"binary"===valEnc||"object"!=typeof obj.value&&(obj.value=stringed),obj},Level.prototype.iterator=function(options){return"object"!=typeof options&&(options={}),new Iterator(this.idb,options)},Level.prototype._batch=function(array,options,callback){var i,k,copiedOp,currentOp,modified=[];if(0===array.length)return setTimeout(callback,0);for(i=0;i0&&this._count++>=this._limit&&(shouldCall=!1),shouldCall&&this.callback(!1,cursor.key,cursor.value),cursor&&cursor.continue()},Iterator.prototype._next=function(callback){return callback?this._keyRangeError?callback():(this._started||(this.createIterator(),this._started=!0),void(this.callback=callback)):new Error("next() requires a callback argument")}},{"abstract-leveldown":63,ltgt:81,util:137}],61:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;if(err=this._db._checkKeyValue(value,"value",this._db._isBuffer))throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:86}],62:[function(require,module,exports){arguments[4][15][0].apply(exports,arguments)},{_process:86,dup:15}],63:[function(require,module,exports){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");if("object"!=typeof options&&(options={}),"function"==typeof this._open)return this._open(options,callback);process.nextTick(callback)},AbstractLevelDOWN.prototype.close=function(callback){if("function"!=typeof callback)throw new Error("close() requires a callback argument");if("function"==typeof this._close)return this._close(callback);process.nextTick(callback)},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(err=this._checkKeyValue(value,"value",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));"object"!=typeof options&&(options={});for(var e,err,i=0,l=array.length;i2?arguments[2]:null;if(l===+l)for(i=0;i=0&&"[object Function]"===toString.call(value.callee)),isArguments}},{}],68:[function(require,module,exports){!function(){"use strict";var keysShim,has=Object.prototype.hasOwnProperty,toString=Object.prototype.toString,forEach=require("./foreach"),isArgs=require("./isArguments"),hasDontEnumBug=!{toString:null}.propertyIsEnumerable("toString"),hasProtoEnumBug=function(){}.propertyIsEnumerable("prototype"),dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];keysShim=function(object){var isObject=null!==object&&"object"==typeof object,isFunction="[object Function]"===toString.call(object),isArguments=isArgs(object),theKeys=[];if(!isObject&&!isFunction&&!isArguments)throw new TypeError("Object.keys called on a non-object");if(isArguments)forEach(object,function(value){theKeys.push(value)});else{var name,skipProto=hasProtoEnumBug&&isFunction;for(name in object)skipProto&&"prototype"===name||!has.call(object,name)||theKeys.push(name)}if(hasDontEnumBug){var ctor=object.constructor,skipConstructor=ctor&&ctor.prototype===object;forEach(dontEnums,function(dontEnum){skipConstructor&&"constructor"===dontEnum||!has.call(object,dontEnum)||theKeys.push(dontEnum)})}return theKeys},module.exports=keysShim}()},{"./foreach":65,"./isArguments":67}],69:[function(require,module,exports){function hasKeys(source){return null!==source&&("object"==typeof source||"function"==typeof source)}module.exports=hasKeys},{}],70:[function(require,module,exports){function extend(){for(var target={},i=0;i-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){return!(!isObject(value)||isMasked(value))&&(isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor).test(toSource(value))}function getMapData(map,key){var data=map.__data__;return isKeyable(key)?data["string"==typeof key?"string":"hash"]:data.map}function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:void 0}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function toSource(func){if(null!=func){try{return funcToString.call(func)}catch(e){}try{return func+""}catch(e){}}return""}function eq(value,other){return value===other||value!==value&&other!==other}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var difference=function(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=120&&array.length>=120)?new SetCache(othIndex&&array):void 0}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}var HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:"" +}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),splice=arrayProto.splice,nativeMax=Math.max,nativeMin=Math.min,Map=getNative(root,"Map"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var intersection=function(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=null==entries?0:entries.length;for(this.clear();++indexarrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&COMPARE_UNORDERED_FLAG?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index-1&&value%1==0&&value-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function stubArray(){return[]}function stubFalse(){return!1}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2,MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",arrayTag="[object Array]",asyncTag="[object AsyncFunction]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",nullTag="[object Null]",objectTag="[object Object]",proxyTag="[object Proxy]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",undefinedTag="[object Undefined]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags["[object Float32Array]"]=typedArrayTags["[object Float64Array]"]=typedArrayTags["[object Int8Array]"]=typedArrayTags["[object Int16Array]"]=typedArrayTags["[object Int32Array]"]=typedArrayTags["[object Uint8Array]"]=typedArrayTags["[object Uint8ClampedArray]"]=typedArrayTags["[object Uint16Array]"]=typedArrayTags["[object Uint32Array]"]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags["[object WeakMap]"]=!1;var freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),nativeObjectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Buffer=moduleExports?root.Buffer:void 0,Symbol=root.Symbol,Uint8Array=root.Uint8Array,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,symToStringTag=Symbol?Symbol.toStringTag:void 0,nativeGetSymbols=Object.getOwnPropertySymbols,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),DataView=getNative(root,"DataView"),Map=getNative(root,"Map"),Promise=getNative(root,"Promise"),Set=getNative(root,"Set"),WeakMap=getNative(root,"WeakMap"),nativeCreate=getNative(Object,"create"),dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap),symbolProto=Symbol?Symbol.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0;Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas,Stack.prototype.clear=stackClear,Stack.prototype.delete=stackDelete,Stack.prototype.get=stackGet,Stack.prototype.has=stackHas,Stack.prototype.set=stackSet;var getSymbols=nativeGetSymbols?function(object){return null==object?[]:(object=Object(object),arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol)}))}:stubArray,getTag=baseGetTag;(DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag||Map&&getTag(new Map)!=mapTag||Promise&&"[object Promise]"!=getTag(Promise.resolve())||Set&&getTag(new Set)!=setTag||WeakMap&&"[object WeakMap]"!=getTag(new WeakMap))&&(getTag=function(value){var result=baseGetTag(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):"";if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return"[object Promise]";case setCtorString:return setTag;case weakMapCtorString:return"[object WeakMap]"}return result});var isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isBuffer=nativeIsBuffer||stubFalse,isTypedArray=nodeIsTypedArray?function(func){return function(value){return func(value)}}(nodeIsTypedArray):baseIsTypedArray;module.exports=isEqual}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],77:[function(require,module,exports){function baseSortedIndex(array,value,retHighest){var low=0,high=array?array.length:low;if("number"==typeof value&&value===value&&high<=HALF_MAX_ARRAY_LENGTH){for(;low>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computedlength?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=length?array:baseSlice(array,start,end)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=void 0===start?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toFinite(value){if(!value)return 0===value?value:0;if((value=toNumber(value))===INFINITY||value===-INFINITY){return(value<0?-1:1)*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}var FUNC_ERROR_TEXT="Expected a function",INFINITY=1/0,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,symbolTag="[object Symbol]",reTrim=/^\s+|\s+$/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt,objectProto=Object.prototype,objectToString=objectProto.toString,nativeMax=Math.max;module.exports=spread},{}],79:[function(require,module,exports){(function(global){function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayIncludes(array,value){return!!(array?array.length:0)&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){return!(!isObject(value)||isMasked(value))&&(isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor).test(toSource(value))}function baseUniq(array,iteratee,comparator){var index=-1,includes=arrayIncludes,length=array.length,isCommon=!0,result=[],seen=result;if(comparator)isCommon=!1,includes=arrayIncludesWith;else if(length>=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}function noop(){} +var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),Set=getNative(root,"Set"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:noop,union=function(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexb?1:0};var lowerBoundKey=exports.lowerBoundKey=function(range){return hasKey(range,"gt")||hasKey(range,"gte")||hasKey(range,"min")||(range.reverse?hasKey(range,"end"):hasKey(range,"start"))||void 0},lowerBound=exports.lowerBound=function(range,def){var k=lowerBoundKey(range);return k?range[k]:def},lowerBoundInclusive=exports.lowerBoundInclusive=function(range){return!has(range,"gt")},upperBoundInclusive=exports.upperBoundInclusive=function(range){return!has(range,"lt")},lowerBoundExclusive=exports.lowerBoundExclusive=function(range){return!lowerBoundInclusive(range)},upperBoundExclusive=exports.upperBoundExclusive=function(range){return!upperBoundInclusive(range)},upperBoundKey=exports.upperBoundKey=function(range){return hasKey(range,"lt")||hasKey(range,"lte")||hasKey(range,"max")||(range.reverse?hasKey(range,"start"):hasKey(range,"end"))||void 0},upperBound=exports.upperBound=function(range,def){var k=upperBoundKey(range);return k?range[k]:def};exports.start=function(range,def){return range.reverse?upperBound(range,def):lowerBound(range,def)},exports.end=function(range,def){return range.reverse?lowerBound(range,def):upperBound(range,def)},exports.startInclusive=function(range){return range.reverse?upperBoundInclusive(range):lowerBoundInclusive(range)},exports.endInclusive=function(range){return range.reverse?lowerBoundInclusive(range):upperBoundInclusive(range)},exports.toLtgt=function(range,_range,map,lower,upper){_range=_range||{},map=map||id;var defaults=arguments.length>3,lb=exports.lowerBoundKey(range),ub=exports.upperBoundKey(range);return lb?"gt"===lb?_range.gt=map(range.gt,!1):_range.gte=map(range[lb],!1):defaults&&(_range.gte=map(lower,!1)),ub?"lt"===ub?_range.lt=map(range.lt,!0):_range.lte=map(range[ub],!0):defaults&&(_range.lte=map(upper,!0)),null!=range.reverse&&(_range.reverse=!!range.reverse),has(_range,"max")&&delete _range.max,has(_range,"min")&&delete _range.min,has(_range,"start")&&delete _range.start,has(_range,"end")&&delete _range.end,_range},exports.contains=function(range,key,compare){compare=compare||exports.compare;var lb=lowerBound(range);if(isDef(lb)){var cmp=compare(key,lb);if(cmp<0||0===cmp&&lowerBoundExclusive(range))return!1}var ub=upperBound(range);if(isDef(ub)){var cmp=compare(key,ub);if(cmp>0||0===cmp&&upperBoundExclusive(range))return!1}return!0},exports.filter=function(range,compare){return function(key){return exports.contains(range,key,compare)}}}).call(this,{isBuffer:require("../is-buffer/index.js")})},{"../is-buffer/index.js":43}],82:[function(require,module,exports){const getNGramsOfMultipleLengths=function(inputArray,nGramLengths){var outputArray=[];return nGramLengths.forEach(function(len){outputArray=outputArray.concat(getNGramsOfSingleLength(inputArray,len))}),outputArray},getNGramsOfRangeOfLengths=function(inputArray,nGramLengths){for(var outputArray=[],i=nGramLengths.gte;i<=nGramLengths.lte;i++)outputArray=outputArray.concat(getNGramsOfSingleLength(inputArray,i));return outputArray},getNGramsOfSingleLength=function(inputArray,nGramLength){return inputArray.slice(nGramLength-1).map(function(item,i){return inputArray.slice(i,i+nGramLength)})};exports.ngram=function(inputArray,nGramLength){switch(nGramLength.constructor){case Array:return getNGramsOfMultipleLengths(inputArray,nGramLength);case Number:return getNGramsOfSingleLength(inputArray,nGramLength);case Object:return getNGramsOfRangeOfLengths(inputArray,nGramLength)}}},{}],83:[function(require,module,exports){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}function onceStrict(fn){var f=function(){if(f.called)throw new Error(f.onceError);return f.called=!0,f.value=fn.apply(this,arguments)},name=fn.name||"Function wrapped with `once`";return f.onceError=name+" shouldn't be called more than once",f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),module.exports.strict=wrappy(onceStrict),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:!0})})},{wrappy:138}],84:[function(require,module,exports){exports.endianness=function(){return"LE"},exports.hostname=function(){return"undefined"!=typeof location?location.hostname:""},exports.loadavg=function(){return[]},exports.uptime=function(){return 0},exports.freemem=function(){return Number.MAX_VALUE},exports.totalmem=function(){return Number.MAX_VALUE},exports.cpus=function(){return[]},exports.type=function(){return"Browser"},exports.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},exports.networkInterfaces=exports.getNetworkInterfaces=function(){return{}},exports.arch=function(){return"javascript"},exports.platform=function(){return"browser"},exports.tmpdir=exports.tmpDir=function(){return"/tmp"},exports.EOL="\n"},{}],85:[function(require,module,exports){(function(process){"use strict";function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function(){fn.call(null,arg1)});case 3:return process.nextTick(function(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;i1)for(var i=1;i0,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})});return streams.reduce(pipe)};module.exports=pump},{"end-of-stream":34,fs:7,once:83}],89:[function(require,module,exports){var pump=require("pump"),inherits=require("inherits"),Duplexify=require("duplexify"),toArray=function(args){return args.length?Array.isArray(args[0])?args[0]:Array.prototype.slice.call(args):[]},define=function(opts){var Pumpify=function(){var streams=toArray(arguments);if(!(this instanceof Pumpify))return new Pumpify(streams);Duplexify.call(this,null,null,opts),streams.length&&this.setPipeline(streams)};return inherits(Pumpify,Duplexify),Pumpify.prototype.setPipeline=function(){var streams=toArray(arguments),self=this,ended=!1,w=streams[0],r=streams[streams.length-1];r=r.readable?r:null,w=w.writable?w:null;var onclose=function(){streams[0].emit("error",new Error("stream was destroyed"))};if(this.on("close",onclose),this.on("prefinish",function(){ended||self.cork()}),pump(streams,function(err){if(self.removeListener("close",onclose),err)return self.destroy(err);ended=!0,self.uncork()}),this.destroyed)return onclose();this.setWritable(w),this.setReadable(r)},Pumpify};module.exports=define({destroy:!1}),module.exports.obj=define({destroy:!1,objectMode:!0,highWaterMark:16})},{duplexify:31,inherits:41,pump:88}],90:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":91}],91:[function(require,module,exports){"use strict";function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),options&&!1===options.readable&&(this.readable=!1),options&&!1===options.writable&&(this.writable=!1),this.allowHalfOpen=!0,options&&!1===options.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",onend)}function onend(){this.allowHalfOpen||this._writableState.ended||processNextTick(onEndNT,this)}function onEndNT(self){self.end()}var processNextTick=require("process-nextick-args"),objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v0?("string"==typeof chunk||Object.getPrototypeOf(chunk)===Buffer.prototype||state.objectMode||(chunk=_uint8ArrayToBuffer(chunk)),addToFront?state.endEmitted?stream.emit("error",new Error("stream.unshift() after end event")):addChunk(stream,state,chunk,!0):state.ended?stream.emit("error",new Error("stream.push() after EOF")):(state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1))):addToFront||(state.reading=!1)}return needMoreData(state)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(nb===str.length?ret+=str:ret+=str.slice(0,n),0===(n-=nb)){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=Buffer.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),0===(n-=nb)){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1,!1!==dest.write(chunk)||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:unpipe;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("safe-buffer").Buffer,destroyImpl=require("./internal/streams/destroy");util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=_isUint8Array(chunk)&&!state.objectMode;return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)},Object.defineProperty(Writable.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){this.end(),cb(err)}}).call(this,require("_process"))},{"./_stream_duplex":91,"./internal/streams/destroy":97,"./internal/streams/stream":98,_process:86,"core-util-is":11,inherits:41,"process-nextick-args":85,"safe-buffer":103,"util-deprecate":134}],96:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function copyBuffer(src,target,offset){src.copy(target,offset)}var Buffer=require("safe-buffer").Buffer;module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return Buffer.alloc(0);if(1===this.length)return this.head.data;for(var ret=Buffer.allocUnsafe(n>>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret},BufferList}()},{"safe-buffer":103}],97:[function(require,module,exports){"use strict";function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;if(readableDestroyed||writableDestroyed)return void(cb?cb(err):!err||this._writableState&&this._writableState.errorEmitted||processNextTick(emitErrorNT,this,err));this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?(processNextTick(emitErrorNT,_this,err),_this._writableState&&(_this._writableState.errorEmitted=!0)):cb&&cb(err)})}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(self,err){self.emit("error",err)}var processNextTick=require("process-nextick-args");module.exports={destroy:destroy,undestroy:undestroy}},{"process-nextick-args":85}],98:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:38}],99:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":100}],100:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":91,"./lib/_stream_passthrough.js":92,"./lib/_stream_readable.js":93,"./lib/_stream_transform.js":94,"./lib/_stream_writable.js":95}],101:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":100}],102:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":95}],103:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0!==fill?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:9}],104:[function(require,module,exports){function throwsMessage(err){return"[Throws: "+(err?err.message:"?")+"]"}function safeGetValueFromPropertyOnObject(obj,property){if(hasProp.call(obj,property))try{return obj[property]}catch(err){return throwsMessage(err)}return obj[property]}function ensureProperties(obj){function visit(obj){if(null===obj||"object"!=typeof obj)return obj;if(-1!==seen.indexOf(obj))return"[Circular]";if(seen.push(obj),"function"==typeof obj.toJSON)try{return visit(obj.toJSON())}catch(err){return throwsMessage(err)}return Array.isArray(obj)?obj.map(visit):Object.keys(obj).reduce(function(result,prop){return result[prop]=visit(safeGetValueFromPropertyOnObject(obj,prop)),result},{})}var seen=[];return visit(obj)}var hasProp=Object.prototype.hasOwnProperty;module.exports=function(data){return JSON.stringify(ensureProperties(data))},module.exports.ensureProperties=ensureProperties},{}],105:[function(require,module,exports){const DBEntries=require("./lib/delete.js").DBEntries,DBWriteCleanStream=require("./lib/replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./lib/replicate.js").DBWriteMergeStream,DocVector=require("./lib/delete.js").DocVector,IndexBatch=require("./lib/add.js").IndexBatch,JSONStream=require("JSONStream"),Readable=require("stream").Readable,RecalibrateDB=require("./lib/delete.js").RecalibrateDB,bunyan=require("bunyan"),del=require("./lib/delete.js"),docProc=require("docproc"),levelup=require("levelup"),pumpify=require("pumpify"),async=require("async");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){var Indexer={};Indexer.options=options;var q=async.queue(function(batch,done){var s;"add"===batch.operation?(s=new Readable({objectMode:!0}),batch.batch.forEach(function(doc){s.push(doc)}),s.push(null),s.pipe(Indexer.defaultPipeline(batch.batchOps)).pipe(Indexer.add()).on("finish",function(){return done()}).on("error",function(err){return done(err)})):"delete"===batch.operation&&(s=new Readable,batch.docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)}))},1);return Indexer.add=function(){return pumpify.obj(new IndexBatch(Indexer),new DBWriteMergeStream(options))},Indexer.concurrentAdd=function(batchOps,batch,done){q.push({batch:batch,batchOps:batchOps,operation:"add"},function(err){done(err)})},Indexer.concurrentDel=function(docIds,done){q.push({docIds:docIds,operation:"delete"},function(err){done(err)})},Indexer.close=function(callback){options.indexes.close(function(err){for(;!options.indexes.isClosed();)options.log.debug("closing...");options.indexes.isClosed()&&(options.log.debug("closed..."),callback(err))})},Indexer.dbWriteStream=function(streamOps){return streamOps=Object.assign({},{merge:!0},streamOps),streamOps.merge?new DBWriteMergeStream(options):new DBWriteCleanStream(options)},Indexer.defaultPipeline=function(batchOptions){return batchOptions=Object.assign({},options,batchOptions),docProc.pipeline(batchOptions)},Indexer.deleteStream=function(options){return pumpify.obj(new DocVector(options),new DBEntries(options),new RecalibrateDB(options))},Indexer.deleter=function(docIds,done){const s=new Readable;docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)})},Indexer.feed=function(ops){return ops&&ops.objectMode?pumpify.obj(Indexer.defaultPipeline(ops),Indexer.add(ops)):pumpify(JSONStream.parse(),Indexer.defaultPipeline(ops),Indexer.add(ops))},Indexer.flush=function(APICallback){del.flush(options,function(err){return APICallback(err)})},callback(err,Indexer)})};const getOptions=function(options,done){if(options=Object.assign({},{deletable:!0,batchSize:1e3,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,searchable:!0,indexPath:"si",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/\s|\\n|\\u0003|[-.,<>]/,stopwords:[],weight:0},options),options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes)done(null,options);else{const leveldown=require("leveldown");levelup(options.indexPath||"si",{valueEncoding:"json",db:leveldown},function(err,db){options.indexes=db,done(err,options)})}}},{"./lib/add.js":106,"./lib/delete.js":107,"./lib/replicate.js":108,JSONStream:3,async:5,bunyan:10,docproc:19,leveldown:59,levelup:72,pumpify:89,stream:127}],106:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),emitIndexKeys=function(s){for(var key in s.deltaIndex)s.push({key:key,value:s.deltaIndex[key]});s.deltaIndex={}},IndexBatch=function(indexer){this.indexer=indexer,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.indexer.options.keySeparator;var that=this;this.indexer.deleter([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.indexer.options.log.info("processing doc "+ingestedDoc.id),that.deltaIndex["DOCUMENT"+sep+ingestedDoc.id+sep]=ingestedDoc.stored;for(var fieldName in ingestedDoc.vector){that.deltaIndex["FIELD"+sep+fieldName]=fieldName;for(var token in ingestedDoc.vector[fieldName]){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token,dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id]),that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.deltaIndex["DOCUMENT-VECTOR"+sep+ingestedDoc.id+sep+fieldName+sep]=ingestedDoc.vector[fieldName]}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.indexer.options.batchSize&&(that.push({totalKeys:totalKeys}),that.indexer.options.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:127,util:137}],107:[function(require,module,exports){const util=require("util"),Transform=require("stream").Transform;exports.flush=function(options,callback){const sep=options.keySeparator;var deleteOps=[];options.indexes.createKeyStream({gte:"0",lte:sep}).on("data",function(data){deleteOps.push({type:"del",key:data})}).on("error",function(err){return options.log.error(err," failed to empty index"),callback(err)}).on("end",function(){options.indexes.batch(deleteOps,callback)})};const DocVector=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DocVector=DocVector,util.inherits(DocVector,Transform),DocVector.prototype._transform=function(docId,encoding,end){docId=JSON.parse(docId);const sep=this.options.keySeparator;var that=this;this.options.indexes.createReadStream({gte:"DOCUMENT-VECTOR"+sep+docId+sep,lte:"DOCUMENT-VECTOR"+sep+docId+sep+sep}).on("data",function(data){that.push(data)}).on("close",function(){return end()})};const DBEntries=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DBEntries=DBEntries, +util.inherits(DBEntries,Transform),DBEntries.prototype._transform=function(vector,encoding,end){const sep=this.options.keySeparator;var docId;for(var k in vector.value){docId=vector.key.split(sep)[1];var field=vector.key.split(sep)[2];this.push({key:"TF"+sep+field+sep+k,value:docId}),this.push({key:"DF"+sep+field+sep+k,value:docId})}return this.push({key:vector.key}),this.push({key:"DOCUMENT"+sep+docId+sep}),end()};const RecalibrateDB=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.RecalibrateDB=RecalibrateDB,util.inherits(RecalibrateDB,Transform),RecalibrateDB.prototype._transform=function(dbEntry,encoding,end){const sep=this.options.keySeparator;var that=this;this.options.indexes.get(dbEntry.key,function(err,value){err&&that.options.log.info(err),value||(value=[]);var docId=dbEntry.value,dbInstruction={};dbInstruction.key=dbEntry.key,dbEntry.key.substring(0,3)==="TF"+sep?(dbInstruction.value=value.filter(function(item){return item[1]!==docId}),0===dbInstruction.value.length?dbInstruction.type="del":dbInstruction.type="put"):dbEntry.key.substring(0,3)==="DF"+sep?(value.splice(value.indexOf(docId),1),dbInstruction.value=value,0===dbInstruction.value.length?dbInstruction.type="del":dbInstruction.type="put"):dbEntry.key.substring(0,9)==="DOCUMENT"+sep?dbInstruction.type="del":dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep&&(dbInstruction.type="del"),that.options.indexes.batch([dbInstruction],function(err){return end()})})}},{stream:127,util:137}],108:[function(require,module,exports){const Transform=require("stream").Transform,Writable=require("stream").Writable,util=require("util"),DBWriteMergeStream=function(options){this.options=options,Writable.call(this,{objectMode:!0})};exports.DBWriteMergeStream=DBWriteMergeStream,util.inherits(DBWriteMergeStream,Writable),DBWriteMergeStream.prototype._write=function(data,encoding,end){if(data.totalKeys)return end();const sep=this.options.keySeparator;var that=this;this.options.indexes.get(data.key,function(err,val){var newVal;newVal=data.key.substring(0,3)==="TF"+sep?data.value.concat(val||[]).sort(function(a,b){return a[0]b[0]?-1:a[1]b[1]?-1:0}):data.key.substring(0,3)==="DF"+sep?data.value.concat(val||[]).sort():"DOCUMENT-COUNT"===data.key?+val+(+data.value||0):data.value,that.options.indexes.put(data.key,newVal,function(err){end()})})};const DBWriteCleanStream=function(options){this.currentBatch=[],this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(DBWriteCleanStream,Transform),DBWriteCleanStream.prototype._transform=function(data,encoding,end){var that=this;this.currentBatch.push(data),this.currentBatch.length%this.options.batchSize==0?this.options.indexes.batch(this.currentBatch,function(err){that.push("indexing batch"),that.currentBatch=[],end()}):end()},DBWriteCleanStream.prototype._flush=function(end){var that=this;this.options.indexes.batch(this.currentBatch,function(err){that.push("remaining data indexed"),end()})},exports.DBWriteCleanStream=DBWriteCleanStream},{stream:127,util:137}],109:[function(require,module,exports){const AvailableFields=require("./lib/AvailableFields.js").AvailableFields,CalculateBuckets=require("./lib/CalculateBuckets.js").CalculateBuckets,CalculateCategories=require("./lib/CalculateCategories.js").CalculateCategories,CalculateEntireResultSet=require("./lib/CalculateEntireResultSet.js").CalculateEntireResultSet,CalculateResultSetPerClause=require("./lib/CalculateResultSetPerClause.js").CalculateResultSetPerClause,CalculateTopScoringDocs=require("./lib/CalculateTopScoringDocs.js").CalculateTopScoringDocs,CalculateTotalHits=require("./lib/CalculateTotalHits.js").CalculateTotalHits,Classify=require("./lib/Classify.js").Classify,FetchDocsFromDB=require("./lib/FetchDocsFromDB.js").FetchDocsFromDB,FetchStoredDoc=require("./lib/FetchStoredDoc.js").FetchStoredDoc,GetIntersectionStream=require("./lib/GetIntersectionStream.js").GetIntersectionStream,MergeOrConditions=require("./lib/MergeOrConditions.js").MergeOrConditions,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,SortTopScoringDocs=require("./lib/SortTopScoringDocs.js").SortTopScoringDocs,bunyan=require("bunyan"),levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),initModule=function(err,Searcher,moduleReady){return Searcher.bucketStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateBuckets(Searcher.options,q.filter||{},q.buckets))},Searcher.categoryStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateCategories(Searcher.options,q))},Searcher.classify=function(ops){return new Classify(Searcher,ops)},Searcher.close=function(callback){Searcher.options.indexes.close(function(err){for(;!Searcher.options.indexes.isClosed();)Searcher.options.log.debug("closing...");Searcher.options.indexes.isClosed()&&(Searcher.options.log.debug("closed..."),callback(err))})},Searcher.availableFields=function(){const sep=Searcher.options.keySeparator;return Searcher.options.indexes.createReadStream({gte:"FIELD"+sep,lte:"FIELD"+sep+sep}).pipe(new AvailableFields(Searcher.options))},Searcher.get=function(docIDs){var s=new Readable({objectMode:!0});return docIDs.forEach(function(id){s.push(id)}),s.push(null),s.pipe(new FetchDocsFromDB(Searcher.options))},Searcher.fieldNames=function(){return Searcher.options.indexes.createReadStream({gte:"FIELD",lte:"FIELD"})},Searcher.match=function(q){return matcher.match(q,Searcher.options)},Searcher.dbReadStream=function(){return Searcher.options.indexes.createReadStream()},Searcher.search=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),q.sort?s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options)):s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreTopScoringDocsTFIDF(Searcher.options)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options))},Searcher.scan=function(q){q=siUtil.getQueryDefaults(q);var s=new Readable({objectMode:!0});return s.push("init"),s.push(null),s.pipe(new GetIntersectionStream(Searcher.options,siUtil.getKeySet(q.query[0].AND,Searcher.options.keySeparator))).pipe(new FetchDocsFromDB(Searcher.options))},Searcher.totalHits=function(q,callback){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateTotalHits(Searcher.options)).on("data",function(totalHits){return callback(null,totalHits)})},moduleReady(err,Searcher)},getOptions=function(options,done){var Searcher={};if(Searcher.options=Object.assign({},{deletable:!0,fieldedSearch:!0,store:!0,indexPath:"si",keySeparator:"○",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/[|' .,\-|(\n)]+/,stopwords:[]},options),Searcher.options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes)return done(null,Searcher);levelup(Searcher.options.indexPath||"si",{valueEncoding:"json"},function(err,db){return Searcher.options.indexes=db,done(err,Searcher)})};module.exports=function(givenOptions,moduleReady){getOptions(givenOptions,function(err,Searcher){initModule(err,Searcher,moduleReady)})}},{"./lib/AvailableFields.js":110,"./lib/CalculateBuckets.js":111,"./lib/CalculateCategories.js":112,"./lib/CalculateEntireResultSet.js":113,"./lib/CalculateResultSetPerClause.js":114,"./lib/CalculateTopScoringDocs.js":115,"./lib/CalculateTotalHits.js":116,"./lib/Classify.js":117,"./lib/FetchDocsFromDB.js":118,"./lib/FetchStoredDoc.js":119,"./lib/GetIntersectionStream.js":120,"./lib/MergeOrConditions.js":121,"./lib/ScoreDocsOnField.js":122,"./lib/ScoreTopScoringDocsTFIDF.js":123,"./lib/SortTopScoringDocs.js":124,"./lib/matcher.js":125,"./lib/siUtil.js":126,bunyan:10,levelup:72,stream:127}],110:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),AvailableFields=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.AvailableFields=AvailableFields,util.inherits(AvailableFields,Transform),AvailableFields.prototype._transform=function(field,encoding,end){return this.push(field.key.split(this.options.keySeparator)[1]),end()}},{stream:127,util:137}],111:[function(require,module,exports){const _intersection=require("lodash.intersection"),_uniq=require("lodash.uniq"),Transform=require("stream").Transform,util=require("util"),CalculateBuckets=function(options,filter,requestedBuckets){this.buckets=requestedBuckets||[],this.filter=filter,this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateBuckets=CalculateBuckets,util.inherits(CalculateBuckets,Transform),CalculateBuckets.prototype._transform=function(mergedQueryClauses,encoding,end){const that=this,sep=this.options.keySeparator;var bucketsProcessed=0;that.buckets.forEach(function(bucket){const gte="DF"+sep+bucket.field+sep+bucket.gte,lte="DF"+sep+bucket.field+sep+bucket.lte+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){var IDSet=_intersection(data.value,mergedQueryClauses.set);IDSet.length>0&&(bucket.value=bucket.value||[],bucket.value=_uniq(bucket.value.concat(IDSet).sort()))}).on("close",function(){if(bucket.set||(bucket.value=bucket.value.length),that.push(bucket),++bucketsProcessed===that.buckets.length)return end()})})}},{"lodash.intersection":75,"lodash.uniq":80,stream:127,util:137}],112:[function(require,module,exports){const _intersection=require("lodash.intersection"),Transform=require("stream").Transform,util=require("util"),CalculateCategories=function(options,q){var category=q.category||[];category.values=[],this.offset=+q.offset,this.pageSize=+q.pageSize,this.category=category,this.options=options,this.query=q.query,Transform.call(this,{objectMode:!0})};exports.CalculateCategories=CalculateCategories,util.inherits(CalculateCategories,Transform),CalculateCategories.prototype._transform=function(mergedQueryClauses,encoding,end){if(!this.category.field)return end(new Error("you need to specify a category"));const sep=this.options.keySeparator,that=this,gte="DF"+sep+this.category.field+sep,lte="DF"+sep+this.category.field+sep+sep;this.category.values=this.category.values||[];var i=this.offset+this.pageSize,j=0;const rs=that.options.indexes.createReadStream({gte:gte,lte:lte});rs.on("data",function(data){if(!(that.offset>j++)){var IDSet=_intersection(data.value,mergedQueryClauses.set);if(IDSet.length>0){var key=data.key.split(sep)[2],value=IDSet.length;that.category.set&&(value=IDSet);var result={key:key,value:value};if(1===that.query.length)try{that.query[0].AND[that.category.field].indexOf(key)>-1&&(result.filter=!0)}catch(e){}i-- >that.offset?that.push(result):rs.destroy()}}}).on("close",function(){return end()})}},{"lodash.intersection":75,stream:127,util:137}],113:[function(require,module,exports){const Transform=require("stream").Transform,_union=require("lodash.union"),util=require("util"),CalculateEntireResultSet=function(options){this.options=options,this.setSoFar=[],Transform.call(this,{objectMode:!0})};exports.CalculateEntireResultSet=CalculateEntireResultSet,util.inherits(CalculateEntireResultSet,Transform),CalculateEntireResultSet.prototype._transform=function(queryClause,encoding,end){return this.setSoFar=_union(queryClause.set,this.setSoFar),end()},CalculateEntireResultSet.prototype._flush=function(end){return this.push({set:this.setSoFar}),end()}},{"lodash.union":79,stream:127,util:137}],114:[function(require,module,exports){const Transform=require("stream").Transform,_difference=require("lodash.difference"),_intersection=require("lodash.intersection"),_spread=require("lodash.spread"),siUtil=require("./siUtil.js"),util=require("util"),CalculateResultSetPerClause=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateResultSetPerClause=CalculateResultSetPerClause,util.inherits(CalculateResultSetPerClause,Transform),CalculateResultSetPerClause.prototype._transform=function(queryClause,encoding,end){const sep=this.options.keySeparator,that=this,frequencies=[];var NOT=function(includeResults){const bigIntersect=_spread(_intersection);var include=bigIntersect(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,termFrequencies:frequencies,BOOST:queryClause.BOOST||0}),end();var i=0,excludeResults=[];siUtil.getKeySet(queryClause.NOT,sep).forEach(function(item){var excludeSet={};that.options.indexes.createReadStream({gte:item[0],lte:item[1]+sep}).on("data",function(data){for(var i=0;ib.id?-1:0}).reduce(function(merged,cur){var lastDoc=merged[merged.length-1];return 0===merged.length||cur.id!==lastDoc.id?merged.push(cur):cur.id===lastDoc.id&&(lastDoc.scoringCriteria=lastDoc.scoringCriteria.concat(cur.scoringCriteria)),merged},[]);return mergedResultSet.map(function(item){return item.scoringCriteria&&(item.score=item.scoringCriteria.reduce(function(acc,val){return{score:+acc.score+ +val.score}},{score:0}).score,item.score=item.score/item.scoringCriteria.length),item}),mergedResultSet.forEach(function(item){that.push(item)}),end()}},{stream:127,util:137}],122:[function(require,module,exports){const Transform=require("stream").Transform,_sortedIndexOf=require("lodash.sortedindexof"),util=require("util"),ScoreDocsOnField=function(options,seekLimit,sort){this.options=options,this.seekLimit=seekLimit,this.sort=sort,Transform.call(this,{objectMode:!0})};exports.ScoreDocsOnField=ScoreDocsOnField,util.inherits(ScoreDocsOnField,Transform),ScoreDocsOnField.prototype._transform=function(clauseSet,encoding,end){const sep=this.options.keySeparator,that=this,gte="TF"+sep+this.sort.field+sep,lte="TF"+sep+this.sort.field+sep+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){for(var i=0;ib.score?-2:a.idb.id?-1:0}):this.resultSet=this.resultSet.sort(function(a,b){return a.score>b.score?2:a.scoreb.id?-1:0}),this.resultSet=this.resultSet.slice(this.q.offset,this.q.offset+this.q.pageSize),this.resultSet.forEach(function(hit){that.push(hit)}),end()}},{stream:127,util:137}],125:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatcherStream=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatcherStream,Transform),MatcherStream.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var results=[];this.options.indexes.createReadStream({start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep}).on("data",function(data){results.push(data)}).on("error",function(err){that.options.log.error("Oh my!",err)}).on("end",function(){return results.sort(function(a,b){return b.value.length-a.value.length}).slice(0,q.limit).forEach(function(item){var m={};switch(q.type){case"ID":m={token:item.key.split(sep)[2],documents:item.value};break;case"count":m={token:item.key.split(sep)[2],documentCount:item.value.length};break;default:m=item.key.split(sep)[2]}that.push(m)}),end()})},exports.match=function(q,options){var s=new Readable({objectMode:!0});return q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple"},q),q.beginsWith.length>5==6?2:byte>>4==14?3:byte>>3==30?4:-1}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j=0?(nb>0&&(self.lastNeed=nb-1),nb):--j=0?(nb>0&&(self.lastNeed=nb-2),nb):--j=0?(nb>0&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0)}function utf8CheckExtraBytes(self,buf,p){if(128!=(192&buf[0]))return self.lastNeed=0,"�".repeat(p);if(self.lastNeed>1&&buf.length>1){if(128!=(192&buf[1]))return self.lastNeed=1,"�".repeat(p+1);if(self.lastNeed>2&&buf.length>2&&128!=(192&buf[2]))return self.lastNeed=2,"�".repeat(p+2)}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0!==r?r:this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(buf.copy(this.lastChar,p,0,buf.length),void(this.lastNeed-=buf.length))}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"�".repeat(this.lastTotal-this.lastNeed):r}function utf16Text(buf,i){if((buf.length-i)%2==0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0===n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3, +1===n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch((encoding=""+encoding)&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(void 0===(r=this.fillLast(buf)))return"";i=this.lastNeed,this.lastNeed=0}else i=0;return itokens.length)return[];for(var ngrams=[],i=0;i<=tokens.length-nGramLength;i++)ngrams.push(tokens.slice(i,i+nGramLength));if(ngrams=ngrams.sort(),1===ngrams.length)return[[ngrams[0],1]];for(var counter=1,lastToken=ngrams[0],vector=[],j=1;j=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){base=" [Function"+(value.name?": "+value.name:"")+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(recurseTimes<0)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;return output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}}),x=args[i];i=0;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return!Error.isPrototypeOf(expected)&&!0===expected.call({},actual)}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError('"block" argument must be a function');"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}var util=require("util/"),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames=function(){return"foo"===function(){}.name}(),assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert.throws=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":134}],4:[function(require,module,exports){(function(process,global){!function(global,factory){"object"==typeof exports&&void 0!==module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory(global.async=global.async||{})}(this,function(exports){"use strict";function slice(arrayLike,start){start|=0;for(var newLen=Math.max(arrayLike.length-start,0),newArr=Array(newLen),idx=0;idx-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function noop(){}function once(fn){return function(){if(null!==fn){var callFn=fn;fn=null,callFn.apply(this,arguments)}}}function baseTimes(n,iteratee){for(var index=-1,result=Array(n);++index-1&&value%1==0&&valuelength?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=length?array:baseSlice(array,start,end)}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function charsStartIndex(strSymbols,chrSymbols){for(var index=-1,length=strSymbols.length;++index-1;);return index}function asciiToArray(string){return string.split("")}function hasUnicode(string){return reHasUnicode.test(string)}function unicodeToArray(string){return string.match(reUnicode)||[]}function stringToArray(string){return hasUnicode(string)?unicodeToArray(string):asciiToArray(string)}function toString(value){return null==value?"":baseToString(value)}function trim(string,chars,guard){if((string=toString(string))&&(guard||void 0===chars))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars);return castSlice(strSymbols,charsStartIndex(strSymbols,chrSymbols),charsEndIndex(strSymbols,chrSymbols)+1).join("")}function parseParams(func){return func=func.toString().replace(STRIP_COMMENTS,""),func=func.match(FN_ARGS)[2].replace(" ",""),func=func?func.split(FN_ARG_SPLIT):[],func=func.map(function(arg){return trim(arg.replace(FN_ARG,""))})}function autoInject(tasks,callback){var newTasks={};baseForOwn(tasks,function(taskFn,key){function newTask(results,taskCb){var newArgs=arrayMap(params,function(name){return results[name]});newArgs.push(taskCb),wrapAsync(taskFn).apply(null,newArgs)}var params,fnIsAsync=isAsync(taskFn),hasNoDeps=!fnIsAsync&&1===taskFn.length||fnIsAsync&&0===taskFn.length;if(isArray(taskFn))params=taskFn.slice(0,-1),taskFn=taskFn[taskFn.length-1],newTasks[key]=params.concat(params.length>0?newTask:taskFn);else if(hasNoDeps)newTasks[key]=taskFn;else{if(params=parseParams(taskFn),0===taskFn.length&&!fnIsAsync&&0===params.length)throw new Error("autoInject task functions require explicit parameters.");fnIsAsync||params.pop(),newTasks[key]=params.concat(newTask)}}),auto(newTasks,callback)}function DLL(){this.head=this.tail=null,this.length=0}function setInitial(dll,node){dll.length=1,dll.head=dll.tail=node}function queue(worker,concurrency,payload){function _insert(data,insertAtFront,callback){if(null!=callback&&"function"!=typeof callback)throw new Error("task callback must be a function");if(q.started=!0,isArray(data)||(data=[data]),0===data.length&&q.idle())return setImmediate$1(function(){q.drain()});for(var i=0,l=data.length;i=0&&workersList.splice(index),task.callback.apply(task,arguments),null!=err&&q.error(err,task.data)}numRunning<=q.concurrency-q.buffer&&q.unsaturated(),q.idle()&&q.drain(),q.process()}}if(null==concurrency)concurrency=1;else if(0===concurrency)throw new Error("Concurrency must not be zero");var _worker=wrapAsync(worker),numRunning=0,workersList=[],isProcessing=!1,q={_tasks:new DLL,concurrency:concurrency,payload:payload,saturated:noop,unsaturated:noop,buffer:concurrency/4,empty:noop,drain:noop,error:noop,started:!1,paused:!1,push:function(data,callback){_insert(data,!1,callback)},kill:function(){q.drain=noop,q._tasks.empty()},unshift:function(data,callback){_insert(data,!0,callback)},remove:function(testFn){q._tasks.remove(testFn)},process:function(){if(!isProcessing){for(isProcessing=!0;!q.paused&&numRunning2&&(result=slice(arguments,1)),results[key]=result,callback(err)})},function(err){callback(err,results)})}function parallelLimit(tasks,callback){_parallel(eachOf,tasks,callback)}function parallelLimit$1(tasks,limit,callback){_parallel(_eachOfLimit(limit),tasks,callback)}function race(tasks,callback){if(callback=once(callback||noop),!isArray(tasks))return callback(new TypeError("First argument to race must be an array of functions"));if(!tasks.length)return callback();for(var i=0,l=tasks.length;ib?1:0}var _iteratee=wrapAsync(iteratee);map(coll,function(x,callback){_iteratee(x,function(err,criteria){ -if(err)return callback(err);callback(null,{value:x,criteria:criteria})})},function(err,results){if(err)return callback(err);callback(null,arrayMap(results.sort(comparator),baseProperty("value")))})}function timeout(asyncFn,milliseconds,info){var fn=wrapAsync(asyncFn);return initialParams(function(args,callback){function timeoutCallback(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,callback(error)}var timer,timedOut=!1;args.push(function(){timedOut||(callback.apply(null,arguments),clearTimeout(timer))}),timer=setTimeout(timeoutCallback,milliseconds),fn.apply(null,args)})}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function timeLimit(count,limit,iteratee,callback){var _iteratee=wrapAsync(iteratee);mapLimit(baseRange(0,count,1),limit,_iteratee,callback)}function transform(coll,accumulator,iteratee,callback){arguments.length<=3&&(callback=iteratee,iteratee=accumulator,accumulator=isArray(coll)?[]:{}),callback=once(callback||noop);var _iteratee=wrapAsync(iteratee);eachOf(coll,function(v,k,cb){_iteratee(accumulator,v,k,cb)},function(err){callback(err,accumulator)})}function tryEach(tasks,callback){var result,error=null;callback=callback||noop,eachSeries(tasks,function(task,callback){wrapAsync(task)(function(err,res){result=arguments.length>2?slice(arguments,1):res,error=err,callback(!err)})},function(){callback(error,result)})}function unmemoize(fn){return function(){return(fn.unmemoized||fn).apply(null,arguments)}}function whilst(test,iteratee,callback){callback=onlyOnce(callback||noop);var _iteratee=wrapAsync(iteratee);if(!test())return callback(null);var next=function(err){if(err)return callback(err);if(test())return _iteratee(next);var args=slice(arguments,1);callback.apply(null,[null].concat(args))};_iteratee(next)}function until(test,iteratee,callback){whilst(function(){return!test.apply(this,arguments)},iteratee,callback)}var _defer,initialParams=function(fn){return function(){var args=slice(arguments),callback=args.pop();fn.call(this,args,callback)}},hasSetImmediate="function"==typeof setImmediate&&setImmediate,hasNextTick="object"==typeof process&&"function"==typeof process.nextTick;_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback;var setImmediate$1=wrap(_defer),supportsSymbol="function"==typeof Symbol,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol$1=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag$1=Symbol$1?Symbol$1.toStringTag:void 0,objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString,nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol$1?Symbol$1.toStringTag:void 0,asyncTag="[object AsyncFunction]",funcTag="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]",MAX_SAFE_INTEGER=9007199254740991,breakLoop={},iteratorSymbol="function"==typeof Symbol&&Symbol.iterator,getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()},argsTag="[object Arguments]",objectProto$3=Object.prototype,hasOwnProperty$2=objectProto$3.hasOwnProperty,propertyIsEnumerable=objectProto$3.propertyIsEnumerable,isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty$2.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,Buffer=moduleExports?root.Buffer:void 0,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,MAX_SAFE_INTEGER$1=9007199254740991,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags["[object Float32Array]"]=typedArrayTags["[object Float64Array]"]=typedArrayTags["[object Int8Array]"]=typedArrayTags["[object Int16Array]"]=typedArrayTags["[object Int32Array]"]=typedArrayTags["[object Uint8Array]"]=typedArrayTags["[object Uint8ClampedArray]"]=typedArrayTags["[object Uint16Array]"]=typedArrayTags["[object Uint32Array]"]=!0,typedArrayTags["[object Arguments]"]=typedArrayTags["[object Array]"]=typedArrayTags["[object ArrayBuffer]"]=typedArrayTags["[object Boolean]"]=typedArrayTags["[object DataView]"]=typedArrayTags["[object Date]"]=typedArrayTags["[object Error]"]=typedArrayTags["[object Function]"]=typedArrayTags["[object Map]"]=typedArrayTags["[object Number]"]=typedArrayTags["[object Object]"]=typedArrayTags["[object RegExp]"]=typedArrayTags["[object Set]"]=typedArrayTags["[object String]"]=typedArrayTags["[object WeakMap]"]=!1;var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,freeProcess=moduleExports$1&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?function(func){return function(value){return func(value)}}(nodeIsTypedArray):baseIsTypedArray,objectProto$2=Object.prototype,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),objectProto$4=Object.prototype,hasOwnProperty$3=objectProto$4.hasOwnProperty,eachOfGeneric=doLimit(eachOfLimit,1/0),eachOf=function(coll,iteratee,callback){(isArrayLike(coll)?eachOfArrayLike:eachOfGeneric)(coll,wrapAsync(iteratee),callback)},map=doParallel(_asyncMap),applyEach=applyEach$1(map),mapLimit=doParallelLimit(_asyncMap),mapSeries=doLimit(mapLimit,1),applyEachSeries=applyEach$1(mapSeries),apply=function(fn){var args=slice(arguments,1);return function(){var callArgs=slice(arguments);return fn.apply(null,args.concat(callArgs))}},baseFor=function(fromRight){return function(object,iteratee,keysFunc){for(var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length;length--;){var key=props[fromRight?length:++index];if(!1===iteratee(iterable[key],key,iterable))break}return object}}(),auto=function(tasks,concurrency,callback){function enqueueTask(key,task){readyTasks.push(function(){runTask(key,task)})}function processQueue(){if(0===readyTasks.length&&0===runningTasks)return callback(null,results);for(;readyTasks.length&&runningTasks2&&(result=slice(arguments,1)),err){var safeResults={};baseForOwn(results,function(val,rkey){safeResults[rkey]=val}),safeResults[key]=result,hasError=!0,listeners=Object.create(null),callback(err,safeResults)}else results[key]=result,taskComplete(key)});runningTasks++;var taskFn=wrapAsync(task[task.length-1]);task.length>1?taskFn(results,taskCallback):taskFn(taskCallback)}}function getDependents(taskName){var result=[];return baseForOwn(tasks,function(task,key){isArray(task)&&baseIndexOf(task,taskName,0)>=0&&result.push(key)}),result}"function"==typeof concurrency&&(callback=concurrency,concurrency=null),callback=once(callback||noop);var keys$$1=keys(tasks),numTasks=keys$$1.length;if(!numTasks)return callback(null);concurrency||(concurrency=numTasks);var results={},runningTasks=0,hasError=!1,listeners=Object.create(null),readyTasks=[],readyToCheck=[],uncheckedDependencies={};baseForOwn(tasks,function(task,key){if(!isArray(task))return enqueueTask(key,[task]),void readyToCheck.push(key);var dependencies=task.slice(0,task.length-1),remainingDependencies=dependencies.length;if(0===remainingDependencies)return enqueueTask(key,task),void readyToCheck.push(key);uncheckedDependencies[key]=remainingDependencies,arrayEach(dependencies,function(dependencyName){if(!tasks[dependencyName])throw new Error("async.auto task `"+key+"` has a non-existent dependency `"+dependencyName+"` in "+dependencies.join(", "));addListener(dependencyName,function(){0===--remainingDependencies&&enqueueTask(key,task)})})}),function(){for(var currentTask,counter=0;readyToCheck.length;)currentTask=readyToCheck.pop(),counter++,arrayEach(getDependents(currentTask),function(dependent){0==--uncheckedDependencies[dependent]&&readyToCheck.push(dependent)});if(counter!==numTasks)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),processQueue()},symbolTag="[object Symbol]",INFINITY=1/0,symbolProto=Symbol$1?Symbol$1.prototype:void 0,symbolToString=symbolProto?symbolProto.toString:void 0,reHasUnicode=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0\\ufe0e\\ufe0f]"),rsCombo="[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",reOptMod="(?:[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]|\\ud83c[\\udffb-\\udfff])?",rsOptJoin="(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*",rsSeq="[\\ufe0e\\ufe0f]?"+reOptMod+rsOptJoin,rsSymbol="(?:"+["[^\\ud800-\\udfff]"+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,"[\\ud800-\\udfff]"].join("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reTrim=/^\s+|\s+$/g,FN_ARGS=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,FN_ARG_SPLIT=/,/,FN_ARG=/(=.+)?(\s*)$/,STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;DLL.prototype.removeLink=function(node){return node.prev?node.prev.next=node.next:this.head=node.next,node.next?node.next.prev=node.prev:this.tail=node.prev,node.prev=node.next=null,this.length-=1,node},DLL.prototype.empty=function(){for(;this.head;)this.shift();return this},DLL.prototype.insertAfter=function(node,newNode){newNode.prev=node,newNode.next=node.next,node.next?node.next.prev=newNode:this.tail=newNode,node.next=newNode,this.length+=1},DLL.prototype.insertBefore=function(node,newNode){newNode.prev=node.prev,newNode.next=node,node.prev?node.prev.next=newNode:this.head=newNode,node.prev=newNode,this.length+=1},DLL.prototype.unshift=function(node){this.head?this.insertBefore(this.head,node):setInitial(this,node)},DLL.prototype.push=function(node){this.tail?this.insertAfter(this.tail,node):setInitial(this,node)},DLL.prototype.shift=function(){return this.head&&this.removeLink(this.head)},DLL.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},DLL.prototype.toArray=function(){for(var arr=Array(this.length),curr=this.head,idx=0;idx=nextNode.priority;)nextNode=nextNode.next;for(var i=0,l=data.length;i0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===b64[len-2]?2:"="===b64[len-1]?1:0}function byteLength(b64){return 3*b64.length/4-placeHoldersCount(b64)}function toByteArray(b64){var i,l,tmp,placeHolders,arr,len=b64.length;placeHolders=placeHoldersCount(b64),arr=new Arr(3*len/4-placeHolders),l=placeHolders>0?len-4:len;var L=0;for(i=0;i>16&255,arr[L++]=tmp>>8&255,arr[L++]=255&tmp;return 2===placeHolders?(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[L++]=255&tmp):1===placeHolders&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[L++]=tmp>>8&255,arr[L++]=255&tmp),arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i=start;ilen2?len2:i+16383));return 1===extraBytes?(tmp=uint8[len-1],output+=lookup[tmp>>2],output+=lookup[tmp<<4&63],output+="=="):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],output+=lookup[tmp>>10],output+=lookup[tmp>>4&63],output+=lookup[tmp<<2&63],output+="="),parts.push(output),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer))return string.byteLength;"string"!=typeof string&&(string=""+string);var len=string.length;if(0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":case void 0:return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),byteOffset=+byteOffset,isNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&("ucs2"===(encoding=String(encoding).toLowerCase())||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;jremaining&&(length=remaining):length=remaining;var strLen=string.length;if(strLen%2!=0)throw new TypeError("Invalid hex string");length>strLen/2&&(length=strLen/2);for(var i=0;i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:secondByte=buf[i+1],128==(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte)>127&&(codePoint=tempCodePoint);break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128==(192&secondByte)&&128==(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte)>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint);break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128==(192&secondByte)&&128==(192&thirdByte)&&128==(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte)>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint)}}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;ilen)&&(end=len);for(var out="",i=start;ilength)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function objectWriteUInt16(buf,value,offset,littleEndian){value<0&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);i>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){value<0&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);i>>8*(littleEndian?i:3-i)&255}function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=stringtrim(str).replace(INVALID_BASE64_RE,""),str.length<2)return"";for(;str.length%4!=0;)str+="=";return str}function stringtrim(str){return str.trim?str.trim():str.replace(/^\s+|\s+$/g,"")}function toHex(n){return n<16?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var codePoint,length=string.length,leadSurrogate=null,bytes=[],i=0;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=65536+(leadSurrogate-55296<<10|codePoint-56320)}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isnan(val){return val!==val}var base64=require("base64-js"),ieee754=require("ieee754"),isArray=require("isarray");exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50,Buffer.TYPED_ARRAY_SUPPORT=void 0!==global.TYPED_ARRAY_SUPPORT?global.TYPED_ARRAY_SUPPORT:function(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}(),exports.kMaxLength=kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(arr){return arr.__proto__=Buffer.prototype,arr},Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0})),Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)},Buffer.isBuffer=function(b){return!(null==b||!b._isBuffer)},Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i0&&(str=this.toString("hex",0,max).match(/.{2}/g).join(" "),this.length>max&&(str+=" ... ")),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target))throw new TypeError("Argument must be a Buffer");if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),start<0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;iremaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,start<0?(start+=len)<0&&(start=0):start>len&&(start=len),end<0?(end+=len)<0&&(end=0):end>len&&(end=len),end0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,byteLength|=0,!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0)}var mul=1,i=0;for(this[offset]=255&value;++i=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++i>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart=0;--i)target[i+targetStart]=this[i+start];else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,end=void 0===end?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":return fastAndSafeJsonStringify(args[i++]);case"%%":return"%";default:return x}}),x=args[i];i=0,format('rotating-file stream "count" is not >= 0: %j in %j',this.count,this)),options.period){var period={hourly:"1h",daily:"1d",weekly:"1w",monthly:"1m",yearly:"1y"}[options.period]||options.period,m=/^([1-9][0-9]*)([hdwmy]|ms)$/.exec(period);if(!m)throw new Error(format('invalid period: "%s"',options.period));this.periodNum=Number(m[1]),this.periodScope=m[2]}else this.periodNum=1,this.periodScope="d";var lastModified=null;try{lastModified=fs.statSync(this.path).mtime.getTime()}catch(err){}var rotateAfterOpen=!1;if(lastModified){lastModified call rotate()"),this.rotate()):this._setupNextRot()},util.inherits(RotatingFileStream,EventEmitter),RotatingFileStream.prototype._debug=function(){return!1},RotatingFileStream.prototype._setupNextRot=function(){this.rotAt=this._calcRotTime(1),this._setRotationTimer()},RotatingFileStream.prototype._setRotationTimer=function(){var self=this,delay=this.rotAt-Date.now();delay>2147483647&&(delay=2147483647),this.timeout=setTimeout(function(){self._debug("_setRotationTimer timeout -> call rotate()"),self.rotate()},delay),"function"==typeof this.timeout.unref&&this.timeout.unref()},RotatingFileStream.prototype._calcRotTime=function(periodOffset){this._debug("_calcRotTime: %s%s",this.periodNum,this.periodScope);var d=new Date;this._debug(" now local: %s",d),this._debug(" now utc: %s",d.toISOString());var rotAt;switch(this.periodScope){case"ms":rotAt=this.rotAt?this.rotAt+this.periodNum*periodOffset:Date.now()+this.periodNum*periodOffset;break;case"h":rotAt=this.rotAt?this.rotAt+60*this.periodNum*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),d.getUTCHours()+periodOffset);break;case"d":rotAt=this.rotAt?this.rotAt+24*this.periodNum*60*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+periodOffset);break;case"w":if(this.rotAt)rotAt=this.rotAt+7*this.periodNum*24*60*60*1e3*periodOffset;else{var dayOffset=7-d.getUTCDay();periodOffset<1&&(dayOffset=-d.getUTCDay()),(periodOffset>1||periodOffset<-1)&&(dayOffset+=7*periodOffset),rotAt=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+dayOffset)}break;case"m":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+this.periodNum*periodOffset,1):Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+periodOffset,1);break;case"y":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear()+this.periodNum*periodOffset,0,1):Date.UTC(d.getUTCFullYear()+periodOffset,0,1);break;default:assert.fail(format('invalid period scope: "%s"',this.periodScope))}if(this._debug()){this._debug(" **rotAt**: %s (utc: %s)",rotAt,new Date(rotAt).toUTCString());var now=Date.now();this._debug(" now: %s (%sms == %smin == %sh to go)",now,rotAt-now,(rotAt-now)/1e3/60,(rotAt-now)/1e3/60/60)}return rotAt},RotatingFileStream.prototype.rotate=function(){function moves(){if(0===self.count||n<0)return finish();var before=self.path,after=self.path+"."+String(n);n>0&&(before+="."+String(n-1)),n-=1,fs.exists(before,function(exists){exists?(self._debug(" mv %s %s",before,after),mv(before,after,function(mvErr){mvErr?(self.emit("error",mvErr),finish()):moves()})):moves()})}function finish(){self._debug(" open %s",self.path),self.stream=fs.createWriteStream(self.path,{flags:"a",encoding:"utf8"});for(var q=self.rotQueue,len=q.length,i=0;iDate.now())return self._setRotationTimer();if(this._debug("rotate"),self.rotating)throw new TypeError("cannot start a rotation when already rotating");self.rotating=!0,self.stream.end();var n=this.count;!function(){var toDel=self.path+"."+String(n-1);0===n&&(toDel=self.path),n-=1,self._debug(" rm %s",toDel),fs.unlink(toDel,function(delErr){moves()})}()},RotatingFileStream.prototype.write=function(s){return this.rotating?(this.rotQueue.push(s),!1):this.stream.write(s)},RotatingFileStream.prototype.end=function(s){this.stream.end()},RotatingFileStream.prototype.destroy=function(s){this.stream.destroy()},RotatingFileStream.prototype.destroySoon=function(s){this.stream.destroySoon()}),util.inherits(RingBuffer,EventEmitter),RingBuffer.prototype.write=function(record){if(!this.writable)throw new Error("RingBuffer has been ended already");return this.records.push(record),this.records.length>this.limit&&this.records.shift(),!0},RingBuffer.prototype.end=function(){arguments.length>0&&this.write.apply(this,Array.prototype.slice.call(arguments)),this.writable=!1},RingBuffer.prototype.destroy=function(){this.writable=!1,this.emit("close")},RingBuffer.prototype.destroySoon=function(){this.destroy()},module.exports=Logger,module.exports.TRACE=10,module.exports.DEBUG=20,module.exports.INFO=INFO,module.exports.WARN=WARN,module.exports.ERROR=ERROR,module.exports.FATAL=60,module.exports.resolveLevel=resolveLevel,module.exports.levelFromName=levelFromName,module.exports.nameFromLevel=nameFromLevel,module.exports.VERSION="1.8.10",module.exports.LOG_VERSION=LOG_VERSION,module.exports.createLogger=function(options){return new Logger(options)},module.exports.RingBuffer=RingBuffer,module.exports.RotatingFileStream=RotatingFileStream,module.exports.safeCycles=safeCycles}).call(this,{isBuffer:require("../../is-buffer/index.js")},require("_process"))},{"../../is-buffer/index.js":42,_process:84,assert:3,events:37,fs:7,os:82,"safe-json-stringify":102,stream:125,util:134}],10:[function(require,module,exports){(function(Buffer){function isArray(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return"[object Date]"===objectToString(d)}function isError(e){return"[object Error]"===objectToString(e)||e instanceof Error}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg}function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=Buffer.isBuffer}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":42}],11:[function(require,module,exports){function DeferredIterator(options){AbstractIterator.call(this,options),this._options=options,this._iterator=null,this._operations=[]}var util=require("util"),AbstractIterator=require("abstract-leveldown").AbstractIterator;util.inherits(DeferredIterator,AbstractIterator),DeferredIterator.prototype.setDb=function(db){var it=this._iterator=db.iterator(this._options);this._operations.forEach(function(op){it[op.method].apply(it,op.args)})},DeferredIterator.prototype._operation=function(method,args){if(this._iterator)return this._iterator[method].apply(this._iterator,args);this._operations.push({method:method,args:args})},"next end".split(" ").forEach(function(m){DeferredIterator.prototype["_"+m]=function(){this._operation(m,arguments)}}),module.exports=DeferredIterator},{"abstract-leveldown":16,util:134}],12:[function(require,module,exports){(function(Buffer,process){function DeferredLevelDOWN(location){AbstractLevelDOWN.call(this,"string"==typeof location?location:""),this._db=void 0,this._operations=[],this._iterators=[]}var util=require("util"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,DeferredIterator=require("./deferred-iterator");util.inherits(DeferredLevelDOWN,AbstractLevelDOWN),DeferredLevelDOWN.prototype.setDb=function(db){this._db=db,this._operations.forEach(function(op){db[op.method].apply(db,op.args)}),this._iterators.forEach(function(it){it.setDb(db)})},DeferredLevelDOWN.prototype._open=function(options,callback){return process.nextTick(callback)},DeferredLevelDOWN.prototype._operation=function(method,args){if(this._db)return this._db[method].apply(this._db,args);this._operations.push({method:method,args:args})},"put get del batch approximateSize".split(" ").forEach(function(m){DeferredLevelDOWN.prototype["_"+m]=function(){this._operation(m,arguments)}}),DeferredLevelDOWN.prototype._isBuffer=function(obj){return Buffer.isBuffer(obj)},DeferredLevelDOWN.prototype._iterator=function(options){if(this._db)return this._db.iterator.apply(this._db,arguments);var it=new DeferredIterator(options);return this._iterators.push(it),it},module.exports=DeferredLevelDOWN,module.exports.DeferredIterator=DeferredIterator}).call(this,{isBuffer:require("../is-buffer/index.js")},require("_process"))},{"../is-buffer/index.js":42,"./deferred-iterator":11,_process:84,"abstract-leveldown":16,util:134}],13:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:84}],14:[function(require,module,exports){(function(process){function AbstractIterator(db){this.db=db,this._ended=!1,this._nexting=!1}AbstractIterator.prototype.next=function(callback){var self=this;if("function"!=typeof callback)throw new Error("next() requires a callback argument");return self._ended?callback(new Error("cannot call next() after end()")):self._nexting?callback(new Error("cannot call next() before previous next() has completed")):(self._nexting=!0,"function"==typeof self._next?self._next(function(){self._nexting=!1,callback.apply(null,arguments)}):void process.nextTick(function(){self._nexting=!1,callback()}))},AbstractIterator.prototype.end=function(callback){if("function"!=typeof callback)throw new Error("end() requires a callback argument");return this._ended?callback(new Error("end() already called on iterator")):(this._ended=!0,"function"==typeof this._end?this._end(callback):void process.nextTick(callback))},module.exports=AbstractIterator}).call(this,require("_process"))},{_process:84}],15:[function(require,module,exports){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location,this.status="new"}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){var self=this,oldStatus=this.status;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");"object"!=typeof options&&(options={}),options.createIfMissing=0!=options.createIfMissing,options.errorIfExists=!!options.errorIfExists,"function"==typeof this._open?(this.status="opening",this._open(options,function(err){if(err)return self.status=oldStatus,callback(err);self.status="open",callback()})):(this.status="open",process.nextTick(callback))},AbstractLevelDOWN.prototype.close=function(callback){var self=this,oldStatus=this.status;if("function"!=typeof callback)throw new Error("close() requires a callback argument");"function"==typeof this._close?(this.status="closing",this._close(function(err){if(err)return self.status=oldStatus,callback(err);self.status="closed",callback()})):(this.status="closed",process.nextTick(callback))},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),options.asBuffer=0!=options.asBuffer,"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),null==value||this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"==typeof array&&(callback=array),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));options&&"object"==typeof options||(options={});for(var e,err,i=0,l=array.length;i<.,\-|]+|\\u0003/},doc.options||{});for(var fieldName in doc.normalised){var fieldOptions=Object.assign({},{separator:options.separator},options.fieldOptions[fieldName]);"[object Array]"===Object.prototype.toString.call(doc.normalised[fieldName])?doc.tokenised[fieldName]=doc.normalised[fieldName]:doc.tokenised[fieldName]=doc.normalised[fieldName].split(fieldOptions.separator)}return this.push(doc),end()}},{stream:125,util:134}],30:[function(require,module,exports){(function(process,Buffer){var stream=require("readable-stream"),eos=require("end-of-stream"),inherits=require("inherits"),shift=require("stream-shift"),SIGNAL_FLUSH=new Buffer([0]),onuncork=function(self,fn){self._corked?self.once("uncork",fn):fn() -},destroyer=function(self,end){return function(err){err?self.destroy("premature close"===err.message?null:err):end&&!self._ended&&self.end()}},end=function(ws,fn){return ws?ws._writableState&&ws._writableState.finished?fn():ws._writableState?ws.end(fn):(ws.end(),void fn()):fn()},toStreams2=function(rs){return new stream.Readable({objectMode:!0,highWaterMark:16}).wrap(rs)},Duplexify=function(writable,readable,opts){if(!(this instanceof Duplexify))return new Duplexify(writable,readable,opts);stream.Duplex.call(this,opts),this._writable=null,this._readable=null,this._readable2=null,this._forwardDestroy=!opts||!1!==opts.destroy,this._forwardEnd=!opts||!1!==opts.end,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,writable&&this.setWritable(writable),readable&&this.setReadable(readable)};inherits(Duplexify,stream.Duplex),Duplexify.obj=function(writable,readable,opts){return opts||(opts={}),opts.objectMode=!0,opts.highWaterMark=16,new Duplexify(writable,readable,opts)},Duplexify.prototype.cork=function(){1==++this._corked&&this.emit("cork")},Duplexify.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},Duplexify.prototype.setWritable=function(writable){if(this._unwrite&&this._unwrite(),this.destroyed)return void(writable&&writable.destroy&&writable.destroy());if(null===writable||!1===writable)return void this.end();var self=this,unend=eos(writable,{writable:!0,readable:!1},destroyer(this,this._forwardEnd)),ondrain=function(){var ondrain=self._ondrain;self._ondrain=null,ondrain&&ondrain()},clear=function(){self._writable.removeListener("drain",ondrain),unend()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=clear,this.uncork()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)return void(readable&&readable.destroy&&readable.destroy());if(null===readable||!1===readable)return this.push(null),void this.resume();var self=this,unend=eos(readable,{writable:!1,readable:!0},destroyer(this)),onreadable=function(){self._forward()},onend=function(){self.push(null)},clear=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()};this._drained=!0,this._readable=readable,this._readable2=readable._readableState?readable:toStreams2(readable),this._readable2.on("readable",onreadable),this._readable2.on("end",onend),this._unread=clear,this._forward()},Duplexify.prototype._read=function(){this._drained=!0,this._forward()},Duplexify.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){this._forwarding=!0;for(var data;this._drained&&null!==(data=shift(this._readable2));)this.destroyed||(this._drained=this.push(data));this._forwarding=!1}},Duplexify.prototype.destroy=function(err){if(!this.destroyed){this.destroyed=!0;var self=this;process.nextTick(function(){self._destroy(err)})}},Duplexify.prototype._destroy=function(err){if(err){var ondrain=this._ondrain;this._ondrain=null,ondrain?ondrain(err):this.emit("error",err)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},Duplexify.prototype._write=function(data,enc,cb){return this.destroyed?cb():this._corked?onuncork(this,this._write.bind(this,data,enc,cb)):data===SIGNAL_FLUSH?this._finish(cb):this._writable?void(!1===this._writable.write(data)?this._ondrain=cb:cb()):cb()},Duplexify.prototype._finish=function(cb){var self=this;this.emit("preend"),onuncork(this,function(){end(self._forwardEnd&&self._writable,function(){!1===self._writableState.prefinished&&(self._writableState.prefinished=!0),self.emit("prefinish"),onuncork(self,cb)})})},Duplexify.prototype.end=function(data,enc,cb){return"function"==typeof data?this.end(null,null,data):"function"==typeof enc?this.end(data,null,enc):(this._ended=!0,data&&this.write(data),this._writableState.ending||this.write(SIGNAL_FLUSH),stream.Writable.prototype.end.call(this,cb))},module.exports=Duplexify}).call(this,require("_process"),require("buffer").Buffer)},{_process:84,buffer:8,"end-of-stream":31,inherits:40,"readable-stream":98,"stream-shift":126}],31:[function(require,module,exports){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback()},onend=function(){readable=!1,writable||callback()},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback(new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:32}],32:[function(require,module,exports){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0})})},{wrappy:135}],33:[function(require,module,exports){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},isChildProcess=function(stream){return stream.stdio&&Array.isArray(stream.stdio)&&3===stream.stdio.length},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback.call(stream)},onend=function(){readable=!1,writable||callback.call(stream)},onexit=function(exitCode){callback.call(stream,exitCode?new Error("exited with error code: "+exitCode):null)},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback.call(stream,new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),isChildProcess(stream)&&stream.on("exit",onexit),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("exit",onexit),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:81}],34:[function(require,module,exports){function init(type,message,cause){prr(this,{type:type,name:type,cause:"string"!=typeof message?message:cause,message:message&&"string"!=typeof message?message.message:message},"ewr")}function CustomError(message,cause){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),init.call(this,"CustomError",message,cause)}function createError(errno,type,proto){var err=function(message,cause){init.call(this,type,message,cause),"FilesystemError"==type&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(errno.errno[this.cause.errno]?errno.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return err.prototype=proto?new proto:new CustomError,err}var prr=require("prr");CustomError.prototype=new Error,module.exports=function(errno){var ce=function(type,proto){return createError(errno,type,proto)};return{CustomError:CustomError,FilesystemError:ce("FilesystemError"),createError:ce}}},{prr:36}],35:[function(require,module,exports){var all=module.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];module.exports.errno={},module.exports.code={},all.forEach(function(error){module.exports.errno[error.errno]=error,module.exports.code[error.code]=error}),module.exports.custom=require("./custom")(module.exports),module.exports.create=module.exports.custom.createError},{"./custom":34}],36:[function(require,module,exports){!function(name,context,definition){void 0!==module&&module.exports?module.exports=definition():context.prr=definition()}(0,this,function(){var setProperty="function"==typeof Object.defineProperty?function(obj,key,options){return Object.defineProperty(obj,key,options),obj}:function(obj,key,options){return obj[key]=options.value,obj},makeOptions=function(value,options){var oo="object"==typeof options,os=!oo&&"string"==typeof options,op=function(p){return oo?!!options[p]:!!os&&options.indexOf(p[0])>-1};return{enumerable:op("enumerable"),configurable:op("configurable"),writable:op("writable"),value:value}};return function(obj,key,value,options){var k;if(options=makeOptions(value,options),"object"==typeof key){for(k in key)Object.hasOwnProperty.call(key,k)&&(options.value=key[k],setProperty(obj,k,options));return obj}return setProperty(obj,key,options)}})},{}],37:[function(require,module,exports){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if((er=arguments[1])instanceof Error)throw er;var err=new Error('Uncaught, unspecified "error" event. ('+er+")");throw err.context=er,err}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args)}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;i0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace()),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-- >0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(position<0)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){return this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},{}],38:[function(require,module,exports){!function(name,definition,global){"use strict";"function"==typeof define?define(definition):void 0!==module&&module.exports?module.exports=definition():global.IDBStore=definition()}(0,function(){"use strict";function mixin(target,source){var name,s;for(name in source)(s=source[name])!==empty[name]&&s!==target[name]&&(target[name]=s);return target}function hasVersionError(errorEvent){return"error"in errorEvent.target?"VersionError"==errorEvent.target.error.name:"errorCode"in errorEvent.target&&12==errorEvent.target.errorCode}var defaultErrorHandler=function(error){throw error},defaultSuccessHandler=function(){},defaults={storeName:"Store",storePrefix:"IDBWrapper-",dbVersion:1,keyPath:"id",autoIncrement:!0,onStoreReady:function(){},onError:defaultErrorHandler,indexes:[],implementationPreference:["indexedDB","webkitIndexedDB","mozIndexedDB","shimIndexedDB"]},IDBStore=function(kwArgs,onStoreReady){void 0===onStoreReady&&"function"==typeof kwArgs&&(onStoreReady=kwArgs),"[object Object]"!=Object.prototype.toString.call(kwArgs)&&(kwArgs={});for(var key in defaults)this[key]=void 0!==kwArgs[key]?kwArgs[key]:defaults[key];this.dbName=this.storePrefix+this.storeName,this.dbVersion=parseInt(this.dbVersion,10)||1,onStoreReady&&(this.onStoreReady=onStoreReady);var env="object"==typeof window?window:self,availableImplementations=this.implementationPreference.filter(function(implName){return implName in env});this.implementation=availableImplementations[0],this.idb=env[this.implementation],this.keyRange=env.IDBKeyRange||env.webkitIDBKeyRange||env.mozIDBKeyRange,this.consts={READ_ONLY:"readonly",READ_WRITE:"readwrite",VERSION_CHANGE:"versionchange",NEXT:"next",NEXT_NO_DUPLICATE:"nextunique",PREV:"prev",PREV_NO_DUPLICATE:"prevunique"},this.openDB()},proto={constructor:IDBStore,version:"1.7.1",db:null,dbName:null,dbVersion:null,store:null,storeName:null,storePrefix:null,keyPath:null,autoIncrement:null,indexes:null,implementationPreference:null,implementation:"",onStoreReady:null,onError:null,_insertIdCount:0,openDB:function(){var openRequest=this.idb.open(this.dbName,this.dbVersion),preventSuccessCallback=!1;openRequest.onerror=function(errorEvent){if(hasVersionError(errorEvent))this.onError(new Error("The version number provided is lower than the existing one."));else{var error;if(errorEvent.target.error)error=errorEvent.target.error;else{var errorMessage="IndexedDB unknown error occurred when opening DB "+this.dbName+" version "+this.dbVersion;"errorCode"in errorEvent.target&&(errorMessage+=" with error code "+errorEvent.target.errorCode),error=new Error(errorMessage)}this.onError(error)}}.bind(this),openRequest.onsuccess=function(event){if(!preventSuccessCallback){if(this.db)return void this.onStoreReady();if(this.db=event.target.result,"string"==typeof this.db.version)return void this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."));if(!this.db.objectStoreNames.contains(this.storeName))return void this.onError(new Error("Object store couldn't be created."));var emptyTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);this.store=emptyTransaction.objectStore(this.storeName);var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(!indexName)return preventSuccessCallback=!0,void this.onError(new Error("Cannot create index: No index name given."));if(this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);this.indexComplies(actualIndex,indexData)||(preventSuccessCallback=!0,this.onError(new Error('Cannot modify index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else preventSuccessCallback=!0,this.onError(new Error('Cannot create new index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))},this),existingIndexes.length&&(preventSuccessCallback=!0,this.onError(new Error('Cannot delete index(es) "'+existingIndexes.toString()+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),preventSuccessCallback||this.onStoreReady()}}.bind(this),openRequest.onupgradeneeded=function(event){if(this.db=event.target.result,this.db.objectStoreNames.contains(this.storeName))this.store=event.target.transaction.objectStore(this.storeName);else{var optionalParameters={autoIncrement:this.autoIncrement};null!==this.keyPath&&(optionalParameters.keyPath=this.keyPath),this.store=this.db.createObjectStore(this.storeName,optionalParameters)}var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(indexName||(preventSuccessCallback=!0,this.onError(new Error("Cannot create index: No index name given."))),this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);this.indexComplies(actualIndex,indexData)||(this.store.deleteIndex(indexName),this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})},this),existingIndexes.length&&existingIndexes.forEach(function(_indexName){this.store.deleteIndex(_indexName)},this)}.bind(this)},deleteDatabase:function(onSuccess,onError){if(this.idb.deleteDatabase){this.db.close();var deleteRequest=this.idb.deleteDatabase(this.dbName);deleteRequest.onsuccess=onSuccess,deleteRequest.onerror=onError}else onError(new Error("Browser does not support IndexedDB deleteDatabase!"))},put:function(key,value,onSuccess,onError){null!==this.keyPath&&(onError=onSuccess,onSuccess=value,value=key),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var putRequest,hasSuccess=!1,result=null,putTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);return putTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},putTransaction.onabort=onError,putTransaction.onerror=onError,null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=putTransaction.objectStore(this.storeName).put(value)):putRequest=putTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},putRequest.onerror=onError,putTransaction},get:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,getTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);getTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getTransaction.onabort=onError,getTransaction.onerror=onError;var getRequest=getTransaction.objectStore(this.storeName).get(key);return getRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getRequest.onerror=onError,getTransaction},remove:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,removeTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);removeTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},removeTransaction.onabort=onError,removeTransaction.onerror=onError;var deleteRequest=removeTransaction.objectStore(this.storeName).delete(key);return deleteRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},deleteRequest.onerror=onError,removeTransaction},batch:function(dataArray,onSuccess,onError){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),"[object Array]"!=Object.prototype.toString.call(dataArray))onError(new Error("dataArray argument must be of type Array."));else if(0===dataArray.length)return onSuccess(!0);var count=dataArray.length,called=!1,hasSuccess=!1,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(hasSuccess)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(){0!==--count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(operation){var type=operation.type,key=operation.key,value=operation.value,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err,type,key))};if("remove"==type){var deleteRequest=batchTransaction.objectStore(this.storeName).delete(key);deleteRequest.onsuccess=onItemSuccess,deleteRequest.onerror=onItemError}else if("put"==type){var putRequest;null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=batchTransaction.objectStore(this.storeName).put(value)):putRequest=batchTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError}},this),batchTransaction},putBatch:function(dataArray,onSuccess,onError){var batchData=dataArray.map(function(item){return{type:"put",value:item}});return this.batch(batchData,onSuccess,onError)},upsertBatch:function(dataArray,options,onSuccess,onError){"function"==typeof options&&(onSuccess=options,onError=onSuccess,options={}),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),options||(options={}),"[object Array]"!=Object.prototype.toString.call(dataArray)&&onError(new Error("dataArray argument must be of type Array."));var keyField=options.keyField||this.keyPath,count=dataArray.length,called=!1,hasSuccess=!1,index=0,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){hasSuccess?onSuccess(dataArray):onError(!1)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){dataArray[index++][keyField]=event.target.result,0!==--count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(record){var putRequest,key=record.key,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err))};null!==this.keyPath?(this._addIdPropertyIfNeeded(record),putRequest=batchTransaction.objectStore(this.storeName).put(record)):putRequest=batchTransaction.objectStore(this.storeName).put(record,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError},this),batchTransaction},removeBatch:function(keyArray,onSuccess,onError){var batchData=keyArray.map(function(key){return{type:"remove",key:key}});return this.batch(batchData,onSuccess,onError)},getBatch:function(keyArray,onSuccess,onError,arrayType){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),arrayType||(arrayType="sparse"),"[object Array]"!=Object.prototype.toString.call(keyArray))onError(new Error("keyArray argument must be of type Array."));else if(0===keyArray.length)return onSuccess([]);var data=[],count=keyArray.length,called=!1,hasSuccess=!1,result=null,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);batchTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){event.target.result||"dense"==arrayType?data.push(event.target.result):"sparse"==arrayType&&data.length++,0===--count&&(called=!0,hasSuccess=!0,result=data)};return keyArray.forEach(function(key){var onItemError=function(err){called=!0,result=err,onError(err),batchTransaction.abort()},getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=onItemError},this),batchTransaction},getAll:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var getAllTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY),store=getAllTransaction.objectStore(this.storeName);return store.getAll?this._getAllNative(getAllTransaction,store,onSuccess,onError):this._getAllCursor(getAllTransaction,store,onSuccess,onError),getAllTransaction},_getAllNative:function(getAllTransaction,store,onSuccess,onError){var hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var getAllRequest=store.getAll();getAllRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getAllRequest.onerror=onError},_getAllCursor:function(getAllTransaction,store,onSuccess,onError){var all=[],hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)}, -getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var cursorRequest=store.openCursor();cursorRequest.onsuccess=function(event){var cursor=event.target.result;cursor?(all.push(cursor.value),cursor.continue()):(hasSuccess=!0,result=all)},cursorRequest.onError=onError},clear:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,clearTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);clearTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},clearTransaction.onabort=onError,clearTransaction.onerror=onError;var clearRequest=clearTransaction.objectStore(this.storeName).clear();return clearRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},clearRequest.onerror=onError,clearTransaction},_addIdPropertyIfNeeded:function(dataObj){void 0===dataObj[this.keyPath]&&(dataObj[this.keyPath]=this._insertIdCount+++Date.now())},getIndexList:function(){return this.store.indexNames},hasIndex:function(indexName){return this.store.indexNames.contains(indexName)},normalizeIndexData:function(indexData){indexData.keyPath=indexData.keyPath||indexData.name,indexData.unique=!!indexData.unique,indexData.multiEntry=!!indexData.multiEntry},indexComplies:function(actual,expected){return["keyPath","unique","multiEntry"].every(function(key){if("multiEntry"==key&&void 0===actual[key]&&!1===expected[key])return!0;if("keyPath"==key&&"[object Array]"==Object.prototype.toString.call(expected[key])){var exp=expected.keyPath,act=actual.keyPath;if("string"==typeof act)return exp.toString()==act;if("function"!=typeof act.contains&&"function"!=typeof act.indexOf)return!1;if(act.length!==exp.length)return!1;for(var i=0,m=exp.length;i>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:1/0*(s?-1:1);m+=Math.pow(2,mLen),e-=eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias),value*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],40:[function(require,module,exports){"function"==typeof Object.create?module.exports=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],41:[function(require,module,exports){var Readable=require("stream").Readable;exports.getIntersectionStream=function(sortedSets){for(var s=new Readable,i=0,ii=[],k=0;ksortedSets[i+1][ii[i+1]])ii[i+1]++;else if(i+2=sortedSets[k].length&&(finished=!0);i=0}return s.push(null),s}},{stream:125}],42:[function(require,module,exports){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}module.exports=function(obj){return null!=obj&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)}},{}],43:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},{}],44:[function(require,module,exports){function isBuffer(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}var Buffer=require("buffer").Buffer;module.exports=isBuffer},{buffer:8}],45:[function(require,module,exports){function Codec(opts){this.opts=opts||{},this.encodings=encodings}var encodings=require("./lib/encodings");module.exports=Codec,Codec.prototype._encoding=function(encoding){return"string"==typeof encoding&&(encoding=encodings[encoding]),encoding||(encoding=encodings.id),encoding},Codec.prototype._keyEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&batchOpts.keyEncoding||opts&&opts.keyEncoding||this.opts.keyEncoding)},Codec.prototype._valueEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&(batchOpts.valueEncoding||batchOpts.encoding)||opts&&(opts.valueEncoding||opts.encoding)||this.opts.valueEncoding||this.opts.encoding)},Codec.prototype.encodeKey=function(key,opts,batchOpts){return this._keyEncoding(opts,batchOpts).encode(key)},Codec.prototype.encodeValue=function(value,opts,batchOpts){return this._valueEncoding(opts,batchOpts).encode(value)},Codec.prototype.decodeKey=function(key,opts){return this._keyEncoding(opts).decode(key)},Codec.prototype.decodeValue=function(value,opts){return this._valueEncoding(opts).decode(value)},Codec.prototype.encodeBatch=function(ops,opts){var self=this;return ops.map(function(_op){var op={type:_op.type,key:self.encodeKey(_op.key,opts,_op)};return self.keyAsBuffer(opts,_op)&&(op.keyEncoding="binary"),_op.prefix&&(op.prefix=_op.prefix),"value"in _op&&(op.value=self.encodeValue(_op.value,opts,_op),self.valueAsBuffer(opts,_op)&&(op.valueEncoding="binary")),op})};var ltgtKeys=["lt","gt","lte","gte","start","end"];Codec.prototype.encodeLtgt=function(ltgt){var self=this,ret={};return Object.keys(ltgt).forEach(function(key){ret[key]=ltgtKeys.indexOf(key)>-1?self.encodeKey(ltgt[key],ltgt):ltgt[key]}),ret},Codec.prototype.createStreamDecoder=function(opts){var self=this;return opts.keys&&opts.values?function(key,value){return{key:self.decodeKey(key,opts),value:self.decodeValue(value,opts)}}:opts.keys?function(key){return self.decodeKey(key,opts)}:opts.values?function(_,value){return self.decodeValue(value,opts)}:function(){}},Codec.prototype.keyAsBuffer=function(opts){return this._keyEncoding(opts).buffer},Codec.prototype.valueAsBuffer=function(opts){return this._valueEncoding(opts).buffer}},{"./lib/encodings":46}],46:[function(require,module,exports){(function(Buffer){function identity(value){return value}function isBinary(data){return void 0===data||null===data||Buffer.isBuffer(data)}exports.utf8=exports["utf-8"]={encode:function(data){return isBinary(data)?data:String(data)},decode:identity,buffer:!1,type:"utf8"},exports.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},exports.binary={encode:function(data){return isBinary(data)?data:new Buffer(data)},decode:identity,buffer:!0,type:"binary"},exports.id={encode:function(data){return data},decode:function(data){return data},buffer:!1,type:"id"},["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"].forEach(function(type){exports[type]={encode:function(data){return isBinary(data)?data:new Buffer(data,type)},decode:function(buffer){return buffer.toString(type)},buffer:!0,type:type}})}).call(this,require("buffer").Buffer)},{buffer:8}],47:[function(require,module,exports){var createError=require("errno").create,LevelUPError=createError("LevelUPError"),NotFoundError=createError("NotFoundError",LevelUPError);NotFoundError.prototype.notFound=!0,NotFoundError.prototype.status=404,module.exports={LevelUPError:LevelUPError,InitializationError:createError("InitializationError",LevelUPError),OpenError:createError("OpenError",LevelUPError),ReadError:createError("ReadError",LevelUPError),WriteError:createError("WriteError",LevelUPError),NotFoundError:NotFoundError,EncodingError:createError("EncodingError",LevelUPError)}},{errno:35}],48:[function(require,module,exports){function ReadStream(iterator,options){if(!(this instanceof ReadStream))return new ReadStream(iterator,options);Readable.call(this,extend(options,{objectMode:!0})),this._iterator=iterator,this._destroyed=!1,this._decoder=null,options&&options.decoder&&(this._decoder=options.decoder),this.on("end",this._cleanup.bind(this))}var inherits=require("inherits"),Readable=require("readable-stream").Readable,extend=require("xtend"),EncodingError=require("level-errors").EncodingError;module.exports=ReadStream,inherits(ReadStream,Readable),ReadStream.prototype._read=function(){var self=this;this._destroyed||this._iterator.next(function(err,key,value){if(!self._destroyed){if(err)return self.emit("error",err);if(void 0===key&&void 0===value)self.push(null);else{if(!self._decoder)return self.push({key:key,value:value});try{var value=self._decoder(key,value)}catch(err){return self.emit("error",new EncodingError(err)),void self.push(null)}self.push(value)}}})},ReadStream.prototype.destroy=ReadStream.prototype._cleanup=function(){var self=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(err){if(err)return self.emit("error",err);self.emit("close")}))}},{inherits:40,"level-errors":47,"readable-stream":55,xtend:136}],49:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],50:[function(require,module,exports){(function(process){function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),options&&!1===options.readable&&(this.readable=!1),options&&!1===options.writable&&(this.writable=!1),this.allowHalfOpen=!0,options&&!1===options.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",onend)}function onend(){this.allowHalfOpen||this._writableState.ended||process.nextTick(this.end.bind(this))}module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys},util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable),function(xs,f){for(var i=0,l=xs.length;i0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk)),addToFront||(state.reading=!1),state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state);else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM)n=MAX_HWM;else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:isNaN(n)||util.isNull(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:n<=0?0:(n>state.highWaterMark&&(state.highWaterMark=roundUpToNextPowerOf2(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return util.isBuffer(chunk)||util.isString(chunk)||util.isNullOrUndefined(chunk)||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?process.nextTick(function(){emitReadable_(stream)}):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(function(){maybeReadMore_(stream,state)}))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=length)ret=stringMode?list.join(""):Buffer.concat(list,length),list.length=0;else if(n0)throw new Error("endReadable called on non-empty stream");state.endEmitted||(state.ended=!0,process.nextTick(function(){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}))}function forEach(xs,f){for(var i=0,l=xs.length;i0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,util.isNull(ret)&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&0===state.length&&endReadable(this),util.isNull(ret)||this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",cleanup),src.removeListener("data",ondata),!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),!1===dest.write(chunk)&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EE.listenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);return dest.on("drain",ondrain),src.on("data",ondata),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i1){for(var cbs=[],c=0;c=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived=55296&&charCode<=56319)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},{buffer:8}],57:[function(require,module,exports){(function(Buffer){function Level(location){if(!(this instanceof Level))return new Level(location);if(!location)throw new Error("constructor requires at least a location argument");this.IDBOptions={},this.location=location}module.exports=Level;var IDB=require("idb-wrapper"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,util=require("util"),Iterator=require("./iterator"),isBuffer=require("isbuffer"),xtend=require("xtend"),toBuffer=require("typedarray-to-buffer");util.inherits(Level,AbstractLevelDOWN),Level.prototype._open=function(options,callback){var self=this,idbOpts={storeName:this.location,autoIncrement:!1,keyPath:null,onStoreReady:function(){callback&&callback(null,self.idb)},onError:function(err){callback&&callback(err)}};xtend(idbOpts,options),this.IDBOptions=idbOpts,this.idb=new IDB(idbOpts)},Level.prototype._get=function(key,options,callback){this.idb.get(key,function(value){if(void 0===value)return callback(new Error("NotFound"));var asBuffer=!0;return!1===options.asBuffer&&(asBuffer=!1),options.raw&&(asBuffer=!1),asBuffer&&(value=value instanceof Uint8Array?toBuffer(value):new Buffer(String(value))),callback(null,value,key)},callback)},Level.prototype._del=function(id,options,callback){this.idb.remove(id,callback,callback)},Level.prototype._put=function(key,value,options,callback){value instanceof ArrayBuffer&&(value=toBuffer(new Uint8Array(value)));var obj=this.convertEncoding(key,value,options);Buffer.isBuffer(obj.value)&&("function"==typeof value.toArrayBuffer?obj.value=new Uint8Array(value.toArrayBuffer()):obj.value=new Uint8Array(value)),this.idb.put(obj.key,obj.value,function(){callback()},callback)},Level.prototype.convertEncoding=function(key,value,options){if(options.raw)return{key:key,value:value};if(value){var stringed=value.toString();"NaN"===stringed&&(value="NaN")}var valEnc=options.valueEncoding,obj={key:key,value:value};return!value||valEnc&&"binary"===valEnc||"object"!=typeof obj.value&&(obj.value=stringed),obj},Level.prototype.iterator=function(options){return"object"!=typeof options&&(options={}),new Iterator(this.idb,options)},Level.prototype._batch=function(array,options,callback){var i,k,copiedOp,currentOp,modified=[];if(0===array.length)return setTimeout(callback,0);for(i=0;i0&&this._count++>=this._limit&&(shouldCall=!1),shouldCall&&this.callback(!1,cursor.key,cursor.value),cursor&&cursor.continue()},Iterator.prototype._next=function(callback){return callback?this._keyRangeError?callback():(this._started||(this.createIterator(),this._started=!0),void(this.callback=callback)):new Error("next() requires a callback argument")}},{"abstract-leveldown":61,ltgt:79,util:134}],59:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;if(err=this._db._checkKeyValue(value,"value",this._db._isBuffer))throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:84}],60:[function(require,module,exports){arguments[4][14][0].apply(exports,arguments)},{_process:84,dup:14}],61:[function(require,module,exports){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");if("object"!=typeof options&&(options={}),"function"==typeof this._open)return this._open(options,callback);process.nextTick(callback)},AbstractLevelDOWN.prototype.close=function(callback){if("function"!=typeof callback)throw new Error("close() requires a callback argument");if("function"==typeof this._close)return this._close(callback);process.nextTick(callback)},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(err=this._checkKeyValue(value,"value",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));"object"!=typeof options&&(options={});for(var e,err,i=0,l=array.length;i2?arguments[2]:null;if(l===+l)for(i=0;i=0&&"[object Function]"===toString.call(value.callee)),isArguments}},{}],66:[function(require,module,exports){!function(){"use strict";var keysShim,has=Object.prototype.hasOwnProperty,toString=Object.prototype.toString,forEach=require("./foreach"),isArgs=require("./isArguments"),hasDontEnumBug=!{toString:null}.propertyIsEnumerable("toString"),hasProtoEnumBug=function(){}.propertyIsEnumerable("prototype"),dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];keysShim=function(object){var isObject=null!==object&&"object"==typeof object,isFunction="[object Function]"===toString.call(object),isArguments=isArgs(object),theKeys=[];if(!isObject&&!isFunction&&!isArguments)throw new TypeError("Object.keys called on a non-object");if(isArguments)forEach(object,function(value){theKeys.push(value)});else{var name,skipProto=hasProtoEnumBug&&isFunction;for(name in object)skipProto&&"prototype"===name||!has.call(object,name)||theKeys.push(name)}if(hasDontEnumBug){var ctor=object.constructor,skipConstructor=ctor&&ctor.prototype===object;forEach(dontEnums,function(dontEnum){skipConstructor&&"constructor"===dontEnum||!has.call(object,dontEnum)||theKeys.push(dontEnum)})}return theKeys},module.exports=keysShim}()},{"./foreach":63,"./isArguments":65}],67:[function(require,module,exports){function hasKeys(source){return null!==source&&("object"==typeof source||"function"==typeof source)}module.exports=hasKeys},{}],68:[function(require,module,exports){function extend(){for(var target={},i=0;i-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){return!(!isObject(value)||isMasked(value))&&(isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor).test(toSource(value))}function getMapData(map,key){var data=map.__data__;return isKeyable(key)?data["string"==typeof key?"string":"hash"]:data.map}function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:void 0}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function toSource(func){if(null!=func){try{return funcToString.call(func)}catch(e){}try{return func+""}catch(e){}}return""}function eq(value,other){return value===other||value!==value&&other!==other}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var difference=function(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=120&&array.length>=120)?new SetCache(othIndex&&array):void 0}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}var HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),splice=arrayProto.splice,nativeMax=Math.max,nativeMin=Math.min,Map=getNative(root,"Map"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var intersection=function(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=null==entries?0:entries.length;for(this.clear();++indexarrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&COMPARE_UNORDERED_FLAG?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index-1&&value%1==0&&value-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function stubArray(){return[]}function stubFalse(){return!1}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2,MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",arrayTag="[object Array]",asyncTag="[object AsyncFunction]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",nullTag="[object Null]",objectTag="[object Object]",proxyTag="[object Proxy]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",undefinedTag="[object Undefined]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags["[object Float32Array]"]=typedArrayTags["[object Float64Array]"]=typedArrayTags["[object Int8Array]"]=typedArrayTags["[object Int16Array]"]=typedArrayTags["[object Int32Array]"]=typedArrayTags["[object Uint8Array]"]=typedArrayTags["[object Uint8ClampedArray]"]=typedArrayTags["[object Uint16Array]"]=typedArrayTags["[object Uint32Array]"]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags["[object WeakMap]"]=!1;var freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),nativeObjectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Buffer=moduleExports?root.Buffer:void 0,Symbol=root.Symbol,Uint8Array=root.Uint8Array,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,symToStringTag=Symbol?Symbol.toStringTag:void 0,nativeGetSymbols=Object.getOwnPropertySymbols,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),DataView=getNative(root,"DataView"),Map=getNative(root,"Map"),Promise=getNative(root,"Promise"),Set=getNative(root,"Set"),WeakMap=getNative(root,"WeakMap"),nativeCreate=getNative(Object,"create"),dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap),symbolProto=Symbol?Symbol.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0;Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas,Stack.prototype.clear=stackClear,Stack.prototype.delete=stackDelete,Stack.prototype.get=stackGet,Stack.prototype.has=stackHas,Stack.prototype.set=stackSet;var getSymbols=nativeGetSymbols?function(object){return null==object?[]:(object=Object(object),arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol)}))}:stubArray,getTag=baseGetTag;(DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag||Map&&getTag(new Map)!=mapTag||Promise&&"[object Promise]"!=getTag(Promise.resolve())||Set&&getTag(new Set)!=setTag||WeakMap&&"[object WeakMap]"!=getTag(new WeakMap))&&(getTag=function(value){var result=baseGetTag(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):"";if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return"[object Promise]";case setCtorString:return setTag;case weakMapCtorString:return"[object WeakMap]"}return result});var isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isBuffer=nativeIsBuffer||stubFalse,isTypedArray=nodeIsTypedArray?function(func){return function(value){return func(value)}}(nodeIsTypedArray):baseIsTypedArray;module.exports=isEqual}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],75:[function(require,module,exports){function baseSortedIndex(array,value,retHighest){var low=0,high=array?array.length:low;if("number"==typeof value&&value===value&&high<=HALF_MAX_ARRAY_LENGTH){for(;low>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computedlength?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=length?array:baseSlice(array,start,end)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=void 0===start?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toFinite(value){if(!value)return 0===value?value:0;if((value=toNumber(value))===INFINITY||value===-INFINITY){return(value<0?-1:1)*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}var FUNC_ERROR_TEXT="Expected a function",INFINITY=1/0,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,symbolTag="[object Symbol]",reTrim=/^\s+|\s+$/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt,objectProto=Object.prototype,objectToString=objectProto.toString,nativeMax=Math.max;module.exports=spread},{}],77:[function(require,module,exports){(function(global){function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayIncludes(array,value){return!!(array?array.length:0)&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){return!(!isObject(value)||isMasked(value))&&(isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor).test(toSource(value))}function baseUniq(array,iteratee,comparator){var index=-1,includes=arrayIncludes,length=array.length,isCommon=!0,result=[],seen=result;if(comparator)isCommon=!1,includes=arrayIncludesWith;else if(length>=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}function noop(){}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),Set=getNative(root,"Set"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:noop,union=function(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexb?1:0};var lowerBoundKey=exports.lowerBoundKey=function(range){return hasKey(range,"gt")||hasKey(range,"gte")||hasKey(range,"min")||(range.reverse?hasKey(range,"end"):hasKey(range,"start"))||void 0},lowerBound=exports.lowerBound=function(range,def){var k=lowerBoundKey(range);return k?range[k]:def},lowerBoundInclusive=exports.lowerBoundInclusive=function(range){return!has(range,"gt")},upperBoundInclusive=exports.upperBoundInclusive=function(range){return!has(range,"lt")},lowerBoundExclusive=exports.lowerBoundExclusive=function(range){return!lowerBoundInclusive(range)},upperBoundExclusive=exports.upperBoundExclusive=function(range){return!upperBoundInclusive(range)},upperBoundKey=exports.upperBoundKey=function(range){return hasKey(range,"lt")||hasKey(range,"lte")||hasKey(range,"max")||(range.reverse?hasKey(range,"start"):hasKey(range,"end"))||void 0},upperBound=exports.upperBound=function(range,def){var k=upperBoundKey(range);return k?range[k]:def};exports.start=function(range,def){return range.reverse?upperBound(range,def):lowerBound(range,def)},exports.end=function(range,def){return range.reverse?lowerBound(range,def):upperBound(range,def)},exports.startInclusive=function(range){return range.reverse?upperBoundInclusive(range):lowerBoundInclusive(range)},exports.endInclusive=function(range){return range.reverse?lowerBoundInclusive(range):upperBoundInclusive(range)},exports.toLtgt=function(range,_range,map,lower,upper){_range=_range||{},map=map||id;var defaults=arguments.length>3,lb=exports.lowerBoundKey(range),ub=exports.upperBoundKey(range);return lb?"gt"===lb?_range.gt=map(range.gt,!1):_range.gte=map(range[lb],!1):defaults&&(_range.gte=map(lower,!1)),ub?"lt"===ub?_range.lt=map(range.lt,!0):_range.lte=map(range[ub],!0):defaults&&(_range.lte=map(upper,!0)),null!=range.reverse&&(_range.reverse=!!range.reverse),has(_range,"max")&&delete _range.max,has(_range,"min")&&delete _range.min,has(_range,"start")&&delete _range.start,has(_range,"end")&&delete _range.end,_range},exports.contains=function(range,key,compare){compare=compare||exports.compare;var lb=lowerBound(range);if(isDef(lb)){var cmp=compare(key,lb);if(cmp<0||0===cmp&&lowerBoundExclusive(range))return!1}var ub=upperBound(range);if(isDef(ub)){var cmp=compare(key,ub);if(cmp>0||0===cmp&&upperBoundExclusive(range))return!1}return!0},exports.filter=function(range,compare){return function(key){return exports.contains(range,key,compare)}}}).call(this,{isBuffer:require("../is-buffer/index.js")})},{"../is-buffer/index.js":42}],80:[function(require,module,exports){const getNGramsOfMultipleLengths=function(inputArray,nGramLengths){var outputArray=[];return nGramLengths.forEach(function(len){outputArray=outputArray.concat(getNGramsOfSingleLength(inputArray,len))}),outputArray},getNGramsOfRangeOfLengths=function(inputArray,nGramLengths){for(var outputArray=[],i=nGramLengths.gte;i<=nGramLengths.lte;i++)outputArray=outputArray.concat(getNGramsOfSingleLength(inputArray,i));return outputArray},getNGramsOfSingleLength=function(inputArray,nGramLength){return inputArray.slice(nGramLength-1).map(function(item,i){return inputArray.slice(i,i+nGramLength)})};exports.ngram=function(inputArray,nGramLength){switch(nGramLength.constructor){case Array: -return getNGramsOfMultipleLengths(inputArray,nGramLength);case Number:return getNGramsOfSingleLength(inputArray,nGramLength);case Object:return getNGramsOfRangeOfLengths(inputArray,nGramLength)}}},{}],81:[function(require,module,exports){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}function onceStrict(fn){var f=function(){if(f.called)throw new Error(f.onceError);return f.called=!0,f.value=fn.apply(this,arguments)},name=fn.name||"Function wrapped with `once`";return f.onceError=name+" shouldn't be called more than once",f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),module.exports.strict=wrappy(onceStrict),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:!0})})},{wrappy:135}],82:[function(require,module,exports){exports.endianness=function(){return"LE"},exports.hostname=function(){return"undefined"!=typeof location?location.hostname:""},exports.loadavg=function(){return[]},exports.uptime=function(){return 0},exports.freemem=function(){return Number.MAX_VALUE},exports.totalmem=function(){return Number.MAX_VALUE},exports.cpus=function(){return[]},exports.type=function(){return"Browser"},exports.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},exports.networkInterfaces=exports.getNetworkInterfaces=function(){return{}},exports.arch=function(){return"javascript"},exports.platform=function(){return"browser"},exports.tmpdir=exports.tmpDir=function(){return"/tmp"},exports.EOL="\n"},{}],83:[function(require,module,exports){(function(process){"use strict";function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function(){fn.call(null,arg1)});case 3:return process.nextTick(function(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;i1)for(var i=1;i0,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})});return streams.reduce(pipe)};module.exports=pump},{"end-of-stream":33,fs:6,once:81}],87:[function(require,module,exports){var pump=require("pump"),inherits=require("inherits"),Duplexify=require("duplexify"),toArray=function(args){return args.length?Array.isArray(args[0])?args[0]:Array.prototype.slice.call(args):[]},define=function(opts){var Pumpify=function(){var streams=toArray(arguments);if(!(this instanceof Pumpify))return new Pumpify(streams);Duplexify.call(this,null,null,opts),streams.length&&this.setPipeline(streams)};return inherits(Pumpify,Duplexify),Pumpify.prototype.setPipeline=function(){var streams=toArray(arguments),self=this,ended=!1,w=streams[0],r=streams[streams.length-1];r=r.readable?r:null,w=w.writable?w:null;var onclose=function(){streams[0].emit("error",new Error("stream was destroyed"))};if(this.on("close",onclose),this.on("prefinish",function(){ended||self.cork()}),pump(streams,function(err){if(self.removeListener("close",onclose),err)return self.destroy(err);ended=!0,self.uncork()}),this.destroyed)return onclose();this.setWritable(w),this.setReadable(r)},Pumpify};module.exports=define({destroy:!1}),module.exports.obj=define({destroy:!1,objectMode:!0,highWaterMark:16})},{duplexify:30,inherits:40,pump:86}],88:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":89}],89:[function(require,module,exports){"use strict";function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),options&&!1===options.readable&&(this.readable=!1),options&&!1===options.writable&&(this.writable=!1),this.allowHalfOpen=!0,options&&!1===options.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",onend)}function onend(){this.allowHalfOpen||this._writableState.ended||processNextTick(onEndNT,this)}function onEndNT(self){self.end()}var processNextTick=require("process-nextick-args"),objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v0?("string"==typeof chunk||Object.getPrototypeOf(chunk)===Buffer.prototype||state.objectMode||(chunk=_uint8ArrayToBuffer(chunk)),addToFront?state.endEmitted?stream.emit("error",new Error("stream.unshift() after end event")):addChunk(stream,state,chunk,!0):state.ended?stream.emit("error",new Error("stream.push() after EOF")):(state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1))):addToFront||(state.reading=!1)}return needMoreData(state)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(nb===str.length?ret+=str:ret+=str.slice(0,n),0===(n-=nb)){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=Buffer.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),0===(n-=nb)){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1,!1!==dest.write(chunk)||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:unpipe;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("safe-buffer").Buffer,destroyImpl=require("./internal/streams/destroy");util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=_isUint8Array(chunk)&&!state.objectMode;return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)},Object.defineProperty(Writable.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){this.end(),cb(err)}}).call(this,require("_process"))},{"./_stream_duplex":89,"./internal/streams/destroy":95,"./internal/streams/stream":96,_process:84,"core-util-is":10,inherits:40,"process-nextick-args":83,"safe-buffer":101,"util-deprecate":131}],94:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function copyBuffer(src,target,offset){src.copy(target,offset)}var Buffer=require("safe-buffer").Buffer;module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return Buffer.alloc(0);if(1===this.length)return this.head.data;for(var ret=Buffer.allocUnsafe(n>>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret},BufferList}()},{"safe-buffer":101}],95:[function(require,module,exports){"use strict";function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;if(readableDestroyed||writableDestroyed)return void(cb?cb(err):!err||this._writableState&&this._writableState.errorEmitted||processNextTick(emitErrorNT,this,err));this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?(processNextTick(emitErrorNT,_this,err),_this._writableState&&(_this._writableState.errorEmitted=!0)):cb&&cb(err)})}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(self,err){self.emit("error",err)}var processNextTick=require("process-nextick-args");module.exports={destroy:destroy,undestroy:undestroy}},{"process-nextick-args":83}],96:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:37}],97:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":98}],98:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":89,"./lib/_stream_passthrough.js":90,"./lib/_stream_readable.js":91,"./lib/_stream_transform.js":92,"./lib/_stream_writable.js":93}],99:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":98}],100:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":93}],101:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0!==fill?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:8}],102:[function(require,module,exports){function throwsMessage(err){return"[Throws: "+(err?err.message:"?")+"]"}function safeGetValueFromPropertyOnObject(obj,property){if(hasProp.call(obj,property))try{return obj[property]}catch(err){return throwsMessage(err)}return obj[property]}function ensureProperties(obj){function visit(obj){if(null===obj||"object"!=typeof obj)return obj;if(-1!==seen.indexOf(obj))return"[Circular]";if(seen.push(obj),"function"==typeof obj.toJSON)try{return visit(obj.toJSON())}catch(err){return throwsMessage(err)}return Array.isArray(obj)?obj.map(visit):Object.keys(obj).reduce(function(result,prop){return result[prop]=visit(safeGetValueFromPropertyOnObject(obj,prop)),result},{})}var seen=[];return visit(obj)}var hasProp=Object.prototype.hasOwnProperty;module.exports=function(data){return JSON.stringify(ensureProperties(data))},module.exports.ensureProperties=ensureProperties},{}],103:[function(require,module,exports){const DBEntries=require("./lib/delete.js").DBEntries,DBWriteCleanStream=require("./lib/replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./lib/replicate.js").DBWriteMergeStream,DocVector=require("./lib/delete.js").DocVector,IndexBatch=require("./lib/add.js").IndexBatch,Readable=require("stream").Readable,RecalibrateDB=require("./lib/delete.js").RecalibrateDB,bunyan=require("bunyan"),del=require("./lib/delete.js"),docProc=require("docproc"),levelup=require("levelup"),pumpify=require("pumpify"),async=require("async");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){var Indexer={};Indexer.options=options;var q=async.queue(function(batch,done){var s;"add"===batch.operation?(s=new Readable({objectMode:!0}),batch.batch.forEach(function(doc){s.push(doc)}),s.push(null),s.pipe(Indexer.defaultPipeline(batch.batchOps)).pipe(Indexer.add()).on("finish",function(){return done()}).on("error",function(err){return done(err)})):"delete"===batch.operation&&(s=new Readable,batch.docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)}))},1);return Indexer.add=function(){return pumpify.obj(new IndexBatch(Indexer),new DBWriteMergeStream(options))},Indexer.concurrentAdd=function(batchOps,batch,done){q.push({batch:batch,batchOps:batchOps,operation:"add"},function(err){done(err)})},Indexer.concurrentDel=function(docIds,done){q.push({docIds:docIds,operation:"delete"},function(err){done(err)})},Indexer.close=function(callback){options.indexes.close(function(err){for(;!options.indexes.isClosed();)options.log.debug("closing...");options.indexes.isClosed()&&(options.log.debug("closed..."),callback(err))})},Indexer.dbWriteStream=function(streamOps){return streamOps=Object.assign({},{merge:!0},streamOps),streamOps.merge?new DBWriteMergeStream(options):new DBWriteCleanStream(options)},Indexer.defaultPipeline=function(batchOptions){return batchOptions=Object.assign({},options,batchOptions),docProc.pipeline(batchOptions)},Indexer.deleteStream=function(options){return pumpify.obj(new DocVector(options),new DBEntries(options),new RecalibrateDB(options))},Indexer.deleter=function(docIds,done){const s=new Readable;docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)})},Indexer.flush=function(APICallback){del.flush(options,function(err){return APICallback(err)})},callback(err,Indexer)})};const getOptions=function(options,done){if(options=Object.assign({},{deletable:!0,batchSize:1e3,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,searchable:!0,indexPath:"si",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/\s|\\n|\\u0003|[-.,<>]/,stopwords:[],weight:0},options),options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes)done(null,options);else{const leveldown=require("leveldown");levelup(options.indexPath||"si",{valueEncoding:"json",db:leveldown},function(err,db){options.indexes=db,done(err,options)})}}},{"./lib/add.js":104,"./lib/delete.js":105,"./lib/replicate.js":106,async:4,bunyan:9,docproc:18,leveldown:57,levelup:70,pumpify:87,stream:125}],104:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),emitIndexKeys=function(s){for(var key in s.deltaIndex)s.push({key:key,value:s.deltaIndex[key]});s.deltaIndex={}},IndexBatch=function(indexer){this.indexer=indexer,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.indexer.options.keySeparator;var that=this;this.indexer.deleter([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.indexer.options.log.info("processing doc "+ingestedDoc.id),that.deltaIndex["DOCUMENT"+sep+ingestedDoc.id+sep]=ingestedDoc.stored;for(var fieldName in ingestedDoc.vector){that.deltaIndex["FIELD"+sep+fieldName]=fieldName;for(var token in ingestedDoc.vector[fieldName]){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token,dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id]),that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.deltaIndex["DOCUMENT-VECTOR"+sep+ingestedDoc.id+sep+fieldName+sep]=ingestedDoc.vector[fieldName]}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.indexer.options.batchSize&&(that.push({totalKeys:totalKeys}),that.indexer.options.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:125,util:134}],105:[function(require,module,exports){const util=require("util"),Transform=require("stream").Transform;exports.flush=function(options,callback){const sep=options.keySeparator;var deleteOps=[];options.indexes.createKeyStream({gte:"0",lte:sep}).on("data",function(data){deleteOps.push({type:"del",key:data})}).on("error",function(err){return options.log.error(err," failed to empty index"),callback(err)}).on("end",function(){options.indexes.batch(deleteOps,callback)})};const DocVector=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DocVector=DocVector,util.inherits(DocVector,Transform),DocVector.prototype._transform=function(docId,encoding,end){docId=JSON.parse(docId);const sep=this.options.keySeparator;var that=this;this.options.indexes.createReadStream({gte:"DOCUMENT-VECTOR"+sep+docId+sep,lte:"DOCUMENT-VECTOR"+sep+docId+sep+sep}).on("data",function(data){that.push(data)}).on("close",function(){return end()})};const DBEntries=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DBEntries=DBEntries,util.inherits(DBEntries,Transform),DBEntries.prototype._transform=function(vector,encoding,end){const sep=this.options.keySeparator;var docId;for(var k in vector.value){docId=vector.key.split(sep)[1];var field=vector.key.split(sep)[2];this.push({key:"TF"+sep+field+sep+k,value:docId}),this.push({key:"DF"+sep+field+sep+k,value:docId})}return this.push({key:vector.key}),this.push({key:"DOCUMENT"+sep+docId+sep}),end()};const RecalibrateDB=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.RecalibrateDB=RecalibrateDB,util.inherits(RecalibrateDB,Transform),RecalibrateDB.prototype._transform=function(dbEntry,encoding,end){const sep=this.options.keySeparator;var that=this;this.options.indexes.get(dbEntry.key,function(err,value){err&&that.options.log.info(err),value||(value=[]);var docId=dbEntry.value,dbInstruction={};dbInstruction.key=dbEntry.key,dbEntry.key.substring(0,3)==="TF"+sep?(dbInstruction.value=value.filter(function(item){return item[1]!==docId}),0===dbInstruction.value.length?dbInstruction.type="del":dbInstruction.type="put"):dbEntry.key.substring(0,3)==="DF"+sep?(value.splice(value.indexOf(docId),1),dbInstruction.value=value,0===dbInstruction.value.length?dbInstruction.type="del":dbInstruction.type="put"):dbEntry.key.substring(0,9)==="DOCUMENT"+sep?dbInstruction.type="del":dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep&&(dbInstruction.type="del"),that.options.indexes.batch([dbInstruction],function(err){return end()})})}},{stream:125,util:134}],106:[function(require,module,exports){const Transform=require("stream").Transform,Writable=require("stream").Writable,util=require("util"),DBWriteMergeStream=function(options){this.options=options,Writable.call(this,{objectMode:!0})};exports.DBWriteMergeStream=DBWriteMergeStream,util.inherits(DBWriteMergeStream,Writable),DBWriteMergeStream.prototype._write=function(data,encoding,end){if(data.totalKeys)return end();const sep=this.options.keySeparator;var that=this;this.options.indexes.get(data.key,function(err,val){var newVal;newVal=data.key.substring(0,3)==="TF"+sep?data.value.concat(val||[]).sort(function(a,b){return a[0]b[0]?-1:a[1]b[1]?-1:0}):data.key.substring(0,3)==="DF"+sep?data.value.concat(val||[]).sort():"DOCUMENT-COUNT"===data.key?+val+(+data.value||0):data.value,that.options.indexes.put(data.key,newVal,function(err){end()})})};const DBWriteCleanStream=function(options){this.currentBatch=[],this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(DBWriteCleanStream,Transform),DBWriteCleanStream.prototype._transform=function(data,encoding,end){var that=this;this.currentBatch.push(data),this.currentBatch.length%this.options.batchSize==0?this.options.indexes.batch(this.currentBatch,function(err){that.push("indexing batch"),that.currentBatch=[],end()}):end()},DBWriteCleanStream.prototype._flush=function(end){var that=this;this.options.indexes.batch(this.currentBatch,function(err){that.push("remaining data indexed"),end()})},exports.DBWriteCleanStream=DBWriteCleanStream},{stream:125,util:134}],107:[function(require,module,exports){const AvailableFields=require("./lib/AvailableFields.js").AvailableFields,CalculateBuckets=require("./lib/CalculateBuckets.js").CalculateBuckets,CalculateCategories=require("./lib/CalculateCategories.js").CalculateCategories,CalculateEntireResultSet=require("./lib/CalculateEntireResultSet.js").CalculateEntireResultSet,CalculateResultSetPerClause=require("./lib/CalculateResultSetPerClause.js").CalculateResultSetPerClause,CalculateTopScoringDocs=require("./lib/CalculateTopScoringDocs.js").CalculateTopScoringDocs,CalculateTotalHits=require("./lib/CalculateTotalHits.js").CalculateTotalHits,Classify=require("./lib/Classify.js").Classify,FetchDocsFromDB=require("./lib/FetchDocsFromDB.js").FetchDocsFromDB,FetchStoredDoc=require("./lib/FetchStoredDoc.js").FetchStoredDoc,GetIntersectionStream=require("./lib/GetIntersectionStream.js").GetIntersectionStream,MergeOrConditions=require("./lib/MergeOrConditions.js").MergeOrConditions,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,SortTopScoringDocs=require("./lib/SortTopScoringDocs.js").SortTopScoringDocs,bunyan=require("bunyan"),levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),initModule=function(err,Searcher,moduleReady){return Searcher.bucketStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateBuckets(Searcher.options,q.filter||{},q.buckets))},Searcher.categoryStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateCategories(Searcher.options,q))},Searcher.classify=function(ops){return new Classify(Searcher,ops)},Searcher.close=function(callback){Searcher.options.indexes.close(function(err){for(;!Searcher.options.indexes.isClosed();)Searcher.options.log.debug("closing...");Searcher.options.indexes.isClosed()&&(Searcher.options.log.debug("closed..."),callback(err))})},Searcher.availableFields=function(){const sep=Searcher.options.keySeparator;return Searcher.options.indexes.createReadStream({gte:"FIELD"+sep,lte:"FIELD"+sep+sep}).pipe(new AvailableFields(Searcher.options))},Searcher.get=function(docIDs){var s=new Readable({objectMode:!0});return docIDs.forEach(function(id){s.push(id)}),s.push(null),s.pipe(new FetchDocsFromDB(Searcher.options))},Searcher.fieldNames=function(){return Searcher.options.indexes.createReadStream({gte:"FIELD",lte:"FIELD"})},Searcher.match=function(q){return matcher.match(q,Searcher.options)},Searcher.dbReadStream=function(){return Searcher.options.indexes.createReadStream()},Searcher.search=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),q.sort?s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options)):s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreTopScoringDocsTFIDF(Searcher.options)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options))},Searcher.scan=function(q){q=siUtil.getQueryDefaults(q);var s=new Readable({objectMode:!0});return s.push("init"),s.push(null),s.pipe(new GetIntersectionStream(Searcher.options,siUtil.getKeySet(q.query[0].AND,Searcher.options.keySeparator))).pipe(new FetchDocsFromDB(Searcher.options))},Searcher.totalHits=function(q,callback){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateTotalHits(Searcher.options)).on("data",function(totalHits){return callback(null,totalHits)})},moduleReady(err,Searcher)},getOptions=function(options,done){var Searcher={};if(Searcher.options=Object.assign({},{deletable:!0,fieldedSearch:!0,store:!0,indexPath:"si",keySeparator:"○",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/[|' .,\-|(\n)]+/,stopwords:[]},options),Searcher.options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes)return done(null,Searcher);levelup(Searcher.options.indexPath||"si",{valueEncoding:"json"},function(err,db){return Searcher.options.indexes=db,done(err,Searcher)})};module.exports=function(givenOptions,moduleReady){getOptions(givenOptions,function(err,Searcher){initModule(err,Searcher,moduleReady)})}},{"./lib/AvailableFields.js":108,"./lib/CalculateBuckets.js":109,"./lib/CalculateCategories.js":110,"./lib/CalculateEntireResultSet.js":111,"./lib/CalculateResultSetPerClause.js":112,"./lib/CalculateTopScoringDocs.js":113,"./lib/CalculateTotalHits.js":114,"./lib/Classify.js":115,"./lib/FetchDocsFromDB.js":116,"./lib/FetchStoredDoc.js":117,"./lib/GetIntersectionStream.js":118,"./lib/MergeOrConditions.js":119,"./lib/ScoreDocsOnField.js":120,"./lib/ScoreTopScoringDocsTFIDF.js":121,"./lib/SortTopScoringDocs.js":122,"./lib/matcher.js":123,"./lib/siUtil.js":124,bunyan:9,levelup:70,stream:125}],108:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),AvailableFields=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.AvailableFields=AvailableFields,util.inherits(AvailableFields,Transform),AvailableFields.prototype._transform=function(field,encoding,end){return this.push(field.key.split(this.options.keySeparator)[1]),end()}},{stream:125,util:134}],109:[function(require,module,exports){const _intersection=require("lodash.intersection"),_uniq=require("lodash.uniq"),Transform=require("stream").Transform,util=require("util"),CalculateBuckets=function(options,filter,requestedBuckets){this.buckets=requestedBuckets||[],this.filter=filter,this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateBuckets=CalculateBuckets,util.inherits(CalculateBuckets,Transform),CalculateBuckets.prototype._transform=function(mergedQueryClauses,encoding,end){const that=this,sep=this.options.keySeparator;var bucketsProcessed=0;that.buckets.forEach(function(bucket){const gte="DF"+sep+bucket.field+sep+bucket.gte,lte="DF"+sep+bucket.field+sep+bucket.lte+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){var IDSet=_intersection(data.value,mergedQueryClauses.set);IDSet.length>0&&(bucket.value=bucket.value||[],bucket.value=_uniq(bucket.value.concat(IDSet).sort()))}).on("close",function(){if(bucket.set||(bucket.value=bucket.value.length),that.push(bucket),++bucketsProcessed===that.buckets.length)return end()})})}},{"lodash.intersection":73,"lodash.uniq":78,stream:125,util:134}],110:[function(require,module,exports){const _intersection=require("lodash.intersection"),Transform=require("stream").Transform,util=require("util"),CalculateCategories=function(options,q){var category=q.category||[];category.values=[],this.offset=+q.offset,this.pageSize=+q.pageSize,this.category=category,this.options=options,this.query=q.query,Transform.call(this,{objectMode:!0})};exports.CalculateCategories=CalculateCategories,util.inherits(CalculateCategories,Transform),CalculateCategories.prototype._transform=function(mergedQueryClauses,encoding,end){if(!this.category.field)return end(new Error("you need to specify a category"));const sep=this.options.keySeparator,that=this,gte="DF"+sep+this.category.field+sep,lte="DF"+sep+this.category.field+sep+sep;this.category.values=this.category.values||[];var i=this.offset+this.pageSize,j=0;const rs=that.options.indexes.createReadStream({gte:gte,lte:lte});rs.on("data",function(data){if(!(that.offset>j++)){var IDSet=_intersection(data.value,mergedQueryClauses.set);if(IDSet.length>0){var key=data.key.split(sep)[2],value=IDSet.length;that.category.set&&(value=IDSet);var result={key:key,value:value};if(1===that.query.length)try{that.query[0].AND[that.category.field].indexOf(key)>-1&&(result.filter=!0)}catch(e){}i-- >that.offset?that.push(result):rs.destroy()}}}).on("close",function(){return end()})}},{"lodash.intersection":73,stream:125,util:134}],111:[function(require,module,exports){const Transform=require("stream").Transform,_union=require("lodash.union"),util=require("util"),CalculateEntireResultSet=function(options){this.options=options,this.setSoFar=[],Transform.call(this,{objectMode:!0})};exports.CalculateEntireResultSet=CalculateEntireResultSet,util.inherits(CalculateEntireResultSet,Transform),CalculateEntireResultSet.prototype._transform=function(queryClause,encoding,end){return this.setSoFar=_union(queryClause.set,this.setSoFar),end()},CalculateEntireResultSet.prototype._flush=function(end){return this.push({set:this.setSoFar}),end()}},{"lodash.union":77,stream:125,util:134}],112:[function(require,module,exports){const Transform=require("stream").Transform,_difference=require("lodash.difference"),_intersection=require("lodash.intersection"),_spread=require("lodash.spread"),siUtil=require("./siUtil.js"),util=require("util"),CalculateResultSetPerClause=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateResultSetPerClause=CalculateResultSetPerClause,util.inherits(CalculateResultSetPerClause,Transform),CalculateResultSetPerClause.prototype._transform=function(queryClause,encoding,end){const sep=this.options.keySeparator,that=this,frequencies=[];var NOT=function(includeResults){const bigIntersect=_spread(_intersection);var include=bigIntersect(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,termFrequencies:frequencies,BOOST:queryClause.BOOST||0}),end();var i=0,excludeResults=[];siUtil.getKeySet(queryClause.NOT,sep).forEach(function(item){var excludeSet={};that.options.indexes.createReadStream({gte:item[0],lte:item[1]+sep}).on("data",function(data){for(var i=0;ib.id?-1:0}).reduce(function(merged,cur){var lastDoc=merged[merged.length-1];return 0===merged.length||cur.id!==lastDoc.id?merged.push(cur):cur.id===lastDoc.id&&(lastDoc.scoringCriteria=lastDoc.scoringCriteria.concat(cur.scoringCriteria)),merged},[]);return mergedResultSet.map(function(item){return item.scoringCriteria&&(item.score=item.scoringCriteria.reduce(function(acc,val){return{score:+acc.score+ +val.score}},{score:0}).score,item.score=item.score/item.scoringCriteria.length),item}),mergedResultSet.forEach(function(item){that.push(item)}),end()}},{stream:125,util:134}],120:[function(require,module,exports){const Transform=require("stream").Transform,_sortedIndexOf=require("lodash.sortedindexof"),util=require("util"),ScoreDocsOnField=function(options,seekLimit,sort){this.options=options,this.seekLimit=seekLimit,this.sort=sort,Transform.call(this,{objectMode:!0})};exports.ScoreDocsOnField=ScoreDocsOnField,util.inherits(ScoreDocsOnField,Transform),ScoreDocsOnField.prototype._transform=function(clauseSet,encoding,end){const sep=this.options.keySeparator,that=this,gte="TF"+sep+this.sort.field+sep,lte="TF"+sep+this.sort.field+sep+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){for(var i=0;ib.score?-2:a.idb.id?-1:0}):this.resultSet=this.resultSet.sort(function(a,b){return a.score>b.score?2:a.scoreb.id?-1:0}),this.resultSet=this.resultSet.slice(this.q.offset,this.q.offset+this.q.pageSize),this.resultSet.forEach(function(hit){that.push(hit)}),end()}},{stream:125,util:134}],123:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatcherStream=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatcherStream,Transform),MatcherStream.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var results=[];this.options.indexes.createReadStream({start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep}).on("data",function(data){results.push(data)}).on("error",function(err){that.options.log.error("Oh my!",err)}).on("end",function(){return results.sort(function(a,b){return b.value.length-a.value.length}).slice(0,q.limit).forEach(function(item){var m={};switch(q.type){case"ID":m={token:item.key.split(sep)[2],documents:item.value};break;case"count":m={token:item.key.split(sep)[2],documentCount:item.value.length};break;default:m=item.key.split(sep)[2]}that.push(m)}),end()})},exports.match=function(q,options){var s=new Readable({objectMode:!0});return q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple"},q),q.beginsWith.length>5==6?2:byte>>4==14?3:byte>>3==30?4:-1}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j=0?(nb>0&&(self.lastNeed=nb-1),nb):--j=0?(nb>0&&(self.lastNeed=nb-2),nb):--j=0?(nb>0&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0)}function utf8CheckExtraBytes(self,buf,p){if(128!=(192&buf[0]))return self.lastNeed=0,"�".repeat(p);if(self.lastNeed>1&&buf.length>1){if(128!=(192&buf[1]))return self.lastNeed=1,"�".repeat(p+1);if(self.lastNeed>2&&buf.length>2&&128!=(192&buf[2]))return self.lastNeed=2,"�".repeat(p+2)}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0!==r?r:this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(buf.copy(this.lastChar,p,0,buf.length),void(this.lastNeed-=buf.length))}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"�".repeat(this.lastTotal-this.lastNeed):r}function utf16Text(buf,i){if((buf.length-i)%2==0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0===n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch((encoding=""+encoding)&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(void 0===(r=this.fillLast(buf)))return"";i=this.lastNeed,this.lastNeed=0}else i=0;return itokens.length)return[];for(var ngrams=[],i=0;i<=tokens.length-nGramLength;i++)ngrams.push(tokens.slice(i,i+nGramLength));if(ngrams=ngrams.sort(),1===ngrams.length)return[[ngrams[0],1]];for(var counter=1,lastToken=ngrams[0],vector=[],j=1;j=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){base=" [Function"+(value.name?": "+value.name:"")+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(recurseTimes<0)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;return output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}}),x=args[i];i-1&&(err.message="Invalid JSON ("+err.message+")"),stream.emit("error",err)},stream},exports.stringify=function(op,sep,cl,indent){indent=indent||0,!1===op?(op="",sep="\n",cl=""):null==op&&(op="[\n",sep="\n,\n",cl="\n]\n");var stream,first=!0,anyData=!1;return stream=through(function(data){anyData=!0;try{var json=JSON.stringify(data,null,indent)}catch(err){return stream.emit("error",err)}first?(first=!1,stream.queue(op+json)):stream.queue(sep+json)},function(data){anyData||stream.queue(op),stream.queue(cl),stream.queue(null)})},exports.stringifyObject=function(op,sep,cl,indent){indent=indent||0,!1===op?(op="",sep="\n",cl=""):null==op&&(op="{\n",sep="\n,\n",cl="\n}\n");var first=!0,anyData=!1;return through(function(data){anyData=!0;var json=JSON.stringify(data[0])+":"+JSON.stringify(data[1],null,indent);first?(first=!1,this.queue(op+json)):this.queue(sep+json)},function(data){anyData||this.queue(op),this.queue(cl),this.queue(null)})},module.parent||"browser"===process.title||process.stdin.pipe(exports.parse(process.argv[2])).pipe(exports.stringify("[",",\n","]\n",2)).pipe(process.stdout)}).call(this,require("_process"),require("buffer").Buffer)},{_process:86,buffer:9,jsonparse:46,through:132}],4:[function(require,module,exports){(function(global){"use strict";function compare(a,b){if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i=0;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return!Error.isPrototypeOf(expected)&&!0===expected.call({},actual)}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError('"block" argument must be a function');"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}var util=require("util/"),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames=function(){return"foo"===function(){}.name}(),assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert.throws=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":137}],5:[function(require,module,exports){(function(process,global){!function(global,factory){"object"==typeof exports&&void 0!==module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory(global.async=global.async||{})}(this,function(exports){"use strict";function slice(arrayLike,start){start|=0;for(var newLen=Math.max(arrayLike.length-start,0),newArr=Array(newLen),idx=0;idx-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function noop(){}function once(fn){return function(){if(null!==fn){var callFn=fn;fn=null,callFn.apply(this,arguments)}}}function baseTimes(n,iteratee){for(var index=-1,result=Array(n);++index-1&&value%1==0&&valuelength?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=length?array:baseSlice(array,start,end)}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function charsStartIndex(strSymbols,chrSymbols){for(var index=-1,length=strSymbols.length;++index-1;);return index}function asciiToArray(string){return string.split("")}function hasUnicode(string){return reHasUnicode.test(string)}function unicodeToArray(string){return string.match(reUnicode)||[]}function stringToArray(string){return hasUnicode(string)?unicodeToArray(string):asciiToArray(string)}function toString(value){return null==value?"":baseToString(value)}function trim(string,chars,guard){if((string=toString(string))&&(guard||void 0===chars))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars);return castSlice(strSymbols,charsStartIndex(strSymbols,chrSymbols),charsEndIndex(strSymbols,chrSymbols)+1).join("")}function parseParams(func){return func=func.toString().replace(STRIP_COMMENTS,""),func=func.match(FN_ARGS)[2].replace(" ",""),func=func?func.split(FN_ARG_SPLIT):[],func=func.map(function(arg){return trim(arg.replace(FN_ARG,""))})}function autoInject(tasks,callback){var newTasks={};baseForOwn(tasks,function(taskFn,key){function newTask(results,taskCb){var newArgs=arrayMap(params,function(name){return results[name]});newArgs.push(taskCb),wrapAsync(taskFn).apply(null,newArgs)}var params,fnIsAsync=isAsync(taskFn),hasNoDeps=!fnIsAsync&&1===taskFn.length||fnIsAsync&&0===taskFn.length;if(isArray(taskFn))params=taskFn.slice(0,-1),taskFn=taskFn[taskFn.length-1],newTasks[key]=params.concat(params.length>0?newTask:taskFn);else if(hasNoDeps)newTasks[key]=taskFn;else{if(params=parseParams(taskFn),0===taskFn.length&&!fnIsAsync&&0===params.length)throw new Error("autoInject task functions require explicit parameters.");fnIsAsync||params.pop(),newTasks[key]=params.concat(newTask)}}),auto(newTasks,callback)}function DLL(){this.head=this.tail=null,this.length=0}function setInitial(dll,node){dll.length=1,dll.head=dll.tail=node}function queue(worker,concurrency,payload){function _insert(data,insertAtFront,callback){if(null!=callback&&"function"!=typeof callback)throw new Error("task callback must be a function");if(q.started=!0,isArray(data)||(data=[data]),0===data.length&&q.idle())return setImmediate$1(function(){q.drain()});for(var i=0,l=data.length;i=0&&workersList.splice(index),task.callback.apply(task,arguments),null!=err&&q.error(err,task.data)}numRunning<=q.concurrency-q.buffer&&q.unsaturated(),q.idle()&&q.drain(),q.process()}}if(null==concurrency)concurrency=1;else if(0===concurrency)throw new Error("Concurrency must not be zero");var _worker=wrapAsync(worker),numRunning=0,workersList=[],isProcessing=!1,q={_tasks:new DLL,concurrency:concurrency,payload:payload,saturated:noop,unsaturated:noop,buffer:concurrency/4,empty:noop,drain:noop,error:noop,started:!1,paused:!1,push:function(data,callback){_insert(data,!1,callback)},kill:function(){q.drain=noop,q._tasks.empty()},unshift:function(data,callback){_insert(data,!0,callback)},remove:function(testFn){q._tasks.remove(testFn)},process:function(){if(!isProcessing){for(isProcessing=!0;!q.paused&&numRunning2&&(result=slice(arguments,1)),results[key]=result,callback(err)})},function(err){callback(err,results)})}function parallelLimit(tasks,callback){_parallel(eachOf,tasks,callback)}function parallelLimit$1(tasks,limit,callback){_parallel(_eachOfLimit(limit),tasks,callback)}function race(tasks,callback){if(callback=once(callback||noop),!isArray(tasks))return callback(new TypeError("First argument to race must be an array of functions"));if(!tasks.length)return callback();for(var i=0,l=tasks.length;ib?1:0}var _iteratee=wrapAsync(iteratee);map(coll,function(x,callback){_iteratee(x,function(err,criteria){if(err)return callback(err);callback(null,{value:x,criteria:criteria})})},function(err,results){if(err)return callback(err);callback(null,arrayMap(results.sort(comparator),baseProperty("value")))})}function timeout(asyncFn,milliseconds,info){var fn=wrapAsync(asyncFn);return initialParams(function(args,callback){function timeoutCallback(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,callback(error)}var timer,timedOut=!1;args.push(function(){timedOut||(callback.apply(null,arguments),clearTimeout(timer))}),timer=setTimeout(timeoutCallback,milliseconds),fn.apply(null,args)})}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function timeLimit(count,limit,iteratee,callback){var _iteratee=wrapAsync(iteratee);mapLimit(baseRange(0,count,1),limit,_iteratee,callback)}function transform(coll,accumulator,iteratee,callback){arguments.length<=3&&(callback=iteratee,iteratee=accumulator,accumulator=isArray(coll)?[]:{}),callback=once(callback||noop);var _iteratee=wrapAsync(iteratee);eachOf(coll,function(v,k,cb){_iteratee(accumulator,v,k,cb)},function(err){callback(err,accumulator)})}function tryEach(tasks,callback){var result,error=null;callback=callback||noop,eachSeries(tasks,function(task,callback){wrapAsync(task)(function(err,res){result=arguments.length>2?slice(arguments,1):res,error=err,callback(!err)})},function(){callback(error,result)})}function unmemoize(fn){return function(){return(fn.unmemoized||fn).apply(null,arguments)}}function whilst(test,iteratee,callback){callback=onlyOnce(callback||noop);var _iteratee=wrapAsync(iteratee);if(!test())return callback(null);var next=function(err){if(err)return callback(err);if(test())return _iteratee(next);var args=slice(arguments,1);callback.apply(null,[null].concat(args))};_iteratee(next)}function until(test,iteratee,callback){whilst(function(){return!test.apply(this,arguments)},iteratee,callback)}var _defer,initialParams=function(fn){return function(){var args=slice(arguments),callback=args.pop();fn.call(this,args,callback)}},hasSetImmediate="function"==typeof setImmediate&&setImmediate,hasNextTick="object"==typeof process&&"function"==typeof process.nextTick;_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback;var setImmediate$1=wrap(_defer),supportsSymbol="function"==typeof Symbol,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),Symbol$1=root.Symbol,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag$1=Symbol$1?Symbol$1.toStringTag:void 0,objectProto$1=Object.prototype,nativeObjectToString$1=objectProto$1.toString,nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol$1?Symbol$1.toStringTag:void 0,asyncTag="[object AsyncFunction]",funcTag="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]",MAX_SAFE_INTEGER=9007199254740991,breakLoop={},iteratorSymbol="function"==typeof Symbol&&Symbol.iterator,getIterator=function(coll){return iteratorSymbol&&coll[iteratorSymbol]&&coll[iteratorSymbol]()},argsTag="[object Arguments]",objectProto$3=Object.prototype,hasOwnProperty$2=objectProto$3.hasOwnProperty,propertyIsEnumerable=objectProto$3.propertyIsEnumerable,isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty$2.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,Buffer=moduleExports?root.Buffer:void 0,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse,MAX_SAFE_INTEGER$1=9007199254740991,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags["[object Float32Array]"]=typedArrayTags["[object Float64Array]"]=typedArrayTags["[object Int8Array]"]=typedArrayTags["[object Int16Array]"]=typedArrayTags["[object Int32Array]"]=typedArrayTags["[object Uint8Array]"]=typedArrayTags["[object Uint8ClampedArray]"]=typedArrayTags["[object Uint16Array]"]=typedArrayTags["[object Uint32Array]"]=!0,typedArrayTags["[object Arguments]"]=typedArrayTags["[object Array]"]=typedArrayTags["[object ArrayBuffer]"]=typedArrayTags["[object Boolean]"]=typedArrayTags["[object DataView]"]=typedArrayTags["[object Date]"]=typedArrayTags["[object Error]"]=typedArrayTags["[object Function]"]=typedArrayTags["[object Map]"]=typedArrayTags["[object Number]"]=typedArrayTags["[object Object]"]=typedArrayTags["[object RegExp]"]=typedArrayTags["[object Set]"]=typedArrayTags["[object String]"]=typedArrayTags["[object WeakMap]"]=!1;var freeExports$1="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule$1=freeExports$1&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports$1=freeModule$1&&freeModule$1.exports===freeExports$1,freeProcess=moduleExports$1&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?function(func){return function(value){return func(value)}}(nodeIsTypedArray):baseIsTypedArray,objectProto$2=Object.prototype,hasOwnProperty$1=objectProto$2.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),objectProto$4=Object.prototype,hasOwnProperty$3=objectProto$4.hasOwnProperty,eachOfGeneric=doLimit(eachOfLimit,1/0),eachOf=function(coll,iteratee,callback){(isArrayLike(coll)?eachOfArrayLike:eachOfGeneric)(coll,wrapAsync(iteratee),callback)},map=doParallel(_asyncMap),applyEach=applyEach$1(map),mapLimit=doParallelLimit(_asyncMap),mapSeries=doLimit(mapLimit,1),applyEachSeries=applyEach$1(mapSeries),apply=function(fn){var args=slice(arguments,1);return function(){var callArgs=slice(arguments);return fn.apply(null,args.concat(callArgs))}},baseFor=function(fromRight){return function(object,iteratee,keysFunc){for(var index=-1,iterable=Object(object),props=keysFunc(object),length=props.length;length--;){var key=props[fromRight?length:++index];if(!1===iteratee(iterable[key],key,iterable))break}return object}}(),auto=function(tasks,concurrency,callback){function enqueueTask(key,task){readyTasks.push(function(){runTask(key,task)})}function processQueue(){if(0===readyTasks.length&&0===runningTasks)return callback(null,results);for(;readyTasks.length&&runningTasks2&&(result=slice(arguments,1)),err){var safeResults={};baseForOwn(results,function(val,rkey){safeResults[rkey]=val}),safeResults[key]=result,hasError=!0,listeners=Object.create(null),callback(err,safeResults)}else results[key]=result,taskComplete(key)});runningTasks++;var taskFn=wrapAsync(task[task.length-1]);task.length>1?taskFn(results,taskCallback):taskFn(taskCallback)}}function getDependents(taskName){var result=[];return baseForOwn(tasks,function(task,key){isArray(task)&&baseIndexOf(task,taskName,0)>=0&&result.push(key)}),result}"function"==typeof concurrency&&(callback=concurrency,concurrency=null),callback=once(callback||noop);var keys$$1=keys(tasks),numTasks=keys$$1.length;if(!numTasks)return callback(null);concurrency||(concurrency=numTasks);var results={},runningTasks=0,hasError=!1,listeners=Object.create(null),readyTasks=[],readyToCheck=[],uncheckedDependencies={};baseForOwn(tasks,function(task,key){if(!isArray(task))return enqueueTask(key,[task]),void readyToCheck.push(key);var dependencies=task.slice(0,task.length-1),remainingDependencies=dependencies.length;if(0===remainingDependencies)return enqueueTask(key,task),void readyToCheck.push(key);uncheckedDependencies[key]=remainingDependencies,arrayEach(dependencies,function(dependencyName){if(!tasks[dependencyName])throw new Error("async.auto task `"+key+"` has a non-existent dependency `"+dependencyName+"` in "+dependencies.join(", "));addListener(dependencyName,function(){0===--remainingDependencies&&enqueueTask(key,task)})})}),function(){for(var currentTask,counter=0;readyToCheck.length;)currentTask=readyToCheck.pop(),counter++,arrayEach(getDependents(currentTask),function(dependent){0==--uncheckedDependencies[dependent]&&readyToCheck.push(dependent)});if(counter!==numTasks)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),processQueue()},symbolTag="[object Symbol]",INFINITY=1/0,symbolProto=Symbol$1?Symbol$1.prototype:void 0,symbolToString=symbolProto?symbolProto.toString:void 0,reHasUnicode=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0\\ufe0e\\ufe0f]"),rsCombo="[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",reOptMod="(?:[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]|\\ud83c[\\udffb-\\udfff])?",rsOptJoin="(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*",rsSeq="[\\ufe0e\\ufe0f]?"+reOptMod+rsOptJoin,rsSymbol="(?:"+["[^\\ud800-\\udfff]"+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,"[\\ud800-\\udfff]"].join("|")+")",reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reTrim=/^\s+|\s+$/g,FN_ARGS=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,FN_ARG_SPLIT=/,/,FN_ARG=/(=.+)?(\s*)$/,STRIP_COMMENTS=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;DLL.prototype.removeLink=function(node){return node.prev?node.prev.next=node.next:this.head=node.next,node.next?node.next.prev=node.prev:this.tail=node.prev,node.prev=node.next=null,this.length-=1,node},DLL.prototype.empty=function(){for(;this.head;)this.shift();return this},DLL.prototype.insertAfter=function(node,newNode){newNode.prev=node,newNode.next=node.next,node.next?node.next.prev=newNode:this.tail=newNode,node.next=newNode,this.length+=1},DLL.prototype.insertBefore=function(node,newNode){newNode.prev=node.prev,newNode.next=node,node.prev?node.prev.next=newNode:this.head=newNode,node.prev=newNode,this.length+=1},DLL.prototype.unshift=function(node){this.head?this.insertBefore(this.head,node):setInitial(this,node)},DLL.prototype.push=function(node){this.tail?this.insertAfter(this.tail,node):setInitial(this,node)},DLL.prototype.shift=function(){return this.head&&this.removeLink(this.head)},DLL.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},DLL.prototype.toArray=function(){for(var arr=Array(this.length),curr=this.head,idx=0;idx=nextNode.priority;)nextNode=nextNode.next;for(var i=0,l=data.length;i0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===b64[len-2]?2:"="===b64[len-1]?1:0}function byteLength(b64){return 3*b64.length/4-placeHoldersCount(b64)}function toByteArray(b64){var i,l,tmp,placeHolders,arr,len=b64.length;placeHolders=placeHoldersCount(b64),arr=new Arr(3*len/4-placeHolders),l=placeHolders>0?len-4:len;var L=0;for(i=0;i>16&255,arr[L++]=tmp>>8&255,arr[L++]=255&tmp;return 2===placeHolders?(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[L++]=255&tmp):1===placeHolders&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[L++]=tmp>>8&255,arr[L++]=255&tmp),arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i=start;ilen2?len2:i+16383));return 1===extraBytes?(tmp=uint8[len-1],output+=lookup[tmp>>2],output+=lookup[tmp<<4&63],output+="=="):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],output+=lookup[tmp>>10],output+=lookup[tmp>>4&63],output+=lookup[tmp<<2&63],output+="="),parts.push(output),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer))return string.byteLength;"string"!=typeof string&&(string=""+string);var len=string.length;if(0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":case void 0:return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),byteOffset=+byteOffset,isNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&("ucs2"===(encoding=String(encoding).toLowerCase())||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2, +valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;jremaining&&(length=remaining):length=remaining;var strLen=string.length;if(strLen%2!=0)throw new TypeError("Invalid hex string");length>strLen/2&&(length=strLen/2);for(var i=0;i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:secondByte=buf[i+1],128==(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte)>127&&(codePoint=tempCodePoint);break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128==(192&secondByte)&&128==(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte)>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint);break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128==(192&secondByte)&&128==(192&thirdByte)&&128==(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte)>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint)}}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;ilen)&&(end=len);for(var out="",i=start;ilength)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function objectWriteUInt16(buf,value,offset,littleEndian){value<0&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);i>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){value<0&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);i>>8*(littleEndian?i:3-i)&255}function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=stringtrim(str).replace(INVALID_BASE64_RE,""),str.length<2)return"";for(;str.length%4!=0;)str+="=";return str}function stringtrim(str){return str.trim?str.trim():str.replace(/^\s+|\s+$/g,"")}function toHex(n){return n<16?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var codePoint,length=string.length,leadSurrogate=null,bytes=[],i=0;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=65536+(leadSurrogate-55296<<10|codePoint-56320)}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isnan(val){return val!==val}var base64=require("base64-js"),ieee754=require("ieee754"),isArray=require("isarray");exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50,Buffer.TYPED_ARRAY_SUPPORT=void 0!==global.TYPED_ARRAY_SUPPORT?global.TYPED_ARRAY_SUPPORT:function(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}(),exports.kMaxLength=kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(arr){return arr.__proto__=Buffer.prototype,arr},Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0})),Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)},Buffer.isBuffer=function(b){return!(null==b||!b._isBuffer)},Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i0&&(str=this.toString("hex",0,max).match(/.{2}/g).join(" "),this.length>max&&(str+=" ... ")),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target))throw new TypeError("Argument must be a Buffer");if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),start<0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;iremaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,start<0?(start+=len)<0&&(start=0):start>len&&(start=len),end<0?(end+=len)<0&&(end=0):end>len&&(end=len),end0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,byteLength|=0,!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0)}var mul=1,i=0;for(this[offset]=255&value;++i=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++i>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart=0;--i)target[i+targetStart]=this[i+start];else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,end=void 0===end?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":return fastAndSafeJsonStringify(args[i++]);case"%%":return"%";default:return x}}),x=args[i];i=0,format('rotating-file stream "count" is not >= 0: %j in %j',this.count,this)),options.period){var period={hourly:"1h",daily:"1d",weekly:"1w",monthly:"1m",yearly:"1y"}[options.period]||options.period,m=/^([1-9][0-9]*)([hdwmy]|ms)$/.exec(period);if(!m)throw new Error(format('invalid period: "%s"',options.period));this.periodNum=Number(m[1]),this.periodScope=m[2]}else this.periodNum=1,this.periodScope="d";var lastModified=null;try{lastModified=fs.statSync(this.path).mtime.getTime()}catch(err){}var rotateAfterOpen=!1;if(lastModified){lastModified call rotate()"),this.rotate()):this._setupNextRot()},util.inherits(RotatingFileStream,EventEmitter),RotatingFileStream.prototype._debug=function(){return!1},RotatingFileStream.prototype._setupNextRot=function(){this.rotAt=this._calcRotTime(1),this._setRotationTimer()},RotatingFileStream.prototype._setRotationTimer=function(){var self=this,delay=this.rotAt-Date.now();delay>2147483647&&(delay=2147483647),this.timeout=setTimeout(function(){self._debug("_setRotationTimer timeout -> call rotate()"),self.rotate()},delay),"function"==typeof this.timeout.unref&&this.timeout.unref()},RotatingFileStream.prototype._calcRotTime=function(periodOffset){this._debug("_calcRotTime: %s%s",this.periodNum,this.periodScope);var d=new Date;this._debug(" now local: %s",d),this._debug(" now utc: %s",d.toISOString());var rotAt;switch(this.periodScope){case"ms":rotAt=this.rotAt?this.rotAt+this.periodNum*periodOffset:Date.now()+this.periodNum*periodOffset;break;case"h":rotAt=this.rotAt?this.rotAt+60*this.periodNum*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),d.getUTCHours()+periodOffset);break;case"d":rotAt=this.rotAt?this.rotAt+24*this.periodNum*60*60*1e3*periodOffset:Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+periodOffset);break;case"w":if(this.rotAt)rotAt=this.rotAt+7*this.periodNum*24*60*60*1e3*periodOffset;else{var dayOffset=7-d.getUTCDay();periodOffset<1&&(dayOffset=-d.getUTCDay()),(periodOffset>1||periodOffset<-1)&&(dayOffset+=7*periodOffset),rotAt=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()+dayOffset)}break;case"m":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+this.periodNum*periodOffset,1):Date.UTC(d.getUTCFullYear(),d.getUTCMonth()+periodOffset,1);break;case"y":rotAt=this.rotAt?Date.UTC(d.getUTCFullYear()+this.periodNum*periodOffset,0,1):Date.UTC(d.getUTCFullYear()+periodOffset,0,1);break;default:assert.fail(format('invalid period scope: "%s"',this.periodScope))}if(this._debug()){this._debug(" **rotAt**: %s (utc: %s)",rotAt,new Date(rotAt).toUTCString());var now=Date.now();this._debug(" now: %s (%sms == %smin == %sh to go)",now,rotAt-now,(rotAt-now)/1e3/60,(rotAt-now)/1e3/60/60)}return rotAt},RotatingFileStream.prototype.rotate=function(){function moves(){if(0===self.count||n<0)return finish();var before=self.path,after=self.path+"."+String(n);n>0&&(before+="."+String(n-1)),n-=1,fs.exists(before,function(exists){exists?(self._debug(" mv %s %s",before,after),mv(before,after,function(mvErr){mvErr?(self.emit("error",mvErr),finish()):moves()})):moves()})}function finish(){self._debug(" open %s",self.path),self.stream=fs.createWriteStream(self.path,{flags:"a",encoding:"utf8"});for(var q=self.rotQueue,len=q.length,i=0;iDate.now())return self._setRotationTimer();if(this._debug("rotate"),self.rotating)throw new TypeError("cannot start a rotation when already rotating");self.rotating=!0,self.stream.end();var n=this.count;!function(){var toDel=self.path+"."+String(n-1);0===n&&(toDel=self.path),n-=1,self._debug(" rm %s",toDel),fs.unlink(toDel,function(delErr){moves()})}()},RotatingFileStream.prototype.write=function(s){return this.rotating?(this.rotQueue.push(s),!1):this.stream.write(s)},RotatingFileStream.prototype.end=function(s){this.stream.end()},RotatingFileStream.prototype.destroy=function(s){this.stream.destroy()},RotatingFileStream.prototype.destroySoon=function(s){this.stream.destroySoon()}),util.inherits(RingBuffer,EventEmitter),RingBuffer.prototype.write=function(record){if(!this.writable)throw new Error("RingBuffer has been ended already");return this.records.push(record),this.records.length>this.limit&&this.records.shift(),!0},RingBuffer.prototype.end=function(){arguments.length>0&&this.write.apply(this,Array.prototype.slice.call(arguments)),this.writable=!1},RingBuffer.prototype.destroy=function(){this.writable=!1,this.emit("close")},RingBuffer.prototype.destroySoon=function(){this.destroy()},module.exports=Logger,module.exports.TRACE=10,module.exports.DEBUG=20,module.exports.INFO=INFO,module.exports.WARN=WARN,module.exports.ERROR=ERROR,module.exports.FATAL=60,module.exports.resolveLevel=resolveLevel,module.exports.levelFromName=levelFromName,module.exports.nameFromLevel=nameFromLevel,module.exports.VERSION="1.8.10",module.exports.LOG_VERSION=LOG_VERSION,module.exports.createLogger=function(options){return new Logger(options)},module.exports.RingBuffer=RingBuffer,module.exports.RotatingFileStream=RotatingFileStream,module.exports.safeCycles=safeCycles}).call(this,{isBuffer:require("../../is-buffer/index.js")},require("_process"))},{"../../is-buffer/index.js":43,_process:86,assert:4,events:38,fs:8,os:84,"safe-json-stringify":104,stream:127,util:137}],11:[function(require,module,exports){(function(Buffer){function isArray(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return"[object Date]"===objectToString(d)}function isError(e){return"[object Error]"===objectToString(e)||e instanceof Error}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg}function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=Buffer.isBuffer}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":43}],12:[function(require,module,exports){function DeferredIterator(options){AbstractIterator.call(this,options),this._options=options,this._iterator=null,this._operations=[]}var util=require("util"),AbstractIterator=require("abstract-leveldown").AbstractIterator;util.inherits(DeferredIterator,AbstractIterator),DeferredIterator.prototype.setDb=function(db){var it=this._iterator=db.iterator(this._options);this._operations.forEach(function(op){it[op.method].apply(it,op.args)})},DeferredIterator.prototype._operation=function(method,args){if(this._iterator)return this._iterator[method].apply(this._iterator,args);this._operations.push({method:method,args:args})},"next end".split(" ").forEach(function(m){DeferredIterator.prototype["_"+m]=function(){this._operation(m,arguments)}}),module.exports=DeferredIterator},{"abstract-leveldown":17,util:137}],13:[function(require,module,exports){(function(Buffer,process){function DeferredLevelDOWN(location){AbstractLevelDOWN.call(this,"string"==typeof location?location:""),this._db=void 0,this._operations=[],this._iterators=[]}var util=require("util"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,DeferredIterator=require("./deferred-iterator");util.inherits(DeferredLevelDOWN,AbstractLevelDOWN),DeferredLevelDOWN.prototype.setDb=function(db){this._db=db,this._operations.forEach(function(op){db[op.method].apply(db,op.args)}),this._iterators.forEach(function(it){it.setDb(db)})},DeferredLevelDOWN.prototype._open=function(options,callback){return process.nextTick(callback)},DeferredLevelDOWN.prototype._operation=function(method,args){if(this._db)return this._db[method].apply(this._db,args);this._operations.push({method:method,args:args})},"put get del batch approximateSize".split(" ").forEach(function(m){DeferredLevelDOWN.prototype["_"+m]=function(){this._operation(m,arguments)}}),DeferredLevelDOWN.prototype._isBuffer=function(obj){return Buffer.isBuffer(obj)},DeferredLevelDOWN.prototype._iterator=function(options){if(this._db)return this._db.iterator.apply(this._db,arguments);var it=new DeferredIterator(options);return this._iterators.push(it),it},module.exports=DeferredLevelDOWN,module.exports.DeferredIterator=DeferredIterator}).call(this,{isBuffer:require("../is-buffer/index.js")},require("_process"))},{"../is-buffer/index.js":43,"./deferred-iterator":12,_process:86,"abstract-leveldown":17,util:137}],14:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKey(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:86}],15:[function(require,module,exports){(function(process){function AbstractIterator(db){this.db=db,this._ended=!1,this._nexting=!1}AbstractIterator.prototype.next=function(callback){var self=this;if("function"!=typeof callback)throw new Error("next() requires a callback argument");return self._ended?callback(new Error("cannot call next() after end()")):self._nexting?callback(new Error("cannot call next() before previous next() has completed")):(self._nexting=!0,"function"==typeof self._next?self._next(function(){self._nexting=!1,callback.apply(null,arguments)}):void process.nextTick(function(){self._nexting=!1,callback()}))},AbstractIterator.prototype.end=function(callback){if("function"!=typeof callback)throw new Error("end() requires a callback argument");return this._ended?callback(new Error("end() already called on iterator")):(this._ended=!0,"function"==typeof this._end?this._end(callback):void process.nextTick(callback))},module.exports=AbstractIterator}).call(this,require("_process"))},{_process:86}],16:[function(require,module,exports){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location,this.status="new"}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){var self=this,oldStatus=this.status;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");"object"!=typeof options&&(options={}),options.createIfMissing=0!=options.createIfMissing,options.errorIfExists=!!options.errorIfExists,"function"==typeof this._open?(this.status="opening",this._open(options,function(err){if(err)return self.status=oldStatus,callback(err);self.status="open",callback()})):(this.status="open",process.nextTick(callback))},AbstractLevelDOWN.prototype.close=function(callback){var self=this,oldStatus=this.status;if("function"!=typeof callback)throw new Error("close() requires a callback argument");"function"==typeof this._close?(this.status="closing",this._close(function(err){if(err)return self.status=oldStatus,callback(err);self.status="closed",callback()})):(this.status="closed",process.nextTick(callback))},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),options.asBuffer=0!=options.asBuffer,"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),null==value||this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKey(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"==typeof array&&(callback=array),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));options&&"object"==typeof options||(options={});for(var e,err,i=0,l=array.length;i<.,\-|]+|\\u0003/},doc.options||{});for(var fieldName in doc.normalised){var fieldOptions=Object.assign({},{separator:options.separator},options.fieldOptions[fieldName]);"[object Array]"===Object.prototype.toString.call(doc.normalised[fieldName])?doc.tokenised[fieldName]=doc.normalised[fieldName]:doc.tokenised[fieldName]=doc.normalised[fieldName].split(fieldOptions.separator)}return this.push(doc),end()}},{stream:127,util:137}],31:[function(require,module,exports){(function(process,Buffer){var stream=require("readable-stream"),eos=require("end-of-stream"),inherits=require("inherits"),shift=require("stream-shift"),SIGNAL_FLUSH=new Buffer([0]),onuncork=function(self,fn){self._corked?self.once("uncork",fn):fn()},destroyer=function(self,end){return function(err){err?self.destroy("premature close"===err.message?null:err):end&&!self._ended&&self.end()}},end=function(ws,fn){return ws?ws._writableState&&ws._writableState.finished?fn():ws._writableState?ws.end(fn):(ws.end(),void fn()):fn()},toStreams2=function(rs){return new stream.Readable({objectMode:!0,highWaterMark:16}).wrap(rs)},Duplexify=function(writable,readable,opts){if(!(this instanceof Duplexify))return new Duplexify(writable,readable,opts);stream.Duplex.call(this,opts),this._writable=null,this._readable=null,this._readable2=null,this._forwardDestroy=!opts||!1!==opts.destroy,this._forwardEnd=!opts||!1!==opts.end,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,writable&&this.setWritable(writable),readable&&this.setReadable(readable)};inherits(Duplexify,stream.Duplex),Duplexify.obj=function(writable,readable,opts){return opts||(opts={}),opts.objectMode=!0,opts.highWaterMark=16,new Duplexify(writable,readable,opts)},Duplexify.prototype.cork=function(){1==++this._corked&&this.emit("cork")},Duplexify.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},Duplexify.prototype.setWritable=function(writable){if(this._unwrite&&this._unwrite(),this.destroyed)return void(writable&&writable.destroy&&writable.destroy());if(null===writable||!1===writable)return void this.end();var self=this,unend=eos(writable,{writable:!0,readable:!1},destroyer(this,this._forwardEnd)),ondrain=function(){var ondrain=self._ondrain;self._ondrain=null,ondrain&&ondrain()},clear=function(){self._writable.removeListener("drain",ondrain),unend()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=clear,this.uncork()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)return void(readable&&readable.destroy&&readable.destroy());if(null===readable||!1===readable)return this.push(null),void this.resume();var self=this,unend=eos(readable,{writable:!1,readable:!0},destroyer(this)),onreadable=function(){self._forward()},onend=function(){self.push(null)},clear=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()};this._drained=!0,this._readable=readable,this._readable2=readable._readableState?readable:toStreams2(readable),this._readable2.on("readable",onreadable),this._readable2.on("end",onend),this._unread=clear,this._forward()},Duplexify.prototype._read=function(){this._drained=!0,this._forward()},Duplexify.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){this._forwarding=!0;for(var data;this._drained&&null!==(data=shift(this._readable2));)this.destroyed||(this._drained=this.push(data));this._forwarding=!1}},Duplexify.prototype.destroy=function(err){if(!this.destroyed){this.destroyed=!0;var self=this;process.nextTick(function(){self._destroy(err)})}},Duplexify.prototype._destroy=function(err){if(err){var ondrain=this._ondrain;this._ondrain=null,ondrain?ondrain(err):this.emit("error",err)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},Duplexify.prototype._write=function(data,enc,cb){return this.destroyed?cb():this._corked?onuncork(this,this._write.bind(this,data,enc,cb)):data===SIGNAL_FLUSH?this._finish(cb):this._writable?void(!1===this._writable.write(data)?this._ondrain=cb:cb()):cb()},Duplexify.prototype._finish=function(cb){var self=this;this.emit("preend"),onuncork(this,function(){end(self._forwardEnd&&self._writable,function(){!1===self._writableState.prefinished&&(self._writableState.prefinished=!0),self.emit("prefinish"),onuncork(self,cb)})})},Duplexify.prototype.end=function(data,enc,cb){return"function"==typeof data?this.end(null,null,data):"function"==typeof enc?this.end(data,null,enc):(this._ended=!0,data&&this.write(data),this._writableState.ending||this.write(SIGNAL_FLUSH),stream.Writable.prototype.end.call(this,cb))},module.exports=Duplexify}).call(this,require("_process"),require("buffer").Buffer)},{_process:86,buffer:9,"end-of-stream":32,inherits:41,"readable-stream":100,"stream-shift":128}],32:[function(require,module,exports){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback()},onend=function(){readable=!1,writable||callback()},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback(new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:33}],33:[function(require,module,exports){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0})})},{wrappy:138}],34:[function(require,module,exports){var once=require("once"),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},isChildProcess=function(stream){return stream.stdio&&Array.isArray(stream.stdio)&&3===stream.stdio.length},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback.call(stream)},onend=function(){readable=!1,writable||callback.call(stream)},onexit=function(exitCode){callback.call(stream,exitCode?new Error("exited with error code: "+exitCode):null)},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback.call(stream,new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),isChildProcess(stream)&&stream.on("exit",onexit),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("exit",onexit),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},{once:83}],35:[function(require,module,exports){function init(type,message,cause){prr(this,{type:type,name:type,cause:"string"!=typeof message?message:cause,message:message&&"string"!=typeof message?message.message:message},"ewr")}function CustomError(message,cause){Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee),init.call(this,"CustomError",message,cause)}function createError(errno,type,proto){var err=function(message,cause){init.call(this,type,message,cause),"FilesystemError"==type&&(this.code=this.cause.code,this.path=this.cause.path,this.errno=this.cause.errno,this.message=(errno.errno[this.cause.errno]?errno.errno[this.cause.errno].description:this.cause.message)+(this.cause.path?" ["+this.cause.path+"]":"")),Error.call(this),Error.captureStackTrace&&Error.captureStackTrace(this,arguments.callee)};return err.prototype=proto?new proto:new CustomError,err}var prr=require("prr");CustomError.prototype=new Error,module.exports=function(errno){var ce=function(type,proto){return createError(errno,type,proto)};return{CustomError:CustomError,FilesystemError:ce("FilesystemError"),createError:ce}}},{prr:37}],36:[function(require,module,exports){var all=module.exports.all=[{errno:-2,code:"ENOENT",description:"no such file or directory"},{errno:-1,code:"UNKNOWN",description:"unknown error"},{errno:0,code:"OK",description:"success"},{errno:1,code:"EOF",description:"end of file"},{errno:2,code:"EADDRINFO",description:"getaddrinfo error"},{errno:3,code:"EACCES",description:"permission denied"},{errno:4,code:"EAGAIN",description:"resource temporarily unavailable"},{errno:5,code:"EADDRINUSE",description:"address already in use"},{errno:6,code:"EADDRNOTAVAIL",description:"address not available"},{errno:7,code:"EAFNOSUPPORT",description:"address family not supported"},{errno:8,code:"EALREADY",description:"connection already in progress"},{errno:9,code:"EBADF",description:"bad file descriptor"},{errno:10,code:"EBUSY",description:"resource busy or locked"},{errno:11,code:"ECONNABORTED",description:"software caused connection abort"},{errno:12,code:"ECONNREFUSED",description:"connection refused"},{errno:13,code:"ECONNRESET",description:"connection reset by peer"},{errno:14,code:"EDESTADDRREQ",description:"destination address required"},{errno:15,code:"EFAULT",description:"bad address in system call argument"},{errno:16,code:"EHOSTUNREACH",description:"host is unreachable"},{errno:17,code:"EINTR",description:"interrupted system call"},{errno:18,code:"EINVAL",description:"invalid argument"},{errno:19,code:"EISCONN",description:"socket is already connected"},{errno:20,code:"EMFILE",description:"too many open files"},{errno:21,code:"EMSGSIZE",description:"message too long"},{errno:22,code:"ENETDOWN",description:"network is down"},{errno:23,code:"ENETUNREACH",description:"network is unreachable"},{errno:24,code:"ENFILE",description:"file table overflow"},{errno:25,code:"ENOBUFS",description:"no buffer space available"},{errno:26,code:"ENOMEM",description:"not enough memory"},{errno:27,code:"ENOTDIR",description:"not a directory"},{errno:28,code:"EISDIR",description:"illegal operation on a directory"},{errno:29,code:"ENONET",description:"machine is not on the network"},{errno:31,code:"ENOTCONN",description:"socket is not connected"},{errno:32,code:"ENOTSOCK",description:"socket operation on non-socket"},{errno:33,code:"ENOTSUP",description:"operation not supported on socket"},{errno:34,code:"ENOENT",description:"no such file or directory"},{errno:35,code:"ENOSYS",description:"function not implemented"},{errno:36,code:"EPIPE",description:"broken pipe"},{errno:37,code:"EPROTO",description:"protocol error"},{errno:38,code:"EPROTONOSUPPORT",description:"protocol not supported"},{errno:39,code:"EPROTOTYPE",description:"protocol wrong type for socket"},{errno:40,code:"ETIMEDOUT",description:"connection timed out"},{errno:41,code:"ECHARSET",description:"invalid Unicode character"},{errno:42,code:"EAIFAMNOSUPPORT",description:"address family for hostname not supported"},{errno:44,code:"EAISERVICE",description:"servname not supported for ai_socktype"},{errno:45,code:"EAISOCKTYPE",description:"ai_socktype not supported"},{errno:46,code:"ESHUTDOWN",description:"cannot send after transport endpoint shutdown"},{errno:47,code:"EEXIST",description:"file already exists"},{errno:48,code:"ESRCH",description:"no such process"},{errno:49,code:"ENAMETOOLONG",description:"name too long"},{errno:50,code:"EPERM",description:"operation not permitted"},{errno:51,code:"ELOOP",description:"too many symbolic links encountered"},{errno:52,code:"EXDEV",description:"cross-device link not permitted"},{errno:53,code:"ENOTEMPTY",description:"directory not empty"},{errno:54,code:"ENOSPC",description:"no space left on device"},{errno:55,code:"EIO",description:"i/o error"},{errno:56,code:"EROFS",description:"read-only file system"},{errno:57,code:"ENODEV",description:"no such device"},{errno:58,code:"ESPIPE",description:"invalid seek"},{errno:59,code:"ECANCELED",description:"operation canceled"}];module.exports.errno={},module.exports.code={},all.forEach(function(error){module.exports.errno[error.errno]=error,module.exports.code[error.code]=error}),module.exports.custom=require("./custom")(module.exports),module.exports.create=module.exports.custom.createError},{"./custom":35}],37:[function(require,module,exports){!function(name,context,definition){void 0!==module&&module.exports?module.exports=definition():context.prr=definition()}(0,this,function(){var setProperty="function"==typeof Object.defineProperty?function(obj,key,options){return Object.defineProperty(obj,key,options),obj}:function(obj,key,options){return obj[key]=options.value,obj},makeOptions=function(value,options){var oo="object"==typeof options,os=!oo&&"string"==typeof options,op=function(p){return oo?!!options[p]:!!os&&options.indexOf(p[0])>-1};return{enumerable:op("enumerable"),configurable:op("configurable"),writable:op("writable"),value:value}};return function(obj,key,value,options){var k;if(options=makeOptions(value,options),"object"==typeof key){for(k in key)Object.hasOwnProperty.call(key,k)&&(options.value=key[k],setProperty(obj,k,options));return obj}return setProperty(obj,key,options)}})},{}],38:[function(require,module,exports){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if((er=arguments[1])instanceof Error)throw er;var err=new Error('Uncaught, unspecified "error" event. ('+er+")");throw err.context=er,err}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args)}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;i0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace()),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-- >0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(position<0)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){return this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},{}],39:[function(require,module,exports){!function(name,definition,global){"use strict";"function"==typeof define?define(definition):void 0!==module&&module.exports?module.exports=definition():global.IDBStore=definition()}(0,function(){"use strict";function mixin(target,source){var name,s;for(name in source)(s=source[name])!==empty[name]&&s!==target[name]&&(target[name]=s);return target}function hasVersionError(errorEvent){return"error"in errorEvent.target?"VersionError"==errorEvent.target.error.name:"errorCode"in errorEvent.target&&12==errorEvent.target.errorCode}var defaultErrorHandler=function(error){throw error},defaultSuccessHandler=function(){},defaults={storeName:"Store",storePrefix:"IDBWrapper-",dbVersion:1,keyPath:"id",autoIncrement:!0,onStoreReady:function(){},onError:defaultErrorHandler,indexes:[],implementationPreference:["indexedDB","webkitIndexedDB","mozIndexedDB","shimIndexedDB"]},IDBStore=function(kwArgs,onStoreReady){void 0===onStoreReady&&"function"==typeof kwArgs&&(onStoreReady=kwArgs),"[object Object]"!=Object.prototype.toString.call(kwArgs)&&(kwArgs={});for(var key in defaults)this[key]=void 0!==kwArgs[key]?kwArgs[key]:defaults[key];this.dbName=this.storePrefix+this.storeName,this.dbVersion=parseInt(this.dbVersion,10)||1,onStoreReady&&(this.onStoreReady=onStoreReady);var env="object"==typeof window?window:self,availableImplementations=this.implementationPreference.filter(function(implName){return implName in env});this.implementation=availableImplementations[0],this.idb=env[this.implementation],this.keyRange=env.IDBKeyRange||env.webkitIDBKeyRange||env.mozIDBKeyRange,this.consts={READ_ONLY:"readonly",READ_WRITE:"readwrite",VERSION_CHANGE:"versionchange",NEXT:"next",NEXT_NO_DUPLICATE:"nextunique",PREV:"prev",PREV_NO_DUPLICATE:"prevunique"},this.openDB()},proto={constructor:IDBStore,version:"1.7.1",db:null,dbName:null,dbVersion:null,store:null,storeName:null,storePrefix:null,keyPath:null,autoIncrement:null,indexes:null,implementationPreference:null,implementation:"",onStoreReady:null,onError:null,_insertIdCount:0,openDB:function(){var openRequest=this.idb.open(this.dbName,this.dbVersion),preventSuccessCallback=!1;openRequest.onerror=function(errorEvent){if(hasVersionError(errorEvent))this.onError(new Error("The version number provided is lower than the existing one."));else{var error;if(errorEvent.target.error)error=errorEvent.target.error;else{var errorMessage="IndexedDB unknown error occurred when opening DB "+this.dbName+" version "+this.dbVersion;"errorCode"in errorEvent.target&&(errorMessage+=" with error code "+errorEvent.target.errorCode),error=new Error(errorMessage)}this.onError(error)}}.bind(this),openRequest.onsuccess=function(event){if(!preventSuccessCallback){if(this.db)return void this.onStoreReady();if(this.db=event.target.result,"string"==typeof this.db.version)return void this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."));if(!this.db.objectStoreNames.contains(this.storeName))return void this.onError(new Error("Object store couldn't be created."));var emptyTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);this.store=emptyTransaction.objectStore(this.storeName);var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(!indexName)return preventSuccessCallback=!0,void this.onError(new Error("Cannot create index: No index name given."));if(this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);this.indexComplies(actualIndex,indexData)||(preventSuccessCallback=!0,this.onError(new Error('Cannot modify index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else preventSuccessCallback=!0,this.onError(new Error('Cannot create new index "'+indexName+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))},this),existingIndexes.length&&(preventSuccessCallback=!0,this.onError(new Error('Cannot delete index(es) "'+existingIndexes.toString()+'" for current version. Please bump version number to '+(this.dbVersion+1)+"."))),preventSuccessCallback||this.onStoreReady()}}.bind(this),openRequest.onupgradeneeded=function(event){if(this.db=event.target.result,this.db.objectStoreNames.contains(this.storeName))this.store=event.target.transaction.objectStore(this.storeName);else{var optionalParameters={autoIncrement:this.autoIncrement};null!==this.keyPath&&(optionalParameters.keyPath=this.keyPath),this.store=this.db.createObjectStore(this.storeName,optionalParameters)}var existingIndexes=Array.prototype.slice.call(this.getIndexList());this.indexes.forEach(function(indexData){var indexName=indexData.name;if(indexName||(preventSuccessCallback=!0,this.onError(new Error("Cannot create index: No index name given."))),this.normalizeIndexData(indexData),this.hasIndex(indexName)){var actualIndex=this.store.index(indexName);this.indexComplies(actualIndex,indexData)||(this.store.deleteIndex(indexName),this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})),existingIndexes.splice(existingIndexes.indexOf(indexName),1)}else this.store.createIndex(indexName,indexData.keyPath,{unique:indexData.unique,multiEntry:indexData.multiEntry})},this),existingIndexes.length&&existingIndexes.forEach(function(_indexName){this.store.deleteIndex(_indexName)},this)}.bind(this)},deleteDatabase:function(onSuccess,onError){if(this.idb.deleteDatabase){this.db.close();var deleteRequest=this.idb.deleteDatabase(this.dbName);deleteRequest.onsuccess=onSuccess,deleteRequest.onerror=onError}else onError(new Error("Browser does not support IndexedDB deleteDatabase!"))},put:function(key,value,onSuccess,onError){null!==this.keyPath&&(onError=onSuccess,onSuccess=value,value=key),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var putRequest,hasSuccess=!1,result=null,putTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);return putTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},putTransaction.onabort=onError,putTransaction.onerror=onError,null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=putTransaction.objectStore(this.storeName).put(value)):putRequest=putTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},putRequest.onerror=onError,putTransaction},get:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,getTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);getTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getTransaction.onabort=onError,getTransaction.onerror=onError;var getRequest=getTransaction.objectStore(this.storeName).get(key);return getRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getRequest.onerror=onError,getTransaction},remove:function(key,onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,removeTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);removeTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},removeTransaction.onabort=onError,removeTransaction.onerror=onError;var deleteRequest=removeTransaction.objectStore(this.storeName).delete(key);return deleteRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},deleteRequest.onerror=onError,removeTransaction},batch:function(dataArray,onSuccess,onError){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),"[object Array]"!=Object.prototype.toString.call(dataArray))onError(new Error("dataArray argument must be of type Array."));else if(0===dataArray.length)return onSuccess(!0);var count=dataArray.length,called=!1,hasSuccess=!1,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(hasSuccess)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(){0!==--count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(operation){var type=operation.type,key=operation.key,value=operation.value,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err,type,key))};if("remove"==type){var deleteRequest=batchTransaction.objectStore(this.storeName).delete(key);deleteRequest.onsuccess=onItemSuccess,deleteRequest.onerror=onItemError}else if("put"==type){var putRequest;null!==this.keyPath?(this._addIdPropertyIfNeeded(value),putRequest=batchTransaction.objectStore(this.storeName).put(value)):putRequest=batchTransaction.objectStore(this.storeName).put(value,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError}},this),batchTransaction},putBatch:function(dataArray,onSuccess,onError){var batchData=dataArray.map(function(item){return{type:"put",value:item}}) +;return this.batch(batchData,onSuccess,onError)},upsertBatch:function(dataArray,options,onSuccess,onError){"function"==typeof options&&(onSuccess=options,onError=onSuccess,options={}),onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),options||(options={}),"[object Array]"!=Object.prototype.toString.call(dataArray)&&onError(new Error("dataArray argument must be of type Array."));var keyField=options.keyField||this.keyPath,count=dataArray.length,called=!1,hasSuccess=!1,index=0,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);batchTransaction.oncomplete=function(){hasSuccess?onSuccess(dataArray):onError(!1)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){dataArray[index++][keyField]=event.target.result,0!==--count||called||(called=!0,hasSuccess=!0)};return dataArray.forEach(function(record){var putRequest,key=record.key,onItemError=function(err){batchTransaction.abort(),called||(called=!0,onError(err))};null!==this.keyPath?(this._addIdPropertyIfNeeded(record),putRequest=batchTransaction.objectStore(this.storeName).put(record)):putRequest=batchTransaction.objectStore(this.storeName).put(record,key),putRequest.onsuccess=onItemSuccess,putRequest.onerror=onItemError},this),batchTransaction},removeBatch:function(keyArray,onSuccess,onError){var batchData=keyArray.map(function(key){return{type:"remove",key:key}});return this.batch(batchData,onSuccess,onError)},getBatch:function(keyArray,onSuccess,onError,arrayType){if(onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler),arrayType||(arrayType="sparse"),"[object Array]"!=Object.prototype.toString.call(keyArray))onError(new Error("keyArray argument must be of type Array."));else if(0===keyArray.length)return onSuccess([]);var data=[],count=keyArray.length,called=!1,hasSuccess=!1,result=null,batchTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY);batchTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},batchTransaction.onabort=onError,batchTransaction.onerror=onError;var onItemSuccess=function(event){event.target.result||"dense"==arrayType?data.push(event.target.result):"sparse"==arrayType&&data.length++,0===--count&&(called=!0,hasSuccess=!0,result=data)};return keyArray.forEach(function(key){var onItemError=function(err){called=!0,result=err,onError(err),batchTransaction.abort()},getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=onItemError},this),batchTransaction},getAll:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var getAllTransaction=this.db.transaction([this.storeName],this.consts.READ_ONLY),store=getAllTransaction.objectStore(this.storeName);return store.getAll?this._getAllNative(getAllTransaction,store,onSuccess,onError):this._getAllCursor(getAllTransaction,store,onSuccess,onError),getAllTransaction},_getAllNative:function(getAllTransaction,store,onSuccess,onError){var hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var getAllRequest=store.getAll();getAllRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},getAllRequest.onerror=onError},_getAllCursor:function(getAllTransaction,store,onSuccess,onError){var all=[],hasSuccess=!1,result=null;getAllTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},getAllTransaction.onabort=onError,getAllTransaction.onerror=onError;var cursorRequest=store.openCursor();cursorRequest.onsuccess=function(event){var cursor=event.target.result;cursor?(all.push(cursor.value),cursor.continue()):(hasSuccess=!0,result=all)},cursorRequest.onError=onError},clear:function(onSuccess,onError){onError||(onError=defaultErrorHandler),onSuccess||(onSuccess=defaultSuccessHandler);var hasSuccess=!1,result=null,clearTransaction=this.db.transaction([this.storeName],this.consts.READ_WRITE);clearTransaction.oncomplete=function(){(hasSuccess?onSuccess:onError)(result)},clearTransaction.onabort=onError,clearTransaction.onerror=onError;var clearRequest=clearTransaction.objectStore(this.storeName).clear();return clearRequest.onsuccess=function(event){hasSuccess=!0,result=event.target.result},clearRequest.onerror=onError,clearTransaction},_addIdPropertyIfNeeded:function(dataObj){void 0===dataObj[this.keyPath]&&(dataObj[this.keyPath]=this._insertIdCount+++Date.now())},getIndexList:function(){return this.store.indexNames},hasIndex:function(indexName){return this.store.indexNames.contains(indexName)},normalizeIndexData:function(indexData){indexData.keyPath=indexData.keyPath||indexData.name,indexData.unique=!!indexData.unique,indexData.multiEntry=!!indexData.multiEntry},indexComplies:function(actual,expected){return["keyPath","unique","multiEntry"].every(function(key){if("multiEntry"==key&&void 0===actual[key]&&!1===expected[key])return!0;if("keyPath"==key&&"[object Array]"==Object.prototype.toString.call(expected[key])){var exp=expected.keyPath,act=actual.keyPath;if("string"==typeof act)return exp.toString()==act;if("function"!=typeof act.contains&&"function"!=typeof act.indexOf)return!1;if(act.length!==exp.length)return!1;for(var i=0,m=exp.length;i>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:1/0*(s?-1:1);m+=Math.pow(2,mLen),e-=eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias),value*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],41:[function(require,module,exports){"function"==typeof Object.create?module.exports=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],42:[function(require,module,exports){var Readable=require("stream").Readable;exports.getIntersectionStream=function(sortedSets){for(var s=new Readable,i=0,ii=[],k=0;ksortedSets[i+1][ii[i+1]])ii[i+1]++;else if(i+2=sortedSets[k].length&&(finished=!0);i=0}return s.push(null),s}},{stream:127}],43:[function(require,module,exports){function isBuffer(obj){return!!obj.constructor&&"function"==typeof obj.constructor.isBuffer&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return"function"==typeof obj.readFloatLE&&"function"==typeof obj.slice&&isBuffer(obj.slice(0,0))}module.exports=function(obj){return null!=obj&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)}},{}],44:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},{}],45:[function(require,module,exports){function isBuffer(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}var Buffer=require("buffer").Buffer;module.exports=isBuffer},{buffer:9}],46:[function(require,module,exports){(function(Buffer){function Parser(){this.tState=START,this.value=void 0,this.string=void 0,this.stringBuffer=Buffer.alloc?Buffer.alloc(STRING_BUFFER_SIZE):new Buffer(STRING_BUFFER_SIZE),this.stringBufferOffset=0,this.unicode=void 0,this.highSurrogate=void 0,this.key=void 0,this.mode=void 0,this.stack=[],this.state=VALUE,this.bytes_remaining=0,this.bytes_in_sequence=0,this.temp_buffs={2:new Buffer(2),3:new Buffer(3),4:new Buffer(4)},this.offset=-1}var C={},LEFT_BRACE=C.LEFT_BRACE=1,RIGHT_BRACE=C.RIGHT_BRACE=2,LEFT_BRACKET=C.LEFT_BRACKET=3,RIGHT_BRACKET=C.RIGHT_BRACKET=4,COLON=C.COLON=5,COMMA=C.COMMA=6,TRUE=C.TRUE=7,FALSE=C.FALSE=8,NULL=C.NULL=9,STRING=C.STRING=10,NUMBER=C.NUMBER=11,START=C.START=17,STOP=C.STOP=18,TRUE1=C.TRUE1=33,TRUE2=C.TRUE2=34,TRUE3=C.TRUE3=35,FALSE1=C.FALSE1=49,FALSE2=C.FALSE2=50,FALSE3=C.FALSE3=51,FALSE4=C.FALSE4=52,NULL1=C.NULL1=65,NULL2=C.NULL2=66,NULL3=C.NULL3=67,NUMBER1=C.NUMBER1=81,NUMBER3=C.NUMBER3=83,STRING1=C.STRING1=97,STRING2=C.STRING2=98,STRING3=C.STRING3=99,STRING4=C.STRING4=100,STRING5=C.STRING5=101,STRING6=C.STRING6=102,VALUE=C.VALUE=113,KEY=C.KEY=114,OBJECT=C.OBJECT=129,ARRAY=C.ARRAY=130,BACK_SLASH="\\".charCodeAt(0),FORWARD_SLASH="/".charCodeAt(0),BACKSPACE="\b".charCodeAt(0),FORM_FEED="\f".charCodeAt(0),NEWLINE="\n".charCodeAt(0),CARRIAGE_RETURN="\r".charCodeAt(0),TAB="\t".charCodeAt(0),STRING_BUFFER_SIZE=65536;Parser.toknam=function(code){for(var keys=Object.keys(C),i=0,l=keys.length;i=STRING_BUFFER_SIZE&&(this.string+=this.stringBuffer.toString("utf8"),this.stringBufferOffset=0),this.stringBuffer[this.stringBufferOffset++]=char},proto.appendStringBuf=function(buf,start,end){var size=buf.length;"number"==typeof start&&(size="number"==typeof end?end<0?buf.length-start+end:end-start:buf.length-start),size<0&&(size=0),this.stringBufferOffset+size>STRING_BUFFER_SIZE&&(this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0),buf.copy(this.stringBuffer,this.stringBufferOffset,start,end),this.stringBufferOffset+=size},proto.write=function(buffer){"string"==typeof buffer&&(buffer=new Buffer(buffer));for(var n,i=0,l=buffer.length;i=48&&n<64)this.string=String.fromCharCode(n),this.tState=NUMBER3;else if(32!==n&&9!==n&&10!==n&&13!==n)return this.charError(buffer,i)}else if(this.tState===STRING1)if(n=buffer[i],this.bytes_remaining>0){for(var j=0;j=128){if(n<=193||n>244)return this.onError(new Error("Invalid UTF-8 character at position "+i+" in state "+Parser.toknam(this.tState)));if(n>=194&&n<=223&&(this.bytes_in_sequence=2),n>=224&&n<=239&&(this.bytes_in_sequence=3),n>=240&&n<=244&&(this.bytes_in_sequence=4),this.bytes_in_sequence+i>buffer.length){for(var k=0;k<=buffer.length-1-i;k++)this.temp_buffs[this.bytes_in_sequence][k]=buffer[i+k];this.bytes_remaining=i+this.bytes_in_sequence-buffer.length,i=buffer.length-1}else this.appendStringBuf(buffer,i,i+this.bytes_in_sequence),i=i+this.bytes_in_sequence-1}else if(34===n)this.tState=START,this.string+=this.stringBuffer.toString("utf8",0,this.stringBufferOffset),this.stringBufferOffset=0,this.onToken(STRING,this.string),this.offset+=Buffer.byteLength(this.string,"utf8")+1,this.string=void 0;else if(92===n)this.tState=STRING2;else{if(!(n>=32))return this.charError(buffer,i);this.appendStringChar(n)}else if(this.tState===STRING2)if(34===(n=buffer[i]))this.appendStringChar(n),this.tState=STRING1;else if(92===n)this.appendStringChar(BACK_SLASH),this.tState=STRING1;else if(47===n)this.appendStringChar(FORWARD_SLASH),this.tState=STRING1;else if(98===n)this.appendStringChar(BACKSPACE),this.tState=STRING1;else if(102===n)this.appendStringChar(FORM_FEED),this.tState=STRING1;else if(110===n)this.appendStringChar(NEWLINE),this.tState=STRING1;else if(114===n)this.appendStringChar(CARRIAGE_RETURN),this.tState=STRING1;else if(116===n)this.appendStringChar(TAB),this.tState=STRING1;else{if(117!==n)return this.charError(buffer,i);this.unicode="",this.tState=STRING3}else if(this.tState===STRING3||this.tState===STRING4||this.tState===STRING5||this.tState===STRING6){if(!((n=buffer[i])>=48&&n<64||n>64&&n<=70||n>96&&n<=102))return this.charError(buffer,i);if(this.unicode+=String.fromCharCode(n),this.tState++===STRING6){var intVal=parseInt(this.unicode,16);this.unicode=void 0,void 0!==this.highSurrogate&&intVal>=56320&&intVal<57344?(this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate,intVal))),this.highSurrogate=void 0):void 0===this.highSurrogate&&intVal>=55296&&intVal<56320?this.highSurrogate=intVal:(void 0!==this.highSurrogate&&(this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate))),this.highSurrogate=void 0),this.appendStringBuf(new Buffer(String.fromCharCode(intVal)))),this.tState=STRING1}}else if(this.tState===NUMBER1||this.tState===NUMBER3)switch(n=buffer[i]){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 46:case 101:case 69:case 43:case 45:this.string+=String.fromCharCode(n),this.tState=NUMBER3;break;default:this.tState=START;var result=Number(this.string);if(isNaN(result))return this.charError(buffer,i);this.string.match(/[0-9]+/)==this.string&&result.toString()!=this.string?this.onToken(STRING,this.string):this.onToken(NUMBER,result),this.offset+=this.string.length-1,this.string=void 0,i--}else if(this.tState===TRUE1){if(114!==buffer[i])return this.charError(buffer,i);this.tState=TRUE2}else if(this.tState===TRUE2){if(117!==buffer[i])return this.charError(buffer,i);this.tState=TRUE3}else if(this.tState===TRUE3){if(101!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(TRUE,!0),this.offset+=3}else if(this.tState===FALSE1){if(97!==buffer[i])return this.charError(buffer,i);this.tState=FALSE2}else if(this.tState===FALSE2){if(108!==buffer[i])return this.charError(buffer,i);this.tState=FALSE3}else if(this.tState===FALSE3){if(115!==buffer[i])return this.charError(buffer,i);this.tState=FALSE4}else if(this.tState===FALSE4){if(101!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(FALSE,!1),this.offset+=4}else if(this.tState===NULL1){if(117!==buffer[i])return this.charError(buffer,i);this.tState=NULL2}else if(this.tState===NULL2){if(108!==buffer[i])return this.charError(buffer,i);this.tState=NULL3}else if(this.tState===NULL3){if(108!==buffer[i])return this.charError(buffer,i);this.tState=START,this.onToken(NULL,null),this.offset+=3}},proto.onToken=function(token,value){},proto.parseError=function(token,value){this.tState=STOP,this.onError(new Error("Unexpected "+Parser.toknam(token)+(value?"("+JSON.stringify(value)+")":"")+" in state "+Parser.toknam(this.state)))},proto.push=function(){this.stack.push({value:this.value,key:this.key,mode:this.mode})},proto.pop=function(){var value=this.value,parent=this.stack.pop();this.value=parent.value,this.key=parent.key,this.mode=parent.mode,this.emit(value),this.mode||(this.state=VALUE)},proto.emit=function(value){this.mode&&(this.state=COMMA),this.onValue(value)},proto.onValue=function(value){},proto.onToken=function(token,value){if(this.state===VALUE)if(token===STRING||token===NUMBER||token===TRUE||token===FALSE||token===NULL)this.value&&(this.value[this.key]=value),this.emit(value);else if(token===LEFT_BRACE)this.push(),this.value?this.value=this.value[this.key]={}:this.value={},this.key=void 0,this.state=KEY,this.mode=OBJECT;else if(token===LEFT_BRACKET)this.push(),this.value?this.value=this.value[this.key]=[]:this.value=[],this.key=0,this.mode=ARRAY,this.state=VALUE;else if(token===RIGHT_BRACE){if(this.mode!==OBJECT)return this.parseError(token,value);this.pop()}else{if(token!==RIGHT_BRACKET)return this.parseError(token,value);if(this.mode!==ARRAY)return this.parseError(token,value);this.pop()}else if(this.state===KEY)if(token===STRING)this.key=value,this.state=COLON;else{if(token!==RIGHT_BRACE)return this.parseError(token,value);this.pop()}else if(this.state===COLON){if(token!==COLON)return this.parseError(token,value);this.state=VALUE}else{if(this.state!==COMMA)return this.parseError(token,value);if(token===COMMA)this.mode===ARRAY?(this.key++,this.state=VALUE):this.mode===OBJECT&&(this.state=KEY);else{if(!(token===RIGHT_BRACKET&&this.mode===ARRAY||token===RIGHT_BRACE&&this.mode===OBJECT))return this.parseError(token,value);this.pop()}}},Parser.C=C,module.exports=Parser}).call(this,require("buffer").Buffer)},{buffer:9}],47:[function(require,module,exports){function Codec(opts){this.opts=opts||{},this.encodings=encodings}var encodings=require("./lib/encodings");module.exports=Codec,Codec.prototype._encoding=function(encoding){return"string"==typeof encoding&&(encoding=encodings[encoding]),encoding||(encoding=encodings.id),encoding},Codec.prototype._keyEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&batchOpts.keyEncoding||opts&&opts.keyEncoding||this.opts.keyEncoding)},Codec.prototype._valueEncoding=function(opts,batchOpts){return this._encoding(batchOpts&&(batchOpts.valueEncoding||batchOpts.encoding)||opts&&(opts.valueEncoding||opts.encoding)||this.opts.valueEncoding||this.opts.encoding)},Codec.prototype.encodeKey=function(key,opts,batchOpts){return this._keyEncoding(opts,batchOpts).encode(key)},Codec.prototype.encodeValue=function(value,opts,batchOpts){return this._valueEncoding(opts,batchOpts).encode(value)},Codec.prototype.decodeKey=function(key,opts){return this._keyEncoding(opts).decode(key)},Codec.prototype.decodeValue=function(value,opts){return this._valueEncoding(opts).decode(value)},Codec.prototype.encodeBatch=function(ops,opts){var self=this;return ops.map(function(_op){var op={type:_op.type,key:self.encodeKey(_op.key,opts,_op)};return self.keyAsBuffer(opts,_op)&&(op.keyEncoding="binary"),_op.prefix&&(op.prefix=_op.prefix),"value"in _op&&(op.value=self.encodeValue(_op.value,opts,_op),self.valueAsBuffer(opts,_op)&&(op.valueEncoding="binary")),op})};var ltgtKeys=["lt","gt","lte","gte","start","end"];Codec.prototype.encodeLtgt=function(ltgt){var self=this,ret={};return Object.keys(ltgt).forEach(function(key){ret[key]=ltgtKeys.indexOf(key)>-1?self.encodeKey(ltgt[key],ltgt):ltgt[key]}),ret},Codec.prototype.createStreamDecoder=function(opts){var self=this;return opts.keys&&opts.values?function(key,value){return{key:self.decodeKey(key,opts),value:self.decodeValue(value,opts)}}:opts.keys?function(key){return self.decodeKey(key,opts)}:opts.values?function(_,value){return self.decodeValue(value,opts)}:function(){}},Codec.prototype.keyAsBuffer=function(opts){return this._keyEncoding(opts).buffer},Codec.prototype.valueAsBuffer=function(opts){return this._valueEncoding(opts).buffer}},{"./lib/encodings":48}],48:[function(require,module,exports){(function(Buffer){function identity(value){return value}function isBinary(data){return void 0===data||null===data||Buffer.isBuffer(data)}exports.utf8=exports["utf-8"]={encode:function(data){return isBinary(data)?data:String(data)},decode:identity,buffer:!1,type:"utf8"},exports.json={encode:JSON.stringify,decode:JSON.parse,buffer:!1,type:"json"},exports.binary={encode:function(data){return isBinary(data)?data:new Buffer(data)},decode:identity,buffer:!0,type:"binary"},exports.id={encode:function(data){return data},decode:function(data){return data},buffer:!1,type:"id"},["hex","ascii","base64","ucs2","ucs-2","utf16le","utf-16le"].forEach(function(type){exports[type]={encode:function(data){return isBinary(data)?data:new Buffer(data,type)},decode:function(buffer){return buffer.toString(type)},buffer:!0,type:type}})}).call(this,require("buffer").Buffer)},{buffer:9}],49:[function(require,module,exports){var createError=require("errno").create,LevelUPError=createError("LevelUPError"),NotFoundError=createError("NotFoundError",LevelUPError);NotFoundError.prototype.notFound=!0,NotFoundError.prototype.status=404,module.exports={LevelUPError:LevelUPError,InitializationError:createError("InitializationError",LevelUPError),OpenError:createError("OpenError",LevelUPError),ReadError:createError("ReadError",LevelUPError),WriteError:createError("WriteError",LevelUPError),NotFoundError:NotFoundError,EncodingError:createError("EncodingError",LevelUPError)}},{errno:36}],50:[function(require,module,exports){function ReadStream(iterator,options){if(!(this instanceof ReadStream))return new ReadStream(iterator,options);Readable.call(this,extend(options,{objectMode:!0})),this._iterator=iterator,this._destroyed=!1,this._decoder=null,options&&options.decoder&&(this._decoder=options.decoder),this.on("end",this._cleanup.bind(this))}var inherits=require("inherits"),Readable=require("readable-stream").Readable,extend=require("xtend"),EncodingError=require("level-errors").EncodingError;module.exports=ReadStream,inherits(ReadStream,Readable),ReadStream.prototype._read=function(){var self=this;this._destroyed||this._iterator.next(function(err,key,value){if(!self._destroyed){if(err)return self.emit("error",err);if(void 0===key&&void 0===value)self.push(null);else{if(!self._decoder)return self.push({key:key,value:value});try{var value=self._decoder(key,value)}catch(err){return self.emit("error",new EncodingError(err)),void self.push(null)}self.push(value)}}})},ReadStream.prototype.destroy=ReadStream.prototype._cleanup=function(){var self=this;this._destroyed||(this._destroyed=!0,this._iterator.end(function(err){if(err)return self.emit("error",err);self.emit("close")}))}},{inherits:41,"level-errors":49,"readable-stream":57,xtend:139}],51:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],52:[function(require,module,exports){(function(process){function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),options&&!1===options.readable&&(this.readable=!1),options&&!1===options.writable&&(this.writable=!1),this.allowHalfOpen=!0,options&&!1===options.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",onend)}function onend(){this.allowHalfOpen||this._writableState.ended||process.nextTick(this.end.bind(this))}module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys},util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable),function(xs,f){for(var i=0,l=xs.length;i0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk)),addToFront||(state.reading=!1),state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state);else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM)n=MAX_HWM;else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:isNaN(n)||util.isNull(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:n<=0?0:(n>state.highWaterMark&&(state.highWaterMark=roundUpToNextPowerOf2(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return util.isBuffer(chunk)||util.isString(chunk)||util.isNullOrUndefined(chunk)||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?process.nextTick(function(){emitReadable_(stream)}):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(function(){maybeReadMore_(stream,state)}))}function maybeReadMore_(stream,state){ +for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=length)ret=stringMode?list.join(""):Buffer.concat(list,length),list.length=0;else if(n0)throw new Error("endReadable called on non-empty stream");state.endEmitted||(state.ended=!0,process.nextTick(function(){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}))}function forEach(xs,f){for(var i=0,l=xs.length;i0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,util.isNull(ret)&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&0===state.length&&endReadable(this),util.isNull(ret)||this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",cleanup),src.removeListener("data",ondata),!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),!1===dest.write(chunk)&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EE.listenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);return dest.on("drain",ondrain),src.on("data",ondata),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i1){for(var cbs=[],c=0;c=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived=55296&&charCode<=56319)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},{buffer:9}],59:[function(require,module,exports){(function(Buffer){function Level(location){if(!(this instanceof Level))return new Level(location);if(!location)throw new Error("constructor requires at least a location argument");this.IDBOptions={},this.location=location}module.exports=Level;var IDB=require("idb-wrapper"),AbstractLevelDOWN=require("abstract-leveldown").AbstractLevelDOWN,util=require("util"),Iterator=require("./iterator"),isBuffer=require("isbuffer"),xtend=require("xtend"),toBuffer=require("typedarray-to-buffer");util.inherits(Level,AbstractLevelDOWN),Level.prototype._open=function(options,callback){var self=this,idbOpts={storeName:this.location,autoIncrement:!1,keyPath:null,onStoreReady:function(){callback&&callback(null,self.idb)},onError:function(err){callback&&callback(err)}};xtend(idbOpts,options),this.IDBOptions=idbOpts,this.idb=new IDB(idbOpts)},Level.prototype._get=function(key,options,callback){this.idb.get(key,function(value){if(void 0===value)return callback(new Error("NotFound"));var asBuffer=!0;return!1===options.asBuffer&&(asBuffer=!1),options.raw&&(asBuffer=!1),asBuffer&&(value=value instanceof Uint8Array?toBuffer(value):new Buffer(String(value))),callback(null,value,key)},callback)},Level.prototype._del=function(id,options,callback){this.idb.remove(id,callback,callback)},Level.prototype._put=function(key,value,options,callback){value instanceof ArrayBuffer&&(value=toBuffer(new Uint8Array(value)));var obj=this.convertEncoding(key,value,options);Buffer.isBuffer(obj.value)&&("function"==typeof value.toArrayBuffer?obj.value=new Uint8Array(value.toArrayBuffer()):obj.value=new Uint8Array(value)),this.idb.put(obj.key,obj.value,function(){callback()},callback)},Level.prototype.convertEncoding=function(key,value,options){if(options.raw)return{key:key,value:value};if(value){var stringed=value.toString();"NaN"===stringed&&(value="NaN")}var valEnc=options.valueEncoding,obj={key:key,value:value};return!value||valEnc&&"binary"===valEnc||"object"!=typeof obj.value&&(obj.value=stringed),obj},Level.prototype.iterator=function(options){return"object"!=typeof options&&(options={}),new Iterator(this.idb,options)},Level.prototype._batch=function(array,options,callback){var i,k,copiedOp,currentOp,modified=[];if(0===array.length)return setTimeout(callback,0);for(i=0;i0&&this._count++>=this._limit&&(shouldCall=!1),shouldCall&&this.callback(!1,cursor.key,cursor.value),cursor&&cursor.continue()},Iterator.prototype._next=function(callback){return callback?this._keyRangeError?callback():(this._started||(this.createIterator(),this._started=!0),void(this.callback=callback)):new Error("next() requires a callback argument")}},{"abstract-leveldown":63,ltgt:81,util:137}],61:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._checkWritten=function(){if(this._written)throw new Error("write() already called on this batch")},AbstractChainedBatch.prototype.put=function(key,value){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;if(err=this._db._checkKeyValue(value,"value",this._db._isBuffer))throw err;return this._db._isBuffer(key)||(key=String(key)),this._db._isBuffer(value)||(value=String(value)),"function"==typeof this._put?this._put(key,value):this._operations.push({type:"put",key:key,value:value}),this},AbstractChainedBatch.prototype.del=function(key){this._checkWritten();var err=this._db._checkKeyValue(key,"key",this._db._isBuffer);if(err)throw err;return this._db._isBuffer(key)||(key=String(key)),"function"==typeof this._del?this._del(key):this._operations.push({type:"del",key:key}),this},AbstractChainedBatch.prototype.clear=function(){return this._checkWritten(),this._operations=[],"function"==typeof this._clear&&this._clear(),this},AbstractChainedBatch.prototype.write=function(options,callback){if(this._checkWritten(),"function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("write() requires a callback argument");return"object"!=typeof options&&(options={}),this._written=!0,"function"==typeof this._write?this._write(callback):"function"==typeof this._db._batch?this._db._batch(this._operations,options,callback):void process.nextTick(callback)},module.exports=AbstractChainedBatch}).call(this,require("_process"))},{_process:86}],62:[function(require,module,exports){arguments[4][15][0].apply(exports,arguments)},{_process:86,dup:15}],63:[function(require,module,exports){(function(Buffer,process){function AbstractLevelDOWN(location){if(!arguments.length||void 0===location)throw new Error("constructor requires at least a location argument");if("string"!=typeof location)throw new Error("constructor requires a location string argument");this.location=location}var xtend=require("xtend"),AbstractIterator=require("./abstract-iterator"),AbstractChainedBatch=require("./abstract-chained-batch");AbstractLevelDOWN.prototype.open=function(options,callback){if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("open() requires a callback argument");if("object"!=typeof options&&(options={}),"function"==typeof this._open)return this._open(options,callback);process.nextTick(callback)},AbstractLevelDOWN.prototype.close=function(callback){if("function"!=typeof callback)throw new Error("close() requires a callback argument");if("function"==typeof this._close)return this._close(callback);process.nextTick(callback)},AbstractLevelDOWN.prototype.get=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("get() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._get?this._get(key,options,callback):void process.nextTick(function(){callback(new Error("NotFound"))}))},AbstractLevelDOWN.prototype.put=function(key,value,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("put() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(err=this._checkKeyValue(value,"value",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),this._isBuffer(value)||process.browser||(value=String(value)),"object"!=typeof options&&(options={}),"function"==typeof this._put?this._put(key,value,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.del=function(key,options,callback){var err;if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("del() requires a callback argument");return(err=this._checkKeyValue(key,"key",this._isBuffer))?callback(err):(this._isBuffer(key)||(key=String(key)),"object"!=typeof options&&(options={}),"function"==typeof this._del?this._del(key,options,callback):void process.nextTick(callback))},AbstractLevelDOWN.prototype.batch=function(array,options,callback){if(!arguments.length)return this._chainedBatch();if("function"==typeof options&&(callback=options),"function"!=typeof callback)throw new Error("batch(array) requires a callback argument");if(!Array.isArray(array))return callback(new Error("batch(array) requires an array argument"));"object"!=typeof options&&(options={});for(var e,err,i=0,l=array.length;i2?arguments[2]:null;if(l===+l)for(i=0;i=0&&"[object Function]"===toString.call(value.callee)),isArguments}},{}],68:[function(require,module,exports){!function(){"use strict";var keysShim,has=Object.prototype.hasOwnProperty,toString=Object.prototype.toString,forEach=require("./foreach"),isArgs=require("./isArguments"),hasDontEnumBug=!{toString:null}.propertyIsEnumerable("toString"),hasProtoEnumBug=function(){}.propertyIsEnumerable("prototype"),dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];keysShim=function(object){var isObject=null!==object&&"object"==typeof object,isFunction="[object Function]"===toString.call(object),isArguments=isArgs(object),theKeys=[];if(!isObject&&!isFunction&&!isArguments)throw new TypeError("Object.keys called on a non-object");if(isArguments)forEach(object,function(value){theKeys.push(value)});else{var name,skipProto=hasProtoEnumBug&&isFunction;for(name in object)skipProto&&"prototype"===name||!has.call(object,name)||theKeys.push(name)}if(hasDontEnumBug){var ctor=object.constructor,skipConstructor=ctor&&ctor.prototype===object;forEach(dontEnums,function(dontEnum){skipConstructor&&"constructor"===dontEnum||!has.call(object,dontEnum)||theKeys.push(dontEnum)})}return theKeys},module.exports=keysShim}()},{"./foreach":65,"./isArguments":67}],69:[function(require,module,exports){function hasKeys(source){return null!==source&&("object"==typeof source||"function"==typeof source)}module.exports=hasKeys},{}],70:[function(require,module,exports){function extend(){for(var target={},i=0;i-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){return!(!isObject(value)||isMasked(value))&&(isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor).test(toSource(value))}function getMapData(map,key){var data=map.__data__;return isKeyable(key)?data["string"==typeof key?"string":"hash"]:data.map}function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:void 0}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isKeyable(value){var type=typeof value;return"string"==type||"number"==type||"symbol"==type||"boolean"==type?"__proto__"!==value:null===value}function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}function toSource(func){if(null!=func){try{return funcToString.call(func)}catch(e){}try{return func+""}catch(e){}}return""}function eq(value,other){return value===other||value!==value&&other!==other}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var difference=function(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=120&&array.length>=120)?new SetCache(othIndex&&array):void 0}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}var HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:"" +}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),splice=arrayProto.splice,nativeMax=Math.max,nativeMin=Math.min,Map=getNative(root,"Map"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var intersection=function(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=null==entries?0:entries.length;for(this.clear();++indexarrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&COMPARE_UNORDERED_FLAG?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index-1&&value%1==0&&value-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function stubArray(){return[]}function stubFalse(){return!1}var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2,MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",arrayTag="[object Array]",asyncTag="[object AsyncFunction]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",nullTag="[object Null]",objectTag="[object Object]",proxyTag="[object Proxy]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",undefinedTag="[object Undefined]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags["[object Float32Array]"]=typedArrayTags["[object Float64Array]"]=typedArrayTags["[object Int8Array]"]=typedArrayTags["[object Int16Array]"]=typedArrayTags["[object Int32Array]"]=typedArrayTags["[object Uint8Array]"]=typedArrayTags["[object Uint8ClampedArray]"]=typedArrayTags["[object Uint16Array]"]=typedArrayTags["[object Uint32Array]"]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags["[object WeakMap]"]=!1;var freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),nativeObjectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Buffer=moduleExports?root.Buffer:void 0,Symbol=root.Symbol,Uint8Array=root.Uint8Array,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,symToStringTag=Symbol?Symbol.toStringTag:void 0,nativeGetSymbols=Object.getOwnPropertySymbols,nativeIsBuffer=Buffer?Buffer.isBuffer:void 0,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),DataView=getNative(root,"DataView"),Map=getNative(root,"Map"),Promise=getNative(root,"Promise"),Set=getNative(root,"Set"),WeakMap=getNative(root,"WeakMap"),nativeCreate=getNative(Object,"create"),dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap),symbolProto=Symbol?Symbol.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0;Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas,Stack.prototype.clear=stackClear,Stack.prototype.delete=stackDelete,Stack.prototype.get=stackGet,Stack.prototype.has=stackHas,Stack.prototype.set=stackSet;var getSymbols=nativeGetSymbols?function(object){return null==object?[]:(object=Object(object),arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol)}))}:stubArray,getTag=baseGetTag;(DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag||Map&&getTag(new Map)!=mapTag||Promise&&"[object Promise]"!=getTag(Promise.resolve())||Set&&getTag(new Set)!=setTag||WeakMap&&"[object WeakMap]"!=getTag(new WeakMap))&&(getTag=function(value){var result=baseGetTag(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):"";if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return"[object Promise]";case setCtorString:return setTag;case weakMapCtorString:return"[object WeakMap]"}return result});var isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isBuffer=nativeIsBuffer||stubFalse,isTypedArray=nodeIsTypedArray?function(func){return function(value){return func(value)}}(nodeIsTypedArray):baseIsTypedArray;module.exports=isEqual}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],77:[function(require,module,exports){function baseSortedIndex(array,value,retHighest){var low=0,high=array?array.length:low;if("number"==typeof value&&value===value&&high<=HALF_MAX_ARRAY_LENGTH){for(;low>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computedlength?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index=length?array:baseSlice(array,start,end)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=void 0===start?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toFinite(value){if(!value)return 0===value?value:0;if((value=toNumber(value))===INFINITY||value===-INFINITY){return(value<0?-1:1)*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}var FUNC_ERROR_TEXT="Expected a function",INFINITY=1/0,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,symbolTag="[object Symbol]",reTrim=/^\s+|\s+$/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,freeParseInt=parseInt,objectProto=Object.prototype,objectToString=objectProto.toString,nativeMax=Math.max;module.exports=spread},{}],79:[function(require,module,exports){(function(global){function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayIncludes(array,value){return!!(array?array.length:0)&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){return!(!isObject(value)||isMasked(value))&&(isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor).test(toSource(value))}function baseUniq(array,iteratee,comparator){var index=-1,includes=arrayIncludes,length=array.length,isCommon=!0,result=[],seen=result;if(comparator)isCommon=!1,includes=arrayIncludesWith;else if(length>=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}function noop(){} +var LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=Symbol?Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),Set=getNative(root,"Set"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:noop,union=function(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++indexb?1:0};var lowerBoundKey=exports.lowerBoundKey=function(range){return hasKey(range,"gt")||hasKey(range,"gte")||hasKey(range,"min")||(range.reverse?hasKey(range,"end"):hasKey(range,"start"))||void 0},lowerBound=exports.lowerBound=function(range,def){var k=lowerBoundKey(range);return k?range[k]:def},lowerBoundInclusive=exports.lowerBoundInclusive=function(range){return!has(range,"gt")},upperBoundInclusive=exports.upperBoundInclusive=function(range){return!has(range,"lt")},lowerBoundExclusive=exports.lowerBoundExclusive=function(range){return!lowerBoundInclusive(range)},upperBoundExclusive=exports.upperBoundExclusive=function(range){return!upperBoundInclusive(range)},upperBoundKey=exports.upperBoundKey=function(range){return hasKey(range,"lt")||hasKey(range,"lte")||hasKey(range,"max")||(range.reverse?hasKey(range,"start"):hasKey(range,"end"))||void 0},upperBound=exports.upperBound=function(range,def){var k=upperBoundKey(range);return k?range[k]:def};exports.start=function(range,def){return range.reverse?upperBound(range,def):lowerBound(range,def)},exports.end=function(range,def){return range.reverse?lowerBound(range,def):upperBound(range,def)},exports.startInclusive=function(range){return range.reverse?upperBoundInclusive(range):lowerBoundInclusive(range)},exports.endInclusive=function(range){return range.reverse?lowerBoundInclusive(range):upperBoundInclusive(range)},exports.toLtgt=function(range,_range,map,lower,upper){_range=_range||{},map=map||id;var defaults=arguments.length>3,lb=exports.lowerBoundKey(range),ub=exports.upperBoundKey(range);return lb?"gt"===lb?_range.gt=map(range.gt,!1):_range.gte=map(range[lb],!1):defaults&&(_range.gte=map(lower,!1)),ub?"lt"===ub?_range.lt=map(range.lt,!0):_range.lte=map(range[ub],!0):defaults&&(_range.lte=map(upper,!0)),null!=range.reverse&&(_range.reverse=!!range.reverse),has(_range,"max")&&delete _range.max,has(_range,"min")&&delete _range.min,has(_range,"start")&&delete _range.start,has(_range,"end")&&delete _range.end,_range},exports.contains=function(range,key,compare){compare=compare||exports.compare;var lb=lowerBound(range);if(isDef(lb)){var cmp=compare(key,lb);if(cmp<0||0===cmp&&lowerBoundExclusive(range))return!1}var ub=upperBound(range);if(isDef(ub)){var cmp=compare(key,ub);if(cmp>0||0===cmp&&upperBoundExclusive(range))return!1}return!0},exports.filter=function(range,compare){return function(key){return exports.contains(range,key,compare)}}}).call(this,{isBuffer:require("../is-buffer/index.js")})},{"../is-buffer/index.js":43}],82:[function(require,module,exports){const getNGramsOfMultipleLengths=function(inputArray,nGramLengths){var outputArray=[];return nGramLengths.forEach(function(len){outputArray=outputArray.concat(getNGramsOfSingleLength(inputArray,len))}),outputArray},getNGramsOfRangeOfLengths=function(inputArray,nGramLengths){for(var outputArray=[],i=nGramLengths.gte;i<=nGramLengths.lte;i++)outputArray=outputArray.concat(getNGramsOfSingleLength(inputArray,i));return outputArray},getNGramsOfSingleLength=function(inputArray,nGramLength){return inputArray.slice(nGramLength-1).map(function(item,i){return inputArray.slice(i,i+nGramLength)})};exports.ngram=function(inputArray,nGramLength){switch(nGramLength.constructor){case Array:return getNGramsOfMultipleLengths(inputArray,nGramLength);case Number:return getNGramsOfSingleLength(inputArray,nGramLength);case Object:return getNGramsOfRangeOfLengths(inputArray,nGramLength)}}},{}],83:[function(require,module,exports){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}function onceStrict(fn){var f=function(){if(f.called)throw new Error(f.onceError);return f.called=!0,f.value=fn.apply(this,arguments)},name=fn.name||"Function wrapped with `once`";return f.onceError=name+" shouldn't be called more than once",f.called=!1,f}var wrappy=require("wrappy");module.exports=wrappy(once),module.exports.strict=wrappy(onceStrict),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return onceStrict(this)},configurable:!0})})},{wrappy:138}],84:[function(require,module,exports){exports.endianness=function(){return"LE"},exports.hostname=function(){return"undefined"!=typeof location?location.hostname:""},exports.loadavg=function(){return[]},exports.uptime=function(){return 0},exports.freemem=function(){return Number.MAX_VALUE},exports.totalmem=function(){return Number.MAX_VALUE},exports.cpus=function(){return[]},exports.type=function(){return"Browser"},exports.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},exports.networkInterfaces=exports.getNetworkInterfaces=function(){return{}},exports.arch=function(){return"javascript"},exports.platform=function(){return"browser"},exports.tmpdir=exports.tmpDir=function(){return"/tmp"},exports.EOL="\n"},{}],85:[function(require,module,exports){(function(process){"use strict";function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function(){fn.call(null,arg1)});case 3:return process.nextTick(function(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;i1)for(var i=1;i0,function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))})});return streams.reduce(pipe)};module.exports=pump},{"end-of-stream":34,fs:7,once:83}],89:[function(require,module,exports){var pump=require("pump"),inherits=require("inherits"),Duplexify=require("duplexify"),toArray=function(args){return args.length?Array.isArray(args[0])?args[0]:Array.prototype.slice.call(args):[]},define=function(opts){var Pumpify=function(){var streams=toArray(arguments);if(!(this instanceof Pumpify))return new Pumpify(streams);Duplexify.call(this,null,null,opts),streams.length&&this.setPipeline(streams)};return inherits(Pumpify,Duplexify),Pumpify.prototype.setPipeline=function(){var streams=toArray(arguments),self=this,ended=!1,w=streams[0],r=streams[streams.length-1];r=r.readable?r:null,w=w.writable?w:null;var onclose=function(){streams[0].emit("error",new Error("stream was destroyed"))};if(this.on("close",onclose),this.on("prefinish",function(){ended||self.cork()}),pump(streams,function(err){if(self.removeListener("close",onclose),err)return self.destroy(err);ended=!0,self.uncork()}),this.destroyed)return onclose();this.setWritable(w),this.setReadable(r)},Pumpify};module.exports=define({destroy:!1}),module.exports.obj=define({destroy:!1,objectMode:!0,highWaterMark:16})},{duplexify:31,inherits:41,pump:88}],90:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":91}],91:[function(require,module,exports){"use strict";function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),options&&!1===options.readable&&(this.readable=!1),options&&!1===options.writable&&(this.writable=!1),this.allowHalfOpen=!0,options&&!1===options.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",onend)}function onend(){this.allowHalfOpen||this._writableState.ended||processNextTick(onEndNT,this)}function onEndNT(self){self.end()}var processNextTick=require("process-nextick-args"),objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v0?("string"==typeof chunk||Object.getPrototypeOf(chunk)===Buffer.prototype||state.objectMode||(chunk=_uint8ArrayToBuffer(chunk)),addToFront?state.endEmitted?stream.emit("error",new Error("stream.unshift() after end event")):addChunk(stream,state,chunk,!0):state.ended?stream.emit("error",new Error("stream.push() after EOF")):(state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1))):addToFront||(state.reading=!1)}return needMoreData(state)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(nb===str.length?ret+=str:ret+=str.slice(0,n),0===(n-=nb)){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=Buffer.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),0===(n-=nb)){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1,!1!==dest.write(chunk)||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:unpipe;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("safe-buffer").Buffer,destroyImpl=require("./internal/streams/destroy");util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=_isUint8Array(chunk)&&!state.objectMode;return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)},Object.defineProperty(Writable.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){this.end(),cb(err)}}).call(this,require("_process"))},{"./_stream_duplex":91,"./internal/streams/destroy":97,"./internal/streams/stream":98,_process:86,"core-util-is":11,inherits:41,"process-nextick-args":85,"safe-buffer":103,"util-deprecate":134}],96:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function copyBuffer(src,target,offset){src.copy(target,offset)}var Buffer=require("safe-buffer").Buffer;module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return Buffer.alloc(0);if(1===this.length)return this.head.data;for(var ret=Buffer.allocUnsafe(n>>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret},BufferList}()},{"safe-buffer":103}],97:[function(require,module,exports){"use strict";function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;if(readableDestroyed||writableDestroyed)return void(cb?cb(err):!err||this._writableState&&this._writableState.errorEmitted||processNextTick(emitErrorNT,this,err));this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?(processNextTick(emitErrorNT,_this,err),_this._writableState&&(_this._writableState.errorEmitted=!0)):cb&&cb(err)})}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT(self,err){self.emit("error",err)}var processNextTick=require("process-nextick-args");module.exports={destroy:destroy,undestroy:undestroy}},{"process-nextick-args":85}],98:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:38}],99:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":100}],100:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":91,"./lib/_stream_passthrough.js":92,"./lib/_stream_readable.js":93,"./lib/_stream_transform.js":94,"./lib/_stream_writable.js":95}],101:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":100}],102:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":95}],103:[function(require,module,exports){function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}var buffer=require("buffer"),Buffer=buffer.Buffer;Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0!==fill?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:9}],104:[function(require,module,exports){function throwsMessage(err){return"[Throws: "+(err?err.message:"?")+"]"}function safeGetValueFromPropertyOnObject(obj,property){if(hasProp.call(obj,property))try{return obj[property]}catch(err){return throwsMessage(err)}return obj[property]}function ensureProperties(obj){function visit(obj){if(null===obj||"object"!=typeof obj)return obj;if(-1!==seen.indexOf(obj))return"[Circular]";if(seen.push(obj),"function"==typeof obj.toJSON)try{return visit(obj.toJSON())}catch(err){return throwsMessage(err)}return Array.isArray(obj)?obj.map(visit):Object.keys(obj).reduce(function(result,prop){return result[prop]=visit(safeGetValueFromPropertyOnObject(obj,prop)),result},{})}var seen=[];return visit(obj)}var hasProp=Object.prototype.hasOwnProperty;module.exports=function(data){return JSON.stringify(ensureProperties(data))},module.exports.ensureProperties=ensureProperties},{}],105:[function(require,module,exports){const DBEntries=require("./lib/delete.js").DBEntries,DBWriteCleanStream=require("./lib/replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./lib/replicate.js").DBWriteMergeStream,DocVector=require("./lib/delete.js").DocVector,IndexBatch=require("./lib/add.js").IndexBatch,JSONStream=require("JSONStream"),Readable=require("stream").Readable,RecalibrateDB=require("./lib/delete.js").RecalibrateDB,bunyan=require("bunyan"),del=require("./lib/delete.js"),docProc=require("docproc"),levelup=require("levelup"),pumpify=require("pumpify"),async=require("async");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){var Indexer={};Indexer.options=options;var q=async.queue(function(batch,done){var s;"add"===batch.operation?(s=new Readable({objectMode:!0}),batch.batch.forEach(function(doc){s.push(doc)}),s.push(null),s.pipe(Indexer.defaultPipeline(batch.batchOps)).pipe(Indexer.add()).on("finish",function(){return done()}).on("error",function(err){return done(err)})):"delete"===batch.operation&&(s=new Readable,batch.docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)}))},1);return Indexer.add=function(){return pumpify.obj(new IndexBatch(Indexer),new DBWriteMergeStream(options))},Indexer.concurrentAdd=function(batchOps,batch,done){q.push({batch:batch,batchOps:batchOps,operation:"add"},function(err){done(err)})},Indexer.concurrentDel=function(docIds,done){q.push({docIds:docIds,operation:"delete"},function(err){done(err)})},Indexer.close=function(callback){options.indexes.close(function(err){for(;!options.indexes.isClosed();)options.log.debug("closing...");options.indexes.isClosed()&&(options.log.debug("closed..."),callback(err))})},Indexer.dbWriteStream=function(streamOps){return streamOps=Object.assign({},{merge:!0},streamOps),streamOps.merge?new DBWriteMergeStream(options):new DBWriteCleanStream(options)},Indexer.defaultPipeline=function(batchOptions){return batchOptions=Object.assign({},options,batchOptions),docProc.pipeline(batchOptions)},Indexer.deleteStream=function(options){return pumpify.obj(new DocVector(options),new DBEntries(options),new RecalibrateDB(options))},Indexer.deleter=function(docIds,done){const s=new Readable;docIds.forEach(function(docId){s.push(JSON.stringify(docId))}),s.push(null),s.pipe(Indexer.deleteStream(options)).on("data",function(){}).on("end",function(){done(null)})},Indexer.feed=function(ops){return ops&&ops.objectMode?pumpify.obj(Indexer.defaultPipeline(ops),Indexer.add(ops)):pumpify(JSONStream.parse(),Indexer.defaultPipeline(ops),Indexer.add(ops))},Indexer.flush=function(APICallback){del.flush(options,function(err){return APICallback(err)})},callback(err,Indexer)})};const getOptions=function(options,done){if(options=Object.assign({},{deletable:!0,batchSize:1e3,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,searchable:!0,indexPath:"si",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/\s|\\n|\\u0003|[-.,<>]/,stopwords:[],weight:0},options),options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes)done(null,options);else{const leveldown=require("leveldown");levelup(options.indexPath||"si",{valueEncoding:"json",db:leveldown},function(err,db){options.indexes=db,done(err,options)})}}},{"./lib/add.js":106,"./lib/delete.js":107,"./lib/replicate.js":108,JSONStream:3,async:5,bunyan:10,docproc:19,leveldown:59,levelup:72,pumpify:89,stream:127}],106:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),emitIndexKeys=function(s){for(var key in s.deltaIndex)s.push({key:key,value:s.deltaIndex[key]});s.deltaIndex={}},IndexBatch=function(indexer){this.indexer=indexer,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.indexer.options.keySeparator;var that=this;this.indexer.deleter([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.indexer.options.log.info("processing doc "+ingestedDoc.id),that.deltaIndex["DOCUMENT"+sep+ingestedDoc.id+sep]=ingestedDoc.stored;for(var fieldName in ingestedDoc.vector){that.deltaIndex["FIELD"+sep+fieldName]=fieldName;for(var token in ingestedDoc.vector[fieldName]){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token,dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id]),that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.deltaIndex["DOCUMENT-VECTOR"+sep+ingestedDoc.id+sep+fieldName+sep]=ingestedDoc.vector[fieldName]}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.indexer.options.batchSize&&(that.push({totalKeys:totalKeys}),that.indexer.options.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:127,util:137}],107:[function(require,module,exports){const util=require("util"),Transform=require("stream").Transform;exports.flush=function(options,callback){const sep=options.keySeparator;var deleteOps=[];options.indexes.createKeyStream({gte:"0",lte:sep}).on("data",function(data){deleteOps.push({type:"del",key:data})}).on("error",function(err){return options.log.error(err," failed to empty index"),callback(err)}).on("end",function(){options.indexes.batch(deleteOps,callback)})};const DocVector=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DocVector=DocVector,util.inherits(DocVector,Transform),DocVector.prototype._transform=function(docId,encoding,end){docId=JSON.parse(docId);const sep=this.options.keySeparator;var that=this;this.options.indexes.createReadStream({gte:"DOCUMENT-VECTOR"+sep+docId+sep,lte:"DOCUMENT-VECTOR"+sep+docId+sep+sep}).on("data",function(data){that.push(data)}).on("close",function(){return end()})};const DBEntries=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.DBEntries=DBEntries, +util.inherits(DBEntries,Transform),DBEntries.prototype._transform=function(vector,encoding,end){const sep=this.options.keySeparator;var docId;for(var k in vector.value){docId=vector.key.split(sep)[1];var field=vector.key.split(sep)[2];this.push({key:"TF"+sep+field+sep+k,value:docId}),this.push({key:"DF"+sep+field+sep+k,value:docId})}return this.push({key:vector.key}),this.push({key:"DOCUMENT"+sep+docId+sep}),end()};const RecalibrateDB=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.RecalibrateDB=RecalibrateDB,util.inherits(RecalibrateDB,Transform),RecalibrateDB.prototype._transform=function(dbEntry,encoding,end){const sep=this.options.keySeparator;var that=this;this.options.indexes.get(dbEntry.key,function(err,value){err&&that.options.log.info(err),value||(value=[]);var docId=dbEntry.value,dbInstruction={};dbInstruction.key=dbEntry.key,dbEntry.key.substring(0,3)==="TF"+sep?(dbInstruction.value=value.filter(function(item){return item[1]!==docId}),0===dbInstruction.value.length?dbInstruction.type="del":dbInstruction.type="put"):dbEntry.key.substring(0,3)==="DF"+sep?(value.splice(value.indexOf(docId),1),dbInstruction.value=value,0===dbInstruction.value.length?dbInstruction.type="del":dbInstruction.type="put"):dbEntry.key.substring(0,9)==="DOCUMENT"+sep?dbInstruction.type="del":dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep&&(dbInstruction.type="del"),that.options.indexes.batch([dbInstruction],function(err){return end()})})}},{stream:127,util:137}],108:[function(require,module,exports){const Transform=require("stream").Transform,Writable=require("stream").Writable,util=require("util"),DBWriteMergeStream=function(options){this.options=options,Writable.call(this,{objectMode:!0})};exports.DBWriteMergeStream=DBWriteMergeStream,util.inherits(DBWriteMergeStream,Writable),DBWriteMergeStream.prototype._write=function(data,encoding,end){if(data.totalKeys)return end();const sep=this.options.keySeparator;var that=this;this.options.indexes.get(data.key,function(err,val){var newVal;newVal=data.key.substring(0,3)==="TF"+sep?data.value.concat(val||[]).sort(function(a,b){return a[0]b[0]?-1:a[1]b[1]?-1:0}):data.key.substring(0,3)==="DF"+sep?data.value.concat(val||[]).sort():"DOCUMENT-COUNT"===data.key?+val+(+data.value||0):data.value,that.options.indexes.put(data.key,newVal,function(err){end()})})};const DBWriteCleanStream=function(options){this.currentBatch=[],this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(DBWriteCleanStream,Transform),DBWriteCleanStream.prototype._transform=function(data,encoding,end){var that=this;this.currentBatch.push(data),this.currentBatch.length%this.options.batchSize==0?this.options.indexes.batch(this.currentBatch,function(err){that.push("indexing batch"),that.currentBatch=[],end()}):end()},DBWriteCleanStream.prototype._flush=function(end){var that=this;this.options.indexes.batch(this.currentBatch,function(err){that.push("remaining data indexed"),end()})},exports.DBWriteCleanStream=DBWriteCleanStream},{stream:127,util:137}],109:[function(require,module,exports){const AvailableFields=require("./lib/AvailableFields.js").AvailableFields,CalculateBuckets=require("./lib/CalculateBuckets.js").CalculateBuckets,CalculateCategories=require("./lib/CalculateCategories.js").CalculateCategories,CalculateEntireResultSet=require("./lib/CalculateEntireResultSet.js").CalculateEntireResultSet,CalculateResultSetPerClause=require("./lib/CalculateResultSetPerClause.js").CalculateResultSetPerClause,CalculateTopScoringDocs=require("./lib/CalculateTopScoringDocs.js").CalculateTopScoringDocs,CalculateTotalHits=require("./lib/CalculateTotalHits.js").CalculateTotalHits,Classify=require("./lib/Classify.js").Classify,FetchDocsFromDB=require("./lib/FetchDocsFromDB.js").FetchDocsFromDB,FetchStoredDoc=require("./lib/FetchStoredDoc.js").FetchStoredDoc,GetIntersectionStream=require("./lib/GetIntersectionStream.js").GetIntersectionStream,MergeOrConditions=require("./lib/MergeOrConditions.js").MergeOrConditions,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,SortTopScoringDocs=require("./lib/SortTopScoringDocs.js").SortTopScoringDocs,bunyan=require("bunyan"),levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),initModule=function(err,Searcher,moduleReady){return Searcher.bucketStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateBuckets(Searcher.options,q.filter||{},q.buckets))},Searcher.categoryStream=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateCategories(Searcher.options,q))},Searcher.classify=function(ops){return new Classify(Searcher,ops)},Searcher.close=function(callback){Searcher.options.indexes.close(function(err){for(;!Searcher.options.indexes.isClosed();)Searcher.options.log.debug("closing...");Searcher.options.indexes.isClosed()&&(Searcher.options.log.debug("closed..."),callback(err))})},Searcher.availableFields=function(){const sep=Searcher.options.keySeparator;return Searcher.options.indexes.createReadStream({gte:"FIELD"+sep,lte:"FIELD"+sep+sep}).pipe(new AvailableFields(Searcher.options))},Searcher.get=function(docIDs){var s=new Readable({objectMode:!0});return docIDs.forEach(function(id){s.push(id)}),s.push(null),s.pipe(new FetchDocsFromDB(Searcher.options))},Searcher.fieldNames=function(){return Searcher.options.indexes.createReadStream({gte:"FIELD",lte:"FIELD"})},Searcher.match=function(q){return matcher.match(q,Searcher.options)},Searcher.dbReadStream=function(){return Searcher.options.indexes.createReadStream()},Searcher.search=function(q){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});return q.query.forEach(function(clause){s.push(clause)}),s.push(null),q.sort?s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options)):s.pipe(new CalculateResultSetPerClause(Searcher.options)).pipe(new CalculateTopScoringDocs(Searcher.options,q.offset+q.pageSize)).pipe(new ScoreTopScoringDocsTFIDF(Searcher.options)).pipe(new MergeOrConditions(q)).pipe(new SortTopScoringDocs(q)).pipe(new FetchStoredDoc(Searcher.options))},Searcher.scan=function(q){q=siUtil.getQueryDefaults(q);var s=new Readable({objectMode:!0});return s.push("init"),s.push(null),s.pipe(new GetIntersectionStream(Searcher.options,siUtil.getKeySet(q.query[0].AND,Searcher.options.keySeparator))).pipe(new FetchDocsFromDB(Searcher.options))},Searcher.totalHits=function(q,callback){q=siUtil.getQueryDefaults(q);const s=new Readable({objectMode:!0});q.query.forEach(function(clause){s.push(clause)}),s.push(null),s.pipe(new CalculateResultSetPerClause(Searcher.options,q.filter||{})).pipe(new CalculateEntireResultSet(Searcher.options)).pipe(new CalculateTotalHits(Searcher.options)).on("data",function(totalHits){return callback(null,totalHits)})},moduleReady(err,Searcher)},getOptions=function(options,done){var Searcher={};if(Searcher.options=Object.assign({},{deletable:!0,fieldedSearch:!0,store:!0,indexPath:"si",keySeparator:"○",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/[|' .,\-|(\n)]+/,stopwords:[]},options),Searcher.options.log=bunyan.createLogger({name:"search-index",level:options.logLevel}),options.indexes)return done(null,Searcher);levelup(Searcher.options.indexPath||"si",{valueEncoding:"json"},function(err,db){return Searcher.options.indexes=db,done(err,Searcher)})};module.exports=function(givenOptions,moduleReady){getOptions(givenOptions,function(err,Searcher){initModule(err,Searcher,moduleReady)})}},{"./lib/AvailableFields.js":110,"./lib/CalculateBuckets.js":111,"./lib/CalculateCategories.js":112,"./lib/CalculateEntireResultSet.js":113,"./lib/CalculateResultSetPerClause.js":114,"./lib/CalculateTopScoringDocs.js":115,"./lib/CalculateTotalHits.js":116,"./lib/Classify.js":117,"./lib/FetchDocsFromDB.js":118,"./lib/FetchStoredDoc.js":119,"./lib/GetIntersectionStream.js":120,"./lib/MergeOrConditions.js":121,"./lib/ScoreDocsOnField.js":122,"./lib/ScoreTopScoringDocsTFIDF.js":123,"./lib/SortTopScoringDocs.js":124,"./lib/matcher.js":125,"./lib/siUtil.js":126,bunyan:10,levelup:72,stream:127}],110:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),AvailableFields=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.AvailableFields=AvailableFields,util.inherits(AvailableFields,Transform),AvailableFields.prototype._transform=function(field,encoding,end){return this.push(field.key.split(this.options.keySeparator)[1]),end()}},{stream:127,util:137}],111:[function(require,module,exports){const _intersection=require("lodash.intersection"),_uniq=require("lodash.uniq"),Transform=require("stream").Transform,util=require("util"),CalculateBuckets=function(options,filter,requestedBuckets){this.buckets=requestedBuckets||[],this.filter=filter,this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateBuckets=CalculateBuckets,util.inherits(CalculateBuckets,Transform),CalculateBuckets.prototype._transform=function(mergedQueryClauses,encoding,end){const that=this,sep=this.options.keySeparator;var bucketsProcessed=0;that.buckets.forEach(function(bucket){const gte="DF"+sep+bucket.field+sep+bucket.gte,lte="DF"+sep+bucket.field+sep+bucket.lte+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){var IDSet=_intersection(data.value,mergedQueryClauses.set);IDSet.length>0&&(bucket.value=bucket.value||[],bucket.value=_uniq(bucket.value.concat(IDSet).sort()))}).on("close",function(){if(bucket.set||(bucket.value=bucket.value.length),that.push(bucket),++bucketsProcessed===that.buckets.length)return end()})})}},{"lodash.intersection":75,"lodash.uniq":80,stream:127,util:137}],112:[function(require,module,exports){const _intersection=require("lodash.intersection"),Transform=require("stream").Transform,util=require("util"),CalculateCategories=function(options,q){var category=q.category||[];category.values=[],this.offset=+q.offset,this.pageSize=+q.pageSize,this.category=category,this.options=options,this.query=q.query,Transform.call(this,{objectMode:!0})};exports.CalculateCategories=CalculateCategories,util.inherits(CalculateCategories,Transform),CalculateCategories.prototype._transform=function(mergedQueryClauses,encoding,end){if(!this.category.field)return end(new Error("you need to specify a category"));const sep=this.options.keySeparator,that=this,gte="DF"+sep+this.category.field+sep,lte="DF"+sep+this.category.field+sep+sep;this.category.values=this.category.values||[];var i=this.offset+this.pageSize,j=0;const rs=that.options.indexes.createReadStream({gte:gte,lte:lte});rs.on("data",function(data){if(!(that.offset>j++)){var IDSet=_intersection(data.value,mergedQueryClauses.set);if(IDSet.length>0){var key=data.key.split(sep)[2],value=IDSet.length;that.category.set&&(value=IDSet);var result={key:key,value:value};if(1===that.query.length)try{that.query[0].AND[that.category.field].indexOf(key)>-1&&(result.filter=!0)}catch(e){}i-- >that.offset?that.push(result):rs.destroy()}}}).on("close",function(){return end()})}},{"lodash.intersection":75,stream:127,util:137}],113:[function(require,module,exports){const Transform=require("stream").Transform,_union=require("lodash.union"),util=require("util"),CalculateEntireResultSet=function(options){this.options=options,this.setSoFar=[],Transform.call(this,{objectMode:!0})};exports.CalculateEntireResultSet=CalculateEntireResultSet,util.inherits(CalculateEntireResultSet,Transform),CalculateEntireResultSet.prototype._transform=function(queryClause,encoding,end){return this.setSoFar=_union(queryClause.set,this.setSoFar),end()},CalculateEntireResultSet.prototype._flush=function(end){return this.push({set:this.setSoFar}),end()}},{"lodash.union":79,stream:127,util:137}],114:[function(require,module,exports){const Transform=require("stream").Transform,_difference=require("lodash.difference"),_intersection=require("lodash.intersection"),_spread=require("lodash.spread"),siUtil=require("./siUtil.js"),util=require("util"),CalculateResultSetPerClause=function(options){this.options=options,Transform.call(this,{objectMode:!0})};exports.CalculateResultSetPerClause=CalculateResultSetPerClause,util.inherits(CalculateResultSetPerClause,Transform),CalculateResultSetPerClause.prototype._transform=function(queryClause,encoding,end){const sep=this.options.keySeparator,that=this,frequencies=[];var NOT=function(includeResults){const bigIntersect=_spread(_intersection);var include=bigIntersect(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,termFrequencies:frequencies,BOOST:queryClause.BOOST||0}),end();var i=0,excludeResults=[];siUtil.getKeySet(queryClause.NOT,sep).forEach(function(item){var excludeSet={};that.options.indexes.createReadStream({gte:item[0],lte:item[1]+sep}).on("data",function(data){for(var i=0;ib.id?-1:0}).reduce(function(merged,cur){var lastDoc=merged[merged.length-1];return 0===merged.length||cur.id!==lastDoc.id?merged.push(cur):cur.id===lastDoc.id&&(lastDoc.scoringCriteria=lastDoc.scoringCriteria.concat(cur.scoringCriteria)),merged},[]);return mergedResultSet.map(function(item){return item.scoringCriteria&&(item.score=item.scoringCriteria.reduce(function(acc,val){return{score:+acc.score+ +val.score}},{score:0}).score,item.score=item.score/item.scoringCriteria.length),item}),mergedResultSet.forEach(function(item){that.push(item)}),end()}},{stream:127,util:137}],122:[function(require,module,exports){const Transform=require("stream").Transform,_sortedIndexOf=require("lodash.sortedindexof"),util=require("util"),ScoreDocsOnField=function(options,seekLimit,sort){this.options=options,this.seekLimit=seekLimit,this.sort=sort,Transform.call(this,{objectMode:!0})};exports.ScoreDocsOnField=ScoreDocsOnField,util.inherits(ScoreDocsOnField,Transform),ScoreDocsOnField.prototype._transform=function(clauseSet,encoding,end){const sep=this.options.keySeparator,that=this,gte="TF"+sep+this.sort.field+sep,lte="TF"+sep+this.sort.field+sep+sep;that.options.indexes.createReadStream({gte:gte,lte:lte}).on("data",function(data){for(var i=0;ib.score?-2:a.idb.id?-1:0}):this.resultSet=this.resultSet.sort(function(a,b){return a.score>b.score?2:a.scoreb.id?-1:0}),this.resultSet=this.resultSet.slice(this.q.offset,this.q.offset+this.q.pageSize),this.resultSet.forEach(function(hit){that.push(hit)}),end()}},{stream:127,util:137}],125:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatcherStream=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatcherStream,Transform),MatcherStream.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var results=[];this.options.indexes.createReadStream({start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep}).on("data",function(data){results.push(data)}).on("error",function(err){that.options.log.error("Oh my!",err)}).on("end",function(){return results.sort(function(a,b){return b.value.length-a.value.length}).slice(0,q.limit).forEach(function(item){var m={};switch(q.type){case"ID":m={token:item.key.split(sep)[2],documents:item.value};break;case"count":m={token:item.key.split(sep)[2],documentCount:item.value.length};break;default:m=item.key.split(sep)[2]}that.push(m)}),end()})},exports.match=function(q,options){var s=new Readable({objectMode:!0});return q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple"},q),q.beginsWith.length>5==6?2:byte>>4==14?3:byte>>3==30?4:-1}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j=0?(nb>0&&(self.lastNeed=nb-1),nb):--j=0?(nb>0&&(self.lastNeed=nb-2),nb):--j=0?(nb>0&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0)}function utf8CheckExtraBytes(self,buf,p){if(128!=(192&buf[0]))return self.lastNeed=0,"�".repeat(p);if(self.lastNeed>1&&buf.length>1){if(128!=(192&buf[1]))return self.lastNeed=1,"�".repeat(p+1);if(self.lastNeed>2&&buf.length>2&&128!=(192&buf[2]))return self.lastNeed=2,"�".repeat(p+2)}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0!==r?r:this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(buf.copy(this.lastChar,p,0,buf.length),void(this.lastNeed-=buf.length))}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"�".repeat(this.lastTotal-this.lastNeed):r}function utf16Text(buf,i){if((buf.length-i)%2==0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0===n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3, +1===n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch((encoding=""+encoding)&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(void 0===(r=this.fillLast(buf)))return"";i=this.lastNeed,this.lastNeed=0}else i=0;return itokens.length)return[];for(var ngrams=[],i=0;i<=tokens.length-nGramLength;i++)ngrams.push(tokens.slice(i,i+nGramLength));if(ngrams=ngrams.sort(),1===ngrams.length)return[[ngrams[0],1]];for(var counter=1,lastToken=ngrams[0],vector=[],j=1;j=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){base=" [Function"+(value.name?": "+value.name:"")+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(recurseTimes<0)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;return output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}}),x=args[i];i=4" @@ -10,7 +10,7 @@ "dependencies": { "bunyan": "^1.8.10", "levelup": "^1.3.8", - "search-index-adder": "^0.3.0", + "search-index-adder": "^0.3.1", "search-index-searcher": "^0.2.3" }, "devDependencies": { diff --git a/test/node/mocha-tests/328-test.js b/test/node/mocha-tests/328-test.js index b7dff9e7..2fb896ea 100644 --- a/test/node/mocha-tests/328-test.js +++ b/test/node/mocha-tests/328-test.js @@ -43,8 +43,7 @@ describe('bug 328', function() { }, function (err, thisSI) { if (err) false.should.eql(true) si = thisSI - s.pipe(si.defaultPipeline()) - .pipe(si.add()) + s.pipe(si.feed({ objectMode: true })) .on('data', function (data) { // nowt }) diff --git a/test/node/mocha-tests/boost-test.js b/test/node/mocha-tests/boost-test.js index 1fdd0713..3b5337dd 100644 --- a/test/node/mocha-tests/boost-test.js +++ b/test/node/mocha-tests/boost-test.js @@ -96,8 +96,7 @@ describe('boosting', function () { }, function (err, thisSI) { if (err) false.should.eql(true) si = thisSI - s.pipe(si.defaultPipeline()) - .pipe(si.add()) + s.pipe(si.feed({ objectMode: true })) .on('finish', function () { true.should.be.exactly(true) return done() diff --git a/test/node/mocha-tests/bucket-test.js b/test/node/mocha-tests/bucket-test.js index d43d0543..3aab7356 100644 --- a/test/node/mocha-tests/bucket-test.js +++ b/test/node/mocha-tests/bucket-test.js @@ -54,8 +54,7 @@ describe('init the search index', function() { it('should index test data into the index', function (done) { getStream() - .pipe(index.defaultPipeline()) - .pipe(index.add()) + .pipe(index.feed({ objectMode: true })) .on('finish', function () { return done() }) diff --git a/test/node/mocha-tests/delete-test.js b/test/node/mocha-tests/delete-test.js index df01fd6e..025f67b7 100644 --- a/test/node/mocha-tests/delete-test.js +++ b/test/node/mocha-tests/delete-test.js @@ -49,8 +49,7 @@ describe('deleting: ', function () { test: 'this is the fourth doc' }) s.push(null) - s.pipe(si.defaultPipeline()) - .pipe(si.add()) + s.pipe(si.feed({ objectMode: true })) .on('finish', function () { done() }) @@ -100,8 +99,7 @@ describe('deleting: ', function () { test: 'this is the first doc' }) s.push(null) - s.pipe(si.defaultPipeline()) - .pipe(si.add()) + s.pipe(si.feed({ objectMode: true })) .on('finish', function () { done() }) diff --git a/test/node/mocha-tests/facet-test.js b/test/node/mocha-tests/facet-test.js index 2cef5870..8d2b71ff 100644 --- a/test/node/mocha-tests/facet-test.js +++ b/test/node/mocha-tests/facet-test.js @@ -114,8 +114,7 @@ describe('categories: ', function () { if (err) false.should.eql(true) si = thisSI s.pipe(JSONStream.parse()) - .pipe(si.defaultPipeline()) - .pipe(si.add()) + .pipe(si.feed({ objectMode: true })) .on('finish', function () { return done() }) diff --git a/test/node/mocha-tests/fieldsToStore-test.js b/test/node/mocha-tests/fieldsToStore-test.js index 850d0a6a..a0f5ae95 100644 --- a/test/node/mocha-tests/fieldsToStore-test.js +++ b/test/node/mocha-tests/fieldsToStore-test.js @@ -98,14 +98,14 @@ describe('storing fields: ', function () { if (err) false.should.eql(true) si = thisSI getStream() - .pipe(si.defaultPipeline({ + .pipe(si.feed({ + objectMode: true, fieldOptions: { description: { storeable: false } } })) - .pipe(si.add()) .on('finish', function () { true.should.be.exactly(true) return done() @@ -148,16 +148,14 @@ describe('storing fields: ', function () { if (err) false.should.eql(true) si2 = thisSI getStream() - .pipe(si2.defaultPipeline({ + .pipe(si2.feed({ + objectMode: true, fieldOptions: { name: { storeable: true } } })) - .pipe(si2.add()) - .on('data', function (data) { - }) .on('finish', function () { true.should.be.exactly(true) return done() diff --git a/test/node/mocha-tests/flush-test.js b/test/node/mocha-tests/flush-test.js index 3731ebd1..0ae1132e 100644 --- a/test/node/mocha-tests/flush-test.js +++ b/test/node/mocha-tests/flush-test.js @@ -94,8 +94,7 @@ describe('boosting', function () { }, function (err, thisSI) { if (err) false.should.eql(true) si = thisSI - s.pipe(si.defaultPipeline()) - .pipe(si.add()) + s.pipe(si.feed({ objectMode: true })) .on('finish', function () { true.should.be.exactly(true) return done() diff --git a/test/node/mocha-tests/get-test.js b/test/node/mocha-tests/get-test.js index 14624bb0..a3b02451 100644 --- a/test/node/mocha-tests/get-test.js +++ b/test/node/mocha-tests/get-test.js @@ -47,8 +47,8 @@ describe('.get-ting: ', function () { test: 'this is the fourth doc' }) s.push(null) - s.pipe(si.defaultPipeline()) - .pipe(si.add()).on('finish', function () { + s.pipe(si.feed({ objectMode: true })) + .on('finish', function () { done() }) }) diff --git a/test/node/mocha-tests/indexing-test-2.js b/test/node/mocha-tests/indexing-test-2.js index aeaac481..28d6c11a 100644 --- a/test/node/mocha-tests/indexing-test-2.js +++ b/test/node/mocha-tests/indexing-test-2.js @@ -40,8 +40,7 @@ describe('Indexing API', function () { // jshint ignore:line should.exist(si) if (err) false.should.eql(true) var i = 0 - s.pipe(si.defaultPipeline()) - .pipe(si.add()) + s.pipe(si.feed({ objectMode: true })) .on('finish', function () { si.dbReadStream() .on('data', function (data) { diff --git a/test/node/mocha-tests/indexing-test.js b/test/node/mocha-tests/indexing-test.js index 2a63f848..916e52e0 100644 --- a/test/node/mocha-tests/indexing-test.js +++ b/test/node/mocha-tests/indexing-test.js @@ -31,8 +31,7 @@ describe('Indexing API', function () { } s.push(doc) s.push(null) - s.pipe(si.defaultPipeline()) - .pipe(si.add()) + s.pipe(si.feed({ objectMode: true })) .on('finish', function () { si.get(['1']) .on('data', function (data) { @@ -44,27 +43,6 @@ describe('Indexing API', function () { }) }) - it('should allow indexing with undefined options object', function (done) { - var s = new Readable({ objectMode: true }) - var doc = { - id: '2', - title: 'Mad Science is on the Rise', - body: 'Mad, mad things are happening.' - } - s.push(doc) - s.push(null) - s.pipe(si.defaultPipeline()) - .pipe(si.add(undefined)) - .on('finish', function () { - si.get(['2']).on('data', function (data) { - data.should.eql(doc) - }) - .on('end', function () { - return done() - }) - }) - }) - it('should allow indexing with a custom separator', function (done) { var doc = { id: '3', @@ -74,9 +52,10 @@ describe('Indexing API', function () { var i = 0 s.push(doc) s.push(null) - s.pipe(si.defaultPipeline({ + s.pipe(si.feed({ + objectMode: true, separator: /\s+/ - })).pipe(si.add()) + })) .on('finish', function () { si.search({ query: [{ @@ -101,9 +80,10 @@ describe('Indexing API', function () { var i = 0 s.push(doc) s.push(null) - s.pipe(si.defaultPipeline({ + s.pipe(si.feed({ + objectMode: true, separator: /\s+/ - })).pipe(si.add()) + })) .on('finish', function () { si.search({ query: [{ @@ -122,7 +102,7 @@ describe('Indexing API', function () { it('can count docs', function (done) { si.countDocs(function (err, docCount) { if (err) false.should.eql(true) - docCount.should.be.exactly(3) + docCount.should.be.exactly(2) return done() }) }) diff --git a/test/node/mocha-tests/instantiation-test.js b/test/node/mocha-tests/instantiation-test.js index e56751b3..b6fea754 100644 --- a/test/node/mocha-tests/instantiation-test.js +++ b/test/node/mocha-tests/instantiation-test.js @@ -60,16 +60,14 @@ describe('Instantiation: ', function () { }) it('should index test data into the first index', function (done) { - sOne.pipe(siOne.defaultPipeline()) - .pipe(siOne.add()) + sOne.pipe(siOne.feed({ objectMode: true })) .on('finish', function () { return done() }) }) it('should index test data into the second index', function (done) { - sTwo.pipe(siTwo.defaultPipeline()) - .pipe(siTwo.add()) + sTwo.pipe(siTwo.feed({ objectMode: true })) .on('finish', function () { return done() }) diff --git a/test/node/mocha-tests/matching-test.js b/test/node/mocha-tests/matching-test.js index bca4902a..fdf24c79 100644 --- a/test/node/mocha-tests/matching-test.js +++ b/test/node/mocha-tests/matching-test.js @@ -54,7 +54,8 @@ describe('Matching epub: ', function () { spineItemPath: 'epub_content/accessible_epub_4/EPUB/ch03s09.xhtml' }) s.push(null) - s.pipe(index.defaultPipeline({ + s.pipe(index.feed({ + objectMode: true, batchName: 'epubdata', fieldOptions: { id: { @@ -65,7 +66,6 @@ describe('Matching epub: ', function () { } } })) - .pipe(index.add()) .on('finish', function () { true.should.be.exactly(true) return done() diff --git a/test/node/mocha-tests/non-ascii-char-test.js b/test/node/mocha-tests/non-ascii-char-test.js index 66d16b07..15659fe2 100644 --- a/test/node/mocha-tests/non-ascii-char-test.js +++ b/test/node/mocha-tests/non-ascii-char-test.js @@ -36,12 +36,8 @@ describe('Indexing and searching non-ascii characters: ', function () { }) it('should index test data', function (done) { - s.pipe(si.defaultPipeline()) - .pipe(si.add()) - .on('data', function (data) { - - }) - .on('end', function () { + s.pipe(si.feed({ objectMode: true })) + .on('finish', function () { true.should.be.exactly(true) return done() }) diff --git a/test/node/mocha-tests/or-test.js b/test/node/mocha-tests/or-test.js index bbd96f67..2010012f 100644 --- a/test/node/mocha-tests/or-test.js +++ b/test/node/mocha-tests/or-test.js @@ -93,8 +93,7 @@ describe('OR-ing: ', function () { }, function (err, thisSI) { ;(!err).should.be.exactly(true) si = thisSI - s.pipe(si.defaultPipeline()) - .pipe(si.add()) + s.pipe(si.feed({ objectMode: true })) .on('finish', function () { true.should.be.exactly(true) return done() diff --git a/test/node/mocha-tests/phrase-search-test.js b/test/node/mocha-tests/phrase-search-test.js index 077fc7e9..debde25b 100644 --- a/test/node/mocha-tests/phrase-search-test.js +++ b/test/node/mocha-tests/phrase-search-test.js @@ -42,7 +42,8 @@ describe('ngrams (phrase search): ', function () { if (err) false.should.eql(true) si = thisSi getDataStream() - .pipe(si.defaultPipeline({ + .pipe(si.feed({ + objectMode: true, stopwords: [], nGramLength: {gte: 1, lte: 3} })) @@ -62,11 +63,11 @@ describe('ngrams (phrase search): ', function () { if (err) false.should.eql(true) si2 = thisSi getDataStream() - .pipe(si2.defaultPipeline({ + .pipe(si2.feed({ + objectMode: true, stopwords: [], nGramLength: [1, 5] })) - .pipe(si2.add()) .on('finish', function () { true.should.be.exactly(true) return done() @@ -83,7 +84,8 @@ describe('ngrams (phrase search): ', function () { if (err) false.should.eql(true) si3 = thisSi getDataStream() - .pipe(si3.defaultPipeline({ + .pipe(si3.feed({ + objectMode: true, fieldOptions: { name: { nGramLength: {gte: 1, lte: 3} @@ -93,7 +95,6 @@ describe('ngrams (phrase search): ', function () { } } })) - .pipe(si3.add()) .on('finish', function () { true.should.be.exactly(true) return done() @@ -110,14 +111,14 @@ describe('ngrams (phrase search): ', function () { if (err) false.should.eql(true) si4 = thisSi getDataStream() - .pipe(si4.defaultPipeline({ + .pipe(si4.feed({ + objectMode: true, fieldOptions: { name: { separator: 'x' } } })) - .pipe(si4.add()) .on('finish', function () { true.should.be.exactly(true) return done() diff --git a/test/node/mocha-tests/preserve-case-test.js b/test/node/mocha-tests/preserve-case-test.js index dd4d0486..27583ff3 100644 --- a/test/node/mocha-tests/preserve-case-test.js +++ b/test/node/mocha-tests/preserve-case-test.js @@ -52,10 +52,10 @@ describe('testing case: ', function () { it('should index test data into the index', function (done) { getDocStream().pipe(JSONStream.parse()) - .pipe(si.defaultPipeline({ + .pipe(si.feed({ + objectMode: true, preserveCase: true })) - .pipe(si.add()) .on('finish', function () { done() }) @@ -102,10 +102,10 @@ describe('testing case: ', function () { it('should index test data into the index', function (done) { getDocStream().pipe(JSONStream.parse()) - .pipe(si2.defaultPipeline({ + .pipe(si2.feed({ + objectMode: true, preserveCase: false })) - .pipe(si2.add()) .on('finish', function () { done() }) diff --git a/test/node/mocha-tests/providing-levelup-test.js b/test/node/mocha-tests/providing-levelup-test.js index 36ba22a2..f433af05 100644 --- a/test/node/mocha-tests/providing-levelup-test.js +++ b/test/node/mocha-tests/providing-levelup-test.js @@ -38,12 +38,8 @@ describe('Making a search-index with a vanilla (leveldown) levelup: ', function body: 'this is my doc' }) s.push(null) - s.pipe(si.defaultPipeline()) - .pipe(si.add()) - .on('data', function (data) { - - }) - .on('end', function () { + s.pipe(si.feed({ objectMode: true })) + .on('finish', function () { si.search({ query: [{ AND: {'*': ['now sadly defunct']} diff --git a/test/node/mocha-tests/relevancy-test.js b/test/node/mocha-tests/relevancy-test.js index a2e1d9f6..a28f9989 100644 --- a/test/node/mocha-tests/relevancy-test.js +++ b/test/node/mocha-tests/relevancy-test.js @@ -40,8 +40,7 @@ describe('some simple relevancy tests: ', function () { }, function (err, thisSI) { if (err) false.should.eql(true) si = thisSI - s.pipe(si.defaultPipeline()) - .pipe(si.add()) + s.pipe(si.feed({ objectMode: true })) .on('finish', function () { true.should.be.exactly(true) return done() diff --git a/test/node/mocha-tests/scan-test.js b/test/node/mocha-tests/scan-test.js index 554ccfa8..1636830a 100644 --- a/test/node/mocha-tests/scan-test.js +++ b/test/node/mocha-tests/scan-test.js @@ -97,8 +97,7 @@ describe('scanning: ', function () { }, function (err, thisSi) { ;(err === null).should.be.exactly(true) si = thisSi - s.pipe(si.defaultPipeline()) - .pipe(si.add()) + s.pipe(si.feed({ objectMode: true })) .on('finish', function () { true.should.be.exactly(true) return done() diff --git a/test/node/mocha-tests/search-test.js b/test/node/mocha-tests/search-test.js index f10c8f05..d855cf7a 100644 --- a/test/node/mocha-tests/search-test.js +++ b/test/node/mocha-tests/search-test.js @@ -23,16 +23,9 @@ describe('simple search test', function() { }) it('should post and index a file of data', function (done) { - var i = 0 fs.createReadStream('./node_modules/reuters-21578-json/data/fullFileStream/justTen.str') - .pipe(JSONStream.parse()) - .on('data', function (d) { - i++ - }) - .pipe(si.defaultPipeline()) - .pipe(si.add()) + .pipe(si.feed()) .on('finish', function () { - i.should.be.exactly(10) return done() }) .on('error', function (error) { diff --git a/test/node/mocha-tests/sorting-test.js b/test/node/mocha-tests/sorting-test.js index 1fc538de..19cabd3f 100644 --- a/test/node/mocha-tests/sorting-test.js +++ b/test/node/mocha-tests/sorting-test.js @@ -98,7 +98,8 @@ describe('sorting: ', function () { }, function (err, thisSI) { should(err).not.ok si = thisSI - s.pipe(si.defaultPipeline({ + s.pipe(si.feed({ + objectMode: true, fieldOptions: { price: { sortable: true @@ -109,7 +110,6 @@ describe('sorting: ', function () { } } })) - .pipe(si.add()) .on('finish', function () { true.should.be.exactly(true) return done() diff --git a/test/node/mocha-tests/sqlite-test.js b/test/node/mocha-tests/sqlite-test.js index 4d118fb3..1c02f892 100644 --- a/test/node/mocha-tests/sqlite-test.js +++ b/test/node/mocha-tests/sqlite-test.js @@ -47,8 +47,7 @@ describe('sqllite compatability: ', function () { body: 'this is my doc' }) s.push(null) - s.pipe(si.defaultPipeline()) - .pipe(si.add()) + s.pipe(si.feed({ objectMode: true })) .on('finish', function () { si.search({ query: [{ diff --git a/test/node/mocha-tests/stopword-test.js b/test/node/mocha-tests/stopword-test.js index 52e6daa8..6dcb9452 100644 --- a/test/node/mocha-tests/stopword-test.js +++ b/test/node/mocha-tests/stopword-test.js @@ -72,10 +72,7 @@ describe('stopwords: ', function () { if (err) false.should.eql(true) si = thisSi getDataStream() - .pipe(si.defaultPipeline()) - .pipe(si.add()) - .on('data', function (data) { - }) + .pipe(si.feed({ objectMode: true })) .on('finish', function () { true.should.be.exactly(true) return done() @@ -107,12 +104,10 @@ describe('stopwords: ', function () { if (err) false.should.eql(true) siNO = thisSi getDataStream() - .pipe(siNO.defaultPipeline({ + .pipe(siNO.feed({ + objectMode: true, stopwords: sw.no })) - .pipe(siNO.add()) - .on('data', function (data) { - }) .on('finish', function () { true.should.be.exactly(true) return done() @@ -158,12 +153,10 @@ describe('stopwords: ', function () { if (err) false.should.eql(true) siFood = thisSi getFoodStream() - .pipe(siFood.defaultPipeline({ + .pipe(siFood.feed({ + objectMode: true, stopwords: [] })) - .pipe(siFood.add()) - .on('data', function (data) { - }) .on('finish', function () { true.should.be.exactly(true) return done() diff --git a/test/node/mocha-tests/stream-test.js b/test/node/mocha-tests/stream-test.js index 190732f8..4676cd8f 100644 --- a/test/node/mocha-tests/stream-test.js +++ b/test/node/mocha-tests/stream-test.js @@ -41,9 +41,7 @@ describe('stopwords: ', function () { this.timeout(5000) const filePath = './node_modules/reuters-21578-json/data/fullFileStream/justTen.str' fs.createReadStream(filePath) - .pipe(JSONStream.parse()) - .pipe(si.defaultPipeline()) - .pipe(si.add()) + .pipe(si.feed()) .on('data', function (data) {}).on('finish', function () { done() }) diff --git a/test/node/tape-tests/classifier-test.js b/test/node/tape-tests/classifier-test.js index d98f42f2..e4f30bc1 100644 --- a/test/node/tape-tests/classifier-test.js +++ b/test/node/tape-tests/classifier-test.js @@ -94,11 +94,7 @@ test('initialize a search index', function (t) { logLevel: logLevel }, function (err, indexer) { t.error(err) - s.pipe(indexer.defaultPipeline()) - .pipe(indexer.add()) - .on('data', function (data) { - // tum te tum... - }) + s.pipe(indexer.feed({ objectMode: true })) .on('finish', function () { indexer.close(function (err) { t.error(err) diff --git a/test/node/tape-tests/stream-test.js b/test/node/tape-tests/stream-test.js index ee953dc9..5604fe55 100644 --- a/test/node/tape-tests/stream-test.js +++ b/test/node/tape-tests/stream-test.js @@ -28,8 +28,7 @@ test('add docs using a stream', function (t) { }) } s.push(null) - s.pipe(index.defaultPipeline()) - .pipe(index.add()) + s.pipe(index.feed({ objectMode: true })) .on('finish', function () { t.pass('ended ok') })