diff --git a/dist/search-index.js b/dist/search-index.js index b2d6e292..2ad23e76 100644 --- a/dist/search-index.js +++ b/dist/search-index.js @@ -88,7 +88,7 @@ const getOptions = function (options, done) { } } -},{"./siUtil.js":2,"js-logger":45,"leveldown":59,"levelup":72,"search-index-adder":105,"search-index-searcher":110}],2:[function(require,module,exports){ +},{"./siUtil.js":2,"js-logger":42,"leveldown":56,"levelup":69,"search-index-adder":100,"search-index-searcher":105}],2:[function(require,module,exports){ module.exports = function(siOptions) { var siUtil = {} @@ -381,501 +381,7 @@ if(!module.parent && process.title !== 'browser') { }).call(this,require('_process'),require("buffer").Buffer) -},{"_process":86,"buffer":9,"jsonparse":46,"through":153}],4:[function(require,module,exports){ -(function (global){ -'use strict'; - -// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js -// original notice: - -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -function compare(a, b) { - if (a === b) { - return 0; - } - - var x = a.length; - var y = b.length; - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - - if (x < y) { - return -1; - } - if (y < x) { - return 1; - } - return 0; -} -function isBuffer(b) { - if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { - return global.Buffer.isBuffer(b); - } - return !!(b != null && b._isBuffer); -} - -// based on node assert, original notice: - -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -var util = require('util/'); -var hasOwn = Object.prototype.hasOwnProperty; -var pSlice = Array.prototype.slice; -var functionsHaveNames = (function () { - return function foo() {}.name === 'foo'; -}()); -function pToString (obj) { - return Object.prototype.toString.call(obj); -} -function isView(arrbuf) { - if (isBuffer(arrbuf)) { - return false; - } - if (typeof global.ArrayBuffer !== 'function') { - return false; - } - if (typeof ArrayBuffer.isView === 'function') { - return ArrayBuffer.isView(arrbuf); - } - if (!arrbuf) { - return false; - } - if (arrbuf instanceof DataView) { - return true; - } - if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { - return true; - } - return false; -} -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = module.exports = ok; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) - -var regex = /\s*function\s+([^\(\s]*)\s*/; -// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js -function getName(func) { - if (!util.isFunction(func)) { - return; - } - if (functionsHaveNames) { - return func.name; - } - var str = func.toString(); - var match = str.match(regex); - return match && match[1]; -} -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - - // try to strip useless frames - var fn_name = getName(stackStartFunction); - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } - - this.stack = out; - } - } -}; - -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); - -function truncate(s, n) { - if (typeof s === 'string') { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} -function inspect(something) { - if (functionsHaveNames || !util.isFunction(something)) { - return util.inspect(something); - } - var rawname = getName(something); - var name = rawname ? ': ' + rawname : ''; - return '[Function' + name + ']'; -} -function getMessage(self) { - return truncate(inspect(self.actual), 128) + ' ' + - self.operator + ' ' + - truncate(inspect(self.expected), 128); -} - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; - -assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); - } -}; - -function _deepEqual(actual, expected, strict, memos) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - } else if (isBuffer(actual) && isBuffer(expected)) { - return compare(actual, expected) === 0; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if ((actual === null || typeof actual !== 'object') && - (expected === null || typeof expected !== 'object')) { - return strict ? actual === expected : actual == expected; - - // If both values are instances of typed arrays, wrap their underlying - // ArrayBuffers in a Buffer each to increase performance - // This optimization requires the arrays to have the same type as checked by - // Object.prototype.toString (aka pToString). Never perform binary - // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their - // bit patterns are not identical. - } else if (isView(actual) && isView(expected) && - pToString(actual) === pToString(expected) && - !(actual instanceof Float32Array || - actual instanceof Float64Array)) { - return compare(new Uint8Array(actual.buffer), - new Uint8Array(expected.buffer)) === 0; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else if (isBuffer(actual) !== isBuffer(expected)) { - return false; - } else { - memos = memos || {actual: [], expected: []}; - - var actualIndex = memos.actual.indexOf(actual); - if (actualIndex !== -1) { - if (actualIndex === memos.expected.indexOf(expected)) { - return true; - } - } - - memos.actual.push(actual); - memos.expected.push(expected); - - return objEquiv(actual, expected, strict, memos); - } -} - -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv(a, b, strict, actualVisitedObjects) { - if (a === null || a === undefined || b === null || b === undefined) - return false; - // if one is a primitive, the other must be same - if (util.isPrimitive(a) || util.isPrimitive(b)) - return a === b; - if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) - return false; - var aIsArgs = isArguments(a); - var bIsArgs = isArguments(b); - if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) - return false; - if (aIsArgs) { - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b, strict); - } - var ka = objectKeys(a); - var kb = objectKeys(b); - var key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length !== kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] !== kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) - return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; - -assert.notDeepStrictEqual = notDeepStrictEqual; -function notDeepStrictEqual(actual, expected, message) { - if (_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); - } -} - - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; - -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } - - try { - if (actual instanceof expected) { - return true; - } - } catch (e) { - // Ignore. The instanceof check doesn't work for arrow functions. - } - - if (Error.isPrototypeOf(expected)) { - return false; - } - - return expected.call({}, actual) === true; -} - -function _tryBlock(block) { - var error; - try { - block(); - } catch (e) { - error = e; - } - return error; -} - -function _throws(shouldThrow, block, expected, message) { - var actual; - - if (typeof block !== 'function') { - throw new TypeError('"block" argument must be a function'); - } - - if (typeof expected === 'string') { - message = expected; - expected = null; - } - - actual = _tryBlock(block); - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } - - var userProvidedMessage = typeof message === 'string'; - var isUnwantedException = !shouldThrow && util.isError(actual); - var isUnexpectedException = !shouldThrow && actual && !expected; - - if ((isUnwantedException && - userProvidedMessage && - expectedException(actual, expected)) || - isUnexpectedException) { - fail(actual, expected, 'Got unwanted exception' + message); - } - - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } -} - -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws(true, block, error, message); -}; - -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { - _throws(false, block, error, message); -}; - -assert.ifError = function(err) { if (err) throw err; }; - -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); - } - return keys; -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"util/":158}],5:[function(require,module,exports){ +},{"_process":82,"buffer":7,"jsonparse":43,"through":148}],4:[function(require,module,exports){ (function (process,global){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : @@ -6454,7 +5960,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":86}],6:[function(require,module,exports){ +},{"_process":82}],5:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength @@ -6570,11 +6076,9 @@ function fromByteArray (uint8) { return parts.join('') } -},{}],7:[function(require,module,exports){ +},{}],6:[function(require,module,exports){ -},{}],8:[function(require,module,exports){ -arguments[4][7][0].apply(exports,arguments) -},{"dup":7}],9:[function(require,module,exports){ +},{}],7:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. @@ -8224,1781 +7728,150 @@ Buffer.prototype.fill = function fill (val, start, end, encoding) { var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 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 < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare -} - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"base64-js":6,"ieee754":39,"isarray":43}],10:[function(require,module,exports){ -(function (Buffer,process){ -/** - * Copyright (c) 2017 Trent Mick. - * Copyright (c) 2017 Joyent Inc. - * - * The bunyan logging library for node.js. - * - * -*- mode: js -*- - * vim: expandtab:ts=4:sw=4 - */ - -var VERSION = '1.8.12'; - -/* - * Bunyan log format version. This becomes the 'v' field on all log records. - * This will be incremented if there is any backward incompatible change to - * the log record format. Details will be in 'CHANGES.md' (the change log). - */ -var LOG_VERSION = 0; - - -var xxx = function xxx(s) { // internal dev/debug logging - var args = ['XX' + 'X: '+s].concat( - Array.prototype.slice.call(arguments, 1)); - console.error.apply(this, args); -}; -var xxx = function xxx() {}; // comment out to turn on debug logging - - -/* - * Runtime environment notes: - * - * Bunyan is intended to run in a number of runtime environments. Here are - * some notes on differences for those envs and how the code copes. - * - * - node.js: The primary target environment. - * - NW.js: http://nwjs.io/ An *app* environment that feels like both a - * node env -- it has node-like globals (`process`, `global`) and - * browser-like globals (`window`, `navigator`). My *understanding* is that - * bunyan can operate as if this is vanilla node.js. - * - browser: Failing the above, we sniff using the `window` global - * . - * - browserify: http://browserify.org/ A browser-targetting bundler of - * node.js deps. The runtime is a browser env, so can't use fs access, - * etc. Browserify's build looks for `require()` imports - * to bundle. For some imports it won't be able to handle, we "hide" - * from browserify with `require('frobshizzle' + '')`. - * - Other? Please open issues if things are broken. - */ -var runtimeEnv; -if (typeof (process) !== 'undefined' && process.versions) { - if (process.versions.nw) { - runtimeEnv = 'nw'; - } else if (process.versions.node) { - runtimeEnv = 'node'; - } -} -if (!runtimeEnv && typeof (window) !== 'undefined' && - window.window === window) { - runtimeEnv = 'browser'; -} -if (!runtimeEnv) { - throw new Error('unknown runtime environment'); -} - - -var os, fs, dtrace; -if (runtimeEnv === 'browser') { - os = { - hostname: function () { - return window.location.host; - } - }; - fs = {}; - dtrace = null; -} else { - os = require('os'); - fs = require('fs'); - try { - dtrace = require('dtrace-provider' + ''); - } catch (e) { - dtrace = null; - } -} -var util = require('util'); -var assert = require('assert'); -var EventEmitter = require('events').EventEmitter; -var stream = require('stream'); - -try { - var safeJsonStringify = require('safe-json-stringify'); -} catch (e) { - safeJsonStringify = null; -} -if (process.env.BUNYAN_TEST_NO_SAFE_JSON_STRINGIFY) { - safeJsonStringify = null; -} - -// The 'mv' module is required for rotating-file stream support. -try { - var mv = require('mv' + ''); -} catch (e) { - mv = null; -} - -try { - var sourceMapSupport = require('source-map-support' + ''); -} catch (_) { - sourceMapSupport = null; -} - - -//---- Internal support stuff - -/** - * A shallow copy of an object. Bunyan logging attempts to never cause - * exceptions, so this function attempts to handle non-objects gracefully. - */ -function objCopy(obj) { - if (obj == null) { // null or undefined - return obj; - } else if (Array.isArray(obj)) { - return obj.slice(); - } else if (typeof (obj) === 'object') { - var copy = {}; - Object.keys(obj).forEach(function (k) { - copy[k] = obj[k]; - }); - return copy; - } else { - return obj; - } -} - -var format = util.format; -if (!format) { - // If node < 0.6, then use its `util.format`: - // : - var inspect = util.inspect; - var formatRegExp = /%[sdj%]/g; - format = function format(f) { - if (typeof (f) !== 'string') { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function (x) { - if (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; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (x === null || typeof (x) !== 'object') { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; - }; -} - - -/** - * Gather some caller info 3 stack levels up. - * See . - */ -function getCaller3Info() { - if (this === undefined) { - // Cannot access caller info in 'strict' mode. - return; - } - var obj = {}; - var saveLimit = Error.stackTraceLimit; - var savePrepare = Error.prepareStackTrace; - Error.stackTraceLimit = 3; - - Error.prepareStackTrace = function (_, stack) { - var caller = stack[2]; - if (sourceMapSupport) { - caller = sourceMapSupport.wrapCallSite(caller); - } - obj.file = caller.getFileName(); - obj.line = caller.getLineNumber(); - var func = caller.getFunctionName(); - if (func) - obj.func = func; - }; - Error.captureStackTrace(this, getCaller3Info); - this.stack; - - Error.stackTraceLimit = saveLimit; - Error.prepareStackTrace = savePrepare; - return obj; -} - - -function _indent(s, indent) { - if (!indent) indent = ' '; - var lines = s.split(/\r?\n/g); - return indent + lines.join('\n' + indent); -} - - -/** - * Warn about an bunyan processing error. - * - * @param msg {String} Message with which to warn. - * @param dedupKey {String} Optional. A short string key for this warning to - * have its warning only printed once. - */ -function _warn(msg, dedupKey) { - assert.ok(msg); - if (dedupKey) { - if (_warned[dedupKey]) { - return; - } - _warned[dedupKey] = true; - } - process.stderr.write(msg + '\n'); -} -function _haveWarned(dedupKey) { - return _warned[dedupKey]; -} -var _warned = {}; - - -function ConsoleRawStream() {} -ConsoleRawStream.prototype.write = function (rec) { - if (rec.level < INFO) { - console.log(rec); - } else if (rec.level < WARN) { - console.info(rec); - } else if (rec.level < ERROR) { - console.warn(rec); - } else { - console.error(rec); - } -}; - - -//---- Levels - -var TRACE = 10; -var DEBUG = 20; -var INFO = 30; -var WARN = 40; -var ERROR = 50; -var FATAL = 60; - -var levelFromName = { - 'trace': TRACE, - 'debug': DEBUG, - 'info': INFO, - 'warn': WARN, - 'error': ERROR, - 'fatal': FATAL -}; -var nameFromLevel = {}; -Object.keys(levelFromName).forEach(function (name) { - nameFromLevel[levelFromName[name]] = name; -}); - -// Dtrace probes. -var dtp = undefined; -var probes = dtrace && {}; - -/** - * Resolve a level number, name (upper or lowercase) to a level number value. - * - * @param nameOrNum {String|Number} A level name (case-insensitive) or positive - * integer level. - * @api public - */ -function resolveLevel(nameOrNum) { - var level; - var type = typeof (nameOrNum); - if (type === 'string') { - level = levelFromName[nameOrNum.toLowerCase()]; - if (!level) { - throw new Error(format('unknown level name: "%s"', nameOrNum)); - } - } else if (type !== 'number') { - throw new TypeError(format('cannot resolve level: invalid arg (%s):', - type, nameOrNum)); - } else if (nameOrNum < 0 || Math.floor(nameOrNum) !== nameOrNum) { - throw new TypeError(format('level is not a positive integer: %s', - nameOrNum)); - } else { - level = nameOrNum; - } - return level; -} - - -function isWritable(obj) { - if (obj instanceof stream.Writable) { - return true; - } - return typeof (obj.write) === 'function'; -} - - -//---- Logger class - -/** - * Create a Logger instance. - * - * @param options {Object} See documentation for full details. At minimum - * this must include a 'name' string key. Configuration keys: - * - `streams`: specify the logger output streams. This is an array of - * objects with these fields: - * - `type`: The stream type. See README.md for full details. - * Often this is implied by the other fields. Examples are - * 'file', 'stream' and "raw". - * - `level`: Defaults to 'info'. - * - `path` or `stream`: The specify the file path or writeable - * stream to which log records are written. E.g. - * `stream: process.stdout`. - * - `closeOnExit` (boolean): Optional. Default is true for a - * 'file' stream when `path` is given, false otherwise. - * See README.md for full details. - * - `level`: set the level for a single output stream (cannot be used - * with `streams`) - * - `stream`: the output stream for a logger with just one, e.g. - * `process.stdout` (cannot be used with `streams`) - * - `serializers`: object mapping log record field names to - * serializing functions. See README.md for details. - * - `src`: Boolean (default false). Set true to enable 'src' automatic - * field with log call source info. - * All other keys are log record fields. - * - * An alternative *internal* call signature is used for creating a child: - * new Logger(, [, ]); - * - * @param _childSimple (Boolean) An assertion that the given `_childOptions` - * (a) only add fields (no config) and (b) no serialization handling is - * required for them. IOW, this is a fast path for frequent child - * creation. - */ -function Logger(options, _childOptions, _childSimple) { - xxx('Logger start:', options) - if (!(this instanceof Logger)) { - return new Logger(options, _childOptions); - } - - // Input arg validation. - var parent; - if (_childOptions !== undefined) { - parent = options; - options = _childOptions; - if (!(parent instanceof Logger)) { - throw new TypeError( - 'invalid Logger creation: do not pass a second arg'); - } - } - if (!options) { - throw new TypeError('options (object) is required'); - } - if (!parent) { - if (!options.name) { - throw new TypeError('options.name (string) is required'); - } - } else { - if (options.name) { - throw new TypeError( - 'invalid options.name: child cannot set logger name'); - } - } - if (options.stream && options.streams) { - throw new TypeError('cannot mix "streams" and "stream" options'); - } - if (options.streams && !Array.isArray(options.streams)) { - throw new TypeError('invalid options.streams: must be an array') - } - if (options.serializers && (typeof (options.serializers) !== 'object' || - Array.isArray(options.serializers))) { - throw new TypeError('invalid options.serializers: must be an object') - } - - EventEmitter.call(this); - - // Fast path for simple child creation. - if (parent && _childSimple) { - // `_isSimpleChild` is a signal to stream close handling that this child - // owns none of its streams. - this._isSimpleChild = true; - - this._level = parent._level; - this.streams = parent.streams; - this.serializers = parent.serializers; - this.src = parent.src; - var fields = this.fields = {}; - var parentFieldNames = Object.keys(parent.fields); - for (var i = 0; i < parentFieldNames.length; i++) { - var name = parentFieldNames[i]; - fields[name] = parent.fields[name]; - } - var names = Object.keys(options); - for (var i = 0; i < names.length; i++) { - var name = names[i]; - fields[name] = options[name]; - } - return; - } - - // Start values. - var self = this; - if (parent) { - this._level = parent._level; - this.streams = []; - for (var i = 0; i < parent.streams.length; i++) { - var s = objCopy(parent.streams[i]); - s.closeOnExit = false; // Don't own parent stream. - this.streams.push(s); - } - this.serializers = objCopy(parent.serializers); - this.src = parent.src; - this.fields = objCopy(parent.fields); - if (options.level) { - this.level(options.level); - } - } else { - this._level = Number.POSITIVE_INFINITY; - this.streams = []; - this.serializers = null; - this.src = false; - this.fields = {}; - } - - if (!dtp && dtrace) { - dtp = dtrace.createDTraceProvider('bunyan'); - - for (var level in levelFromName) { - var probe; - - probes[levelFromName[level]] = probe = - dtp.addProbe('log-' + level, 'char *'); - - // Explicitly add a reference to dtp to prevent it from being GC'd - probe.dtp = dtp; - } - - dtp.enable(); - } - - // Handle *config* options (i.e. options that are not just plain data - // for log records). - if (options.stream) { - self.addStream({ - type: 'stream', - stream: options.stream, - closeOnExit: false, - level: options.level - }); - } else if (options.streams) { - options.streams.forEach(function (s) { - self.addStream(s, options.level); - }); - } else if (parent && options.level) { - this.level(options.level); - } else if (!parent) { - if (runtimeEnv === 'browser') { - /* - * In the browser we'll be emitting to console.log by default. - * Any console.log worth its salt these days can nicely render - * and introspect objects (e.g. the Firefox and Chrome console) - * so let's emit the raw log record. Are there browsers for which - * that breaks things? - */ - self.addStream({ - type: 'raw', - stream: new ConsoleRawStream(), - closeOnExit: false, - level: options.level - }); - } else { - self.addStream({ - type: 'stream', - stream: process.stdout, - closeOnExit: false, - level: options.level - }); - } - } - if (options.serializers) { - self.addSerializers(options.serializers); - } - if (options.src) { - this.src = true; - } - xxx('Logger: ', self) - - // Fields. - // These are the default fields for log records (minus the attributes - // removed in this constructor). To allow storing raw log records - // (unrendered), `this.fields` must never be mutated. Create a copy for - // any changes. - var fields = objCopy(options); - delete fields.stream; - delete fields.level; - delete fields.streams; - delete fields.serializers; - delete fields.src; - if (this.serializers) { - this._applySerializers(fields); - } - if (!fields.hostname && !self.fields.hostname) { - fields.hostname = os.hostname(); - } - if (!fields.pid) { - fields.pid = process.pid; - } - Object.keys(fields).forEach(function (k) { - self.fields[k] = fields[k]; - }); -} - -util.inherits(Logger, EventEmitter); - - -/** - * Add a stream - * - * @param stream {Object}. Object with these fields: - * - `type`: The stream type. See README.md for full details. - * Often this is implied by the other fields. Examples are - * 'file', 'stream' and "raw". - * - `path` or `stream`: The specify the file path or writeable - * stream to which log records are written. E.g. - * `stream: process.stdout`. - * - `level`: Optional. Falls back to `defaultLevel`. - * - `closeOnExit` (boolean): Optional. Default is true for a - * 'file' stream when `path` is given, false otherwise. - * See README.md for full details. - * @param defaultLevel {Number|String} Optional. A level to use if - * `stream.level` is not set. If neither is given, this defaults to INFO. - */ -Logger.prototype.addStream = function addStream(s, defaultLevel) { - var self = this; - if (defaultLevel === null || defaultLevel === undefined) { - defaultLevel = INFO; - } - - s = objCopy(s); - - // Implicit 'type' from other args. - if (!s.type) { - if (s.stream) { - s.type = 'stream'; - } else if (s.path) { - s.type = 'file' - } - } - s.raw = (s.type === 'raw'); // PERF: Allow for faster check in `_emit`. - - if (s.level !== undefined) { - s.level = resolveLevel(s.level); - } else { - s.level = resolveLevel(defaultLevel); - } - if (s.level < self._level) { - self._level = s.level; - } - - switch (s.type) { - case 'stream': - assert.ok(isWritable(s.stream), - '"stream" stream is not writable: ' + util.inspect(s.stream)); - - if (!s.closeOnExit) { - s.closeOnExit = false; - } - break; - case 'file': - if (s.reemitErrorEvents === undefined) { - s.reemitErrorEvents = true; - } - if (!s.stream) { - s.stream = fs.createWriteStream(s.path, - {flags: 'a', encoding: 'utf8'}); - if (!s.closeOnExit) { - s.closeOnExit = true; - } - } else { - if (!s.closeOnExit) { - s.closeOnExit = false; - } - } - break; - case 'rotating-file': - assert.ok(!s.stream, - '"rotating-file" stream should not give a "stream"'); - assert.ok(s.path); - assert.ok(mv, '"rotating-file" stream type is not supported: ' - + 'missing "mv" module'); - s.stream = new RotatingFileStream(s); - if (!s.closeOnExit) { - s.closeOnExit = true; - } - break; - case 'raw': - if (!s.closeOnExit) { - s.closeOnExit = false; - } - break; - default: - throw new TypeError('unknown stream type "' + s.type + '"'); - } - - if (s.reemitErrorEvents && typeof (s.stream.on) === 'function') { - // TODO: When we have `.close()`, it should remove event - // listeners to not leak Logger instances. - s.stream.on('error', function onStreamError(err) { - self.emit('error', err, s); - }); - } - - self.streams.push(s); - delete self.haveNonRawStreams; // reset -} - - -/** - * Add serializers - * - * @param serializers {Object} Optional. Object mapping log record field names - * to serializing functions. See README.md for details. - */ -Logger.prototype.addSerializers = function addSerializers(serializers) { - var self = this; - - if (!self.serializers) { - self.serializers = {}; - } - Object.keys(serializers).forEach(function (field) { - var serializer = serializers[field]; - if (typeof (serializer) !== 'function') { - throw new TypeError(format( - 'invalid serializer for "%s" field: must be a function', - field)); - } else { - self.serializers[field] = serializer; - } - }); -} - - - -/** - * Create a child logger, typically to add a few log record fields. - * - * This can be useful when passing a logger to a sub-component, e.g. a - * 'wuzzle' component of your service: - * - * var wuzzleLog = log.child({component: 'wuzzle'}) - * var wuzzle = new Wuzzle({..., log: wuzzleLog}) - * - * Then log records from the wuzzle code will have the same structure as - * the app log, *plus the component='wuzzle' field*. - * - * @param options {Object} Optional. Set of options to apply to the child. - * All of the same options for a new Logger apply here. Notes: - * - The parent's streams are inherited and cannot be removed in this - * call. Any given `streams` are *added* to the set inherited from - * the parent. - * - The parent's serializers are inherited, though can effectively be - * overwritten by using duplicate keys. - * - Can use `level` to set the level of the streams inherited from - * the parent. The level for the parent is NOT affected. - * @param simple {Boolean} Optional. Set to true to assert that `options` - * (a) only add fields (no config) and (b) no serialization handling is - * required for them. IOW, this is a fast path for frequent child - * creation. See 'tools/timechild.js' for numbers. - */ -Logger.prototype.child = function (options, simple) { - return new (this.constructor)(this, options || {}, simple); -} - - -/** - * A convenience method to reopen 'file' streams on a logger. This can be - * useful with external log rotation utilities that move and re-open log files - * (e.g. logrotate on Linux, logadm on SmartOS/Illumos). Those utilities - * typically have rotation options to copy-and-truncate the log file, but - * you may not want to use that. An alternative is to do this in your - * application: - * - * var log = bunyan.createLogger(...); - * ... - * process.on('SIGUSR2', function () { - * log.reopenFileStreams(); - * }); - * ... - * - * See . - */ -Logger.prototype.reopenFileStreams = function () { - var self = this; - self.streams.forEach(function (s) { - if (s.type === 'file') { - if (s.stream) { - // Not sure if typically would want this, or more immediate - // `s.stream.destroy()`. - s.stream.end(); - s.stream.destroySoon(); - delete s.stream; - } - s.stream = fs.createWriteStream(s.path, - {flags: 'a', encoding: 'utf8'}); - s.stream.on('error', function (err) { - self.emit('error', err, s); - }); - } - }); -}; - - -/* BEGIN JSSTYLED */ -/** - * Close this logger. - * - * This closes streams (that it owns, as per 'endOnClose' attributes on - * streams), etc. Typically you **don't** need to bother calling this. -Logger.prototype.close = function () { - if (this._closed) { - return; - } - if (!this._isSimpleChild) { - self.streams.forEach(function (s) { - if (s.endOnClose) { - xxx('closing stream s:', s); - s.stream.end(); - s.endOnClose = false; - } - }); - } - this._closed = true; -} - */ -/* END JSSTYLED */ - - -/** - * Get/set the level of all streams on this logger. - * - * Get Usage: - * // Returns the current log level (lowest level of all its streams). - * log.level() -> INFO - * - * Set Usage: - * log.level(INFO) // set all streams to level INFO - * log.level('info') // can use 'info' et al aliases - */ -Logger.prototype.level = function level(value) { - if (value === undefined) { - return this._level; - } - var newLevel = resolveLevel(value); - var len = this.streams.length; - for (var i = 0; i < len; i++) { - this.streams[i].level = newLevel; - } - this._level = newLevel; -} - - -/** - * Get/set the level of a particular stream on this logger. - * - * Get Usage: - * // Returns an array of the levels of each stream. - * log.levels() -> [TRACE, INFO] - * - * // Returns a level of the identified stream. - * log.levels(0) -> TRACE // level of stream at index 0 - * log.levels('foo') // level of stream with name 'foo' - * - * Set Usage: - * log.levels(0, INFO) // set level of stream 0 to INFO - * log.levels(0, 'info') // can use 'info' et al aliases - * log.levels('foo', WARN) // set stream named 'foo' to WARN - * - * Stream names: When streams are defined, they can optionally be given - * a name. For example, - * log = new Logger({ - * streams: [ - * { - * name: 'foo', - * path: '/var/log/my-service/foo.log' - * level: 'trace' - * }, - * ... - * - * @param name {String|Number} The stream index or name. - * @param value {Number|String} The level value (INFO) or alias ('info'). - * If not given, this is a 'get' operation. - * @throws {Error} If there is no stream with the given name. - */ -Logger.prototype.levels = function levels(name, value) { - if (name === undefined) { - assert.equal(value, undefined); - return this.streams.map( - function (s) { return s.level }); - } - var stream; - if (typeof (name) === 'number') { - stream = this.streams[name]; - if (stream === undefined) { - throw new Error('invalid stream index: ' + name); - } - } else { - var len = this.streams.length; - for (var i = 0; i < len; i++) { - var s = this.streams[i]; - if (s.name === name) { - stream = s; - break; - } - } - if (!stream) { - throw new Error(format('no stream with name "%s"', name)); - } - } - if (value === undefined) { - return stream.level; - } else { - var newLevel = resolveLevel(value); - stream.level = newLevel; - if (newLevel < this._level) { - this._level = newLevel; - } - } -} - - -/** - * Apply registered serializers to the appropriate keys in the given fields. - * - * Pre-condition: This is only called if there is at least one serializer. - * - * @param fields (Object) The log record fields. - * @param excludeFields (Object) Optional mapping of keys to `true` for - * keys to NOT apply a serializer. - */ -Logger.prototype._applySerializers = function (fields, excludeFields) { - var self = this; - - xxx('_applySerializers: excludeFields', excludeFields); - - // Check each serializer against these (presuming number of serializers - // is typically less than number of fields). - Object.keys(this.serializers).forEach(function (name) { - if (fields[name] === undefined || - (excludeFields && excludeFields[name])) - { - return; - } - xxx('_applySerializers; apply to "%s" key', name) - try { - fields[name] = self.serializers[name](fields[name]); - } catch (err) { - _warn(format('bunyan: ERROR: Exception thrown from the "%s" ' - + 'Bunyan serializer. This should never happen. This is a bug ' - + 'in that serializer function.\n%s', - name, err.stack || err)); - fields[name] = format('(Error in Bunyan log "%s" serializer ' - + 'broke field. See stderr for details.)', name); - } - }); -} - - -/** - * Emit a log record. - * - * @param rec {log record} - * @param noemit {Boolean} Optional. Set to true to skip emission - * and just return the JSON string. - */ -Logger.prototype._emit = function (rec, noemit) { - var i; - - // Lazily determine if this Logger has non-'raw' streams. If there are - // any, then we need to stringify the log record. - if (this.haveNonRawStreams === undefined) { - this.haveNonRawStreams = false; - for (i = 0; i < this.streams.length; i++) { - if (!this.streams[i].raw) { - this.haveNonRawStreams = true; - break; - } - } - } - - // Stringify the object (creates a warning str on error). - var str; - if (noemit || this.haveNonRawStreams) { - str = fastAndSafeJsonStringify(rec) + '\n'; - } - - if (noemit) - return str; - - var level = rec.level; - for (i = 0; i < this.streams.length; i++) { - var s = this.streams[i]; - if (s.level <= level) { - xxx('writing log rec "%s" to "%s" stream (%d <= %d): %j', - rec.msg, s.type, s.level, level, rec); - s.stream.write(s.raw ? rec : str); - } - }; - - return str; -} - - -/** - * Build a record object suitable for emitting from the arguments - * provided to the a log emitter. - */ -function mkRecord(log, minLevel, args) { - var excludeFields, fields, msgArgs; - if (args[0] instanceof Error) { - // `log.(err, ...)` - fields = { - // Use this Logger's err serializer, if defined. - err: (log.serializers && log.serializers.err - ? log.serializers.err(args[0]) - : Logger.stdSerializers.err(args[0])) - }; - excludeFields = {err: true}; - if (args.length === 1) { - msgArgs = [fields.err.message]; - } else { - msgArgs = args.slice(1); - } - } else if (typeof (args[0]) !== 'object' || Array.isArray(args[0])) { - // `log.(msg, ...)` - fields = null; - msgArgs = args.slice(); - } else if (Buffer.isBuffer(args[0])) { // `log.(buf, ...)` - // Almost certainly an error, show `inspect(buf)`. See bunyan - // issue #35. - fields = null; - msgArgs = args.slice(); - msgArgs[0] = util.inspect(msgArgs[0]); - } else { // `log.(fields, msg, ...)` - fields = args[0]; - if (fields && args.length === 1 && fields.err && - fields.err instanceof Error) - { - msgArgs = [fields.err.message]; - } else { - msgArgs = args.slice(1); - } - } - - // Build up the record object. - var rec = objCopy(log.fields); - var level = rec.level = minLevel; - var recFields = (fields ? objCopy(fields) : null); - if (recFields) { - if (log.serializers) { - log._applySerializers(recFields, excludeFields); - } - Object.keys(recFields).forEach(function (k) { - rec[k] = recFields[k]; - }); - } - rec.msg = format.apply(log, msgArgs); - if (!rec.time) { - rec.time = (new Date()); - } - // Get call source info - if (log.src && !rec.src) { - rec.src = getCaller3Info() - } - rec.v = LOG_VERSION; - - return rec; -}; - - -/** - * Build an array that dtrace-provider can use to fire a USDT probe. If we've - * already built the appropriate string, we use it. Otherwise, build the - * record object and stringify it. - */ -function mkProbeArgs(str, log, minLevel, msgArgs) { - return [ str || log._emit(mkRecord(log, minLevel, msgArgs), true) ]; -} - - -/** - * Build a log emitter function for level minLevel. I.e. this is the - * creator of `log.info`, `log.error`, etc. - */ -function mkLogEmitter(minLevel) { - return function () { - var log = this; - var str = null; - var rec = null; - - if (!this._emit) { - /* - * Show this invalid Bunyan usage warning *once*. - * - * See for - * an example of how this can happen. - */ - var dedupKey = 'unbound'; - if (!_haveWarned[dedupKey]) { - var caller = getCaller3Info(); - _warn(format('bunyan usage error: %s:%s: attempt to log ' - + 'with an unbound log method: `this` is: %s', - caller.file, caller.line, util.inspect(this)), - dedupKey); - } - return; - } else if (arguments.length === 0) { // `log.()` - return (this._level <= minLevel); - } - - var msgArgs = new Array(arguments.length); - for (var i = 0; i < msgArgs.length; ++i) { - msgArgs[i] = arguments[i]; - } - - if (this._level <= minLevel) { - rec = mkRecord(log, minLevel, msgArgs); - str = this._emit(rec); - } - - if (probes) { - probes[minLevel].fire(mkProbeArgs, str, log, minLevel, msgArgs); - } - } -} - - -/** - * The functions below log a record at a specific level. - * - * Usages: - * log.() -> boolean is-trace-enabled - * log.( err, [ msg, ...]) - * log.( msg, ...) - * log.( fields, msg, ...) - * - * where is the lowercase version of the log level. E.g.: - * - * log.info() - * - * @params fields {Object} Optional set of additional fields to log. - * @params msg {String} Log message. This can be followed by additional - * arguments that are handled like - * [util.format](http://nodejs.org/docs/latest/api/all.html#util.format). - */ -Logger.prototype.trace = mkLogEmitter(TRACE); -Logger.prototype.debug = mkLogEmitter(DEBUG); -Logger.prototype.info = mkLogEmitter(INFO); -Logger.prototype.warn = mkLogEmitter(WARN); -Logger.prototype.error = mkLogEmitter(ERROR); -Logger.prototype.fatal = mkLogEmitter(FATAL); - - - -//---- Standard serializers -// A serializer is a function that serializes a JavaScript object to a -// JSON representation for logging. There is a standard set of presumed -// interesting objects in node.js-land. - -Logger.stdSerializers = {}; - -// Serialize an HTTP request. -Logger.stdSerializers.req = function (req) { - if (!req || !req.connection) - return req; - return { - method: req.method, - url: req.url, - headers: req.headers, - remoteAddress: req.connection.remoteAddress, - remotePort: req.connection.remotePort - }; - // Trailers: Skipping for speed. If you need trailers in your app, then - // make a custom serializer. - //if (Object.keys(trailers).length > 0) { - // obj.trailers = req.trailers; - //} -}; - -// Serialize an HTTP response. -Logger.stdSerializers.res = function (res) { - if (!res || !res.statusCode) - return res; - return { - statusCode: res.statusCode, - header: res._header - } -}; - - -/* - * This function dumps long stack traces for exceptions having a cause() - * method. The error classes from - * [verror](https://github.com/davepacheco/node-verror) and - * [restify v2.0](https://github.com/mcavage/node-restify) are examples. - * - * Based on `dumpException` in - * https://github.com/davepacheco/node-extsprintf/blob/master/lib/extsprintf.js - */ -function getFullErrorStack(ex) -{ - var ret = ex.stack || ex.toString(); - if (ex.cause && typeof (ex.cause) === 'function') { - var cex = ex.cause(); - if (cex) { - ret += '\nCaused by: ' + getFullErrorStack(cex); - } - } - return (ret); -} - -// Serialize an Error object -// (Core error properties are enumerable in node 0.4, not in 0.6). -var errSerializer = Logger.stdSerializers.err = function (err) { - if (!err || !err.stack) - return err; - var obj = { - message: err.message, - name: err.name, - stack: getFullErrorStack(err), - code: err.code, - signal: err.signal - } - return obj; -}; - - -// A JSON stringifier that handles cycles safely - tracks seen values in a Set. -function safeCyclesSet() { - var seen = new Set(); - return function (key, val) { - if (!val || typeof (val) !== 'object') { - return val; - } - if (seen.has(val)) { - return '[Circular]'; - } - seen.add(val); - return val; - }; -} - -/** - * A JSON stringifier that handles cycles safely - tracks seen vals in an Array. - * - * Note: This approach has performance problems when dealing with large objects, - * see trentm/node-bunyan#445, but since this is the only option for node 0.10 - * and earlier (as Set was introduced in Node 0.12), it's used as a fallback - * when Set is not available. - */ -function safeCyclesArray() { - var seen = []; - return function (key, val) { - if (!val || typeof (val) !== 'object') { - return val; - } - if (seen.indexOf(val) !== -1) { - return '[Circular]'; - } - seen.push(val); - return val; - }; -} - -/** - * A JSON stringifier that handles cycles safely. - * - * Usage: JSON.stringify(obj, safeCycles()) - * - * Choose the best safe cycle function from what is available - see - * trentm/node-bunyan#445. - */ -var safeCycles = typeof (Set) !== 'undefined' ? safeCyclesSet : safeCyclesArray; - -/** - * A fast JSON.stringify that handles cycles and getter exceptions (when - * safeJsonStringify is installed). - * - * This function attempts to use the regular JSON.stringify for speed, but on - * error (e.g. JSON cycle detection exception) it falls back to safe stringify - * handlers that can deal with cycles and/or getter exceptions. - */ -function fastAndSafeJsonStringify(rec) { - try { - return JSON.stringify(rec); - } catch (ex) { - try { - return JSON.stringify(rec, safeCycles()); - } catch (e) { - if (safeJsonStringify) { - return safeJsonStringify(rec); - } else { - var dedupKey = e.stack.split(/\n/g, 3).join('\n'); - _warn('bunyan: ERROR: Exception in ' - + '`JSON.stringify(rec)`. You can install the ' - + '"safe-json-stringify" module to have Bunyan fallback ' - + 'to safer stringification. Record:\n' - + _indent(format('%s\n%s', util.inspect(rec), e.stack)), - dedupKey); - return format('(Exception in JSON.stringify(rec): %j. ' - + 'See stderr for details.)', e.message); - } - } - } -} - - -var RotatingFileStream = null; -if (mv) { - -RotatingFileStream = function RotatingFileStream(options) { - this.path = options.path; - - this.count = (options.count == null ? 10 : options.count); - assert.equal(typeof (this.count), 'number', - format('rotating-file stream "count" is not a number: %j (%s) in %j', - this.count, typeof (this.count), this)); - assert.ok(this.count >= 0, - format('rotating-file stream "count" is not >= 0: %j in %j', - this.count, this)); - - // Parse `options.period`. - if (options.period) { - // where scope is: - // h hours (at the start of the hour) - // d days (at the start of the day, i.e. just after midnight) - // w weeks (at the start of Sunday) - // m months (on the first of the month) - // y years (at the start of Jan 1st) - // with special values 'hourly' (1h), 'daily' (1d), "weekly" (1w), - // 'monthly' (1m) and 'yearly' (1y) - var period = { - 'hourly': '1h', - 'daily': '1d', - 'weekly': '1w', - 'monthly': '1m', - 'yearly': '1y' - }[options.period] || options.period; - var 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 { - var fileInfo = fs.statSync(this.path); - lastModified = fileInfo.mtime.getTime(); - } - catch (err) { - // file doesn't exist - } - var rotateAfterOpen = false; - if (lastModified) { - var lastRotTime = this._calcRotTime(0); - if (lastModified < lastRotTime) { - rotateAfterOpen = true; - } - } - - // TODO: template support for backup files - // template: - // default is %P.%n - // '/var/log/archive/foo.log' -> foo.log.%n - // '/var/log/archive/foo.log.%n' - // codes: - // XXX support strftime codes (per node version of those) - // or whatever module. Pick non-colliding for extra - // codes - // %P `path` base value - // %n integer number of rotated log (1,2,3,...) - // %d datetime in YYYY-MM-DD_HH-MM-SS - // XXX what should default date format be? - // prior art? Want to avoid ':' in - // filenames (illegal on Windows for one). - - this.stream = fs.createWriteStream(this.path, - {flags: 'a', encoding: 'utf8'}); - - this.rotQueue = []; - this.rotating = false; - if (rotateAfterOpen) { - this._debug('rotateAfterOpen -> call rotate()'); - this.rotate(); - } else { - this._setupNextRot(); - } -} - -util.inherits(RotatingFileStream, EventEmitter); - -RotatingFileStream.prototype._debug = function () { - // Set this to `true` to add debug logging. - if (false) { - if (arguments.length === 0) { - return true; - } - var args = Array.prototype.slice.call(arguments); - args[0] = '[' + (new Date().toISOString()) + ', ' - + this.path + '] ' + args[0]; - console.log.apply(this, args); - } else { - return false; - } -}; - -RotatingFileStream.prototype._setupNextRot = function () { - this.rotAt = this._calcRotTime(1); - this._setRotationTimer(); -} - -RotatingFileStream.prototype._setRotationTimer = function () { - var self = this; - var delay = this.rotAt - Date.now(); - // Cap timeout to Node's max setTimeout, see - // . - var TIMEOUT_MAX = 2147483647; // 2^31-1 - if (delay > TIMEOUT_MAX) { - delay = TIMEOUT_MAX; - } - this.timeout = setTimeout( - function () { - self._debug('_setRotationTimer timeout -> call rotate()'); - self.rotate(); - }, - delay); - if (typeof (this.timeout.unref) === 'function') { - this.timeout.unref(); - } -} - -RotatingFileStream.prototype._calcRotTime = -function _calcRotTime(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': - // Hidden millisecond period for debugging. - if (this.rotAt) { - rotAt = this.rotAt + this.periodNum * periodOffset; - } else { - rotAt = Date.now() + this.periodNum * periodOffset; - } - break; - case 'h': - if (this.rotAt) { - rotAt = this.rotAt + this.periodNum * 60 * 60 * 1000 * periodOffset; - } else { - // First time: top of the next hour. - rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), - d.getUTCDate(), d.getUTCHours() + periodOffset); - } - break; - case 'd': - if (this.rotAt) { - rotAt = this.rotAt + this.periodNum * 24 * 60 * 60 * 1000 - * periodOffset; - } else { - // First time: start of tomorrow (i.e. at the coming midnight) UTC. - rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), - d.getUTCDate() + periodOffset); - } - break; - case 'w': - // Currently, always on Sunday morning at 00:00:00 (UTC). - if (this.rotAt) { - rotAt = this.rotAt + this.periodNum * 7 * 24 * 60 * 60 * 1000 - * periodOffset; - } else { - // First time: this coming Sunday. - var dayOffset = (7 - d.getUTCDay()); - if (periodOffset < 1) { - dayOffset = -d.getUTCDay(); - } - if (periodOffset > 1 || periodOffset < -1) { - dayOffset += 7 * periodOffset; - } - rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), - d.getUTCDate() + dayOffset); - } - break; - case 'm': - if (this.rotAt) { - rotAt = Date.UTC(d.getUTCFullYear(), - d.getUTCMonth() + this.periodNum * periodOffset, 1); - } else { - // First time: the start of the next month. - rotAt = Date.UTC(d.getUTCFullYear(), - d.getUTCMonth() + periodOffset, 1); - } - break; - case 'y': - if (this.rotAt) { - rotAt = Date.UTC(d.getUTCFullYear() + this.periodNum * periodOffset, - 0, 1); - } else { - // First time: the start of the next year. - rotAt = 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)/1000/60, - (rotAt-now)/1000/60/60); - } - return rotAt; -}; - -RotatingFileStream.prototype.rotate = function rotate() { - // XXX What about shutdown? - var self = this; - - // If rotation period is > ~25 days, we have to break into multiple - // setTimeout's. See . - if (self.rotAt && self.rotAt > Date.now()) { - return self._setRotationTimer(); - } - - this._debug('rotate'); - if (self.rotating) { - throw new TypeError('cannot start a rotation when already rotating'); - } - self.rotating = true; - - self.stream.end(); // XXX can do moves sync after this? test at high rate - - function del() { - var toDel = self.path + '.' + String(n - 1); - if (n === 0) { - toDel = self.path; - } - n -= 1; - self._debug(' rm %s', toDel); - fs.unlink(toDel, function (delErr) { - //XXX handle err other than not exists - moves(); - }); - } - - function moves() { - if (self.count === 0 || n < 0) { - return finish(); - } - var before = self.path; - var after = self.path + '.' + String(n); - if (n > 0) { - before += '.' + String(n - 1); - } - n -= 1; - fs.exists(before, function (exists) { - if (!exists) { - moves(); - } else { - self._debug(' mv %s %s', before, after); - mv(before, after, function (mvErr) { - if (mvErr) { - self.emit('error', mvErr); - finish(); // XXX finish here? - } else { - moves(); - } - }); - } - }) - } - - function finish() { - self._debug(' open %s', self.path); - self.stream = fs.createWriteStream(self.path, - {flags: 'a', encoding: 'utf8'}); - var q = self.rotQueue, len = q.length; - for (var i = 0; i < len; i++) { - self.stream.write(q[i]); - } - self.rotQueue = []; - self.rotating = false; - self.emit('drain'); - self._setupNextRot(); - } - - var n = this.count; - del(); -}; - -RotatingFileStream.prototype.write = function write(s) { - if (this.rotating) { - this.rotQueue.push(s); - return false; - } else { - return this.stream.write(s); - } -}; - -RotatingFileStream.prototype.end = function end(s) { - this.stream.end(); -}; - -RotatingFileStream.prototype.destroy = function destroy(s) { - this.stream.destroy(); -}; - -RotatingFileStream.prototype.destroySoon = function destroySoon(s) { - this.stream.destroySoon(); -}; - -} /* if (mv) */ - + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} -/** - * RingBuffer is a Writable Stream that just stores the last N records in - * memory. - * - * @param options {Object}, with the following fields: - * - * - limit: number of records to keep in memory - */ -function RingBuffer(options) { - this.limit = options && options.limit ? options.limit : 100; - this.writable = true; - this.records = []; - EventEmitter.call(this); +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) } -util.inherits(RingBuffer, EventEmitter); +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] -RingBuffer.prototype.write = function (record) { - if (!this.writable) - throw (new Error('RingBuffer has been ended already')); + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) - this.records.push(record); + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } - if (this.records.length > this.limit) - this.records.shift(); + // valid lead + leadSurrogate = codePoint - return (true); -}; + continue + } -RingBuffer.prototype.end = function () { - if (arguments.length > 0) - this.write.apply(this, Array.prototype.slice.call(arguments)); - this.writable = false; -}; + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } -RingBuffer.prototype.destroy = function () { - this.writable = false; - this.emit('close'); -}; + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } -RingBuffer.prototype.destroySoon = function () { - this.destroy(); -}; + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + return bytes +} -//---- Exports +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} -module.exports = Logger; +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break -module.exports.TRACE = TRACE; -module.exports.DEBUG = DEBUG; -module.exports.INFO = INFO; -module.exports.WARN = WARN; -module.exports.ERROR = ERROR; -module.exports.FATAL = FATAL; -module.exports.resolveLevel = resolveLevel; -module.exports.levelFromName = levelFromName; -module.exports.nameFromLevel = nameFromLevel; + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } -module.exports.VERSION = VERSION; -module.exports.LOG_VERSION = LOG_VERSION; + return byteArray +} -module.exports.createLogger = function createLogger(options) { - return new Logger(options); -}; +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} -module.exports.RingBuffer = RingBuffer; -module.exports.RotatingFileStream = RotatingFileStream; +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} -// Useful for custom `type == 'raw'` streams that may do JSON stringification -// of log records themselves. Usage: -// var str = JSON.stringify(rec, bunyan.safeCycles()); -module.exports.safeCycles = safeCycles; +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} -}).call(this,{"isBuffer":require("../../is-buffer/index.js")},require('_process')) -},{"../../is-buffer/index.js":42,"_process":86,"assert":4,"events":37,"fs":8,"os":84,"safe-json-stringify":104,"stream":148,"util":158}],11:[function(require,module,exports){ +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"base64-js":5,"ieee754":36,"isarray":40}],8:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // @@ -10109,7 +7982,7 @@ function objectToString(o) { } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":42}],12:[function(require,module,exports){ +},{"../../is-buffer/index.js":39}],9:[function(require,module,exports){ var util = require('util') , AbstractIterator = require('abstract-leveldown').AbstractIterator @@ -10145,7 +8018,7 @@ DeferredIterator.prototype._operation = function (method, args) { module.exports = DeferredIterator; -},{"abstract-leveldown":17,"util":158}],13:[function(require,module,exports){ +},{"abstract-leveldown":14,"util":153}],10:[function(require,module,exports){ (function (Buffer,process){ var util = require('util') , AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN @@ -10205,7 +8078,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":12,"_process":86,"abstract-leveldown":17,"util":158}],14:[function(require,module,exports){ +},{"../is-buffer/index.js":39,"./deferred-iterator":9,"_process":82,"abstract-leveldown":14,"util":153}],11:[function(require,module,exports){ (function (process){ /* Copyright (c) 2017 Rod Vagg, MIT License */ @@ -10297,7 +8170,7 @@ AbstractChainedBatch.prototype.write = function (options, callback) { module.exports = AbstractChainedBatch }).call(this,require('_process')) -},{"_process":86}],15:[function(require,module,exports){ +},{"_process":82}],12:[function(require,module,exports){ (function (process){ /* Copyright (c) 2017 Rod Vagg, MIT License */ @@ -10350,7 +8223,7 @@ AbstractIterator.prototype.end = function (callback) { module.exports = AbstractIterator }).call(this,require('_process')) -},{"_process":86}],16:[function(require,module,exports){ +},{"_process":82}],13:[function(require,module,exports){ (function (Buffer,process){ /* Copyright (c) 2017 Rod Vagg, MIT License */ @@ -10625,13 +8498,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":14,"./abstract-iterator":15,"_process":86,"xtend":160}],17:[function(require,module,exports){ +},{"../../../is-buffer/index.js":39,"./abstract-chained-batch":11,"./abstract-iterator":12,"_process":82,"xtend":155}],14:[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":14,"./abstract-iterator":15,"./abstract-leveldown":16,"./is-leveldown":18}],18:[function(require,module,exports){ +},{"./abstract-chained-batch":11,"./abstract-iterator":12,"./abstract-leveldown":13,"./is-leveldown":15}],15:[function(require,module,exports){ var AbstractLevelDOWN = require('./abstract-leveldown') function isLevelDOWN (db) { @@ -10647,7 +8520,7 @@ function isLevelDOWN (db) { module.exports = isLevelDOWN -},{"./abstract-leveldown":16}],19:[function(require,module,exports){ +},{"./abstract-leveldown":13}],16:[function(require,module,exports){ const pumpify = require('pumpify') const stopwords = [] @@ -10714,7 +8587,7 @@ exports.customPipeline = function (pl) { return pumpify.obj.apply(this, pl) } -},{"./pipeline/CalculateTermFrequency.js":20,"./pipeline/CharacterNormaliser.js":21,"./pipeline/CreateCompositeVector.js":22,"./pipeline/CreateSortVectors.js":23,"./pipeline/CreateStoredDocument.js":24,"./pipeline/FieldedSearch.js":25,"./pipeline/IngestDoc.js":26,"./pipeline/LowCase.js":27,"./pipeline/NormaliseFields.js":28,"./pipeline/RemoveStopWords.js":29,"./pipeline/Spy.js":30,"./pipeline/Tokeniser.js":31,"pumpify":89}],20:[function(require,module,exports){ +},{"./pipeline/CalculateTermFrequency.js":17,"./pipeline/CharacterNormaliser.js":18,"./pipeline/CreateCompositeVector.js":19,"./pipeline/CreateSortVectors.js":20,"./pipeline/CreateStoredDocument.js":21,"./pipeline/FieldedSearch.js":22,"./pipeline/IngestDoc.js":23,"./pipeline/LowCase.js":24,"./pipeline/NormaliseFields.js":25,"./pipeline/RemoveStopWords.js":26,"./pipeline/Spy.js":27,"./pipeline/Tokeniser.js":28,"pumpify":85}],17:[function(require,module,exports){ const tv = require('term-vector') const tf = require('term-frequency') const Transform = require('stream').Transform @@ -10761,7 +8634,7 @@ CalculateTermFrequency.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":148,"term-frequency":151,"term-vector":152,"util":158}],21:[function(require,module,exports){ +},{"stream":143,"term-frequency":146,"term-vector":147,"util":153}],18:[function(require,module,exports){ // removes stopwords from indexed docs const Transform = require('stream').Transform const util = require('util') @@ -10794,7 +8667,7 @@ CharacterNormaliser.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":148,"util":158}],22:[function(require,module,exports){ +},{"stream":143,"util":153}],19:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -10830,7 +8703,7 @@ CreateCompositeVector.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":148,"util":158}],23:[function(require,module,exports){ +},{"stream":143,"util":153}],20:[function(require,module,exports){ const tf = require('term-frequency') const tv = require('term-vector') const Transform = require('stream').Transform @@ -10867,7 +8740,7 @@ CreateSortVectors.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":148,"term-frequency":151,"term-vector":152,"util":158}],24:[function(require,module,exports){ +},{"stream":143,"term-frequency":146,"term-vector":147,"util":153}],21:[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 @@ -10898,7 +8771,7 @@ CreateStoredDocument.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":148,"util":158}],25:[function(require,module,exports){ +},{"stream":143,"util":153}],22:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -10923,7 +8796,7 @@ FieldedSearch.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":148,"util":158}],26:[function(require,module,exports){ +},{"stream":143,"util":153}],23:[function(require,module,exports){ const util = require('util') const Transform = require('stream').Transform @@ -10959,7 +8832,7 @@ IngestDoc.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":148,"util":158}],27:[function(require,module,exports){ +},{"stream":143,"util":153}],24:[function(require,module,exports){ // insert all search tokens in lower case const Transform = require('stream').Transform const util = require('util') @@ -10993,7 +8866,7 @@ LowCase.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":148,"util":158}],28:[function(require,module,exports){ +},{"stream":143,"util":153}],25:[function(require,module,exports){ const util = require('util') const Transform = require('stream').Transform @@ -11037,7 +8910,7 @@ NormaliseFields.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":148,"util":158}],29:[function(require,module,exports){ +},{"stream":143,"util":153}],26:[function(require,module,exports){ // removes stopwords from indexed docs const Transform = require('stream').Transform const util = require('util') @@ -11068,7 +8941,7 @@ RemoveStopWords.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":148,"util":158}],30:[function(require,module,exports){ +},{"stream":143,"util":153}],27:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -11083,7 +8956,7 @@ Spy.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":148,"util":158}],31:[function(require,module,exports){ +},{"stream":143,"util":153}],28:[function(require,module,exports){ // split up fields in to arrays of tokens const Transform = require('stream').Transform const util = require('util') @@ -11115,7 +8988,7 @@ Tokeniser.prototype._transform = function (doc, encoding, end) { return end() } -},{"stream":148,"util":158}],32:[function(require,module,exports){ +},{"stream":143,"util":153}],29:[function(require,module,exports){ (function (process,Buffer){ var stream = require('readable-stream') var eos = require('end-of-stream') @@ -11347,7 +9220,7 @@ Duplexify.prototype.end = function(data, enc, cb) { module.exports = Duplexify }).call(this,require('_process'),require("buffer").Buffer) -},{"_process":86,"buffer":9,"end-of-stream":33,"inherits":40,"readable-stream":100,"stream-shift":149}],33:[function(require,module,exports){ +},{"_process":82,"buffer":7,"end-of-stream":30,"inherits":37,"readable-stream":96,"stream-shift":144}],30:[function(require,module,exports){ var once = require('once'); var noop = function() {}; @@ -11432,7 +9305,7 @@ var eos = function(stream, opts, callback) { module.exports = eos; -},{"once":83}],34:[function(require,module,exports){ +},{"once":80}],31:[function(require,module,exports){ var prr = require('prr') function init (type, message, cause) { @@ -11489,7 +9362,7 @@ module.exports = function (errno) { } } -},{"prr":36}],35:[function(require,module,exports){ +},{"prr":33}],32:[function(require,module,exports){ var all = module.exports.all = [ { errno: -2, @@ -11804,7 +9677,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":31}],33:[function(require,module,exports){ /*! * prr * (c) 2013 Rod Vagg @@ -11868,7 +9741,7 @@ module.exports.create = module.exports.custom.createError return prr }) -},{}],37:[function(require,module,exports){ +},{}],34:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -12172,7 +10045,7 @@ function isUndefined(arg) { return arg === void 0; } -},{}],38:[function(require,module,exports){ +},{}],35:[function(require,module,exports){ /*global window:false, self:false, define:false, module:false */ /** @@ -13579,7 +11452,7 @@ function isUndefined(arg) { }, this); -},{}],39:[function(require,module,exports){ +},{}],36:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 @@ -13665,7 +11538,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],40:[function(require,module,exports){ +},{}],37:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { @@ -13690,7 +11563,7 @@ if (typeof Object.create === 'function') { } } -},{}],41:[function(require,module,exports){ +},{}],38:[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 @@ -13756,7 +11629,7 @@ exports.getIntersectionStream = function(sortedSets) { return s } -},{"stream":148}],42:[function(require,module,exports){ +},{"stream":143}],39:[function(require,module,exports){ /*! * Determine if an object is a Buffer * @@ -13779,14 +11652,14 @@ function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } -},{}],43:[function(require,module,exports){ +},{}],40:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; -},{}],44:[function(require,module,exports){ +},{}],41:[function(require,module,exports){ var Buffer = require('buffer').Buffer; module.exports = isBuffer; @@ -13796,7 +11669,7 @@ function isBuffer (o) { || /\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o)); } -},{"buffer":9}],45:[function(require,module,exports){ +},{"buffer":7}],42:[function(require,module,exports){ /*! * js-logger - http://github.com/jonnyreeves/js-logger * Jonny Reeves, http://jonnyreeves.co.uk/ @@ -14067,7 +11940,7 @@ function isBuffer (o) { } }(this)); -},{}],46:[function(require,module,exports){ +},{}],43:[function(require,module,exports){ (function (Buffer){ /*global Buffer*/ // Named constants with unique integer values @@ -14484,7 +12357,7 @@ Parser.C = C; module.exports = Parser; }).call(this,require("buffer").Buffer) -},{"buffer":9}],47:[function(require,module,exports){ +},{"buffer":7}],44:[function(require,module,exports){ var encodings = require('./lib/encodings'); module.exports = Codec; @@ -14592,7 +12465,7 @@ Codec.prototype.valueAsBuffer = function(opts){ }; -},{"./lib/encodings":48}],48:[function(require,module,exports){ +},{"./lib/encodings":45}],45:[function(require,module,exports){ (function (Buffer){ exports.utf8 = exports['utf-8'] = { encode: function(data){ @@ -14672,7 +12545,7 @@ function isBinary(data){ } }).call(this,require("buffer").Buffer) -},{"buffer":9}],49:[function(require,module,exports){ +},{"buffer":7}],46:[function(require,module,exports){ /* Copyright (c) 2012-2017 LevelUP contributors * See list at * MIT License @@ -14696,7 +12569,7 @@ module.exports = { , EncodingError : createError('EncodingError', LevelUPError) } -},{"errno":35}],50:[function(require,module,exports){ +},{"errno":32}],47:[function(require,module,exports){ var inherits = require('inherits'); var Readable = require('readable-stream').Readable; var extend = require('xtend'); @@ -14754,12 +12627,12 @@ ReadStream.prototype._cleanup = function(){ }; -},{"inherits":40,"level-errors":49,"readable-stream":57,"xtend":160}],51:[function(require,module,exports){ +},{"inherits":37,"level-errors":46,"readable-stream":54,"xtend":155}],48:[function(require,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; -},{}],52:[function(require,module,exports){ +},{}],49:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -14852,7 +12725,7 @@ function forEach (xs, f) { } }).call(this,require('_process')) -},{"./_stream_readable":54,"./_stream_writable":56,"_process":86,"core-util-is":11,"inherits":40}],53:[function(require,module,exports){ +},{"./_stream_readable":51,"./_stream_writable":53,"_process":82,"core-util-is":8,"inherits":37}],50:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -14900,7 +12773,7 @@ PassThrough.prototype._transform = function(chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":55,"core-util-is":11,"inherits":40}],54:[function(require,module,exports){ +},{"./_stream_transform":52,"core-util-is":8,"inherits":37}],51:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -15855,7 +13728,7 @@ function indexOf (xs, x) { } }).call(this,require('_process')) -},{"./_stream_duplex":52,"_process":86,"buffer":9,"core-util-is":11,"events":37,"inherits":40,"isarray":51,"stream":148,"string_decoder/":58,"util":7}],55:[function(require,module,exports){ +},{"./_stream_duplex":49,"_process":82,"buffer":7,"core-util-is":8,"events":34,"inherits":37,"isarray":48,"stream":143,"string_decoder/":55,"util":6}],52:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -16066,7 +13939,7 @@ function done(stream, er) { return stream.push(null); } -},{"./_stream_duplex":52,"core-util-is":11,"inherits":40}],56:[function(require,module,exports){ +},{"./_stream_duplex":49,"core-util-is":8,"inherits":37}],53:[function(require,module,exports){ (function (process){ // Copyright Joyent, Inc. and other Node contributors. // @@ -16547,7 +14420,7 @@ function endWritable(stream, state, cb) { } }).call(this,require('_process')) -},{"./_stream_duplex":52,"_process":86,"buffer":9,"core-util-is":11,"inherits":40,"stream":148}],57:[function(require,module,exports){ +},{"./_stream_duplex":49,"_process":82,"buffer":7,"core-util-is":8,"inherits":37,"stream":143}],54:[function(require,module,exports){ (function (process){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = require('stream'); @@ -16561,7 +14434,7 @@ if (!process.browser && process.env.READABLE_STREAM === 'disable') { } }).call(this,require('_process')) -},{"./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":148}],58:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":49,"./lib/_stream_passthrough.js":50,"./lib/_stream_readable.js":51,"./lib/_stream_transform.js":52,"./lib/_stream_writable.js":53,"_process":82,"stream":143}],55:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -16784,7 +14657,7 @@ function base64DetectIncompleteChar(buffer) { this.charLength = this.charReceived ? 3 : 0; } -},{"buffer":9}],59:[function(require,module,exports){ +},{"buffer":7}],56:[function(require,module,exports){ (function (Buffer){ module.exports = Level @@ -16962,7 +14835,7 @@ var checkKeyValue = Level.prototype._checkKeyValue = function (obj, type) { } }).call(this,require("buffer").Buffer) -},{"./iterator":60,"abstract-leveldown":63,"buffer":9,"idb-wrapper":38,"isbuffer":44,"typedarray-to-buffer":154,"util":158,"xtend":70}],60:[function(require,module,exports){ +},{"./iterator":57,"abstract-leveldown":60,"buffer":7,"idb-wrapper":35,"isbuffer":41,"typedarray-to-buffer":149,"util":153,"xtend":67}],57:[function(require,module,exports){ var util = require('util') var AbstractIterator = require('abstract-leveldown').AbstractIterator var ltgt = require('ltgt') @@ -17036,7 +14909,7 @@ Iterator.prototype._next = function (callback) { this.callback = callback } -},{"abstract-leveldown":63,"ltgt":81,"util":158}],61:[function(require,module,exports){ +},{"abstract-leveldown":60,"ltgt":78,"util":153}],58:[function(require,module,exports){ (function (process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -17120,7 +14993,7 @@ AbstractChainedBatch.prototype.write = function (options, callback) { module.exports = AbstractChainedBatch }).call(this,require('_process')) -},{"_process":86}],62:[function(require,module,exports){ +},{"_process":82}],59:[function(require,module,exports){ (function (process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -17173,7 +15046,7 @@ AbstractIterator.prototype.end = function (callback) { module.exports = AbstractIterator }).call(this,require('_process')) -},{"_process":86}],63:[function(require,module,exports){ +},{"_process":82}],60:[function(require,module,exports){ (function (Buffer,process){ /* Copyright (c) 2013 Rod Vagg, MIT License */ @@ -17433,7 +15306,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":61,"./abstract-iterator":62,"_process":86,"xtend":64}],64:[function(require,module,exports){ +},{"../../../is-buffer/index.js":39,"./abstract-chained-batch":58,"./abstract-iterator":59,"_process":82,"xtend":61}],61:[function(require,module,exports){ module.exports = extend function extend() { @@ -17452,7 +15325,7 @@ function extend() { return target } -},{}],65:[function(require,module,exports){ +},{}],62:[function(require,module,exports){ var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; @@ -17494,11 +15367,11 @@ module.exports = function forEach(obj, fn) { }; -},{}],66:[function(require,module,exports){ +},{}],63:[function(require,module,exports){ module.exports = Object.keys || require('./shim'); -},{"./shim":68}],67:[function(require,module,exports){ +},{"./shim":65}],64:[function(require,module,exports){ var toString = Object.prototype.toString; module.exports = function isArguments(value) { @@ -17516,7 +15389,7 @@ module.exports = function isArguments(value) { }; -},{}],68:[function(require,module,exports){ +},{}],65:[function(require,module,exports){ (function () { "use strict"; @@ -17580,7 +15453,7 @@ module.exports = function isArguments(value) { }()); -},{"./foreach":65,"./isArguments":67}],69:[function(require,module,exports){ +},{"./foreach":62,"./isArguments":64}],66:[function(require,module,exports){ module.exports = hasKeys function hasKeys(source) { @@ -17589,7 +15462,7 @@ function hasKeys(source) { typeof source === "function") } -},{}],70:[function(require,module,exports){ +},{}],67:[function(require,module,exports){ var Keys = require("object-keys") var hasKeys = require("./has-keys") @@ -17616,7 +15489,7 @@ function extend() { return target } -},{"./has-keys":69,"object-keys":66}],71:[function(require,module,exports){ +},{"./has-keys":66,"object-keys":63}],68:[function(require,module,exports){ /* Copyright (c) 2012-2016 LevelUP contributors * See list at * MIT License @@ -17701,7 +15574,7 @@ Batch.prototype.write = function (callback) { module.exports = Batch -},{"./util":73,"level-errors":49}],72:[function(require,module,exports){ +},{"./util":70,"level-errors":46}],69:[function(require,module,exports){ (function (process){ /* Copyright (c) 2012-2016 LevelUP contributors * See list at @@ -18068,7 +15941,7 @@ module.exports.repair = deprecate( ) }).call(this,require('_process')) -},{"./batch":71,"./leveldown":7,"./util":73,"_process":86,"deferred-leveldown":13,"events":37,"level-codec":47,"level-errors":49,"level-iterator-stream":50,"prr":87,"util":158,"xtend":160}],73:[function(require,module,exports){ +},{"./batch":68,"./leveldown":6,"./util":70,"_process":82,"deferred-leveldown":10,"events":34,"level-codec":44,"level-errors":46,"level-iterator-stream":47,"prr":83,"util":153,"xtend":155}],70:[function(require,module,exports){ /* Copyright (c) 2012-2016 LevelUP contributors * See list at * MIT License @@ -18104,7 +15977,7 @@ module.exports = { isDefined: isDefined } -},{}],74:[function(require,module,exports){ +},{}],71:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -19278,7 +17151,7 @@ function isObjectLike(value) { module.exports = difference; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],75:[function(require,module,exports){ +},{}],72:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -20347,7 +18220,7 @@ function isObjectLike(value) { module.exports = intersection; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],76:[function(require,module,exports){ +},{}],73:[function(require,module,exports){ (function (global){ /** * Lodash (Custom Build) @@ -22199,7 +20072,7 @@ function stubFalse() { module.exports = isEqual; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],77:[function(require,module,exports){ +},{}],74:[function(require,module,exports){ /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` @@ -22452,7 +20325,7 @@ function identity(value) { module.exports = sortedIndexOf; -},{}],78:[function(require,module,exports){ +},{}],75:[function(require,module,exports){ /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` @@ -22858,7 +20731,7 @@ function toNumber(value) { module.exports = spread; -},{}],79:[function(require,module,exports){ +},{}],76:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -24043,7 +21916,7 @@ function noop() { module.exports = union; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],80:[function(require,module,exports){ +},{}],77:[function(require,module,exports){ (function (global){ /** * lodash (Custom Build) @@ -24943,7 +22816,7 @@ function noop() { module.exports = uniq; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],81:[function(require,module,exports){ +},{}],78:[function(require,module,exports){ (function (Buffer){ exports.compare = function (a, b) { @@ -25116,7 +22989,7 @@ exports.filter = function (range, compare) { }).call(this,{"isBuffer":require("../is-buffer/index.js")}) -},{"../is-buffer/index.js":42}],82:[function(require,module,exports){ +},{"../is-buffer/index.js":39}],79:[function(require,module,exports){ // nGramLengths is of the form [ 9, 10 ] const getNGramsOfMultipleLengths = function (inputArray, nGramLengths) { @@ -25151,7 +23024,7 @@ exports.ngram = function (inputArray, nGramLength) { } } -},{}],83:[function(require,module,exports){ +},{}],80:[function(require,module,exports){ var wrappy = require('wrappy') module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) @@ -25195,54 +23068,7 @@ function onceStrict (fn) { return f } -},{"wrappy":159}],84:[function(require,module,exports){ -exports.endianness = function () { return 'LE' }; - -exports.hostname = function () { - if (typeof location !== 'undefined') { - return location.hostname - } - else return ''; -}; - -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 () { - if (typeof navigator !== 'undefined') { - return navigator.appVersion; - } - return ''; -}; - -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){ +},{"wrappy":154}],81:[function(require,module,exports){ (function (process){ 'use strict'; @@ -25289,7 +23115,7 @@ function nextTick(fn, arg1, arg2, arg3) { } }).call(this,require('_process')) -},{"_process":86}],86:[function(require,module,exports){ +},{"_process":82}],82:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -25475,9 +23301,9 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],87:[function(require,module,exports){ -arguments[4][36][0].apply(exports,arguments) -},{"dup":36}],88:[function(require,module,exports){ +},{}],83:[function(require,module,exports){ +arguments[4][33][0].apply(exports,arguments) +},{"dup":33}],84:[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 @@ -25559,7 +23385,7 @@ var pump = function () { module.exports = pump -},{"end-of-stream":33,"fs":7,"once":83}],89:[function(require,module,exports){ +},{"end-of-stream":30,"fs":6,"once":80}],85:[function(require,module,exports){ var pump = require('pump') var inherits = require('inherits') var Duplexify = require('duplexify') @@ -25616,10 +23442,10 @@ var define = function(opts) { module.exports = define({destroy:false}) module.exports.obj = define({destroy:false, objectMode:true, highWaterMark:16}) -},{"duplexify":32,"inherits":40,"pump":88}],90:[function(require,module,exports){ +},{"duplexify":29,"inherits":37,"pump":84}],86:[function(require,module,exports){ module.exports = require('./lib/_stream_duplex.js'); -},{"./lib/_stream_duplex.js":91}],91:[function(require,module,exports){ +},{"./lib/_stream_duplex.js":87}],87:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -25744,7 +23570,7 @@ function forEach(xs, f) { f(xs[i], i); } } -},{"./_stream_readable":93,"./_stream_writable":95,"core-util-is":11,"inherits":40,"process-nextick-args":85}],92:[function(require,module,exports){ +},{"./_stream_readable":89,"./_stream_writable":91,"core-util-is":8,"inherits":37,"process-nextick-args":81}],88:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -25792,7 +23618,7 @@ function PassThrough(options) { PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; -},{"./_stream_transform":94,"core-util-is":11,"inherits":40}],93:[function(require,module,exports){ +},{"./_stream_transform":90,"core-util-is":8,"inherits":37}],89:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -26802,7 +24628,7 @@ function indexOf(xs, x) { return -1; } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./_stream_duplex":91,"./internal/streams/BufferList":96,"./internal/streams/destroy":97,"./internal/streams/stream":98,"_process":86,"core-util-is":11,"events":37,"inherits":40,"isarray":43,"process-nextick-args":85,"safe-buffer":103,"string_decoder/":150,"util":7}],94:[function(require,module,exports){ +},{"./_stream_duplex":87,"./internal/streams/BufferList":92,"./internal/streams/destroy":93,"./internal/streams/stream":94,"_process":82,"core-util-is":8,"events":34,"inherits":37,"isarray":40,"process-nextick-args":81,"safe-buffer":99,"string_decoder/":145,"util":6}],90:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -27017,7 +24843,7 @@ function done(stream, er, data) { return stream.push(null); } -},{"./_stream_duplex":91,"core-util-is":11,"inherits":40}],95:[function(require,module,exports){ +},{"./_stream_duplex":87,"core-util-is":8,"inherits":37}],91:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -27684,7 +25510,7 @@ Writable.prototype._destroy = function (err, cb) { cb(err); }; }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./_stream_duplex":91,"./internal/streams/destroy":97,"./internal/streams/stream":98,"_process":86,"core-util-is":11,"inherits":40,"process-nextick-args":85,"safe-buffer":103,"util-deprecate":155}],96:[function(require,module,exports){ +},{"./_stream_duplex":87,"./internal/streams/destroy":93,"./internal/streams/stream":94,"_process":82,"core-util-is":8,"inherits":37,"process-nextick-args":81,"safe-buffer":99,"util-deprecate":150}],92:[function(require,module,exports){ 'use strict'; /**/ @@ -27759,7 +25585,7 @@ module.exports = function () { return BufferList; }(); -},{"safe-buffer":103}],97:[function(require,module,exports){ +},{"safe-buffer":99}],93:[function(require,module,exports){ 'use strict'; /**/ @@ -27832,13 +25658,13 @@ module.exports = { destroy: destroy, undestroy: undestroy }; -},{"process-nextick-args":85}],98:[function(require,module,exports){ +},{"process-nextick-args":81}],94:[function(require,module,exports){ module.exports = require('events').EventEmitter; -},{"events":37}],99:[function(require,module,exports){ +},{"events":34}],95:[function(require,module,exports){ module.exports = require('./readable').PassThrough -},{"./readable":100}],100:[function(require,module,exports){ +},{"./readable":96}],96:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; @@ -27847,13 +25673,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":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){ +},{"./lib/_stream_duplex.js":87,"./lib/_stream_passthrough.js":88,"./lib/_stream_readable.js":89,"./lib/_stream_transform.js":90,"./lib/_stream_writable.js":91}],97:[function(require,module,exports){ module.exports = require('./readable').Transform -},{"./readable":100}],102:[function(require,module,exports){ +},{"./readable":96}],98:[function(require,module,exports){ module.exports = require('./lib/_stream_writable.js'); -},{"./lib/_stream_writable.js":95}],103:[function(require,module,exports){ +},{"./lib/_stream_writable.js":91}],99:[function(require,module,exports){ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') var Buffer = buffer.Buffer @@ -27917,68 +25743,7 @@ SafeBuffer.allocUnsafeSlow = function (size) { return buffer.SlowBuffer(size) } -},{"buffer":9}],104:[function(require,module,exports){ -var hasProp = Object.prototype.hasOwnProperty; - -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) { - var seen = [ ]; // store references to objects we have seen before - - function visit(obj) { - if (obj === null || typeof obj !== 'object') { - return obj; - } - - if (seen.indexOf(obj) !== -1) { - return '[Circular]'; - } - seen.push(obj); - - if (typeof obj.toJSON === 'function') { - try { - return visit(obj.toJSON()); - } catch(err) { - return throwsMessage(err); - } - } - - if (Array.isArray(obj)) { - return obj.map(visit); - } - - return Object.keys(obj).reduce(function(result, prop) { - // prevent faulty defined getter properties - result[prop] = visit(safeGetValueFromPropertyOnObject(obj, prop)); - return result; - }, {}); - }; - - return visit(obj); -} - -module.exports = function(data) { - return JSON.stringify(ensureProperties(data)); -} - -module.exports.ensureProperties = ensureProperties; - -},{}],105:[function(require,module,exports){ +},{"buffer":7}],100:[function(require,module,exports){ /* search-index-adder @@ -27987,7 +25752,7 @@ standalone */ -const bunyan = require('bunyan') +const Logger = require('js-logger') const levelup = require('levelup') const API = require('./lib/API.js') @@ -28026,7 +25791,8 @@ const getOptions = function (options, done) { storeVector: true, searchable: true, indexPath: 'si', - logLevel: 'error', + logLevel: 'ERROR', + logHandler: Logger.createDefaultHandler(), nGramLength: 1, nGramSeparator: ' ', separator: /\s|\\n|\\u0003|[-.,<>]/, @@ -28034,10 +25800,13 @@ const getOptions = function (options, done) { weight: 0, wildcard: true }, options) - options.log = bunyan.createLogger({ - name: 'search-index', - level: options.logLevel - }) + options.log = Logger.get('search-index-adder') + // We pass the log level as string because the Logger[logLevel] returns + // an object, and Object.assign deosn't make deep assign so it breakes + // We used toUpperCase() for backward compatibility + options.log.setLevel(Logger[options.logLevel.toUpperCase()]) + // Use the global one because the library doesn't support providing handler to named logger + Logger.setHandler(options.logHandler) if (!options.indexes) { const leveldown = require('leveldown') levelup(options.indexPath || 'si', { @@ -28052,7 +25821,7 @@ const getOptions = function (options, done) { } } -},{"./lib/API.js":106,"bunyan":10,"leveldown":59,"levelup":72}],106:[function(require,module,exports){ +},{"./lib/API.js":101,"js-logger":42,"leveldown":56,"levelup":69}],101:[function(require,module,exports){ const DBEntries = require('./delete.js').DBEntries const DBWriteCleanStream = require('./replicate.js').DBWriteCleanStream const DBWriteMergeStream = require('./replicate.js').DBWriteMergeStream @@ -28213,7 +25982,7 @@ module.exports = function (options) { return Indexer } -},{"./add.js":107,"./delete.js":108,"./replicate.js":109,"JSONStream":3,"async":5,"docproc":19,"pumpify":89,"stream":148}],107:[function(require,module,exports){ +},{"./add.js":102,"./delete.js":103,"./replicate.js":104,"JSONStream":3,"async":4,"docproc":16,"pumpify":85,"stream":143}],102:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -28287,7 +26056,7 @@ IndexBatch.prototype._flush = function (end) { return end() } -},{"stream":148,"util":158}],108:[function(require,module,exports){ +},{"stream":143,"util":153}],103:[function(require,module,exports){ // deletes all references to a document from the search index const util = require('util') @@ -28451,7 +26220,7 @@ RecalibrateDB.prototype._transform = function (dbEntry, encoding, end) { }) } -},{"stream":148,"util":158}],109:[function(require,module,exports){ +},{"stream":143,"util":153}],104:[function(require,module,exports){ const Transform = require('stream').Transform const Writable = require('stream').Writable const util = require('util') @@ -28528,7 +26297,8 @@ DBWriteCleanStream.prototype._flush = function (end) { } exports.DBWriteCleanStream = DBWriteCleanStream -},{"stream":148,"util":158}],110:[function(require,module,exports){ +},{"stream":143,"util":153}],105:[function(require,module,exports){ +const Logger = require('js-logger') const AvailableFields = require('./lib/AvailableFields.js').AvailableFields const CalculateBuckets = require('./lib/CalculateBuckets.js').CalculateBuckets const CalculateCategories = require('./lib/CalculateCategories.js').CalculateCategories @@ -28545,7 +26315,6 @@ const MergeOrConditionsFieldSort = require('./lib/MergeOrConditionsFieldSort.js' const Readable = require('stream').Readable const ScoreDocsOnField = require('./lib/ScoreDocsOnField.js').ScoreDocsOnField const ScoreTopScoringDocsTFIDF = require('./lib/ScoreTopScoringDocsTFIDF.js').ScoreTopScoringDocsTFIDF -const bunyan = require('bunyan') const levelup = require('levelup') const matcher = require('./lib/matcher.js') const siUtil = require('./lib/siUtil.js') @@ -28707,16 +26476,21 @@ const getOptions = function (options, done) { store: true, indexPath: 'si', keySeparator: '○', - logLevel: 'error', + logLevel: 'ERROR', + logHandler: Logger.createDefaultHandler(), nGramLength: 1, nGramSeparator: ' ', separator: /[|' .,\-|(\n)]+/, stopwords: sw.en }, options) - Searcher.options.log = bunyan.createLogger({ - name: 'search-index', - level: options.logLevel - }) + Searcher.options.log = Logger.get('search-index-searcher') + // We pass the log level as string because the Logger[logLevel] returns + // an object, and Object.assign deosn't make deep assign so it breakes + // We used toUpperCase() for backward compatibility + Searcher.options.log.setLevel(Logger[Searcher.options.logLevel.toUpperCase()]) + // Use the global one because the library doesn't support providing handler to named logger + Logger.setHandler(Searcher.options.logHandler) + if (!options.indexes) { levelup(Searcher.options.indexPath || 'si', { valueEncoding: 'json' @@ -28735,7 +26509,7 @@ module.exports = function (givenOptions, moduleReady) { }) } -},{"./lib/AvailableFields.js":111,"./lib/CalculateBuckets.js":112,"./lib/CalculateCategories.js":113,"./lib/CalculateEntireResultSet.js":114,"./lib/CalculateResultSetPerClause.js":115,"./lib/CalculateTopScoringDocs.js":116,"./lib/CalculateTotalHits.js":117,"./lib/Classify.js":118,"./lib/FetchDocsFromDB.js":119,"./lib/FetchStoredDoc.js":120,"./lib/GetIntersectionStream.js":121,"./lib/MergeOrConditionsFieldSort.js":122,"./lib/MergeOrConditionsTFIDF.js":123,"./lib/ScoreDocsOnField.js":124,"./lib/ScoreTopScoringDocsTFIDF.js":125,"./lib/matcher.js":126,"./lib/siUtil.js":127,"bunyan":10,"levelup":72,"stopword":128,"stream":148}],111:[function(require,module,exports){ +},{"./lib/AvailableFields.js":106,"./lib/CalculateBuckets.js":107,"./lib/CalculateCategories.js":108,"./lib/CalculateEntireResultSet.js":109,"./lib/CalculateResultSetPerClause.js":110,"./lib/CalculateTopScoringDocs.js":111,"./lib/CalculateTotalHits.js":112,"./lib/Classify.js":113,"./lib/FetchDocsFromDB.js":114,"./lib/FetchStoredDoc.js":115,"./lib/GetIntersectionStream.js":116,"./lib/MergeOrConditionsFieldSort.js":117,"./lib/MergeOrConditionsTFIDF.js":118,"./lib/ScoreDocsOnField.js":119,"./lib/ScoreTopScoringDocsTFIDF.js":120,"./lib/matcher.js":121,"./lib/siUtil.js":122,"js-logger":42,"levelup":69,"stopword":123,"stream":143}],106:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -28750,7 +26524,7 @@ AvailableFields.prototype._transform = function (field, encoding, end) { return end() } -},{"stream":148,"util":158}],112:[function(require,module,exports){ +},{"stream":143,"util":153}],107:[function(require,module,exports){ const _intersection = require('lodash.intersection') const _uniq = require('lodash.uniq') const Transform = require('stream').Transform @@ -28791,7 +26565,7 @@ CalculateBuckets.prototype._transform = function (mergedQueryClauses, encoding, }) } -},{"lodash.intersection":75,"lodash.uniq":80,"stream":148,"util":158}],113:[function(require,module,exports){ +},{"lodash.intersection":72,"lodash.uniq":77,"stream":143,"util":153}],108:[function(require,module,exports){ const _intersection = require('lodash.intersection') const Transform = require('stream').Transform const util = require('util') @@ -28854,7 +26628,7 @@ CalculateCategories.prototype._transform = function (mergedQueryClauses, encodin }) } -},{"lodash.intersection":75,"stream":148,"util":158}],114:[function(require,module,exports){ +},{"lodash.intersection":72,"stream":143,"util":153}],109:[function(require,module,exports){ const Transform = require('stream').Transform const _union = require('lodash.union') const util = require('util') @@ -28877,7 +26651,7 @@ CalculateEntireResultSet.prototype._flush = function (end) { return end() } -},{"lodash.union":79,"stream":148,"util":158}],115:[function(require,module,exports){ +},{"lodash.union":76,"stream":143,"util":153}],110:[function(require,module,exports){ const Transform = require('stream').Transform const _difference = require('lodash.difference') const _intersection = require('lodash.intersection') @@ -28973,7 +26747,7 @@ CalculateResultSetPerClause.prototype._transform = function (queryClause, encodi }) } -},{"./siUtil.js":127,"lodash.difference":74,"lodash.intersection":75,"lodash.spread":78,"stream":148,"util":158}],116:[function(require,module,exports){ +},{"./siUtil.js":122,"lodash.difference":71,"lodash.intersection":72,"lodash.spread":75,"stream":143,"util":153}],111:[function(require,module,exports){ const Transform = require('stream').Transform const _sortedIndexOf = require('lodash.sortedindexof') const util = require('util') @@ -29040,7 +26814,7 @@ CalculateTopScoringDocs.prototype._transform = function (clauseSet, encoding, en }) } -},{"lodash.sortedindexof":77,"stream":148,"util":158}],117:[function(require,module,exports){ +},{"lodash.sortedindexof":74,"stream":143,"util":153}],112:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -29057,7 +26831,7 @@ CalculateTotalHits.prototype._transform = function (mergedQueryClauses, encoding end() } -},{"stream":148,"util":158}],118:[function(require,module,exports){ +},{"stream":143,"util":153}],113:[function(require,module,exports){ const Transform = require('stream').Transform const ngraminator = require('ngraminator') const util = require('util') @@ -29127,7 +26901,7 @@ Classify.prototype._flush = function (end) { }) } -},{"ngraminator":82,"stream":148,"util":158}],119:[function(require,module,exports){ +},{"ngraminator":79,"stream":143,"util":153}],114:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -29148,7 +26922,7 @@ FetchDocsFromDB.prototype._transform = function (line, encoding, end) { }) } -},{"stream":148,"util":158}],120:[function(require,module,exports){ +},{"stream":143,"util":153}],115:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -29172,7 +26946,7 @@ FetchStoredDoc.prototype._transform = function (doc, encoding, end) { }) } -},{"stream":148,"util":158}],121:[function(require,module,exports){ +},{"stream":143,"util":153}],116:[function(require,module,exports){ const Transform = require('stream').Transform const iats = require('intersect-arrays-to-stream') const util = require('util') @@ -29207,7 +26981,7 @@ GetIntersectionStream.prototype._transform = function (line, encoding, end) { }) } -},{"intersect-arrays-to-stream":41,"stream":148,"util":158}],122:[function(require,module,exports){ +},{"intersect-arrays-to-stream":38,"stream":143,"util":153}],117:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -29268,7 +27042,7 @@ const getResultMap = (resultSet) => { return resultMap } -},{"stream":148,"util":158}],123:[function(require,module,exports){ +},{"stream":143,"util":153}],118:[function(require,module,exports){ const Transform = require('stream').Transform const util = require('util') @@ -29327,7 +27101,7 @@ const getResultMap = (resultSet) => { return resultMap } -},{"stream":148,"util":158}],124:[function(require,module,exports){ +},{"stream":143,"util":153}],119:[function(require,module,exports){ const Transform = require('stream').Transform const _sortedIndexOf = require('lodash.sortedindexof') const util = require('util') @@ -29378,7 +27152,7 @@ ScoreDocsOnField.prototype._transform = function (clauseSet, encoding, end) { }) } -},{"lodash.sortedindexof":77,"stream":148,"util":158}],125:[function(require,module,exports){ +},{"lodash.sortedindexof":74,"stream":143,"util":153}],120:[function(require,module,exports){ /* Look at the top scoring docs, and work out which terms give hits in them */ @@ -29465,7 +27239,7 @@ const gett = (field, key, gte, lte, df, weight, options) => { }) } -},{"stream":148,"util":158}],126:[function(require,module,exports){ +},{"stream":143,"util":153}],121:[function(require,module,exports){ const Readable = require('stream').Readable const Transform = require('stream').Transform const util = require('util') @@ -29590,7 +27364,7 @@ exports.match = function (q, options) { } } -},{"stream":148,"util":158}],127:[function(require,module,exports){ +},{"stream":143,"util":153}],122:[function(require,module,exports){ exports.getKeySet = function (clause, sep) { var keySet = [] for (var fieldName in clause) { @@ -29639,7 +27413,7 @@ exports.getQueryDefaults = function (q) { }, q) } -},{}],128:[function(require,module,exports){ +},{}],123:[function(require,module,exports){ const defaultStopwords = require('./stopwords_en.js').words exports.removeStopwords = function(tokens, stopwords) { @@ -29672,7 +27446,7 @@ exports.ru = require('./stopwords_ru.js').words exports.sv = require('./stopwords_sv.js').words exports.zh = require('./stopwords_zh.js').words -},{"./stopwords_ar.js":129,"./stopwords_bn.js":130,"./stopwords_br.js":131,"./stopwords_da.js":132,"./stopwords_de.js":133,"./stopwords_en.js":134,"./stopwords_es.js":135,"./stopwords_fa.js":136,"./stopwords_fr.js":137,"./stopwords_hi.js":138,"./stopwords_it.js":139,"./stopwords_ja.js":140,"./stopwords_nl.js":141,"./stopwords_no.js":142,"./stopwords_pl.js":143,"./stopwords_pt.js":144,"./stopwords_ru.js":145,"./stopwords_sv.js":146,"./stopwords_zh.js":147}],129:[function(require,module,exports){ +},{"./stopwords_ar.js":124,"./stopwords_bn.js":125,"./stopwords_br.js":126,"./stopwords_da.js":127,"./stopwords_de.js":128,"./stopwords_en.js":129,"./stopwords_es.js":130,"./stopwords_fa.js":131,"./stopwords_fr.js":132,"./stopwords_hi.js":133,"./stopwords_it.js":134,"./stopwords_ja.js":135,"./stopwords_nl.js":136,"./stopwords_no.js":137,"./stopwords_pl.js":138,"./stopwords_pt.js":139,"./stopwords_ru.js":140,"./stopwords_sv.js":141,"./stopwords_zh.js":142}],124:[function(require,module,exports){ /* The MIT License (MIT) @@ -29704,7 +27478,7 @@ var words = ["،","آض","آمينَ","آه","آهاً","آي","أ","أب","أج // tell the world about the noise words. exports.words = words -},{}],130:[function(require,module,exports){ +},{}],125:[function(require,module,exports){ /* The MIT License (MIT) @@ -29735,7 +27509,7 @@ var words = ["অতএব","অথচ","অথবা","অনুযায়ী // tell the world about the noise words. exports.words = words -},{}],131:[function(require,module,exports){ +},{}],126:[function(require,module,exports){ /* Copyright (c) 2017, Micael Levi @@ -30022,7 +27796,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],132:[function(require,module,exports){ +},{}],127:[function(require,module,exports){ /* Creative Commons – Attribution / ShareAlike 3.0 license http://creativecommons.org/licenses/by-sa/3.0/ @@ -30054,7 +27828,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],133:[function(require,module,exports){ +},{}],128:[function(require,module,exports){ /* */ @@ -30067,7 +27841,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],134:[function(require,module,exports){ +},{}],129:[function(require,module,exports){ /* Copyright (c) 2011, Chris Umbel @@ -30107,7 +27881,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],135:[function(require,module,exports){ +},{}],130:[function(require,module,exports){ /* Copyright (c) 2011, David Przybilla, Chris Umbel @@ -30145,7 +27919,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],136:[function(require,module,exports){ +},{}],131:[function(require,module,exports){ /* Copyright (c) 2011, Chris Umbel Farsi Stop Words by Fardin Koochaki @@ -30185,7 +27959,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],137:[function(require,module,exports){ +},{}],132:[function(require,module,exports){ /* Copyright (c) 2014, Ismaël Héry @@ -30381,7 +28155,7 @@ var words = ['être', 'avoir', 'faire', exports.words = words -},{}],138:[function(require,module,exports){ +},{}],133:[function(require,module,exports){ /* The MIT License (MIT) @@ -30432,7 +28206,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],139:[function(require,module,exports){ +},{}],134:[function(require,module,exports){ /* Copyright (c) 2011, David Przybilla, Chris Umbel @@ -30486,7 +28260,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],140:[function(require,module,exports){ +},{}],135:[function(require,module,exports){ // Original copyright: /* Licensed to the Apache Software Foundation (ASF) under one or more @@ -30547,7 +28321,7 @@ var words = ['の', 'に', 'は', 'を', 'た', 'が', 'で', 'て', 'と', 'し // tell the world about the noise words. exports.words = words -},{}],141:[function(require,module,exports){ +},{}],136:[function(require,module,exports){ /* Copyright (c) 2011, Chris Umbel, Martijn de Boer, Damien van Holten @@ -30592,7 +28366,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],142:[function(require,module,exports){ +},{}],137:[function(require,module,exports){ /* Copyright (c) 2014, Kristoffer Brabrand @@ -30636,7 +28410,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],143:[function(require,module,exports){ +},{}],138:[function(require,module,exports){ /* Copyright (c) 2013, Paweł Łaskarzewski @@ -30700,7 +28474,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],144:[function(require,module,exports){ +},{}],139:[function(require,module,exports){ /* Copyright (c) 2011, Luís Rodrigues @@ -30838,7 +28612,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],145:[function(require,module,exports){ +},{}],140:[function(require,module,exports){ /* Copyright (c) 2011, Polyakov Vladimir, Chris Umbel @@ -30881,7 +28655,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],146:[function(require,module,exports){ +},{}],141:[function(require,module,exports){ /* Creative Commons – Attribution / ShareAlike 3.0 license http://creativecommons.org/licenses/by-sa/3.0/ @@ -30913,7 +28687,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],147:[function(require,module,exports){ +},{}],142:[function(require,module,exports){ /* Copyright (c) 2011, David Przybilla, Chris Umbel @@ -30960,7 +28734,7 @@ var words = [ // tell the world about the noise words. exports.words = words -},{}],148:[function(require,module,exports){ +},{}],143:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -31089,7 +28863,7 @@ Stream.prototype.pipe = function(dest, options) { return dest; }; -},{"events":37,"inherits":40,"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}],149:[function(require,module,exports){ +},{"events":34,"inherits":37,"readable-stream/duplex.js":86,"readable-stream/passthrough.js":95,"readable-stream/readable.js":96,"readable-stream/transform.js":97,"readable-stream/writable.js":98}],144:[function(require,module,exports){ module.exports = shift function shift (stream) { @@ -31111,7 +28885,7 @@ function getStateLength (state) { return state.length } -},{}],150:[function(require,module,exports){ +},{}],145:[function(require,module,exports){ 'use strict'; var Buffer = require('safe-buffer').Buffer; @@ -31384,7 +29158,7 @@ function simpleWrite(buf) { function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } -},{"safe-buffer":103}],151:[function(require,module,exports){ +},{"safe-buffer":99}],146:[function(require,module,exports){ exports.doubleNormalization0point5 = 'doubleNormalization0point5' exports.logNormalization = 'logNormalization' exports.raw = 'raw' @@ -31434,7 +29208,7 @@ exports.getTermFrequency = function (docVector, options) { } } -},{}],152:[function(require,module,exports){ +},{}],147:[function(require,module,exports){ /** * search-index module. * @module term-vector @@ -31500,7 +29274,7 @@ var getTermVectorForNgramLength = function (tokens, nGramLength) { return vector } -},{"lodash.isequal":76}],153:[function(require,module,exports){ +},{"lodash.isequal":73}],148:[function(require,module,exports){ (function (process){ var Stream = require('stream') @@ -31612,7 +29386,7 @@ function through (write, end, opts) { }).call(this,require('_process')) -},{"_process":86,"stream":148}],154:[function(require,module,exports){ +},{"_process":82,"stream":143}],149:[function(require,module,exports){ (function (Buffer){ /** * Convert a typed array to a Buffer without a copy @@ -31635,7 +29409,7 @@ module.exports = function (arr) { } }).call(this,require("buffer").Buffer) -},{"buffer":9}],155:[function(require,module,exports){ +},{"buffer":7}],150:[function(require,module,exports){ (function (global){ /** @@ -31706,16 +29480,16 @@ function config (name) { } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],156:[function(require,module,exports){ -arguments[4][40][0].apply(exports,arguments) -},{"dup":40}],157:[function(require,module,exports){ +},{}],151:[function(require,module,exports){ +arguments[4][37][0].apply(exports,arguments) +},{"dup":37}],152:[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'; } -},{}],158:[function(require,module,exports){ +},{}],153:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -32305,7 +30079,7 @@ function hasOwnProperty(obj, prop) { } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":157,"_process":86,"inherits":156}],159:[function(require,module,exports){ +},{"./support/isBuffer":152,"_process":82,"inherits":151}],154:[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. @@ -32340,7 +30114,7 @@ function wrappy (fn, cb) { } } -},{}],160:[function(require,module,exports){ +},{}],155:[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 d63fecf6..bcacf9cc 100644 --- a/dist/search-index.min.js +++ b/dist/search-index.min.js @@ -1 +1 @@ -!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).SearchIndex=f()}}(function(){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-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:153}],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="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/":158}],5:[function(require,module,exports){(function(process,global){!function(global,factory){factory("object"==typeof exports&&void 0!==module?exports: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)<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,1),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){var timer,timedOut=!1;args.push(function(){timedOut||(callback.apply(null,arguments),clearTimeout(timer))}),timer=setTimeout(function(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,callback(error)},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,setImmediate$1=wrap(_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback),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,nativeObjectToString$1=Object.prototype.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,Buffer=freeModule&&freeModule.exports===freeExports?root.Buffer:void 0,isBuffer=(Buffer?Buffer.isBuffer:void 0)||function(){return!1},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,freeProcess=freeModule$1&&freeModule$1.exports===freeExports$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):function(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]},hasOwnProperty$1=Object.prototype.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),hasOwnProperty$3=Object.prototype.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 numTasks=keys(tasks).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 counter=0;readyToCheck.length;)counter++,arrayEach(getDependents(readyToCheck.pop()),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])?",rsSeq="[\\ufe0e\\ufe0f]?"+reOptMod+("(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*"),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 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;i0?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},exports.fromByteArray=function(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,output="",parts=[],i=0,len2=len-extraBytes;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("")};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 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:128==(192&(secondByte=buf[i+1]))&&(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,"")).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=function(length){return+length!=length&&(length=0),Buffer.alloc(+length)},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){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;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.12",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:86,assert:4,events:37,fs:8,os:84,"safe-json-stringify":104,stream:148,util:158}],11:[function(require,module,exports){(function(Buffer){function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=function(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)},exports.isBoolean=function(arg){return"boolean"==typeof arg},exports.isNull=function(arg){return null===arg},exports.isNullOrUndefined=function(arg){return null==arg},exports.isNumber=function(arg){return"number"==typeof arg},exports.isString=function(arg){return"string"==typeof arg},exports.isSymbol=function(arg){return"symbol"==typeof arg},exports.isUndefined=function(arg){return void 0===arg},exports.isRegExp=function(re){return"[object RegExp]"===objectToString(re)},exports.isObject=function(arg){return"object"==typeof arg&&null!==arg},exports.isDate=function(d){return"[object Date]"===objectToString(d)},exports.isError=function(e){return"[object Error]"===objectToString(e)||e instanceof Error},exports.isFunction=function(arg){return"function"==typeof arg},exports.isPrimitive=function(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg},exports.isBuffer=Buffer.isBuffer}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":42}],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:158}],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":42,"./deferred-iterator":12,_process:86,"abstract-leveldown":17,util:158}],14:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._serializeKey=function(key){return this._db._serializeKey(key)},AbstractChainedBatch.prototype._serializeValue=function(value){return this._db._serializeValue(value)},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 key=this._serializeKey(key),value=this._serializeValue(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 key=this._serializeKey(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"))?callback(err):(key=this._serializeKey(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"))?callback(err):(key=this._serializeKey(key),value=this._serializeValue(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"))?callback(err):(key=this._serializeKey(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:148,util:158}],32:[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)writable&&writable.destroy&&writable.destroy();else if(null!==writable&&!1!==writable){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()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=function(){self._writable.removeListener("drain",ondrain),unend()},this.uncork()}else this.end()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)readable&&readable.destroy&&readable.destroy();else{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)};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=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()},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":33,inherits:40,"readable-stream":100,"stream-shift":149}],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:83}],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),len=(listeners=handler.slice()).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";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)this.onStoreReady();else if(this.db=event.target.result,"string"!=typeof this.db.version)if(this.db.objectStoreNames.contains(this.storeName)){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()}else this.onError(new Error("Object store couldn't be created."));else this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."))}.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&&(onError=onSuccess=options,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;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=function(err){batchTransaction.abort(),called||(called=!0,onError(err))}},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 getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=function(err){called=!0,result=err,onError(err),batchTransaction.abort()}},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))*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:148}],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){var Buffer=require("buffer").Buffer;module.exports=function(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}},{buffer:9}],45:[function(require,module,exports){!function(global){"use strict";var Logger={};Logger.VERSION="1.4.1";var logHandler,contextualLoggersByNameMap={},bind=function(scope,func){return function(){return func.apply(scope,arguments)}},merge=function(){var key,i,args=arguments,target=args[0];for(i=1;i=filterLevel.value},debug:function(){this.invoke(Logger.DEBUG,arguments)},info:function(){this.invoke(Logger.INFO,arguments)},warn:function(){this.invoke(Logger.WARN,arguments)},error:function(){this.invoke(Logger.ERROR,arguments)},time:function(label){"string"==typeof label&&label.length>0&&this.invoke(Logger.TIME,[label,"start"])},timeEnd:function(label){"string"==typeof label&&label.length>0&&this.invoke(Logger.TIME,[label,"end"])},invoke:function(level,msgArgs){logHandler&&this.enabledFor(level)&&logHandler(msgArgs,merge({level:level},this.context))}};var globalLogger=new ContextualLogger({filterLevel:Logger.OFF});!function(){var L=Logger;L.enabledFor=bind(globalLogger,globalLogger.enabledFor),L.debug=bind(globalLogger,globalLogger.debug),L.time=bind(globalLogger,globalLogger.time),L.timeEnd=bind(globalLogger,globalLogger.timeEnd),L.info=bind(globalLogger,globalLogger.info),L.warn=bind(globalLogger,globalLogger.warn),L.error=bind(globalLogger,globalLogger.error),L.log=L.info}(),Logger.setHandler=function(func){logHandler=func},Logger.setLevel=function(level){globalLogger.setLevel(level);for(var key in contextualLoggersByNameMap)contextualLoggersByNameMap.hasOwnProperty(key)&&contextualLoggersByNameMap[key].setLevel(level)},Logger.getLevel=function(){return globalLogger.getLevel()},Logger.get=function(name){return contextualLoggersByNameMap[name]||(contextualLoggersByNameMap[name]=new ContextualLogger(merge({name:name},globalLogger.context)))},Logger.createDefaultHandler=function(options){(options=options||{}).formatter=options.formatter||function(messages,context){context.name&&messages.unshift("["+context.name+"]")};var timerStartTimeByLabelMap={},invokeConsoleMethod=function(hdlr,messages){Function.prototype.apply.call(hdlr,console,messages)};return"undefined"==typeof console?function(){}:function(messages,context){messages=Array.prototype.slice.call(messages);var timerLabel,hdlr=console.log;context.level===Logger.TIME?(timerLabel=(context.name?"["+context.name+"] ":"")+messages[0],"start"===messages[1]?console.time?console.time(timerLabel):timerStartTimeByLabelMap[timerLabel]=(new Date).getTime():console.timeEnd?console.timeEnd(timerLabel):invokeConsoleMethod(hdlr,[timerLabel+": "+((new Date).getTime()-timerStartTimeByLabelMap[timerLabel])+"ms"])):(context.level===Logger.WARN&&console.warn?hdlr=console.warn:context.level===Logger.ERROR&&console.error?hdlr=console.error:context.level===Logger.INFO&&console.info?hdlr=console.info:context.level===Logger.DEBUG&&console.debug&&(hdlr=console.debug),options.formatter(messages,context),invokeConsoleMethod(hdlr,messages))}},Logger.useDefaults=function(options){Logger.setLevel(options&&options.defaultLevel||Logger.DEBUG),Logger.setHandler(Logger.createDefaultHandler(options))},void 0!==module&&module.exports?module.exports=Logger:(Logger._prevLogger=global.Logger,Logger.noConflict=function(){return global.Logger=Logger._prevLogger,Logger},global.Logger=Logger)}(this)},{}],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:function(data){return"string"==typeof data?data:String(data)},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.none={encode:identity,decode:identity,buffer:!1,type:"id"},exports.id=exports.none,["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:35}],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:40,"level-errors":49,"readable-stream":57,xtend:160}],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){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 endFn=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr?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);end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived);var end=(charStr+=buffer.toString(this.encoding,0,end)).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:158}],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){(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}],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){module.exports=function(source){return null!==source&&("object"==typeof source||"function"==typeof source)}},{}],70:[function(require,module,exports){var Keys=require("object-keys"),hasKeys=require("./has-keys");module.exports=function(){for(var target={},i=0;i-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};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=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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};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);++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)}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=function(){this.__data__=nativeCreate?nativeCreate(null):{},this.size=0},Hash.prototype.delete=function(key){var result=this.has(key)&&delete this.__data__[key];return this.size-=result?1:0,result},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){var data=this.__data__;return this.size+=this.has(key)?0:1,data[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[],this.size=0},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),--this.size,0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this},MapCache.prototype.clear=function(){this.size=0,this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){var result=getMapData(this,key).delete(key);return this.size-=result?1:0,result},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){var data=getMapData(this,key),size=data.size;return data.set(key,value),this.size+=data.size==size?0:1,this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)},Stack.prototype.clear=function(){this.__data__=new ListCache,this.size=0},Stack.prototype.delete=function(key){var data=this.__data__,result=data.delete(key);return this.size=data.size,result},Stack.prototype.get=function(key){return this.__data__.get(key)},Stack.prototype.has=function(key){return this.__data__.has(key)},Stack.prototype.set=function(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map||pairs.length>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computedlength?0:length+start),(end=end>length?length: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 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){return value?(value=toNumber(value))===INFINITY||value===-INFINITY?(value<0?-1:1)*MAX_INTEGER:value===value?value:0:0===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,objectToString=Object.prototype.toString,nativeMax=Math.max;module.exports=function(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)})}},{}],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;++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}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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:function(){},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=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},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:function(){};module.exports=function(array){return array&&array.length?baseUniq(array):[]}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],81:[function(require,module,exports){(function(Buffer){function has(obj,key){return Object.hasOwnProperty.call(obj,key)}function isDef(val){return void 0!==val&&""!==val}function has(range,name){return Object.hasOwnProperty.call(range,name)}function hasKey(range,name){return Object.hasOwnProperty.call(range,name)&&name}function id(e){return e}exports.compare=function(a,b){if(Buffer.isBuffer(a)){for(var l=Math.min(a.length,b.length),i=0;ib?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)&&((cmp=compare(key,lb))<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}],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:159}],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";!process.version||0===process.version.indexOf("v0.")||0===process.version.indexOf("v1.")&&0!==process.version.indexOf("v1.8.")?module.exports=function(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)}},{"end-of-stream":33,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:32,inherits:40,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||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(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)?(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 endFn=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr?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,OurUint8Array=global.Uint8Array||function(){},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"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./_stream_duplex":91,"./internal/streams/destroy":97,"./internal/streams/stream":98,_process:86,"core-util-is":11,inherits:40,"process-nextick-args":85,"safe-buffer":103,"util-deprecate":155}],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 emitErrorNT(self,err){self.emit("error",err)}var processNextTick=require("process-nextick-args");module.exports={destroy:function(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;readableDestroyed||writableDestroyed?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)}))},undestroy:function(){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)}}},{"process-nextick-args":85}],98:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:37}],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")).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 bunyan=require("bunyan"),levelup=require("levelup"),API=require("./lib/API.js");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){const api=API(options),Indexer={};return Indexer.options=options,Indexer.add=api.add,Indexer.concurrentAdd=api.concurrentAdd,Indexer.concurrentDel=api.concurrentDel,Indexer.close=api.close,Indexer.dbWriteStream=api.dbWriteStream,Indexer.defaultPipeline=api.defaultPipeline,Indexer.deleteStream=api.deleteStream,Indexer.deleter=api.deleter,Indexer.feed=api.feed,Indexer.flush=api.flush,callback(err,Indexer)})};const getOptions=function(options,done){if(options=Object.assign({},{appendOnly:!1,deletable:!0,batchSize:1e3,compositeField:!0,fastSort:!0,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,storeDocument:!0,storeVector:!0,searchable:!0,indexPath:"si",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/\s|\\n|\\u0003|[-.,<>]/,stopwords:[],weight:0,wildcard:!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/API.js":106,bunyan:10,leveldown:59,levelup:72}],106:[function(require,module,exports){const DBEntries=require("./delete.js").DBEntries,DBWriteCleanStream=require("./replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./replicate.js").DBWriteMergeStream,DocVector=require("./delete.js").DocVector,JSONStream=require("JSONStream"),Readable=require("stream").Readable,RecalibrateDB=require("./delete.js").RecalibrateDB,IndexBatch=require("./add.js").IndexBatch,async=require("async"),del=require("./delete.js"),docProc=require("docproc"),pumpify=require("pumpify");module.exports=function(options){const 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),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={};return Indexer.add=function(ops){const thisOps=Object.assign(options,ops);return pumpify.obj(new IndexBatch(deleter,thisOps),new DBWriteMergeStream(thisOps))},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)).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=deleter,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)})},Indexer}},{"./add.js":107,"./delete.js":108,"./replicate.js":109,JSONStream:3,async:5,docproc:19,pumpify:89,stream:148}],107:[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={}},noop=function(_,cb){cb()},IndexBatch=function(deleter,options){this.batchSize=options.batchSize||1e3,this.deleter=deleter,this.fastSort=options.fastSort,this.appendOnly=options.appendOnly,this.keySeparator=options.keySeparator||"○",this.log=options.log,this.storeDocument=options.storeDocument,this.storeVector=options.storeVector,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.keySeparator,that=this;(this.appendOnly?noop:this.deleter.bind(this.indexer))([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.log.info("processing doc "+ingestedDoc.id),!0===that.storeDocument&&(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]){if(that.fastSort){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id])}var dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.storeVector&&(that.deltaIndex["DOCUMENT-VECTOR"+sep+fieldName+sep+ingestedDoc.id+sep]=ingestedDoc.vector[fieldName])}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.batchSize&&(that.push({totalKeys:totalKeys}),that.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:148,util:158}],108:[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,docKey="DOCUMENT"+sep+docId+sep;this.options.indexes.get(docKey,function(err,val){if(err)return end();var docFields=Object.keys(val);docFields.push("*"),docFields=docFields.map(function(item){return"DOCUMENT-VECTOR"+sep+item+sep+docId+sep});var i=0,pushValue=function(key){if(void 0===key)return that.push({key:"DOCUMENT"+sep+docId+sep,lastPass:!0}),end();that.options.indexes.get(key,function(err,val){err||that.push({key:key,value:val}),pushValue(docFields[i++])})};pushValue(docFields[0])})};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){if(!0===vector.lastPass)return this.push({key:vector.key}),end();const sep=this.options.keySeparator;var that=this,field=vector.key.split(sep)[1],docId=vector.key.split(sep)[2],vectorKeys=Object.keys(vector.value),i=0,pushRecalibrationvalues=function(vec){if(that.push({key:"TF"+sep+field+sep+vectorKeys[i],value:docId}),that.push({key:"DF"+sep+field+sep+vectorKeys[i],value:docId}),++i===vectorKeys.length)return that.push({key:vector.key}),end();pushRecalibrationvalues(vector[vectorKeys[i]])};pushRecalibrationvalues(vector[vectorKeys[0]])};const RecalibrateDB=function(options){this.options=options,this.batch=[],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={};return 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",that.batch.push(dbInstruction),end()):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",that.batch.push(dbInstruction),end()):dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep?(dbInstruction.type="del",that.batch.push(dbInstruction),end()):void(dbEntry.key.substring(0,9)==="DOCUMENT"+sep&&(dbInstruction.type="del",that.batch.push(dbInstruction),that.options.indexes.batch(that.batch,function(err){return that.batch=[],end()})))})}},{stream:148,util:158}],109:[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:148,util:158}],110:[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,MergeOrConditionsTFIDF=require("./lib/MergeOrConditionsTFIDF.js").MergeOrConditionsTFIDF,MergeOrConditionsFieldSort=require("./lib/MergeOrConditionsFieldSort.js").MergeOrConditionsFieldSort,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,bunyan=require("bunyan"),levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),sw=require("stopword"),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 ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditionsFieldSort(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 MergeOrConditionsTFIDF(q.offset,q.pageSize)).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:sw.en},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":111,"./lib/CalculateBuckets.js":112,"./lib/CalculateCategories.js":113,"./lib/CalculateEntireResultSet.js":114,"./lib/CalculateResultSetPerClause.js":115,"./lib/CalculateTopScoringDocs.js":116,"./lib/CalculateTotalHits.js":117,"./lib/Classify.js":118,"./lib/FetchDocsFromDB.js":119,"./lib/FetchStoredDoc.js":120,"./lib/GetIntersectionStream.js":121,"./lib/MergeOrConditionsFieldSort.js":122,"./lib/MergeOrConditionsTFIDF.js":123,"./lib/ScoreDocsOnField.js":124,"./lib/ScoreTopScoringDocsTFIDF.js":125,"./lib/matcher.js":126,"./lib/siUtil.js":127,bunyan:10,levelup:72,stopword:128,stream:148}],111:[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:148,util:158}],112:[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:148,util:158}],113:[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:148,util:158}],114:[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:148,util:158}],115:[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){var include=_spread(_intersection)(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,documentFrequencies:frequencies,WEIGHT:queryClause.WEIGHT||1}),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;i({id:id,scoringCriteria:resultMap[id],score:resultMap[id][0].score})).sort((a,b)=>b.score===a.score?a.idb.id?-1:0:"asc"===that.sortDirection?b.scorea.score).slice(this.offset,this.offset+this.pageSize).forEach(doc=>{that.push(doc)}),end()};const getResultMap=resultSet=>{var resultMap={};return resultSet.forEach(docMatch=>{resultMap[docMatch.id]=resultMap[docMatch.id]||[],resultMap[docMatch.id].push(docMatch),delete docMatch.id}),resultMap}},{stream:148,util:158}],123:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),MergeOrConditionsTFIDF=function(offset,pageSize){this.resultSet=[],this.offset=offset,this.pageSize=pageSize,Transform.call(this,{objectMode:!0})};exports.MergeOrConditionsTFIDF=MergeOrConditionsTFIDF,util.inherits(MergeOrConditionsTFIDF,Transform),MergeOrConditionsTFIDF.prototype._transform=function(doc,encoding,end){return this.resultSet=this.resultSet.concat(doc.matches),end()},MergeOrConditionsTFIDF.prototype._flush=function(end){var that=this,resultMap=getResultMap(this.resultSet);return Object.keys(resultMap).map(id=>({id:id,scoringCriteria:resultMap[id],score:resultMap[id].reduce((sum,matches)=>sum+matches.score,0)/resultMap[id].length})).sort((a,b)=>b.score===a.score?a.idb.id?-1:0:b.score-a.score).slice(this.offset,this.offset+this.pageSize).forEach(doc=>{that.push(doc)}),end()};const getResultMap=resultSet=>{var resultMap={};return resultSet.forEach(docMatch=>{resultMap[docMatch.id]=resultMap[docMatch.id]||[],resultMap[docMatch.id].push(docMatch),delete docMatch.id}),resultMap}},{stream:148,util:158}],124:[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,sortDirection=this.sort.direction||"asc";var tally=0,rangeOptions={gte:"DF"+sep+this.sort.field+sep,lte:"DF"+sep+this.sort.field+sep+sep};"desc"===sortDirection&&(rangeOptions.reverse=!0),clauseSet.topScoringDocs=[],that.options.indexes.createReadStream(rangeOptions).on("data",function(data){var token=data.key.split(sep)[2];"*"!==token&&("desc"===sortDirection&&(data.value=data.value.reverse()),data.value.some(id=>{if(-1!==_sortedIndexOf(clauseSet.set,id)&&(clauseSet.topScoringDocs.push({id:id,score:token}),++tally===that.seekLimit))return!0}))}).on("end",function(){return that.push(clauseSet),end()})}},{"lodash.sortedindexof":77,stream:148,util:158}],125:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),ScoreTopScoringDocsTFIDF=function(options,offset,pageSize){this.options=options,Transform.call(this,{objectMode:!0})};exports.ScoreTopScoringDocsTFIDF=ScoreTopScoringDocsTFIDF,util.inherits(ScoreTopScoringDocsTFIDF,Transform),ScoreTopScoringDocsTFIDF.prototype._transform=function(clause,encoding,end){var that=this,promises=[];clause.topScoringDocs.forEach(doc=>{var docID=doc[1];promises.push(getMatchesForDoc(docID,that.options,clause))}),Promise.all(promises).then(res=>(clause.matches=res,that.push(clause),end()),err=>{console.log(err)})};const getMatchesForDoc=(docID,options,clause)=>new Promise((resolve,reject)=>{var termVectors=clause.documentFrequencies.map(freq=>gett(freq.field,docID,freq.gte,freq.lte,freq.df,clause.WEIGHT,options));Promise.all(termVectors).then(matchedTerms=>{var matches=[].concat.apply([],matchedTerms);resolve({id:docID,matches:matches,score:getScore(matches)})},err=>{console.log(err)})}),getScore=matchedTerms=>matchedTerms.reduce(function(sum,match){return sum+match.score},0)/matchedTerms.length,gett=(field,key,gte,lte,df,weight,options)=>{var s=options.keySeparator;return new Promise((resolve,reject)=>{options.indexes.get("DOCUMENT-VECTOR"+s+field+s+key+s,(err,value)=>{if(err)return reject(err);var matchedTermsWithMagnitude=[];return Object.keys(value).filter(t=>{if(t>=gte&&t<=lte)return!0}).forEach(t=>{var tf=value[t],tfidf=tf*Math.log10(1+1/df),term={field:field,term:t,tf:tf,df:df,tfidf:tfidf,weight:weight,score:tfidf*weight};matchedTermsWithMagnitude.push(term)}),resolve(matchedTermsWithMagnitude)})})}},{stream:148,util:158}],126:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatchMostFrequent=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatchMostFrequent,Transform),MatchMostFrequent.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){var frequencySort=b.value.length-a.value.length;return 0===frequencySort?b.keya.key?-1:0:frequencySort}).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()})};const MatchAlphabetical=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatchAlphabetical,Transform),MatchAlphabetical.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var space={start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep},i=0,rs=this.options.indexes.createReadStream(space);rs.on("data",function(data){var m={};switch(q.type){case"ID":m={token:data.key.split(sep)[2],documents:data.value};break;case"count":m={token:data.key.split(sep)[2],documentCount:data.value.length};break;default:m=data.key.split(sep)[2]}if(that.push(m),++i===q.limit)return rs.destroy(),end()}),rs.on("error",function(err){that.options.log.error("Oh my!",err)}),rs.on("end",function(){return end()})},exports.match=function(q,options){var s=new Readable({objectMode:!0});return(q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple",sort:"frequency"},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 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(1===(ngrams=ngrams.sort()).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:"")+"]"),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)).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 isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==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 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:82,buffer:7,jsonparse:43,through:148}],4:[function(require,module,exports){(function(process,global){!function(global,factory){factory("object"==typeof exports&&void 0!==module?exports: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)<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,1),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){var timer,timedOut=!1;args.push(function(){timedOut||(callback.apply(null,arguments),clearTimeout(timer))}),timer=setTimeout(function(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,callback(error)},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,setImmediate$1=wrap(_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback),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,nativeObjectToString$1=Object.prototype.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,Buffer=freeModule&&freeModule.exports===freeExports?root.Buffer:void 0,isBuffer=(Buffer?Buffer.isBuffer:void 0)||function(){return!1},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,freeProcess=freeModule$1&&freeModule$1.exports===freeExports$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):function(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]},hasOwnProperty$1=Object.prototype.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),hasOwnProperty$3=Object.prototype.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 numTasks=keys(tasks).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 counter=0;readyToCheck.length;)counter++,arrayEach(getDependents(readyToCheck.pop()),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])?",rsSeq="[\\ufe0e\\ufe0f]?"+reOptMod+("(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*"),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 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;i0?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},exports.fromByteArray=function(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,output="",parts=[],i=0,len2=len-extraBytes;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("")};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 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:128==(192&(secondByte=buf[i+1]))&&(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,"")).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=function(length){return+length!=length&&(length=0),Buffer.alloc(+length)},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){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<.,\-|]+|\\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:143,util:153}],29:[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)writable&&writable.destroy&&writable.destroy();else if(null!==writable&&!1!==writable){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()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=function(){self._writable.removeListener("drain",ondrain),unend()},this.uncork()}else this.end()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)readable&&readable.destroy&&readable.destroy();else{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)};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=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()},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:82,buffer:7,"end-of-stream":30,inherits:37,"readable-stream":96,"stream-shift":144}],30:[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:80}],31:[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:33}],32:[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":31}],33:[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)}})},{}],34:[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),len=(listeners=handler.slice()).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)}},{}],35:[function(require,module,exports){!function(name,definition,global){"use strict";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)this.onStoreReady();else if(this.db=event.target.result,"string"!=typeof this.db.version)if(this.db.objectStoreNames.contains(this.storeName)){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()}else this.onError(new Error("Object store couldn't be created."));else this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."))}.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&&(onError=onSuccess=options,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;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=function(err){batchTransaction.abort(),called||(called=!0,onError(err))}},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 getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=function(err){called=!0,result=err,onError(err),batchTransaction.abort()}},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))*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}},{}],37:[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}},{}],38:[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:143}],39:[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)}},{}],40:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},{}],41:[function(require,module,exports){var Buffer=require("buffer").Buffer;module.exports=function(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}},{buffer:7}],42:[function(require,module,exports){!function(global){"use strict";var Logger={};Logger.VERSION="1.4.1";var logHandler,contextualLoggersByNameMap={},bind=function(scope,func){return function(){return func.apply(scope,arguments)}},merge=function(){var key,i,args=arguments,target=args[0];for(i=1;i=filterLevel.value},debug:function(){this.invoke(Logger.DEBUG,arguments)},info:function(){this.invoke(Logger.INFO,arguments)},warn:function(){this.invoke(Logger.WARN,arguments)},error:function(){this.invoke(Logger.ERROR,arguments)},time:function(label){"string"==typeof label&&label.length>0&&this.invoke(Logger.TIME,[label,"start"])},timeEnd:function(label){"string"==typeof label&&label.length>0&&this.invoke(Logger.TIME,[label,"end"])},invoke:function(level,msgArgs){logHandler&&this.enabledFor(level)&&logHandler(msgArgs,merge({level:level},this.context))}};var globalLogger=new ContextualLogger({filterLevel:Logger.OFF});!function(){var L=Logger;L.enabledFor=bind(globalLogger,globalLogger.enabledFor),L.debug=bind(globalLogger,globalLogger.debug),L.time=bind(globalLogger,globalLogger.time),L.timeEnd=bind(globalLogger,globalLogger.timeEnd),L.info=bind(globalLogger,globalLogger.info),L.warn=bind(globalLogger,globalLogger.warn),L.error=bind(globalLogger,globalLogger.error),L.log=L.info}(),Logger.setHandler=function(func){logHandler=func},Logger.setLevel=function(level){globalLogger.setLevel(level);for(var key in contextualLoggersByNameMap)contextualLoggersByNameMap.hasOwnProperty(key)&&contextualLoggersByNameMap[key].setLevel(level)},Logger.getLevel=function(){return globalLogger.getLevel()},Logger.get=function(name){return contextualLoggersByNameMap[name]||(contextualLoggersByNameMap[name]=new ContextualLogger(merge({name:name},globalLogger.context)))},Logger.createDefaultHandler=function(options){(options=options||{}).formatter=options.formatter||function(messages,context){context.name&&messages.unshift("["+context.name+"]")};var timerStartTimeByLabelMap={},invokeConsoleMethod=function(hdlr,messages){Function.prototype.apply.call(hdlr,console,messages)};return"undefined"==typeof console?function(){}:function(messages,context){messages=Array.prototype.slice.call(messages);var timerLabel,hdlr=console.log;context.level===Logger.TIME?(timerLabel=(context.name?"["+context.name+"] ":"")+messages[0],"start"===messages[1]?console.time?console.time(timerLabel):timerStartTimeByLabelMap[timerLabel]=(new Date).getTime():console.timeEnd?console.timeEnd(timerLabel):invokeConsoleMethod(hdlr,[timerLabel+": "+((new Date).getTime()-timerStartTimeByLabelMap[timerLabel])+"ms"])):(context.level===Logger.WARN&&console.warn?hdlr=console.warn:context.level===Logger.ERROR&&console.error?hdlr=console.error:context.level===Logger.INFO&&console.info?hdlr=console.info:context.level===Logger.DEBUG&&console.debug&&(hdlr=console.debug),options.formatter(messages,context),invokeConsoleMethod(hdlr,messages))}},Logger.useDefaults=function(options){Logger.setLevel(options&&options.defaultLevel||Logger.DEBUG),Logger.setHandler(Logger.createDefaultHandler(options))},void 0!==module&&module.exports?module.exports=Logger:(Logger._prevLogger=global.Logger,Logger.noConflict=function(){return global.Logger=Logger._prevLogger,Logger},global.Logger=Logger)}(this)},{}],43:[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:7}],44:[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":45}],45:[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:function(data){return"string"==typeof data?data:String(data)},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.none={encode:identity,decode:identity,buffer:!1,type:"id"},exports.id=exports.none,["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:7}],46:[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:32}],47:[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:37,"level-errors":46,"readable-stream":54,xtend:155}],48:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],49:[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){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 endFn=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr?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);end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived);var end=(charStr+=buffer.toString(this.encoding,0,end)).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:7}],56:[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":60,ltgt:78,util:153}],58:[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:82}],59:[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:82}],60:[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}},{}],65:[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":62,"./isArguments":64}],66:[function(require,module,exports){module.exports=function(source){return null!==source&&("object"==typeof source||"function"==typeof source)}},{}],67:[function(require,module,exports){var Keys=require("object-keys"),hasKeys=require("./has-keys");module.exports=function(){for(var target={},i=0;i-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};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=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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};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);++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)}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=function(){this.__data__=nativeCreate?nativeCreate(null):{},this.size=0},Hash.prototype.delete=function(key){var result=this.has(key)&&delete this.__data__[key];return this.size-=result?1:0,result},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){var data=this.__data__;return this.size+=this.has(key)?0:1,data[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[],this.size=0},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),--this.size,0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this},MapCache.prototype.clear=function(){this.size=0,this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){var result=getMapData(this,key).delete(key);return this.size-=result?1:0,result},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){var data=getMapData(this,key),size=data.size;return data.set(key,value),this.size+=data.size==size?0:1,this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)},Stack.prototype.clear=function(){this.__data__=new ListCache,this.size=0},Stack.prototype.delete=function(key){var data=this.__data__,result=data.delete(key);return this.size=data.size,result},Stack.prototype.get=function(key){return this.__data__.get(key)},Stack.prototype.has=function(key){return this.__data__.has(key)},Stack.prototype.set=function(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map||pairs.length>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computedlength?0:length+start),(end=end>length?length: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 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){return value?(value=toNumber(value))===INFINITY||value===-INFINITY?(value<0?-1:1)*MAX_INTEGER:value===value?value:0:0===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,objectToString=Object.prototype.toString,nativeMax=Math.max;module.exports=function(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)})}},{}],76:[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;++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}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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:function(){},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=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},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:function(){};module.exports=function(array){return array&&array.length?baseUniq(array):[]}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],78:[function(require,module,exports){(function(Buffer){function has(obj,key){return Object.hasOwnProperty.call(obj,key)}function isDef(val){return void 0!==val&&""!==val}function has(range,name){return Object.hasOwnProperty.call(range,name)}function hasKey(range,name){return Object.hasOwnProperty.call(range,name)&&name}function id(e){return e}exports.compare=function(a,b){if(Buffer.isBuffer(a)){for(var l=Math.min(a.length,b.length),i=0;ib?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)&&((cmp=compare(key,lb))<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":39}],79:[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)}}},{}],80:[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:154}],81:[function(require,module,exports){(function(process){"use strict";!process.version||0===process.version.indexOf("v0.")||0===process.version.indexOf("v1.")&&0!==process.version.indexOf("v1.8.")?module.exports=function(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)}},{"end-of-stream":30,fs:6,once:80}],85:[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:29,inherits:37,pump:84}],86:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":87}],87:[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||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(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)?(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 endFn=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr?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,OurUint8Array=global.Uint8Array||function(){},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"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./_stream_duplex":87,"./internal/streams/destroy":93,"./internal/streams/stream":94,_process:82,"core-util-is":8,inherits:37,"process-nextick-args":81,"safe-buffer":99,"util-deprecate":150}],92:[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":99}],93:[function(require,module,exports){"use strict";function emitErrorNT(self,err){self.emit("error",err)}var processNextTick=require("process-nextick-args");module.exports={destroy:function(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;readableDestroyed||writableDestroyed?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)}))},undestroy:function(){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)}}},{"process-nextick-args":81}],94:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:34}],95:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":96}],96:[function(require,module,exports){(exports=module.exports=require("./lib/_stream_readable.js")).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":87,"./lib/_stream_passthrough.js":88,"./lib/_stream_readable.js":89,"./lib/_stream_transform.js":90,"./lib/_stream_writable.js":91}],97:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":96}],98:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":91}],99:[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:7}],100:[function(require,module,exports){const Logger=require("js-logger"),levelup=require("levelup"),API=require("./lib/API.js");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){const api=API(options),Indexer={};return Indexer.options=options,Indexer.add=api.add,Indexer.concurrentAdd=api.concurrentAdd,Indexer.concurrentDel=api.concurrentDel,Indexer.close=api.close,Indexer.dbWriteStream=api.dbWriteStream,Indexer.defaultPipeline=api.defaultPipeline,Indexer.deleteStream=api.deleteStream,Indexer.deleter=api.deleter,Indexer.feed=api.feed,Indexer.flush=api.flush,callback(err,Indexer)})};const getOptions=function(options,done){if(options=Object.assign({},{appendOnly:!1,deletable:!0,batchSize:1e3,compositeField:!0,fastSort:!0,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,storeDocument:!0,storeVector:!0,searchable:!0,indexPath:"si",logLevel:"ERROR",logHandler:Logger.createDefaultHandler(),nGramLength:1,nGramSeparator:" ",separator:/\s|\\n|\\u0003|[-.,<>]/,stopwords:[],weight:0,wildcard:!0},options),options.log=Logger.get("search-index-adder"),options.log.setLevel(Logger[options.logLevel.toUpperCase()]),Logger.setHandler(options.logHandler),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/API.js":101,"js-logger":42,leveldown:56,levelup:69}],101:[function(require,module,exports){const DBEntries=require("./delete.js").DBEntries,DBWriteCleanStream=require("./replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./replicate.js").DBWriteMergeStream,DocVector=require("./delete.js").DocVector,JSONStream=require("JSONStream"),Readable=require("stream").Readable,RecalibrateDB=require("./delete.js").RecalibrateDB,IndexBatch=require("./add.js").IndexBatch,async=require("async"),del=require("./delete.js"),docProc=require("docproc"),pumpify=require("pumpify");module.exports=function(options){const 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),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={};return Indexer.add=function(ops){const thisOps=Object.assign(options,ops);return pumpify.obj(new IndexBatch(deleter,thisOps),new DBWriteMergeStream(thisOps))},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)).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=deleter,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)})},Indexer}},{"./add.js":102,"./delete.js":103,"./replicate.js":104,JSONStream:3,async:4,docproc:16,pumpify:85,stream:143}],102:[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={}},noop=function(_,cb){cb()},IndexBatch=function(deleter,options){this.batchSize=options.batchSize||1e3,this.deleter=deleter,this.fastSort=options.fastSort,this.appendOnly=options.appendOnly,this.keySeparator=options.keySeparator||"○",this.log=options.log,this.storeDocument=options.storeDocument,this.storeVector=options.storeVector,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.keySeparator,that=this;(this.appendOnly?noop:this.deleter.bind(this.indexer))([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.log.info("processing doc "+ingestedDoc.id),!0===that.storeDocument&&(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]){if(that.fastSort){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id])}var dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.storeVector&&(that.deltaIndex["DOCUMENT-VECTOR"+sep+fieldName+sep+ingestedDoc.id+sep]=ingestedDoc.vector[fieldName])}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.batchSize&&(that.push({totalKeys:totalKeys}),that.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:143,util:153}],103:[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,docKey="DOCUMENT"+sep+docId+sep;this.options.indexes.get(docKey,function(err,val){if(err)return end();var docFields=Object.keys(val);docFields.push("*"),docFields=docFields.map(function(item){return"DOCUMENT-VECTOR"+sep+item+sep+docId+sep});var i=0,pushValue=function(key){if(void 0===key)return that.push({key:"DOCUMENT"+sep+docId+sep,lastPass:!0}),end();that.options.indexes.get(key,function(err,val){err||that.push({key:key,value:val}),pushValue(docFields[i++])})};pushValue(docFields[0])})};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){if(!0===vector.lastPass)return this.push({key:vector.key}),end();const sep=this.options.keySeparator;var that=this,field=vector.key.split(sep)[1],docId=vector.key.split(sep)[2],vectorKeys=Object.keys(vector.value),i=0,pushRecalibrationvalues=function(vec){if(that.push({key:"TF"+sep+field+sep+vectorKeys[i],value:docId}),that.push({key:"DF"+sep+field+sep+vectorKeys[i],value:docId}),++i===vectorKeys.length)return that.push({key:vector.key}),end();pushRecalibrationvalues(vector[vectorKeys[i]])};pushRecalibrationvalues(vector[vectorKeys[0]])};const RecalibrateDB=function(options){this.options=options,this.batch=[],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={};return 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",that.batch.push(dbInstruction),end()):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",that.batch.push(dbInstruction),end()):dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep?(dbInstruction.type="del",that.batch.push(dbInstruction),end()):void(dbEntry.key.substring(0,9)==="DOCUMENT"+sep&&(dbInstruction.type="del",that.batch.push(dbInstruction),that.options.indexes.batch(that.batch,function(err){return that.batch=[],end()})))})}},{stream:143,util:153}],104:[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:143,util:153}],105:[function(require,module,exports){const Logger=require("js-logger"),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,MergeOrConditionsTFIDF=require("./lib/MergeOrConditionsTFIDF.js").MergeOrConditionsTFIDF,MergeOrConditionsFieldSort=require("./lib/MergeOrConditionsFieldSort.js").MergeOrConditionsFieldSort,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),sw=require("stopword"),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 ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditionsFieldSort(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 MergeOrConditionsTFIDF(q.offset,q.pageSize)).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",logHandler:Logger.createDefaultHandler(),nGramLength:1,nGramSeparator:" ",separator:/[|' .,\-|(\n)]+/,stopwords:sw.en},options),Searcher.options.log=Logger.get("search-index-searcher"),Searcher.options.log.setLevel(Logger[Searcher.options.logLevel.toUpperCase()]),Logger.setHandler(Searcher.options.logHandler),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":106,"./lib/CalculateBuckets.js":107,"./lib/CalculateCategories.js":108,"./lib/CalculateEntireResultSet.js":109,"./lib/CalculateResultSetPerClause.js":110,"./lib/CalculateTopScoringDocs.js":111,"./lib/CalculateTotalHits.js":112,"./lib/Classify.js":113,"./lib/FetchDocsFromDB.js":114,"./lib/FetchStoredDoc.js":115,"./lib/GetIntersectionStream.js":116,"./lib/MergeOrConditionsFieldSort.js":117,"./lib/MergeOrConditionsTFIDF.js":118,"./lib/ScoreDocsOnField.js":119,"./lib/ScoreTopScoringDocsTFIDF.js":120,"./lib/matcher.js":121,"./lib/siUtil.js":122,"js-logger":42,levelup:69,stopword:123,stream:143}],106:[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:143,util:153}],107:[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":72,"lodash.uniq":77,stream:143,util:153}],108:[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":72,stream:143,util:153}],109:[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":76,stream:143,util:153}],110:[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){var include=_spread(_intersection)(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,documentFrequencies:frequencies,WEIGHT:queryClause.WEIGHT||1}),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;i({id:id,scoringCriteria:resultMap[id],score:resultMap[id][0].score})).sort((a,b)=>b.score===a.score?a.idb.id?-1:0:"asc"===that.sortDirection?b.scorea.score).slice(this.offset,this.offset+this.pageSize).forEach(doc=>{that.push(doc)}),end()};const getResultMap=resultSet=>{var resultMap={};return resultSet.forEach(docMatch=>{resultMap[docMatch.id]=resultMap[docMatch.id]||[],resultMap[docMatch.id].push(docMatch),delete docMatch.id}),resultMap}},{stream:143,util:153}],118:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),MergeOrConditionsTFIDF=function(offset,pageSize){this.resultSet=[],this.offset=offset,this.pageSize=pageSize,Transform.call(this,{objectMode:!0})};exports.MergeOrConditionsTFIDF=MergeOrConditionsTFIDF,util.inherits(MergeOrConditionsTFIDF,Transform),MergeOrConditionsTFIDF.prototype._transform=function(doc,encoding,end){return this.resultSet=this.resultSet.concat(doc.matches),end()},MergeOrConditionsTFIDF.prototype._flush=function(end){var that=this,resultMap=getResultMap(this.resultSet);return Object.keys(resultMap).map(id=>({id:id,scoringCriteria:resultMap[id],score:resultMap[id].reduce((sum,matches)=>sum+matches.score,0)/resultMap[id].length})).sort((a,b)=>b.score===a.score?a.idb.id?-1:0:b.score-a.score).slice(this.offset,this.offset+this.pageSize).forEach(doc=>{that.push(doc)}),end()};const getResultMap=resultSet=>{var resultMap={};return resultSet.forEach(docMatch=>{resultMap[docMatch.id]=resultMap[docMatch.id]||[],resultMap[docMatch.id].push(docMatch),delete docMatch.id}),resultMap}},{stream:143,util:153}],119:[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,sortDirection=this.sort.direction||"asc";var tally=0,rangeOptions={gte:"DF"+sep+this.sort.field+sep,lte:"DF"+sep+this.sort.field+sep+sep};"desc"===sortDirection&&(rangeOptions.reverse=!0),clauseSet.topScoringDocs=[],that.options.indexes.createReadStream(rangeOptions).on("data",function(data){var token=data.key.split(sep)[2];"*"!==token&&("desc"===sortDirection&&(data.value=data.value.reverse()),data.value.some(id=>{if(-1!==_sortedIndexOf(clauseSet.set,id)&&(clauseSet.topScoringDocs.push({id:id,score:token}),++tally===that.seekLimit))return!0}))}).on("end",function(){return that.push(clauseSet),end()})}},{"lodash.sortedindexof":74,stream:143,util:153}],120:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),ScoreTopScoringDocsTFIDF=function(options,offset,pageSize){this.options=options,Transform.call(this,{objectMode:!0})};exports.ScoreTopScoringDocsTFIDF=ScoreTopScoringDocsTFIDF,util.inherits(ScoreTopScoringDocsTFIDF,Transform),ScoreTopScoringDocsTFIDF.prototype._transform=function(clause,encoding,end){var that=this,promises=[];clause.topScoringDocs.forEach(doc=>{var docID=doc[1];promises.push(getMatchesForDoc(docID,that.options,clause))}),Promise.all(promises).then(res=>(clause.matches=res,that.push(clause),end()),err=>{console.log(err)})};const getMatchesForDoc=(docID,options,clause)=>new Promise((resolve,reject)=>{var termVectors=clause.documentFrequencies.map(freq=>gett(freq.field,docID,freq.gte,freq.lte,freq.df,clause.WEIGHT,options));Promise.all(termVectors).then(matchedTerms=>{var matches=[].concat.apply([],matchedTerms);resolve({id:docID,matches:matches,score:getScore(matches)})},err=>{console.log(err)})}),getScore=matchedTerms=>matchedTerms.reduce(function(sum,match){return sum+match.score},0)/matchedTerms.length,gett=(field,key,gte,lte,df,weight,options)=>{var s=options.keySeparator;return new Promise((resolve,reject)=>{options.indexes.get("DOCUMENT-VECTOR"+s+field+s+key+s,(err,value)=>{if(err)return reject(err);var matchedTermsWithMagnitude=[];return Object.keys(value).filter(t=>{if(t>=gte&&t<=lte)return!0}).forEach(t=>{var tf=value[t],tfidf=tf*Math.log10(1+1/df),term={field:field,term:t,tf:tf,df:df,tfidf:tfidf,weight:weight,score:tfidf*weight};matchedTermsWithMagnitude.push(term)}),resolve(matchedTermsWithMagnitude)})})}},{stream:143,util:153}],121:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatchMostFrequent=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatchMostFrequent,Transform),MatchMostFrequent.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){var frequencySort=b.value.length-a.value.length;return 0===frequencySort?b.keya.key?-1:0:frequencySort}).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()})};const MatchAlphabetical=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatchAlphabetical,Transform),MatchAlphabetical.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var space={start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep},i=0,rs=this.options.indexes.createReadStream(space);rs.on("data",function(data){var m={};switch(q.type){case"ID":m={token:data.key.split(sep)[2],documents:data.value};break;case"count":m={token:data.key.split(sep)[2],documentCount:data.value.length};break;default:m=data.key.split(sep)[2]}if(that.push(m),++i===q.limit)return rs.destroy(),end()}),rs.on("error",function(err){that.options.log.error("Oh my!",err)}),rs.on("end",function(){return end()})},exports.match=function(q,options){var s=new Readable({objectMode:!0});return(q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple",sort:"frequency"},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 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(1===(ngrams=ngrams.sort()).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:"")+"]"),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)).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 isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==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 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:153}],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="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/":158}],5:[function(require,module,exports){(function(process,global){!function(global,factory){factory("object"==typeof exports&&void 0!==module?exports: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)<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,1),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){var timer,timedOut=!1;args.push(function(){timedOut||(callback.apply(null,arguments),clearTimeout(timer))}),timer=setTimeout(function(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,callback(error)},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,setImmediate$1=wrap(_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback),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,nativeObjectToString$1=Object.prototype.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,Buffer=freeModule&&freeModule.exports===freeExports?root.Buffer:void 0,isBuffer=(Buffer?Buffer.isBuffer:void 0)||function(){return!1},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,freeProcess=freeModule$1&&freeModule$1.exports===freeExports$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):function(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]},hasOwnProperty$1=Object.prototype.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),hasOwnProperty$3=Object.prototype.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 numTasks=keys(tasks).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 counter=0;readyToCheck.length;)counter++,arrayEach(getDependents(readyToCheck.pop()),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])?",rsSeq="[\\ufe0e\\ufe0f]?"+reOptMod+("(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*"),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 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;i0?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},exports.fromByteArray=function(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,output="",parts=[],i=0,len2=len-extraBytes;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("")};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 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:128==(192&(secondByte=buf[i+1]))&&(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,"")).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=function(length){return+length!=length&&(length=0),Buffer.alloc(+length)},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){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;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.12",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:86,assert:4,events:37,fs:8,os:84,"safe-json-stringify":104,stream:148,util:158}],11:[function(require,module,exports){(function(Buffer){function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=function(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)},exports.isBoolean=function(arg){return"boolean"==typeof arg},exports.isNull=function(arg){return null===arg},exports.isNullOrUndefined=function(arg){return null==arg},exports.isNumber=function(arg){return"number"==typeof arg},exports.isString=function(arg){return"string"==typeof arg},exports.isSymbol=function(arg){return"symbol"==typeof arg},exports.isUndefined=function(arg){return void 0===arg},exports.isRegExp=function(re){return"[object RegExp]"===objectToString(re)},exports.isObject=function(arg){return"object"==typeof arg&&null!==arg},exports.isDate=function(d){return"[object Date]"===objectToString(d)},exports.isError=function(e){return"[object Error]"===objectToString(e)||e instanceof Error},exports.isFunction=function(arg){return"function"==typeof arg},exports.isPrimitive=function(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg},exports.isBuffer=Buffer.isBuffer}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":42}],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:158}],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":42,"./deferred-iterator":12,_process:86,"abstract-leveldown":17,util:158}],14:[function(require,module,exports){(function(process){function AbstractChainedBatch(db){this._db=db,this._operations=[],this._written=!1}AbstractChainedBatch.prototype._serializeKey=function(key){return this._db._serializeKey(key)},AbstractChainedBatch.prototype._serializeValue=function(value){return this._db._serializeValue(value)},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 key=this._serializeKey(key),value=this._serializeValue(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 key=this._serializeKey(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"))?callback(err):(key=this._serializeKey(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"))?callback(err):(key=this._serializeKey(key),value=this._serializeValue(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"))?callback(err):(key=this._serializeKey(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:148,util:158}],32:[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)writable&&writable.destroy&&writable.destroy();else if(null!==writable&&!1!==writable){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()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=function(){self._writable.removeListener("drain",ondrain),unend()},this.uncork()}else this.end()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)readable&&readable.destroy&&readable.destroy();else{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)};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=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()},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":33,inherits:40,"readable-stream":100,"stream-shift":149}],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:83}],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),len=(listeners=handler.slice()).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";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)this.onStoreReady();else if(this.db=event.target.result,"string"!=typeof this.db.version)if(this.db.objectStoreNames.contains(this.storeName)){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()}else this.onError(new Error("Object store couldn't be created."));else this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."))}.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&&(onError=onSuccess=options,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;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=function(err){batchTransaction.abort(),called||(called=!0,onError(err))}},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 getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=function(err){called=!0,result=err,onError(err),batchTransaction.abort()}},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))*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:148}],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){var Buffer=require("buffer").Buffer;module.exports=function(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}},{buffer:9}],45:[function(require,module,exports){!function(global){"use strict";var Logger={};Logger.VERSION="1.4.1";var logHandler,contextualLoggersByNameMap={},bind=function(scope,func){return function(){return func.apply(scope,arguments)}},merge=function(){var key,i,args=arguments,target=args[0];for(i=1;i=filterLevel.value},debug:function(){this.invoke(Logger.DEBUG,arguments)},info:function(){this.invoke(Logger.INFO,arguments)},warn:function(){this.invoke(Logger.WARN,arguments)},error:function(){this.invoke(Logger.ERROR,arguments)},time:function(label){"string"==typeof label&&label.length>0&&this.invoke(Logger.TIME,[label,"start"])},timeEnd:function(label){"string"==typeof label&&label.length>0&&this.invoke(Logger.TIME,[label,"end"])},invoke:function(level,msgArgs){logHandler&&this.enabledFor(level)&&logHandler(msgArgs,merge({level:level},this.context))}};var globalLogger=new ContextualLogger({filterLevel:Logger.OFF});!function(){var L=Logger;L.enabledFor=bind(globalLogger,globalLogger.enabledFor),L.debug=bind(globalLogger,globalLogger.debug),L.time=bind(globalLogger,globalLogger.time),L.timeEnd=bind(globalLogger,globalLogger.timeEnd),L.info=bind(globalLogger,globalLogger.info),L.warn=bind(globalLogger,globalLogger.warn),L.error=bind(globalLogger,globalLogger.error),L.log=L.info}(),Logger.setHandler=function(func){logHandler=func},Logger.setLevel=function(level){globalLogger.setLevel(level);for(var key in contextualLoggersByNameMap)contextualLoggersByNameMap.hasOwnProperty(key)&&contextualLoggersByNameMap[key].setLevel(level)},Logger.getLevel=function(){return globalLogger.getLevel()},Logger.get=function(name){return contextualLoggersByNameMap[name]||(contextualLoggersByNameMap[name]=new ContextualLogger(merge({name:name},globalLogger.context)))},Logger.createDefaultHandler=function(options){(options=options||{}).formatter=options.formatter||function(messages,context){context.name&&messages.unshift("["+context.name+"]")};var timerStartTimeByLabelMap={},invokeConsoleMethod=function(hdlr,messages){Function.prototype.apply.call(hdlr,console,messages)};return"undefined"==typeof console?function(){}:function(messages,context){messages=Array.prototype.slice.call(messages);var timerLabel,hdlr=console.log;context.level===Logger.TIME?(timerLabel=(context.name?"["+context.name+"] ":"")+messages[0],"start"===messages[1]?console.time?console.time(timerLabel):timerStartTimeByLabelMap[timerLabel]=(new Date).getTime():console.timeEnd?console.timeEnd(timerLabel):invokeConsoleMethod(hdlr,[timerLabel+": "+((new Date).getTime()-timerStartTimeByLabelMap[timerLabel])+"ms"])):(context.level===Logger.WARN&&console.warn?hdlr=console.warn:context.level===Logger.ERROR&&console.error?hdlr=console.error:context.level===Logger.INFO&&console.info?hdlr=console.info:context.level===Logger.DEBUG&&console.debug&&(hdlr=console.debug),options.formatter(messages,context),invokeConsoleMethod(hdlr,messages))}},Logger.useDefaults=function(options){Logger.setLevel(options&&options.defaultLevel||Logger.DEBUG),Logger.setHandler(Logger.createDefaultHandler(options))},void 0!==module&&module.exports?module.exports=Logger:(Logger._prevLogger=global.Logger,Logger.noConflict=function(){return global.Logger=Logger._prevLogger,Logger},global.Logger=Logger)}(this)},{}],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:function(data){return"string"==typeof data?data:String(data)},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.none={encode:identity,decode:identity,buffer:!1,type:"id"},exports.id=exports.none,["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:35}],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:40,"level-errors":49,"readable-stream":57,xtend:160}],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){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 endFn=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr?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);end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived);var end=(charStr+=buffer.toString(this.encoding,0,end)).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:158}],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){(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}],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){module.exports=function(source){return null!==source&&("object"==typeof source||"function"==typeof source)}},{}],70:[function(require,module,exports){var Keys=require("object-keys"),hasKeys=require("./has-keys");module.exports=function(){for(var target={},i=0;i-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};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=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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};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);++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)}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=function(){this.__data__=nativeCreate?nativeCreate(null):{},this.size=0},Hash.prototype.delete=function(key){var result=this.has(key)&&delete this.__data__[key];return this.size-=result?1:0,result},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){var data=this.__data__;return this.size+=this.has(key)?0:1,data[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[],this.size=0},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),--this.size,0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this},MapCache.prototype.clear=function(){this.size=0,this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){var result=getMapData(this,key).delete(key);return this.size-=result?1:0,result},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){var data=getMapData(this,key),size=data.size;return data.set(key,value),this.size+=data.size==size?0:1,this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)},Stack.prototype.clear=function(){this.__data__=new ListCache,this.size=0},Stack.prototype.delete=function(key){var data=this.__data__,result=data.delete(key);return this.size=data.size,result},Stack.prototype.get=function(key){return this.__data__.get(key)},Stack.prototype.has=function(key){return this.__data__.has(key)},Stack.prototype.set=function(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map||pairs.length>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computedlength?0:length+start),(end=end>length?length: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 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){return value?(value=toNumber(value))===INFINITY||value===-INFINITY?(value<0?-1:1)*MAX_INTEGER:value===value?value:0:0===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,objectToString=Object.prototype.toString,nativeMax=Math.max;module.exports=function(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)})}},{}],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;++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}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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:function(){},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=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},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:function(){};module.exports=function(array){return array&&array.length?baseUniq(array):[]}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],81:[function(require,module,exports){(function(Buffer){function has(obj,key){return Object.hasOwnProperty.call(obj,key)}function isDef(val){return void 0!==val&&""!==val}function has(range,name){return Object.hasOwnProperty.call(range,name)}function hasKey(range,name){return Object.hasOwnProperty.call(range,name)&&name}function id(e){return e}exports.compare=function(a,b){if(Buffer.isBuffer(a)){for(var l=Math.min(a.length,b.length),i=0;ib?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)&&((cmp=compare(key,lb))<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}],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:159}],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";!process.version||0===process.version.indexOf("v0.")||0===process.version.indexOf("v1.")&&0!==process.version.indexOf("v1.8.")?module.exports=function(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)}},{"end-of-stream":33,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:32,inherits:40,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||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(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)?(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 endFn=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr?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,OurUint8Array=global.Uint8Array||function(){},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"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./_stream_duplex":91,"./internal/streams/destroy":97,"./internal/streams/stream":98,_process:86,"core-util-is":11,inherits:40,"process-nextick-args":85,"safe-buffer":103,"util-deprecate":155}],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 emitErrorNT(self,err){self.emit("error",err)}var processNextTick=require("process-nextick-args");module.exports={destroy:function(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;readableDestroyed||writableDestroyed?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)}))},undestroy:function(){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)}}},{"process-nextick-args":85}],98:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:37}],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")).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 bunyan=require("bunyan"),levelup=require("levelup"),API=require("./lib/API.js");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){const api=API(options),Indexer={};return Indexer.options=options,Indexer.add=api.add,Indexer.concurrentAdd=api.concurrentAdd,Indexer.concurrentDel=api.concurrentDel,Indexer.close=api.close,Indexer.dbWriteStream=api.dbWriteStream,Indexer.defaultPipeline=api.defaultPipeline,Indexer.deleteStream=api.deleteStream,Indexer.deleter=api.deleter,Indexer.feed=api.feed,Indexer.flush=api.flush,callback(err,Indexer)})};const getOptions=function(options,done){if(options=Object.assign({},{appendOnly:!1,deletable:!0,batchSize:1e3,compositeField:!0,fastSort:!0,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,storeDocument:!0,storeVector:!0,searchable:!0,indexPath:"si",logLevel:"error",nGramLength:1,nGramSeparator:" ",separator:/\s|\\n|\\u0003|[-.,<>]/,stopwords:[],weight:0,wildcard:!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/API.js":106,bunyan:10,leveldown:59,levelup:72}],106:[function(require,module,exports){const DBEntries=require("./delete.js").DBEntries,DBWriteCleanStream=require("./replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./replicate.js").DBWriteMergeStream,DocVector=require("./delete.js").DocVector,JSONStream=require("JSONStream"),Readable=require("stream").Readable,RecalibrateDB=require("./delete.js").RecalibrateDB,IndexBatch=require("./add.js").IndexBatch,async=require("async"),del=require("./delete.js"),docProc=require("docproc"),pumpify=require("pumpify");module.exports=function(options){const 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),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={};return Indexer.add=function(ops){const thisOps=Object.assign(options,ops);return pumpify.obj(new IndexBatch(deleter,thisOps),new DBWriteMergeStream(thisOps))},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)).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=deleter,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)})},Indexer}},{"./add.js":107,"./delete.js":108,"./replicate.js":109,JSONStream:3,async:5,docproc:19,pumpify:89,stream:148}],107:[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={}},noop=function(_,cb){cb()},IndexBatch=function(deleter,options){this.batchSize=options.batchSize||1e3,this.deleter=deleter,this.fastSort=options.fastSort,this.appendOnly=options.appendOnly,this.keySeparator=options.keySeparator||"○",this.log=options.log,this.storeDocument=options.storeDocument,this.storeVector=options.storeVector,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.keySeparator,that=this;(this.appendOnly?noop:this.deleter.bind(this.indexer))([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.log.info("processing doc "+ingestedDoc.id),!0===that.storeDocument&&(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]){if(that.fastSort){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id])}var dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.storeVector&&(that.deltaIndex["DOCUMENT-VECTOR"+sep+fieldName+sep+ingestedDoc.id+sep]=ingestedDoc.vector[fieldName])}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.batchSize&&(that.push({totalKeys:totalKeys}),that.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:148,util:158}],108:[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,docKey="DOCUMENT"+sep+docId+sep;this.options.indexes.get(docKey,function(err,val){if(err)return end();var docFields=Object.keys(val);docFields.push("*"),docFields=docFields.map(function(item){return"DOCUMENT-VECTOR"+sep+item+sep+docId+sep});var i=0,pushValue=function(key){if(void 0===key)return that.push({key:"DOCUMENT"+sep+docId+sep,lastPass:!0}),end();that.options.indexes.get(key,function(err,val){err||that.push({key:key,value:val}),pushValue(docFields[i++])})};pushValue(docFields[0])})};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){if(!0===vector.lastPass)return this.push({key:vector.key}),end();const sep=this.options.keySeparator;var that=this,field=vector.key.split(sep)[1],docId=vector.key.split(sep)[2],vectorKeys=Object.keys(vector.value),i=0,pushRecalibrationvalues=function(vec){if(that.push({key:"TF"+sep+field+sep+vectorKeys[i],value:docId}),that.push({key:"DF"+sep+field+sep+vectorKeys[i],value:docId}),++i===vectorKeys.length)return that.push({key:vector.key}),end();pushRecalibrationvalues(vector[vectorKeys[i]])};pushRecalibrationvalues(vector[vectorKeys[0]])};const RecalibrateDB=function(options){this.options=options,this.batch=[],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={};return 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",that.batch.push(dbInstruction),end()):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",that.batch.push(dbInstruction),end()):dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep?(dbInstruction.type="del",that.batch.push(dbInstruction),end()):void(dbEntry.key.substring(0,9)==="DOCUMENT"+sep&&(dbInstruction.type="del",that.batch.push(dbInstruction),that.options.indexes.batch(that.batch,function(err){return that.batch=[],end()})))})}},{stream:148,util:158}],109:[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:148,util:158}],110:[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,MergeOrConditionsTFIDF=require("./lib/MergeOrConditionsTFIDF.js").MergeOrConditionsTFIDF,MergeOrConditionsFieldSort=require("./lib/MergeOrConditionsFieldSort.js").MergeOrConditionsFieldSort,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,bunyan=require("bunyan"),levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),sw=require("stopword"),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 ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditionsFieldSort(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 MergeOrConditionsTFIDF(q.offset,q.pageSize)).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:sw.en},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":111,"./lib/CalculateBuckets.js":112,"./lib/CalculateCategories.js":113,"./lib/CalculateEntireResultSet.js":114,"./lib/CalculateResultSetPerClause.js":115,"./lib/CalculateTopScoringDocs.js":116,"./lib/CalculateTotalHits.js":117,"./lib/Classify.js":118,"./lib/FetchDocsFromDB.js":119,"./lib/FetchStoredDoc.js":120,"./lib/GetIntersectionStream.js":121,"./lib/MergeOrConditionsFieldSort.js":122,"./lib/MergeOrConditionsTFIDF.js":123,"./lib/ScoreDocsOnField.js":124,"./lib/ScoreTopScoringDocsTFIDF.js":125,"./lib/matcher.js":126,"./lib/siUtil.js":127,bunyan:10,levelup:72,stopword:128,stream:148}],111:[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:148,util:158}],112:[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:148,util:158}],113:[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:148,util:158}],114:[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:148,util:158}],115:[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){var include=_spread(_intersection)(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,documentFrequencies:frequencies,WEIGHT:queryClause.WEIGHT||1}),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;i({id:id,scoringCriteria:resultMap[id],score:resultMap[id][0].score})).sort((a,b)=>b.score===a.score?a.idb.id?-1:0:"asc"===that.sortDirection?b.scorea.score).slice(this.offset,this.offset+this.pageSize).forEach(doc=>{that.push(doc)}),end()};const getResultMap=resultSet=>{var resultMap={};return resultSet.forEach(docMatch=>{resultMap[docMatch.id]=resultMap[docMatch.id]||[],resultMap[docMatch.id].push(docMatch),delete docMatch.id}),resultMap}},{stream:148,util:158}],123:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),MergeOrConditionsTFIDF=function(offset,pageSize){this.resultSet=[],this.offset=offset,this.pageSize=pageSize,Transform.call(this,{objectMode:!0})};exports.MergeOrConditionsTFIDF=MergeOrConditionsTFIDF,util.inherits(MergeOrConditionsTFIDF,Transform),MergeOrConditionsTFIDF.prototype._transform=function(doc,encoding,end){return this.resultSet=this.resultSet.concat(doc.matches),end()},MergeOrConditionsTFIDF.prototype._flush=function(end){var that=this,resultMap=getResultMap(this.resultSet);return Object.keys(resultMap).map(id=>({id:id,scoringCriteria:resultMap[id],score:resultMap[id].reduce((sum,matches)=>sum+matches.score,0)/resultMap[id].length})).sort((a,b)=>b.score===a.score?a.idb.id?-1:0:b.score-a.score).slice(this.offset,this.offset+this.pageSize).forEach(doc=>{that.push(doc)}),end()};const getResultMap=resultSet=>{var resultMap={};return resultSet.forEach(docMatch=>{resultMap[docMatch.id]=resultMap[docMatch.id]||[],resultMap[docMatch.id].push(docMatch),delete docMatch.id}),resultMap}},{stream:148,util:158}],124:[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,sortDirection=this.sort.direction||"asc";var tally=0,rangeOptions={gte:"DF"+sep+this.sort.field+sep,lte:"DF"+sep+this.sort.field+sep+sep};"desc"===sortDirection&&(rangeOptions.reverse=!0),clauseSet.topScoringDocs=[],that.options.indexes.createReadStream(rangeOptions).on("data",function(data){var token=data.key.split(sep)[2];"*"!==token&&("desc"===sortDirection&&(data.value=data.value.reverse()),data.value.some(id=>{if(-1!==_sortedIndexOf(clauseSet.set,id)&&(clauseSet.topScoringDocs.push({id:id,score:token}),++tally===that.seekLimit))return!0}))}).on("end",function(){return that.push(clauseSet),end()})}},{"lodash.sortedindexof":77,stream:148,util:158}],125:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),ScoreTopScoringDocsTFIDF=function(options,offset,pageSize){this.options=options,Transform.call(this,{objectMode:!0})};exports.ScoreTopScoringDocsTFIDF=ScoreTopScoringDocsTFIDF,util.inherits(ScoreTopScoringDocsTFIDF,Transform),ScoreTopScoringDocsTFIDF.prototype._transform=function(clause,encoding,end){var that=this,promises=[];clause.topScoringDocs.forEach(doc=>{var docID=doc[1];promises.push(getMatchesForDoc(docID,that.options,clause))}),Promise.all(promises).then(res=>(clause.matches=res,that.push(clause),end()),err=>{console.log(err)})};const getMatchesForDoc=(docID,options,clause)=>new Promise((resolve,reject)=>{var termVectors=clause.documentFrequencies.map(freq=>gett(freq.field,docID,freq.gte,freq.lte,freq.df,clause.WEIGHT,options));Promise.all(termVectors).then(matchedTerms=>{var matches=[].concat.apply([],matchedTerms);resolve({id:docID,matches:matches,score:getScore(matches)})},err=>{console.log(err)})}),getScore=matchedTerms=>matchedTerms.reduce(function(sum,match){return sum+match.score},0)/matchedTerms.length,gett=(field,key,gte,lte,df,weight,options)=>{var s=options.keySeparator;return new Promise((resolve,reject)=>{options.indexes.get("DOCUMENT-VECTOR"+s+field+s+key+s,(err,value)=>{if(err)return reject(err);var matchedTermsWithMagnitude=[];return Object.keys(value).filter(t=>{if(t>=gte&&t<=lte)return!0}).forEach(t=>{var tf=value[t],tfidf=tf*Math.log10(1+1/df),term={field:field,term:t,tf:tf,df:df,tfidf:tfidf,weight:weight,score:tfidf*weight};matchedTermsWithMagnitude.push(term)}),resolve(matchedTermsWithMagnitude)})})}},{stream:148,util:158}],126:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatchMostFrequent=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatchMostFrequent,Transform),MatchMostFrequent.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){var frequencySort=b.value.length-a.value.length;return 0===frequencySort?b.keya.key?-1:0:frequencySort}).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()})};const MatchAlphabetical=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatchAlphabetical,Transform),MatchAlphabetical.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var space={start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep},i=0,rs=this.options.indexes.createReadStream(space);rs.on("data",function(data){var m={};switch(q.type){case"ID":m={token:data.key.split(sep)[2],documents:data.value};break;case"count":m={token:data.key.split(sep)[2],documentCount:data.value.length};break;default:m=data.key.split(sep)[2]}if(that.push(m),++i===q.limit)return rs.destroy(),end()}),rs.on("error",function(err){that.options.log.error("Oh my!",err)}),rs.on("end",function(){return end()})},exports.match=function(q,options){var s=new Readable({objectMode:!0});return(q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple",sort:"frequency"},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 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(1===(ngrams=ngrams.sort()).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:"")+"]"),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)).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 isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==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 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:82,buffer:7,jsonparse:43,through:148}],4:[function(require,module,exports){(function(process,global){!function(global,factory){factory("object"==typeof exports&&void 0!==module?exports: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)<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,1),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){var timer,timedOut=!1;args.push(function(){timedOut||(callback.apply(null,arguments),clearTimeout(timer))}),timer=setTimeout(function(){var name=asyncFn.name||"anonymous",error=new Error('Callback function "'+name+'" timed out.');error.code="ETIMEDOUT",info&&(error.info=info),timedOut=!0,callback(error)},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,setImmediate$1=wrap(_defer=hasSetImmediate?setImmediate:hasNextTick?process.nextTick:fallback),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,nativeObjectToString$1=Object.prototype.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,Buffer=freeModule&&freeModule.exports===freeExports?root.Buffer:void 0,isBuffer=(Buffer?Buffer.isBuffer:void 0)||function(){return!1},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,freeProcess=freeModule$1&&freeModule$1.exports===freeExports$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):function(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]},hasOwnProperty$1=Object.prototype.hasOwnProperty,objectProto$5=Object.prototype,nativeKeys=function(func,transform){return function(arg){return func(transform(arg))}}(Object.keys,Object),hasOwnProperty$3=Object.prototype.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 numTasks=keys(tasks).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 counter=0;readyToCheck.length;)counter++,arrayEach(getDependents(readyToCheck.pop()),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])?",rsSeq="[\\ufe0e\\ufe0f]?"+reOptMod+("(?:\\u200d(?:"+["[^\\ud800-\\udfff]",rsRegional,rsSurrPair].join("|")+")[\\ufe0e\\ufe0f]?"+reOptMod+")*"),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 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;i0?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},exports.fromByteArray=function(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,output="",parts=[],i=0,len2=len-extraBytes;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("")};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 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:128==(192&(secondByte=buf[i+1]))&&(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,"")).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=function(length){return+length!=length&&(length=0),Buffer.alloc(+length)},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){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<.,\-|]+|\\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:143,util:153}],29:[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)writable&&writable.destroy&&writable.destroy();else if(null!==writable&&!1!==writable){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()};this._unwrite&&process.nextTick(ondrain),this._writable=writable,this._writable.on("drain",ondrain),this._unwrite=function(){self._writable.removeListener("drain",ondrain),unend()},this.uncork()}else this.end()},Duplexify.prototype.setReadable=function(readable){if(this._unread&&this._unread(),this.destroyed)readable&&readable.destroy&&readable.destroy();else{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)};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=function(){self._readable2.removeListener("readable",onreadable),self._readable2.removeListener("end",onend),unend()},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:82,buffer:7,"end-of-stream":30,inherits:37,"readable-stream":96,"stream-shift":144}],30:[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:80}],31:[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:33}],32:[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":31}],33:[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)}})},{}],34:[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),len=(listeners=handler.slice()).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)}},{}],35:[function(require,module,exports){!function(name,definition,global){"use strict";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)this.onStoreReady();else if(this.db=event.target.result,"string"!=typeof this.db.version)if(this.db.objectStoreNames.contains(this.storeName)){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()}else this.onError(new Error("Object store couldn't be created."));else this.onError(new Error("The IndexedDB implementation in this browser is outdated. Please upgrade your browser."))}.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&&(onError=onSuccess=options,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;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=function(err){batchTransaction.abort(),called||(called=!0,onError(err))}},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 getRequest=batchTransaction.objectStore(this.storeName).get(key);getRequest.onsuccess=onItemSuccess,getRequest.onerror=function(err){called=!0,result=err,onError(err),batchTransaction.abort()}},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))*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}},{}],37:[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}},{}],38:[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:143}],39:[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)}},{}],40:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},{}],41:[function(require,module,exports){var Buffer=require("buffer").Buffer;module.exports=function(o){return Buffer.isBuffer(o)||/\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o))}},{buffer:7}],42:[function(require,module,exports){!function(global){"use strict";var Logger={};Logger.VERSION="1.4.1";var logHandler,contextualLoggersByNameMap={},bind=function(scope,func){return function(){return func.apply(scope,arguments)}},merge=function(){var key,i,args=arguments,target=args[0];for(i=1;i=filterLevel.value},debug:function(){this.invoke(Logger.DEBUG,arguments)},info:function(){this.invoke(Logger.INFO,arguments)},warn:function(){this.invoke(Logger.WARN,arguments)},error:function(){this.invoke(Logger.ERROR,arguments)},time:function(label){"string"==typeof label&&label.length>0&&this.invoke(Logger.TIME,[label,"start"])},timeEnd:function(label){"string"==typeof label&&label.length>0&&this.invoke(Logger.TIME,[label,"end"])},invoke:function(level,msgArgs){logHandler&&this.enabledFor(level)&&logHandler(msgArgs,merge({level:level},this.context))}};var globalLogger=new ContextualLogger({filterLevel:Logger.OFF});!function(){var L=Logger;L.enabledFor=bind(globalLogger,globalLogger.enabledFor),L.debug=bind(globalLogger,globalLogger.debug),L.time=bind(globalLogger,globalLogger.time),L.timeEnd=bind(globalLogger,globalLogger.timeEnd),L.info=bind(globalLogger,globalLogger.info),L.warn=bind(globalLogger,globalLogger.warn),L.error=bind(globalLogger,globalLogger.error),L.log=L.info}(),Logger.setHandler=function(func){logHandler=func},Logger.setLevel=function(level){globalLogger.setLevel(level);for(var key in contextualLoggersByNameMap)contextualLoggersByNameMap.hasOwnProperty(key)&&contextualLoggersByNameMap[key].setLevel(level)},Logger.getLevel=function(){return globalLogger.getLevel()},Logger.get=function(name){return contextualLoggersByNameMap[name]||(contextualLoggersByNameMap[name]=new ContextualLogger(merge({name:name},globalLogger.context)))},Logger.createDefaultHandler=function(options){(options=options||{}).formatter=options.formatter||function(messages,context){context.name&&messages.unshift("["+context.name+"]")};var timerStartTimeByLabelMap={},invokeConsoleMethod=function(hdlr,messages){Function.prototype.apply.call(hdlr,console,messages)};return"undefined"==typeof console?function(){}:function(messages,context){messages=Array.prototype.slice.call(messages);var timerLabel,hdlr=console.log;context.level===Logger.TIME?(timerLabel=(context.name?"["+context.name+"] ":"")+messages[0],"start"===messages[1]?console.time?console.time(timerLabel):timerStartTimeByLabelMap[timerLabel]=(new Date).getTime():console.timeEnd?console.timeEnd(timerLabel):invokeConsoleMethod(hdlr,[timerLabel+": "+((new Date).getTime()-timerStartTimeByLabelMap[timerLabel])+"ms"])):(context.level===Logger.WARN&&console.warn?hdlr=console.warn:context.level===Logger.ERROR&&console.error?hdlr=console.error:context.level===Logger.INFO&&console.info?hdlr=console.info:context.level===Logger.DEBUG&&console.debug&&(hdlr=console.debug),options.formatter(messages,context),invokeConsoleMethod(hdlr,messages))}},Logger.useDefaults=function(options){Logger.setLevel(options&&options.defaultLevel||Logger.DEBUG),Logger.setHandler(Logger.createDefaultHandler(options))},void 0!==module&&module.exports?module.exports=Logger:(Logger._prevLogger=global.Logger,Logger.noConflict=function(){return global.Logger=Logger._prevLogger,Logger},global.Logger=Logger)}(this)},{}],43:[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:7}],44:[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":45}],45:[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:function(data){return"string"==typeof data?data:String(data)},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.none={encode:identity,decode:identity,buffer:!1,type:"id"},exports.id=exports.none,["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:7}],46:[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:32}],47:[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:37,"level-errors":46,"readable-stream":54,xtend:155}],48:[function(require,module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},{}],49:[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){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 endFn=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr?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);end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived);var end=(charStr+=buffer.toString(this.encoding,0,end)).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:7}],56:[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":60,ltgt:78,util:153}],58:[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:82}],59:[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:82}],60:[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}},{}],65:[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":62,"./isArguments":64}],66:[function(require,module,exports){module.exports=function(source){return null!==source&&("object"==typeof source||"function"==typeof source)}},{}],67:[function(require,module,exports){var Keys=require("object-keys"),hasKeys=require("./has-keys");module.exports=function(){for(var target={},i=0;i-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};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=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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};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);++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)}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=function(){this.__data__=nativeCreate?nativeCreate(null):{},this.size=0},Hash.prototype.delete=function(key){var result=this.has(key)&&delete this.__data__[key];return this.size-=result?1:0,result},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){var data=this.__data__;return this.size+=this.has(key)?0:1,data[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[],this.size=0},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),--this.size,0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this},MapCache.prototype.clear=function(){this.size=0,this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){var result=getMapData(this,key).delete(key);return this.size-=result?1:0,result},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){var data=getMapData(this,key),size=data.size;return data.set(key,value),this.size+=data.size==size?0:1,this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)},Stack.prototype.clear=function(){this.__data__=new ListCache,this.size=0},Stack.prototype.delete=function(key){var data=this.__data__,result=data.delete(key);return this.size=data.size,result},Stack.prototype.get=function(key){return this.__data__.get(key)},Stack.prototype.has=function(key){return this.__data__.has(key)},Stack.prototype.set=function(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map||pairs.length>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computedlength?0:length+start),(end=end>length?length: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 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){return value?(value=toNumber(value))===INFINITY||value===-INFINITY?(value<0?-1:1)*MAX_INTEGER:value===value?value:0:0===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,objectToString=Object.prototype.toString,nativeMax=Math.max;module.exports=function(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)})}},{}],76:[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;++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}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=function(){this.__data__=nativeCreate?nativeCreate(null):{}},Hash.prototype.delete=function(key){return this.has(key)&&delete this.__data__[key]},Hash.prototype.get=function(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0},Hash.prototype.has=function(key){var data=this.__data__;return nativeCreate?void 0!==data[key]:hasOwnProperty.call(data,key)},Hash.prototype.set=function(key,value){return this.__data__[key]=nativeCreate&&void 0===value?HASH_UNDEFINED:value,this},ListCache.prototype.clear=function(){this.__data__=[]},ListCache.prototype.delete=function(key){var data=this.__data__,index=assocIndexOf(data,key);return!(index<0||(index==data.length-1?data.pop():splice.call(data,index,1),0))},ListCache.prototype.get=function(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]},ListCache.prototype.has=function(key){return assocIndexOf(this.__data__,key)>-1},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:function(){},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=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},ListCache.prototype.set=function(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this},MapCache.prototype.clear=function(){this.__data__={hash:new Hash,map:new(Map||ListCache),string:new Hash}},MapCache.prototype.delete=function(key){return getMapData(this,key).delete(key)},MapCache.prototype.get=function(key){return getMapData(this,key).get(key)},MapCache.prototype.has=function(key){return getMapData(this,key).has(key)},MapCache.prototype.set=function(key,value){return getMapData(this,key).set(key,value),this},SetCache.prototype.add=SetCache.prototype.push=function(value){return this.__data__.set(value,HASH_UNDEFINED),this},SetCache.prototype.has=function(value){return this.__data__.has(value)};var createSet=Set&&1/setToArray(new Set([,-0]))[1]==1/0?function(values){return new Set(values)}:function(){};module.exports=function(array){return array&&array.length?baseUniq(array):[]}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],78:[function(require,module,exports){(function(Buffer){function has(obj,key){return Object.hasOwnProperty.call(obj,key)}function isDef(val){return void 0!==val&&""!==val}function has(range,name){return Object.hasOwnProperty.call(range,name)}function hasKey(range,name){return Object.hasOwnProperty.call(range,name)&&name}function id(e){return e}exports.compare=function(a,b){if(Buffer.isBuffer(a)){for(var l=Math.min(a.length,b.length),i=0;ib?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)&&((cmp=compare(key,lb))<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":39}],79:[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)}}},{}],80:[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:154}],81:[function(require,module,exports){(function(process){"use strict";!process.version||0===process.version.indexOf("v0.")||0===process.version.indexOf("v1.")&&0!==process.version.indexOf("v1.8.")?module.exports=function(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)}},{"end-of-stream":30,fs:6,once:80}],85:[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:29,inherits:37,pump:84}],86:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":87}],87:[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||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(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)?(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 endFn=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr?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,OurUint8Array=global.Uint8Array||function(){},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"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./_stream_duplex":87,"./internal/streams/destroy":93,"./internal/streams/stream":94,_process:82,"core-util-is":8,inherits:37,"process-nextick-args":81,"safe-buffer":99,"util-deprecate":150}],92:[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":99}],93:[function(require,module,exports){"use strict";function emitErrorNT(self,err){self.emit("error",err)}var processNextTick=require("process-nextick-args");module.exports={destroy:function(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;readableDestroyed||writableDestroyed?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)}))},undestroy:function(){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)}}},{"process-nextick-args":81}],94:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:34}],95:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":96}],96:[function(require,module,exports){(exports=module.exports=require("./lib/_stream_readable.js")).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":87,"./lib/_stream_passthrough.js":88,"./lib/_stream_readable.js":89,"./lib/_stream_transform.js":90,"./lib/_stream_writable.js":91}],97:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":96}],98:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":91}],99:[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:7}],100:[function(require,module,exports){const Logger=require("js-logger"),levelup=require("levelup"),API=require("./lib/API.js");module.exports=function(givenOptions,callback){getOptions(givenOptions,function(err,options){const api=API(options),Indexer={};return Indexer.options=options,Indexer.add=api.add,Indexer.concurrentAdd=api.concurrentAdd,Indexer.concurrentDel=api.concurrentDel,Indexer.close=api.close,Indexer.dbWriteStream=api.dbWriteStream,Indexer.defaultPipeline=api.defaultPipeline,Indexer.deleteStream=api.deleteStream,Indexer.deleter=api.deleter,Indexer.feed=api.feed,Indexer.flush=api.flush,callback(err,Indexer)})};const getOptions=function(options,done){if(options=Object.assign({},{appendOnly:!1,deletable:!0,batchSize:1e3,compositeField:!0,fastSort:!0,fieldedSearch:!0,fieldOptions:{},preserveCase:!1,keySeparator:"○",storeable:!0,storeDocument:!0,storeVector:!0,searchable:!0,indexPath:"si",logLevel:"ERROR",logHandler:Logger.createDefaultHandler(),nGramLength:1,nGramSeparator:" ",separator:/\s|\\n|\\u0003|[-.,<>]/,stopwords:[],weight:0,wildcard:!0},options),options.log=Logger.get("search-index-adder"),options.log.setLevel(Logger[options.logLevel.toUpperCase()]),Logger.setHandler(options.logHandler),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/API.js":101,"js-logger":42,leveldown:56,levelup:69}],101:[function(require,module,exports){const DBEntries=require("./delete.js").DBEntries,DBWriteCleanStream=require("./replicate.js").DBWriteCleanStream,DBWriteMergeStream=require("./replicate.js").DBWriteMergeStream,DocVector=require("./delete.js").DocVector,JSONStream=require("JSONStream"),Readable=require("stream").Readable,RecalibrateDB=require("./delete.js").RecalibrateDB,IndexBatch=require("./add.js").IndexBatch,async=require("async"),del=require("./delete.js"),docProc=require("docproc"),pumpify=require("pumpify");module.exports=function(options){const 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),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={};return Indexer.add=function(ops){const thisOps=Object.assign(options,ops);return pumpify.obj(new IndexBatch(deleter,thisOps),new DBWriteMergeStream(thisOps))},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)).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=deleter,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)})},Indexer}},{"./add.js":102,"./delete.js":103,"./replicate.js":104,JSONStream:3,async:4,docproc:16,pumpify:85,stream:143}],102:[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={}},noop=function(_,cb){cb()},IndexBatch=function(deleter,options){this.batchSize=options.batchSize||1e3,this.deleter=deleter,this.fastSort=options.fastSort,this.appendOnly=options.appendOnly,this.keySeparator=options.keySeparator||"○",this.log=options.log,this.storeDocument=options.storeDocument,this.storeVector=options.storeVector,this.deltaIndex={},Transform.call(this,{objectMode:!0})};exports.IndexBatch=IndexBatch,util.inherits(IndexBatch,Transform),IndexBatch.prototype._transform=function(ingestedDoc,encoding,end){const sep=this.keySeparator,that=this;(this.appendOnly?noop:this.deleter.bind(this.indexer))([ingestedDoc.id],function(err){err&&that.indexer.log.info(err),that.log.info("processing doc "+ingestedDoc.id),!0===that.storeDocument&&(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]){if(that.fastSort){var vMagnitude=ingestedDoc.vector[fieldName][token],tfKeyName="TF"+sep+fieldName+sep+token;that.deltaIndex[tfKeyName]=that.deltaIndex[tfKeyName]||[],that.deltaIndex[tfKeyName].push([vMagnitude,ingestedDoc.id])}var dfKeyName="DF"+sep+fieldName+sep+token;that.deltaIndex[dfKeyName]=that.deltaIndex[dfKeyName]||[],that.deltaIndex[dfKeyName].push(ingestedDoc.id)}that.storeVector&&(that.deltaIndex["DOCUMENT-VECTOR"+sep+fieldName+sep+ingestedDoc.id+sep]=ingestedDoc.vector[fieldName])}var totalKeys=Object.keys(that.deltaIndex).length;return totalKeys>that.batchSize&&(that.push({totalKeys:totalKeys}),that.log.info("deltaIndex is "+totalKeys+" long, emitting"),emitIndexKeys(that)),end()})},IndexBatch.prototype._flush=function(end){return emitIndexKeys(this),end()}},{stream:143,util:153}],103:[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,docKey="DOCUMENT"+sep+docId+sep;this.options.indexes.get(docKey,function(err,val){if(err)return end();var docFields=Object.keys(val);docFields.push("*"),docFields=docFields.map(function(item){return"DOCUMENT-VECTOR"+sep+item+sep+docId+sep});var i=0,pushValue=function(key){if(void 0===key)return that.push({key:"DOCUMENT"+sep+docId+sep,lastPass:!0}),end();that.options.indexes.get(key,function(err,val){err||that.push({key:key,value:val}),pushValue(docFields[i++])})};pushValue(docFields[0])})};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){if(!0===vector.lastPass)return this.push({key:vector.key}),end();const sep=this.options.keySeparator;var that=this,field=vector.key.split(sep)[1],docId=vector.key.split(sep)[2],vectorKeys=Object.keys(vector.value),i=0,pushRecalibrationvalues=function(vec){if(that.push({key:"TF"+sep+field+sep+vectorKeys[i],value:docId}),that.push({key:"DF"+sep+field+sep+vectorKeys[i],value:docId}),++i===vectorKeys.length)return that.push({key:vector.key}),end();pushRecalibrationvalues(vector[vectorKeys[i]])};pushRecalibrationvalues(vector[vectorKeys[0]])};const RecalibrateDB=function(options){this.options=options,this.batch=[],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={};return 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",that.batch.push(dbInstruction),end()):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",that.batch.push(dbInstruction),end()):dbEntry.key.substring(0,16)==="DOCUMENT-VECTOR"+sep?(dbInstruction.type="del",that.batch.push(dbInstruction),end()):void(dbEntry.key.substring(0,9)==="DOCUMENT"+sep&&(dbInstruction.type="del",that.batch.push(dbInstruction),that.options.indexes.batch(that.batch,function(err){return that.batch=[],end()})))})}},{stream:143,util:153}],104:[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:143,util:153}],105:[function(require,module,exports){const Logger=require("js-logger"),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,MergeOrConditionsTFIDF=require("./lib/MergeOrConditionsTFIDF.js").MergeOrConditionsTFIDF,MergeOrConditionsFieldSort=require("./lib/MergeOrConditionsFieldSort.js").MergeOrConditionsFieldSort,Readable=require("stream").Readable,ScoreDocsOnField=require("./lib/ScoreDocsOnField.js").ScoreDocsOnField,ScoreTopScoringDocsTFIDF=require("./lib/ScoreTopScoringDocsTFIDF.js").ScoreTopScoringDocsTFIDF,levelup=require("levelup"),matcher=require("./lib/matcher.js"),siUtil=require("./lib/siUtil.js"),sw=require("stopword"),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 ScoreDocsOnField(Searcher.options,q.offset+q.pageSize,q.sort)).pipe(new MergeOrConditionsFieldSort(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 MergeOrConditionsTFIDF(q.offset,q.pageSize)).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",logHandler:Logger.createDefaultHandler(),nGramLength:1,nGramSeparator:" ",separator:/[|' .,\-|(\n)]+/,stopwords:sw.en},options),Searcher.options.log=Logger.get("search-index-searcher"),Searcher.options.log.setLevel(Logger[Searcher.options.logLevel.toUpperCase()]),Logger.setHandler(Searcher.options.logHandler),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":106,"./lib/CalculateBuckets.js":107,"./lib/CalculateCategories.js":108,"./lib/CalculateEntireResultSet.js":109,"./lib/CalculateResultSetPerClause.js":110,"./lib/CalculateTopScoringDocs.js":111,"./lib/CalculateTotalHits.js":112,"./lib/Classify.js":113,"./lib/FetchDocsFromDB.js":114,"./lib/FetchStoredDoc.js":115,"./lib/GetIntersectionStream.js":116,"./lib/MergeOrConditionsFieldSort.js":117,"./lib/MergeOrConditionsTFIDF.js":118,"./lib/ScoreDocsOnField.js":119,"./lib/ScoreTopScoringDocsTFIDF.js":120,"./lib/matcher.js":121,"./lib/siUtil.js":122,"js-logger":42,levelup:69,stopword:123,stream:143}],106:[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:143,util:153}],107:[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":72,"lodash.uniq":77,stream:143,util:153}],108:[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":72,stream:143,util:153}],109:[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":76,stream:143,util:153}],110:[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){var include=_spread(_intersection)(includeResults);if(0===siUtil.getKeySet(queryClause.NOT,sep).length)return that.push({queryClause:queryClause,set:include,documentFrequencies:frequencies,WEIGHT:queryClause.WEIGHT||1}),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;i({id:id,scoringCriteria:resultMap[id],score:resultMap[id][0].score})).sort((a,b)=>b.score===a.score?a.idb.id?-1:0:"asc"===that.sortDirection?b.scorea.score).slice(this.offset,this.offset+this.pageSize).forEach(doc=>{that.push(doc)}),end()};const getResultMap=resultSet=>{var resultMap={};return resultSet.forEach(docMatch=>{resultMap[docMatch.id]=resultMap[docMatch.id]||[],resultMap[docMatch.id].push(docMatch),delete docMatch.id}),resultMap}},{stream:143,util:153}],118:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),MergeOrConditionsTFIDF=function(offset,pageSize){this.resultSet=[],this.offset=offset,this.pageSize=pageSize,Transform.call(this,{objectMode:!0})};exports.MergeOrConditionsTFIDF=MergeOrConditionsTFIDF,util.inherits(MergeOrConditionsTFIDF,Transform),MergeOrConditionsTFIDF.prototype._transform=function(doc,encoding,end){return this.resultSet=this.resultSet.concat(doc.matches),end()},MergeOrConditionsTFIDF.prototype._flush=function(end){var that=this,resultMap=getResultMap(this.resultSet);return Object.keys(resultMap).map(id=>({id:id,scoringCriteria:resultMap[id],score:resultMap[id].reduce((sum,matches)=>sum+matches.score,0)/resultMap[id].length})).sort((a,b)=>b.score===a.score?a.idb.id?-1:0:b.score-a.score).slice(this.offset,this.offset+this.pageSize).forEach(doc=>{that.push(doc)}),end()};const getResultMap=resultSet=>{var resultMap={};return resultSet.forEach(docMatch=>{resultMap[docMatch.id]=resultMap[docMatch.id]||[],resultMap[docMatch.id].push(docMatch),delete docMatch.id}),resultMap}},{stream:143,util:153}],119:[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,sortDirection=this.sort.direction||"asc";var tally=0,rangeOptions={gte:"DF"+sep+this.sort.field+sep,lte:"DF"+sep+this.sort.field+sep+sep};"desc"===sortDirection&&(rangeOptions.reverse=!0),clauseSet.topScoringDocs=[],that.options.indexes.createReadStream(rangeOptions).on("data",function(data){var token=data.key.split(sep)[2];"*"!==token&&("desc"===sortDirection&&(data.value=data.value.reverse()),data.value.some(id=>{if(-1!==_sortedIndexOf(clauseSet.set,id)&&(clauseSet.topScoringDocs.push({id:id,score:token}),++tally===that.seekLimit))return!0}))}).on("end",function(){return that.push(clauseSet),end()})}},{"lodash.sortedindexof":74,stream:143,util:153}],120:[function(require,module,exports){const Transform=require("stream").Transform,util=require("util"),ScoreTopScoringDocsTFIDF=function(options,offset,pageSize){this.options=options,Transform.call(this,{objectMode:!0})};exports.ScoreTopScoringDocsTFIDF=ScoreTopScoringDocsTFIDF,util.inherits(ScoreTopScoringDocsTFIDF,Transform),ScoreTopScoringDocsTFIDF.prototype._transform=function(clause,encoding,end){var that=this,promises=[];clause.topScoringDocs.forEach(doc=>{var docID=doc[1];promises.push(getMatchesForDoc(docID,that.options,clause))}),Promise.all(promises).then(res=>(clause.matches=res,that.push(clause),end()),err=>{console.log(err)})};const getMatchesForDoc=(docID,options,clause)=>new Promise((resolve,reject)=>{var termVectors=clause.documentFrequencies.map(freq=>gett(freq.field,docID,freq.gte,freq.lte,freq.df,clause.WEIGHT,options));Promise.all(termVectors).then(matchedTerms=>{var matches=[].concat.apply([],matchedTerms);resolve({id:docID,matches:matches,score:getScore(matches)})},err=>{console.log(err)})}),getScore=matchedTerms=>matchedTerms.reduce(function(sum,match){return sum+match.score},0)/matchedTerms.length,gett=(field,key,gte,lte,df,weight,options)=>{var s=options.keySeparator;return new Promise((resolve,reject)=>{options.indexes.get("DOCUMENT-VECTOR"+s+field+s+key+s,(err,value)=>{if(err)return reject(err);var matchedTermsWithMagnitude=[];return Object.keys(value).filter(t=>{if(t>=gte&&t<=lte)return!0}).forEach(t=>{var tf=value[t],tfidf=tf*Math.log10(1+1/df),term={field:field,term:t,tf:tf,df:df,tfidf:tfidf,weight:weight,score:tfidf*weight};matchedTermsWithMagnitude.push(term)}),resolve(matchedTermsWithMagnitude)})})}},{stream:143,util:153}],121:[function(require,module,exports){const Readable=require("stream").Readable,Transform=require("stream").Transform,util=require("util"),MatchMostFrequent=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatchMostFrequent,Transform),MatchMostFrequent.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){var frequencySort=b.value.length-a.value.length;return 0===frequencySort?b.keya.key?-1:0:frequencySort}).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()})};const MatchAlphabetical=function(q,options){this.options=options,Transform.call(this,{objectMode:!0})};util.inherits(MatchAlphabetical,Transform),MatchAlphabetical.prototype._transform=function(q,encoding,end){const sep=this.options.keySeparator,that=this;var space={start:"DF"+sep+q.field+sep+q.beginsWith,end:"DF"+sep+q.field+sep+q.beginsWith+sep},i=0,rs=this.options.indexes.createReadStream(space);rs.on("data",function(data){var m={};switch(q.type){case"ID":m={token:data.key.split(sep)[2],documents:data.value};break;case"count":m={token:data.key.split(sep)[2],documentCount:data.value.length};break;default:m=data.key.split(sep)[2]}if(that.push(m),++i===q.limit)return rs.destroy(),end()}),rs.on("error",function(err){that.options.log.error("Oh my!",err)}),rs.on("end",function(){return end()})},exports.match=function(q,options){var s=new Readable({objectMode:!0});return(q=Object.assign({},{beginsWith:"",field:"*",threshold:3,limit:10,type:"simple",sort:"frequency"},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 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(1===(ngrams=ngrams.sort()).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:"")+"]"),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)).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 isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==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 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