UNPKG

741 kBJavaScriptView Raw
1// PouchDB in-memory plugin 9.0.0
2// Based on MemDOWN: https://github.com/rvagg/memdown
3//
4// (c) 2012-2024 Dale Harvey and the PouchDB team
5// PouchDB may be freely distributed under the Apache license, version 2.0.
6// For all details and documentation:
7// http://pouchdb.com
8(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
9(function (global){(function (){
10'use strict';
11
12var objectAssign = _dereq_('object.assign/polyfill')();
13
14// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
15// original notice:
16
17/*!
18 * The buffer module from node.js, for the browser.
19 *
20 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
21 * @license MIT
22 */
23function compare(a, b) {
24 if (a === b) {
25 return 0;
26 }
27
28 var x = a.length;
29 var y = b.length;
30
31 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
32 if (a[i] !== b[i]) {
33 x = a[i];
34 y = b[i];
35 break;
36 }
37 }
38
39 if (x < y) {
40 return -1;
41 }
42 if (y < x) {
43 return 1;
44 }
45 return 0;
46}
47function isBuffer(b) {
48 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
49 return global.Buffer.isBuffer(b);
50 }
51 return !!(b != null && b._isBuffer);
52}
53
54// based on node assert, original notice:
55// NB: The URL to the CommonJS spec is kept just for tradition.
56// node-assert has evolved a lot since then, both in API and behavior.
57
58// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
59//
60// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
61//
62// Originally from narwhal.js (http://narwhaljs.org)
63// Copyright (c) 2009 Thomas Robinson <280north.com>
64//
65// Permission is hereby granted, free of charge, to any person obtaining a copy
66// of this software and associated documentation files (the 'Software'), to
67// deal in the Software without restriction, including without limitation the
68// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
69// sell copies of the Software, and to permit persons to whom the Software is
70// furnished to do so, subject to the following conditions:
71//
72// The above copyright notice and this permission notice shall be included in
73// all copies or substantial portions of the Software.
74//
75// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
76// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
77// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
78// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
79// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
80// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
81
82var util = _dereq_('util/');
83var hasOwn = Object.prototype.hasOwnProperty;
84var pSlice = Array.prototype.slice;
85var functionsHaveNames = (function () {
86 return function foo() {}.name === 'foo';
87}());
88function pToString (obj) {
89 return Object.prototype.toString.call(obj);
90}
91function isView(arrbuf) {
92 if (isBuffer(arrbuf)) {
93 return false;
94 }
95 if (typeof global.ArrayBuffer !== 'function') {
96 return false;
97 }
98 if (typeof ArrayBuffer.isView === 'function') {
99 return ArrayBuffer.isView(arrbuf);
100 }
101 if (!arrbuf) {
102 return false;
103 }
104 if (arrbuf instanceof DataView) {
105 return true;
106 }
107 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
108 return true;
109 }
110 return false;
111}
112// 1. The assert module provides functions that throw
113// AssertionError's when particular conditions are not met. The
114// assert module must conform to the following interface.
115
116var assert = module.exports = ok;
117
118// 2. The AssertionError is defined in assert.
119// new assert.AssertionError({ message: message,
120// actual: actual,
121// expected: expected })
122
123var regex = /\s*function\s+([^\(\s]*)\s*/;
124// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
125function getName(func) {
126 if (!util.isFunction(func)) {
127 return;
128 }
129 if (functionsHaveNames) {
130 return func.name;
131 }
132 var str = func.toString();
133 var match = str.match(regex);
134 return match && match[1];
135}
136assert.AssertionError = function AssertionError(options) {
137 this.name = 'AssertionError';
138 this.actual = options.actual;
139 this.expected = options.expected;
140 this.operator = options.operator;
141 if (options.message) {
142 this.message = options.message;
143 this.generatedMessage = false;
144 } else {
145 this.message = getMessage(this);
146 this.generatedMessage = true;
147 }
148 var stackStartFunction = options.stackStartFunction || fail;
149 if (Error.captureStackTrace) {
150 Error.captureStackTrace(this, stackStartFunction);
151 } else {
152 // non v8 browsers so we can have a stacktrace
153 var err = new Error();
154 if (err.stack) {
155 var out = err.stack;
156
157 // try to strip useless frames
158 var fn_name = getName(stackStartFunction);
159 var idx = out.indexOf('\n' + fn_name);
160 if (idx >= 0) {
161 // once we have located the function frame
162 // we need to strip out everything before it (and its line)
163 var next_line = out.indexOf('\n', idx + 1);
164 out = out.substring(next_line + 1);
165 }
166
167 this.stack = out;
168 }
169 }
170};
171
172// assert.AssertionError instanceof Error
173util.inherits(assert.AssertionError, Error);
174
175function truncate(s, n) {
176 if (typeof s === 'string') {
177 return s.length < n ? s : s.slice(0, n);
178 } else {
179 return s;
180 }
181}
182function inspect(something) {
183 if (functionsHaveNames || !util.isFunction(something)) {
184 return util.inspect(something);
185 }
186 var rawname = getName(something);
187 var name = rawname ? ': ' + rawname : '';
188 return '[Function' + name + ']';
189}
190function getMessage(self) {
191 return truncate(inspect(self.actual), 128) + ' ' +
192 self.operator + ' ' +
193 truncate(inspect(self.expected), 128);
194}
195
196// At present only the three keys mentioned above are used and
197// understood by the spec. Implementations or sub modules can pass
198// other keys to the AssertionError's constructor - they will be
199// ignored.
200
201// 3. All of the following functions must throw an AssertionError
202// when a corresponding condition is not met, with a message that
203// may be undefined if not provided. All assertion methods provide
204// both the actual and expected values to the assertion error for
205// display purposes.
206
207function fail(actual, expected, message, operator, stackStartFunction) {
208 throw new assert.AssertionError({
209 message: message,
210 actual: actual,
211 expected: expected,
212 operator: operator,
213 stackStartFunction: stackStartFunction
214 });
215}
216
217// EXTENSION! allows for well behaved errors defined elsewhere.
218assert.fail = fail;
219
220// 4. Pure assertion tests whether a value is truthy, as determined
221// by !!guard.
222// assert.ok(guard, message_opt);
223// This statement is equivalent to assert.equal(true, !!guard,
224// message_opt);. To test strictly for the value true, use
225// assert.strictEqual(true, guard, message_opt);.
226
227function ok(value, message) {
228 if (!value) fail(value, true, message, '==', assert.ok);
229}
230assert.ok = ok;
231
232// 5. The equality assertion tests shallow, coercive equality with
233// ==.
234// assert.equal(actual, expected, message_opt);
235
236assert.equal = function equal(actual, expected, message) {
237 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
238};
239
240// 6. The non-equality assertion tests for whether two objects are not equal
241// with != assert.notEqual(actual, expected, message_opt);
242
243assert.notEqual = function notEqual(actual, expected, message) {
244 if (actual == expected) {
245 fail(actual, expected, message, '!=', assert.notEqual);
246 }
247};
248
249// 7. The equivalence assertion tests a deep equality relation.
250// assert.deepEqual(actual, expected, message_opt);
251
252assert.deepEqual = function deepEqual(actual, expected, message) {
253 if (!_deepEqual(actual, expected, false)) {
254 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
255 }
256};
257
258assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
259 if (!_deepEqual(actual, expected, true)) {
260 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
261 }
262};
263
264function _deepEqual(actual, expected, strict, memos) {
265 // 7.1. All identical values are equivalent, as determined by ===.
266 if (actual === expected) {
267 return true;
268 } else if (isBuffer(actual) && isBuffer(expected)) {
269 return compare(actual, expected) === 0;
270
271 // 7.2. If the expected value is a Date object, the actual value is
272 // equivalent if it is also a Date object that refers to the same time.
273 } else if (util.isDate(actual) && util.isDate(expected)) {
274 return actual.getTime() === expected.getTime();
275
276 // 7.3 If the expected value is a RegExp object, the actual value is
277 // equivalent if it is also a RegExp object with the same source and
278 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
279 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
280 return actual.source === expected.source &&
281 actual.global === expected.global &&
282 actual.multiline === expected.multiline &&
283 actual.lastIndex === expected.lastIndex &&
284 actual.ignoreCase === expected.ignoreCase;
285
286 // 7.4. Other pairs that do not both pass typeof value == 'object',
287 // equivalence is determined by ==.
288 } else if ((actual === null || typeof actual !== 'object') &&
289 (expected === null || typeof expected !== 'object')) {
290 return strict ? actual === expected : actual == expected;
291
292 // If both values are instances of typed arrays, wrap their underlying
293 // ArrayBuffers in a Buffer each to increase performance
294 // This optimization requires the arrays to have the same type as checked by
295 // Object.prototype.toString (aka pToString). Never perform binary
296 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
297 // bit patterns are not identical.
298 } else if (isView(actual) && isView(expected) &&
299 pToString(actual) === pToString(expected) &&
300 !(actual instanceof Float32Array ||
301 actual instanceof Float64Array)) {
302 return compare(new Uint8Array(actual.buffer),
303 new Uint8Array(expected.buffer)) === 0;
304
305 // 7.5 For all other Object pairs, including Array objects, equivalence is
306 // determined by having the same number of owned properties (as verified
307 // with Object.prototype.hasOwnProperty.call), the same set of keys
308 // (although not necessarily the same order), equivalent values for every
309 // corresponding key, and an identical 'prototype' property. Note: this
310 // accounts for both named and indexed properties on Arrays.
311 } else if (isBuffer(actual) !== isBuffer(expected)) {
312 return false;
313 } else {
314 memos = memos || {actual: [], expected: []};
315
316 var actualIndex = memos.actual.indexOf(actual);
317 if (actualIndex !== -1) {
318 if (actualIndex === memos.expected.indexOf(expected)) {
319 return true;
320 }
321 }
322
323 memos.actual.push(actual);
324 memos.expected.push(expected);
325
326 return objEquiv(actual, expected, strict, memos);
327 }
328}
329
330function isArguments(object) {
331 return Object.prototype.toString.call(object) == '[object Arguments]';
332}
333
334function objEquiv(a, b, strict, actualVisitedObjects) {
335 if (a === null || a === undefined || b === null || b === undefined)
336 return false;
337 // if one is a primitive, the other must be same
338 if (util.isPrimitive(a) || util.isPrimitive(b))
339 return a === b;
340 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
341 return false;
342 var aIsArgs = isArguments(a);
343 var bIsArgs = isArguments(b);
344 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
345 return false;
346 if (aIsArgs) {
347 a = pSlice.call(a);
348 b = pSlice.call(b);
349 return _deepEqual(a, b, strict);
350 }
351 var ka = objectKeys(a);
352 var kb = objectKeys(b);
353 var key, i;
354 // having the same number of owned properties (keys incorporates
355 // hasOwnProperty)
356 if (ka.length !== kb.length)
357 return false;
358 //the same set of keys (although not necessarily the same order),
359 ka.sort();
360 kb.sort();
361 //~~~cheap key test
362 for (i = ka.length - 1; i >= 0; i--) {
363 if (ka[i] !== kb[i])
364 return false;
365 }
366 //equivalent values for every corresponding key, and
367 //~~~possibly expensive deep test
368 for (i = ka.length - 1; i >= 0; i--) {
369 key = ka[i];
370 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
371 return false;
372 }
373 return true;
374}
375
376// 8. The non-equivalence assertion tests for any deep inequality.
377// assert.notDeepEqual(actual, expected, message_opt);
378
379assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
380 if (_deepEqual(actual, expected, false)) {
381 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
382 }
383};
384
385assert.notDeepStrictEqual = notDeepStrictEqual;
386function notDeepStrictEqual(actual, expected, message) {
387 if (_deepEqual(actual, expected, true)) {
388 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
389 }
390}
391
392
393// 9. The strict equality assertion tests strict equality, as determined by ===.
394// assert.strictEqual(actual, expected, message_opt);
395
396assert.strictEqual = function strictEqual(actual, expected, message) {
397 if (actual !== expected) {
398 fail(actual, expected, message, '===', assert.strictEqual);
399 }
400};
401
402// 10. The strict non-equality assertion tests for strict inequality, as
403// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
404
405assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
406 if (actual === expected) {
407 fail(actual, expected, message, '!==', assert.notStrictEqual);
408 }
409};
410
411function expectedException(actual, expected) {
412 if (!actual || !expected) {
413 return false;
414 }
415
416 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
417 return expected.test(actual);
418 }
419
420 try {
421 if (actual instanceof expected) {
422 return true;
423 }
424 } catch (e) {
425 // Ignore. The instanceof check doesn't work for arrow functions.
426 }
427
428 if (Error.isPrototypeOf(expected)) {
429 return false;
430 }
431
432 return expected.call({}, actual) === true;
433}
434
435function _tryBlock(block) {
436 var error;
437 try {
438 block();
439 } catch (e) {
440 error = e;
441 }
442 return error;
443}
444
445function _throws(shouldThrow, block, expected, message) {
446 var actual;
447
448 if (typeof block !== 'function') {
449 throw new TypeError('"block" argument must be a function');
450 }
451
452 if (typeof expected === 'string') {
453 message = expected;
454 expected = null;
455 }
456
457 actual = _tryBlock(block);
458
459 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
460 (message ? ' ' + message : '.');
461
462 if (shouldThrow && !actual) {
463 fail(actual, expected, 'Missing expected exception' + message);
464 }
465
466 var userProvidedMessage = typeof message === 'string';
467 var isUnwantedException = !shouldThrow && util.isError(actual);
468 var isUnexpectedException = !shouldThrow && actual && !expected;
469
470 if ((isUnwantedException &&
471 userProvidedMessage &&
472 expectedException(actual, expected)) ||
473 isUnexpectedException) {
474 fail(actual, expected, 'Got unwanted exception' + message);
475 }
476
477 if ((shouldThrow && actual && expected &&
478 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
479 throw actual;
480 }
481}
482
483// 11. Expected to throw an error:
484// assert.throws(block, Error_opt, message_opt);
485
486assert.throws = function(block, /*optional*/error, /*optional*/message) {
487 _throws(true, block, error, message);
488};
489
490// EXTENSION! This is annoying to write outside this module.
491assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
492 _throws(false, block, error, message);
493};
494
495assert.ifError = function(err) { if (err) throw err; };
496
497// Expose a strict only variant of assert
498function strict(value, message) {
499 if (!value) fail(value, true, message, '==', strict);
500}
501assert.strict = objectAssign(strict, assert, {
502 equal: assert.strictEqual,
503 deepEqual: assert.deepStrictEqual,
504 notEqual: assert.notStrictEqual,
505 notDeepEqual: assert.notDeepStrictEqual
506});
507assert.strict.strict = assert.strict;
508
509var objectKeys = Object.keys || function (obj) {
510 var keys = [];
511 for (var key in obj) {
512 if (hasOwn.call(obj, key)) keys.push(key);
513 }
514 return keys;
515};
516
517}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
518},{"object.assign/polyfill":91,"util/":143}],2:[function(_dereq_,module,exports){
519'use strict'
520
521exports.byteLength = byteLength
522exports.toByteArray = toByteArray
523exports.fromByteArray = fromByteArray
524
525var lookup = []
526var revLookup = []
527var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
528
529var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
530for (var i = 0, len = code.length; i < len; ++i) {
531 lookup[i] = code[i]
532 revLookup[code.charCodeAt(i)] = i
533}
534
535// Support decoding URL-safe base64 strings, as Node.js does.
536// See: https://en.wikipedia.org/wiki/Base64#URL_applications
537revLookup['-'.charCodeAt(0)] = 62
538revLookup['_'.charCodeAt(0)] = 63
539
540function getLens (b64) {
541 var len = b64.length
542
543 if (len % 4 > 0) {
544 throw new Error('Invalid string. Length must be a multiple of 4')
545 }
546
547 // Trim off extra bytes after placeholder bytes are found
548 // See: https://github.com/beatgammit/base64-js/issues/42
549 var validLen = b64.indexOf('=')
550 if (validLen === -1) validLen = len
551
552 var placeHoldersLen = validLen === len
553 ? 0
554 : 4 - (validLen % 4)
555
556 return [validLen, placeHoldersLen]
557}
558
559// base64 is 4/3 + up to two characters of the original data
560function byteLength (b64) {
561 var lens = getLens(b64)
562 var validLen = lens[0]
563 var placeHoldersLen = lens[1]
564 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
565}
566
567function _byteLength (b64, validLen, placeHoldersLen) {
568 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
569}
570
571function toByteArray (b64) {
572 var tmp
573 var lens = getLens(b64)
574 var validLen = lens[0]
575 var placeHoldersLen = lens[1]
576
577 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
578
579 var curByte = 0
580
581 // if there are placeholders, only get up to the last complete 4 chars
582 var len = placeHoldersLen > 0
583 ? validLen - 4
584 : validLen
585
586 var i
587 for (i = 0; i < len; i += 4) {
588 tmp =
589 (revLookup[b64.charCodeAt(i)] << 18) |
590 (revLookup[b64.charCodeAt(i + 1)] << 12) |
591 (revLookup[b64.charCodeAt(i + 2)] << 6) |
592 revLookup[b64.charCodeAt(i + 3)]
593 arr[curByte++] = (tmp >> 16) & 0xFF
594 arr[curByte++] = (tmp >> 8) & 0xFF
595 arr[curByte++] = tmp & 0xFF
596 }
597
598 if (placeHoldersLen === 2) {
599 tmp =
600 (revLookup[b64.charCodeAt(i)] << 2) |
601 (revLookup[b64.charCodeAt(i + 1)] >> 4)
602 arr[curByte++] = tmp & 0xFF
603 }
604
605 if (placeHoldersLen === 1) {
606 tmp =
607 (revLookup[b64.charCodeAt(i)] << 10) |
608 (revLookup[b64.charCodeAt(i + 1)] << 4) |
609 (revLookup[b64.charCodeAt(i + 2)] >> 2)
610 arr[curByte++] = (tmp >> 8) & 0xFF
611 arr[curByte++] = tmp & 0xFF
612 }
613
614 return arr
615}
616
617function tripletToBase64 (num) {
618 return lookup[num >> 18 & 0x3F] +
619 lookup[num >> 12 & 0x3F] +
620 lookup[num >> 6 & 0x3F] +
621 lookup[num & 0x3F]
622}
623
624function encodeChunk (uint8, start, end) {
625 var tmp
626 var output = []
627 for (var i = start; i < end; i += 3) {
628 tmp =
629 ((uint8[i] << 16) & 0xFF0000) +
630 ((uint8[i + 1] << 8) & 0xFF00) +
631 (uint8[i + 2] & 0xFF)
632 output.push(tripletToBase64(tmp))
633 }
634 return output.join('')
635}
636
637function fromByteArray (uint8) {
638 var tmp
639 var len = uint8.length
640 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
641 var parts = []
642 var maxChunkLength = 16383 // must be multiple of 3
643
644 // go through the array every three bytes, we'll deal with trailing stuff later
645 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
646 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
647 }
648
649 // pad the end with zeros, but make sure to not forget the extra bytes
650 if (extraBytes === 1) {
651 tmp = uint8[len - 1]
652 parts.push(
653 lookup[tmp >> 2] +
654 lookup[(tmp << 4) & 0x3F] +
655 '=='
656 )
657 } else if (extraBytes === 2) {
658 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
659 parts.push(
660 lookup[tmp >> 10] +
661 lookup[(tmp >> 4) & 0x3F] +
662 lookup[(tmp << 2) & 0x3F] +
663 '='
664 )
665 }
666
667 return parts.join('')
668}
669
670},{}],3:[function(_dereq_,module,exports){
671
672},{}],4:[function(_dereq_,module,exports){
673(function (Buffer){(function (){
674/*!
675 * The buffer module from node.js, for the browser.
676 *
677 * @author Feross Aboukhadijeh <https://feross.org>
678 * @license MIT
679 */
680/* eslint-disable no-proto */
681
682'use strict'
683
684var base64 = _dereq_('base64-js')
685var ieee754 = _dereq_('ieee754')
686var customInspectSymbol =
687 (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
688 ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
689 : null
690
691exports.Buffer = Buffer
692exports.SlowBuffer = SlowBuffer
693exports.INSPECT_MAX_BYTES = 50
694
695var K_MAX_LENGTH = 0x7fffffff
696exports.kMaxLength = K_MAX_LENGTH
697
698/**
699 * If `Buffer.TYPED_ARRAY_SUPPORT`:
700 * === true Use Uint8Array implementation (fastest)
701 * === false Print warning and recommend using `buffer` v4.x which has an Object
702 * implementation (most compatible, even IE6)
703 *
704 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
705 * Opera 11.6+, iOS 4.2+.
706 *
707 * We report that the browser does not support typed arrays if the are not subclassable
708 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
709 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
710 * for __proto__ and has a buggy typed array implementation.
711 */
712Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
713
714if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
715 typeof console.error === 'function') {
716 console.error(
717 'This browser lacks typed array (Uint8Array) support which is required by ' +
718 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
719 )
720}
721
722function typedArraySupport () {
723 // Can typed array instances can be augmented?
724 try {
725 var arr = new Uint8Array(1)
726 var proto = { foo: function () { return 42 } }
727 Object.setPrototypeOf(proto, Uint8Array.prototype)
728 Object.setPrototypeOf(arr, proto)
729 return arr.foo() === 42
730 } catch (e) {
731 return false
732 }
733}
734
735Object.defineProperty(Buffer.prototype, 'parent', {
736 enumerable: true,
737 get: function () {
738 if (!Buffer.isBuffer(this)) return undefined
739 return this.buffer
740 }
741})
742
743Object.defineProperty(Buffer.prototype, 'offset', {
744 enumerable: true,
745 get: function () {
746 if (!Buffer.isBuffer(this)) return undefined
747 return this.byteOffset
748 }
749})
750
751function createBuffer (length) {
752 if (length > K_MAX_LENGTH) {
753 throw new RangeError('The value "' + length + '" is invalid for option "size"')
754 }
755 // Return an augmented `Uint8Array` instance
756 var buf = new Uint8Array(length)
757 Object.setPrototypeOf(buf, Buffer.prototype)
758 return buf
759}
760
761/**
762 * The Buffer constructor returns instances of `Uint8Array` that have their
763 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
764 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
765 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
766 * returns a single octet.
767 *
768 * The `Uint8Array` prototype remains unmodified.
769 */
770
771function Buffer (arg, encodingOrOffset, length) {
772 // Common case.
773 if (typeof arg === 'number') {
774 if (typeof encodingOrOffset === 'string') {
775 throw new TypeError(
776 'The "string" argument must be of type string. Received type number'
777 )
778 }
779 return allocUnsafe(arg)
780 }
781 return from(arg, encodingOrOffset, length)
782}
783
784Buffer.poolSize = 8192 // not used by this implementation
785
786function from (value, encodingOrOffset, length) {
787 if (typeof value === 'string') {
788 return fromString(value, encodingOrOffset)
789 }
790
791 if (ArrayBuffer.isView(value)) {
792 return fromArrayView(value)
793 }
794
795 if (value == null) {
796 throw new TypeError(
797 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
798 'or Array-like Object. Received type ' + (typeof value)
799 )
800 }
801
802 if (isInstance(value, ArrayBuffer) ||
803 (value && isInstance(value.buffer, ArrayBuffer))) {
804 return fromArrayBuffer(value, encodingOrOffset, length)
805 }
806
807 if (typeof SharedArrayBuffer !== 'undefined' &&
808 (isInstance(value, SharedArrayBuffer) ||
809 (value && isInstance(value.buffer, SharedArrayBuffer)))) {
810 return fromArrayBuffer(value, encodingOrOffset, length)
811 }
812
813 if (typeof value === 'number') {
814 throw new TypeError(
815 'The "value" argument must not be of type number. Received type number'
816 )
817 }
818
819 var valueOf = value.valueOf && value.valueOf()
820 if (valueOf != null && valueOf !== value) {
821 return Buffer.from(valueOf, encodingOrOffset, length)
822 }
823
824 var b = fromObject(value)
825 if (b) return b
826
827 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
828 typeof value[Symbol.toPrimitive] === 'function') {
829 return Buffer.from(
830 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
831 )
832 }
833
834 throw new TypeError(
835 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
836 'or Array-like Object. Received type ' + (typeof value)
837 )
838}
839
840/**
841 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
842 * if value is a number.
843 * Buffer.from(str[, encoding])
844 * Buffer.from(array)
845 * Buffer.from(buffer)
846 * Buffer.from(arrayBuffer[, byteOffset[, length]])
847 **/
848Buffer.from = function (value, encodingOrOffset, length) {
849 return from(value, encodingOrOffset, length)
850}
851
852// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
853// https://github.com/feross/buffer/pull/148
854Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
855Object.setPrototypeOf(Buffer, Uint8Array)
856
857function assertSize (size) {
858 if (typeof size !== 'number') {
859 throw new TypeError('"size" argument must be of type number')
860 } else if (size < 0) {
861 throw new RangeError('The value "' + size + '" is invalid for option "size"')
862 }
863}
864
865function alloc (size, fill, encoding) {
866 assertSize(size)
867 if (size <= 0) {
868 return createBuffer(size)
869 }
870 if (fill !== undefined) {
871 // Only pay attention to encoding if it's a string. This
872 // prevents accidentally sending in a number that would
873 // be interpreted as a start offset.
874 return typeof encoding === 'string'
875 ? createBuffer(size).fill(fill, encoding)
876 : createBuffer(size).fill(fill)
877 }
878 return createBuffer(size)
879}
880
881/**
882 * Creates a new filled Buffer instance.
883 * alloc(size[, fill[, encoding]])
884 **/
885Buffer.alloc = function (size, fill, encoding) {
886 return alloc(size, fill, encoding)
887}
888
889function allocUnsafe (size) {
890 assertSize(size)
891 return createBuffer(size < 0 ? 0 : checked(size) | 0)
892}
893
894/**
895 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
896 * */
897Buffer.allocUnsafe = function (size) {
898 return allocUnsafe(size)
899}
900/**
901 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
902 */
903Buffer.allocUnsafeSlow = function (size) {
904 return allocUnsafe(size)
905}
906
907function fromString (string, encoding) {
908 if (typeof encoding !== 'string' || encoding === '') {
909 encoding = 'utf8'
910 }
911
912 if (!Buffer.isEncoding(encoding)) {
913 throw new TypeError('Unknown encoding: ' + encoding)
914 }
915
916 var length = byteLength(string, encoding) | 0
917 var buf = createBuffer(length)
918
919 var actual = buf.write(string, encoding)
920
921 if (actual !== length) {
922 // Writing a hex string, for example, that contains invalid characters will
923 // cause everything after the first invalid character to be ignored. (e.g.
924 // 'abxxcd' will be treated as 'ab')
925 buf = buf.slice(0, actual)
926 }
927
928 return buf
929}
930
931function fromArrayLike (array) {
932 var length = array.length < 0 ? 0 : checked(array.length) | 0
933 var buf = createBuffer(length)
934 for (var i = 0; i < length; i += 1) {
935 buf[i] = array[i] & 255
936 }
937 return buf
938}
939
940function fromArrayView (arrayView) {
941 if (isInstance(arrayView, Uint8Array)) {
942 var copy = new Uint8Array(arrayView)
943 return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
944 }
945 return fromArrayLike(arrayView)
946}
947
948function fromArrayBuffer (array, byteOffset, length) {
949 if (byteOffset < 0 || array.byteLength < byteOffset) {
950 throw new RangeError('"offset" is outside of buffer bounds')
951 }
952
953 if (array.byteLength < byteOffset + (length || 0)) {
954 throw new RangeError('"length" is outside of buffer bounds')
955 }
956
957 var buf
958 if (byteOffset === undefined && length === undefined) {
959 buf = new Uint8Array(array)
960 } else if (length === undefined) {
961 buf = new Uint8Array(array, byteOffset)
962 } else {
963 buf = new Uint8Array(array, byteOffset, length)
964 }
965
966 // Return an augmented `Uint8Array` instance
967 Object.setPrototypeOf(buf, Buffer.prototype)
968
969 return buf
970}
971
972function fromObject (obj) {
973 if (Buffer.isBuffer(obj)) {
974 var len = checked(obj.length) | 0
975 var buf = createBuffer(len)
976
977 if (buf.length === 0) {
978 return buf
979 }
980
981 obj.copy(buf, 0, 0, len)
982 return buf
983 }
984
985 if (obj.length !== undefined) {
986 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
987 return createBuffer(0)
988 }
989 return fromArrayLike(obj)
990 }
991
992 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
993 return fromArrayLike(obj.data)
994 }
995}
996
997function checked (length) {
998 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
999 // length is NaN (which is otherwise coerced to zero.)
1000 if (length >= K_MAX_LENGTH) {
1001 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1002 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
1003 }
1004 return length | 0
1005}
1006
1007function SlowBuffer (length) {
1008 if (+length != length) { // eslint-disable-line eqeqeq
1009 length = 0
1010 }
1011 return Buffer.alloc(+length)
1012}
1013
1014Buffer.isBuffer = function isBuffer (b) {
1015 return b != null && b._isBuffer === true &&
1016 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
1017}
1018
1019Buffer.compare = function compare (a, b) {
1020 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
1021 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
1022 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
1023 throw new TypeError(
1024 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
1025 )
1026 }
1027
1028 if (a === b) return 0
1029
1030 var x = a.length
1031 var y = b.length
1032
1033 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
1034 if (a[i] !== b[i]) {
1035 x = a[i]
1036 y = b[i]
1037 break
1038 }
1039 }
1040
1041 if (x < y) return -1
1042 if (y < x) return 1
1043 return 0
1044}
1045
1046Buffer.isEncoding = function isEncoding (encoding) {
1047 switch (String(encoding).toLowerCase()) {
1048 case 'hex':
1049 case 'utf8':
1050 case 'utf-8':
1051 case 'ascii':
1052 case 'latin1':
1053 case 'binary':
1054 case 'base64':
1055 case 'ucs2':
1056 case 'ucs-2':
1057 case 'utf16le':
1058 case 'utf-16le':
1059 return true
1060 default:
1061 return false
1062 }
1063}
1064
1065Buffer.concat = function concat (list, length) {
1066 if (!Array.isArray(list)) {
1067 throw new TypeError('"list" argument must be an Array of Buffers')
1068 }
1069
1070 if (list.length === 0) {
1071 return Buffer.alloc(0)
1072 }
1073
1074 var i
1075 if (length === undefined) {
1076 length = 0
1077 for (i = 0; i < list.length; ++i) {
1078 length += list[i].length
1079 }
1080 }
1081
1082 var buffer = Buffer.allocUnsafe(length)
1083 var pos = 0
1084 for (i = 0; i < list.length; ++i) {
1085 var buf = list[i]
1086 if (isInstance(buf, Uint8Array)) {
1087 if (pos + buf.length > buffer.length) {
1088 Buffer.from(buf).copy(buffer, pos)
1089 } else {
1090 Uint8Array.prototype.set.call(
1091 buffer,
1092 buf,
1093 pos
1094 )
1095 }
1096 } else if (!Buffer.isBuffer(buf)) {
1097 throw new TypeError('"list" argument must be an Array of Buffers')
1098 } else {
1099 buf.copy(buffer, pos)
1100 }
1101 pos += buf.length
1102 }
1103 return buffer
1104}
1105
1106function byteLength (string, encoding) {
1107 if (Buffer.isBuffer(string)) {
1108 return string.length
1109 }
1110 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
1111 return string.byteLength
1112 }
1113 if (typeof string !== 'string') {
1114 throw new TypeError(
1115 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
1116 'Received type ' + typeof string
1117 )
1118 }
1119
1120 var len = string.length
1121 var mustMatch = (arguments.length > 2 && arguments[2] === true)
1122 if (!mustMatch && len === 0) return 0
1123
1124 // Use a for loop to avoid recursion
1125 var loweredCase = false
1126 for (;;) {
1127 switch (encoding) {
1128 case 'ascii':
1129 case 'latin1':
1130 case 'binary':
1131 return len
1132 case 'utf8':
1133 case 'utf-8':
1134 return utf8ToBytes(string).length
1135 case 'ucs2':
1136 case 'ucs-2':
1137 case 'utf16le':
1138 case 'utf-16le':
1139 return len * 2
1140 case 'hex':
1141 return len >>> 1
1142 case 'base64':
1143 return base64ToBytes(string).length
1144 default:
1145 if (loweredCase) {
1146 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
1147 }
1148 encoding = ('' + encoding).toLowerCase()
1149 loweredCase = true
1150 }
1151 }
1152}
1153Buffer.byteLength = byteLength
1154
1155function slowToString (encoding, start, end) {
1156 var loweredCase = false
1157
1158 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1159 // property of a typed array.
1160
1161 // This behaves neither like String nor Uint8Array in that we set start/end
1162 // to their upper/lower bounds if the value passed is out of range.
1163 // undefined is handled specially as per ECMA-262 6th Edition,
1164 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1165 if (start === undefined || start < 0) {
1166 start = 0
1167 }
1168 // Return early if start > this.length. Done here to prevent potential uint32
1169 // coercion fail below.
1170 if (start > this.length) {
1171 return ''
1172 }
1173
1174 if (end === undefined || end > this.length) {
1175 end = this.length
1176 }
1177
1178 if (end <= 0) {
1179 return ''
1180 }
1181
1182 // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
1183 end >>>= 0
1184 start >>>= 0
1185
1186 if (end <= start) {
1187 return ''
1188 }
1189
1190 if (!encoding) encoding = 'utf8'
1191
1192 while (true) {
1193 switch (encoding) {
1194 case 'hex':
1195 return hexSlice(this, start, end)
1196
1197 case 'utf8':
1198 case 'utf-8':
1199 return utf8Slice(this, start, end)
1200
1201 case 'ascii':
1202 return asciiSlice(this, start, end)
1203
1204 case 'latin1':
1205 case 'binary':
1206 return latin1Slice(this, start, end)
1207
1208 case 'base64':
1209 return base64Slice(this, start, end)
1210
1211 case 'ucs2':
1212 case 'ucs-2':
1213 case 'utf16le':
1214 case 'utf-16le':
1215 return utf16leSlice(this, start, end)
1216
1217 default:
1218 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1219 encoding = (encoding + '').toLowerCase()
1220 loweredCase = true
1221 }
1222 }
1223}
1224
1225// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1226// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1227// reliably in a browserify context because there could be multiple different
1228// copies of the 'buffer' package in use. This method works even for Buffer
1229// instances that were created from another copy of the `buffer` package.
1230// See: https://github.com/feross/buffer/issues/154
1231Buffer.prototype._isBuffer = true
1232
1233function swap (b, n, m) {
1234 var i = b[n]
1235 b[n] = b[m]
1236 b[m] = i
1237}
1238
1239Buffer.prototype.swap16 = function swap16 () {
1240 var len = this.length
1241 if (len % 2 !== 0) {
1242 throw new RangeError('Buffer size must be a multiple of 16-bits')
1243 }
1244 for (var i = 0; i < len; i += 2) {
1245 swap(this, i, i + 1)
1246 }
1247 return this
1248}
1249
1250Buffer.prototype.swap32 = function swap32 () {
1251 var len = this.length
1252 if (len % 4 !== 0) {
1253 throw new RangeError('Buffer size must be a multiple of 32-bits')
1254 }
1255 for (var i = 0; i < len; i += 4) {
1256 swap(this, i, i + 3)
1257 swap(this, i + 1, i + 2)
1258 }
1259 return this
1260}
1261
1262Buffer.prototype.swap64 = function swap64 () {
1263 var len = this.length
1264 if (len % 8 !== 0) {
1265 throw new RangeError('Buffer size must be a multiple of 64-bits')
1266 }
1267 for (var i = 0; i < len; i += 8) {
1268 swap(this, i, i + 7)
1269 swap(this, i + 1, i + 6)
1270 swap(this, i + 2, i + 5)
1271 swap(this, i + 3, i + 4)
1272 }
1273 return this
1274}
1275
1276Buffer.prototype.toString = function toString () {
1277 var length = this.length
1278 if (length === 0) return ''
1279 if (arguments.length === 0) return utf8Slice(this, 0, length)
1280 return slowToString.apply(this, arguments)
1281}
1282
1283Buffer.prototype.toLocaleString = Buffer.prototype.toString
1284
1285Buffer.prototype.equals = function equals (b) {
1286 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1287 if (this === b) return true
1288 return Buffer.compare(this, b) === 0
1289}
1290
1291Buffer.prototype.inspect = function inspect () {
1292 var str = ''
1293 var max = exports.INSPECT_MAX_BYTES
1294 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
1295 if (this.length > max) str += ' ... '
1296 return '<Buffer ' + str + '>'
1297}
1298if (customInspectSymbol) {
1299 Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
1300}
1301
1302Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1303 if (isInstance(target, Uint8Array)) {
1304 target = Buffer.from(target, target.offset, target.byteLength)
1305 }
1306 if (!Buffer.isBuffer(target)) {
1307 throw new TypeError(
1308 'The "target" argument must be one of type Buffer or Uint8Array. ' +
1309 'Received type ' + (typeof target)
1310 )
1311 }
1312
1313 if (start === undefined) {
1314 start = 0
1315 }
1316 if (end === undefined) {
1317 end = target ? target.length : 0
1318 }
1319 if (thisStart === undefined) {
1320 thisStart = 0
1321 }
1322 if (thisEnd === undefined) {
1323 thisEnd = this.length
1324 }
1325
1326 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1327 throw new RangeError('out of range index')
1328 }
1329
1330 if (thisStart >= thisEnd && start >= end) {
1331 return 0
1332 }
1333 if (thisStart >= thisEnd) {
1334 return -1
1335 }
1336 if (start >= end) {
1337 return 1
1338 }
1339
1340 start >>>= 0
1341 end >>>= 0
1342 thisStart >>>= 0
1343 thisEnd >>>= 0
1344
1345 if (this === target) return 0
1346
1347 var x = thisEnd - thisStart
1348 var y = end - start
1349 var len = Math.min(x, y)
1350
1351 var thisCopy = this.slice(thisStart, thisEnd)
1352 var targetCopy = target.slice(start, end)
1353
1354 for (var i = 0; i < len; ++i) {
1355 if (thisCopy[i] !== targetCopy[i]) {
1356 x = thisCopy[i]
1357 y = targetCopy[i]
1358 break
1359 }
1360 }
1361
1362 if (x < y) return -1
1363 if (y < x) return 1
1364 return 0
1365}
1366
1367// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
1368// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
1369//
1370// Arguments:
1371// - buffer - a Buffer to search
1372// - val - a string, Buffer, or number
1373// - byteOffset - an index into `buffer`; will be clamped to an int32
1374// - encoding - an optional encoding, relevant is val is a string
1375// - dir - true for indexOf, false for lastIndexOf
1376function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
1377 // Empty buffer means no match
1378 if (buffer.length === 0) return -1
1379
1380 // Normalize byteOffset
1381 if (typeof byteOffset === 'string') {
1382 encoding = byteOffset
1383 byteOffset = 0
1384 } else if (byteOffset > 0x7fffffff) {
1385 byteOffset = 0x7fffffff
1386 } else if (byteOffset < -0x80000000) {
1387 byteOffset = -0x80000000
1388 }
1389 byteOffset = +byteOffset // Coerce to Number.
1390 if (numberIsNaN(byteOffset)) {
1391 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
1392 byteOffset = dir ? 0 : (buffer.length - 1)
1393 }
1394
1395 // Normalize byteOffset: negative offsets start from the end of the buffer
1396 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
1397 if (byteOffset >= buffer.length) {
1398 if (dir) return -1
1399 else byteOffset = buffer.length - 1
1400 } else if (byteOffset < 0) {
1401 if (dir) byteOffset = 0
1402 else return -1
1403 }
1404
1405 // Normalize val
1406 if (typeof val === 'string') {
1407 val = Buffer.from(val, encoding)
1408 }
1409
1410 // Finally, search either indexOf (if dir is true) or lastIndexOf
1411 if (Buffer.isBuffer(val)) {
1412 // Special case: looking for empty string/buffer always fails
1413 if (val.length === 0) {
1414 return -1
1415 }
1416 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1417 } else if (typeof val === 'number') {
1418 val = val & 0xFF // Search for a byte value [0-255]
1419 if (typeof Uint8Array.prototype.indexOf === 'function') {
1420 if (dir) {
1421 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1422 } else {
1423 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1424 }
1425 }
1426 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
1427 }
1428
1429 throw new TypeError('val must be string, number or Buffer')
1430}
1431
1432function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1433 var indexSize = 1
1434 var arrLength = arr.length
1435 var valLength = val.length
1436
1437 if (encoding !== undefined) {
1438 encoding = String(encoding).toLowerCase()
1439 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1440 encoding === 'utf16le' || encoding === 'utf-16le') {
1441 if (arr.length < 2 || val.length < 2) {
1442 return -1
1443 }
1444 indexSize = 2
1445 arrLength /= 2
1446 valLength /= 2
1447 byteOffset /= 2
1448 }
1449 }
1450
1451 function read (buf, i) {
1452 if (indexSize === 1) {
1453 return buf[i]
1454 } else {
1455 return buf.readUInt16BE(i * indexSize)
1456 }
1457 }
1458
1459 var i
1460 if (dir) {
1461 var foundIndex = -1
1462 for (i = byteOffset; i < arrLength; i++) {
1463 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1464 if (foundIndex === -1) foundIndex = i
1465 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1466 } else {
1467 if (foundIndex !== -1) i -= i - foundIndex
1468 foundIndex = -1
1469 }
1470 }
1471 } else {
1472 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1473 for (i = byteOffset; i >= 0; i--) {
1474 var found = true
1475 for (var j = 0; j < valLength; j++) {
1476 if (read(arr, i + j) !== read(val, j)) {
1477 found = false
1478 break
1479 }
1480 }
1481 if (found) return i
1482 }
1483 }
1484
1485 return -1
1486}
1487
1488Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1489 return this.indexOf(val, byteOffset, encoding) !== -1
1490}
1491
1492Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1493 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1494}
1495
1496Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1497 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1498}
1499
1500function hexWrite (buf, string, offset, length) {
1501 offset = Number(offset) || 0
1502 var remaining = buf.length - offset
1503 if (!length) {
1504 length = remaining
1505 } else {
1506 length = Number(length)
1507 if (length > remaining) {
1508 length = remaining
1509 }
1510 }
1511
1512 var strLen = string.length
1513
1514 if (length > strLen / 2) {
1515 length = strLen / 2
1516 }
1517 for (var i = 0; i < length; ++i) {
1518 var parsed = parseInt(string.substr(i * 2, 2), 16)
1519 if (numberIsNaN(parsed)) return i
1520 buf[offset + i] = parsed
1521 }
1522 return i
1523}
1524
1525function utf8Write (buf, string, offset, length) {
1526 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1527}
1528
1529function asciiWrite (buf, string, offset, length) {
1530 return blitBuffer(asciiToBytes(string), buf, offset, length)
1531}
1532
1533function base64Write (buf, string, offset, length) {
1534 return blitBuffer(base64ToBytes(string), buf, offset, length)
1535}
1536
1537function ucs2Write (buf, string, offset, length) {
1538 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1539}
1540
1541Buffer.prototype.write = function write (string, offset, length, encoding) {
1542 // Buffer#write(string)
1543 if (offset === undefined) {
1544 encoding = 'utf8'
1545 length = this.length
1546 offset = 0
1547 // Buffer#write(string, encoding)
1548 } else if (length === undefined && typeof offset === 'string') {
1549 encoding = offset
1550 length = this.length
1551 offset = 0
1552 // Buffer#write(string, offset[, length][, encoding])
1553 } else if (isFinite(offset)) {
1554 offset = offset >>> 0
1555 if (isFinite(length)) {
1556 length = length >>> 0
1557 if (encoding === undefined) encoding = 'utf8'
1558 } else {
1559 encoding = length
1560 length = undefined
1561 }
1562 } else {
1563 throw new Error(
1564 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1565 )
1566 }
1567
1568 var remaining = this.length - offset
1569 if (length === undefined || length > remaining) length = remaining
1570
1571 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1572 throw new RangeError('Attempt to write outside buffer bounds')
1573 }
1574
1575 if (!encoding) encoding = 'utf8'
1576
1577 var loweredCase = false
1578 for (;;) {
1579 switch (encoding) {
1580 case 'hex':
1581 return hexWrite(this, string, offset, length)
1582
1583 case 'utf8':
1584 case 'utf-8':
1585 return utf8Write(this, string, offset, length)
1586
1587 case 'ascii':
1588 case 'latin1':
1589 case 'binary':
1590 return asciiWrite(this, string, offset, length)
1591
1592 case 'base64':
1593 // Warning: maxLength not taken into account in base64Write
1594 return base64Write(this, string, offset, length)
1595
1596 case 'ucs2':
1597 case 'ucs-2':
1598 case 'utf16le':
1599 case 'utf-16le':
1600 return ucs2Write(this, string, offset, length)
1601
1602 default:
1603 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1604 encoding = ('' + encoding).toLowerCase()
1605 loweredCase = true
1606 }
1607 }
1608}
1609
1610Buffer.prototype.toJSON = function toJSON () {
1611 return {
1612 type: 'Buffer',
1613 data: Array.prototype.slice.call(this._arr || this, 0)
1614 }
1615}
1616
1617function base64Slice (buf, start, end) {
1618 if (start === 0 && end === buf.length) {
1619 return base64.fromByteArray(buf)
1620 } else {
1621 return base64.fromByteArray(buf.slice(start, end))
1622 }
1623}
1624
1625function utf8Slice (buf, start, end) {
1626 end = Math.min(buf.length, end)
1627 var res = []
1628
1629 var i = start
1630 while (i < end) {
1631 var firstByte = buf[i]
1632 var codePoint = null
1633 var bytesPerSequence = (firstByte > 0xEF)
1634 ? 4
1635 : (firstByte > 0xDF)
1636 ? 3
1637 : (firstByte > 0xBF)
1638 ? 2
1639 : 1
1640
1641 if (i + bytesPerSequence <= end) {
1642 var secondByte, thirdByte, fourthByte, tempCodePoint
1643
1644 switch (bytesPerSequence) {
1645 case 1:
1646 if (firstByte < 0x80) {
1647 codePoint = firstByte
1648 }
1649 break
1650 case 2:
1651 secondByte = buf[i + 1]
1652 if ((secondByte & 0xC0) === 0x80) {
1653 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1654 if (tempCodePoint > 0x7F) {
1655 codePoint = tempCodePoint
1656 }
1657 }
1658 break
1659 case 3:
1660 secondByte = buf[i + 1]
1661 thirdByte = buf[i + 2]
1662 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1663 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
1664 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1665 codePoint = tempCodePoint
1666 }
1667 }
1668 break
1669 case 4:
1670 secondByte = buf[i + 1]
1671 thirdByte = buf[i + 2]
1672 fourthByte = buf[i + 3]
1673 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1674 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1675 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1676 codePoint = tempCodePoint
1677 }
1678 }
1679 }
1680 }
1681
1682 if (codePoint === null) {
1683 // we did not generate a valid codePoint so insert a
1684 // replacement char (U+FFFD) and advance only 1 byte
1685 codePoint = 0xFFFD
1686 bytesPerSequence = 1
1687 } else if (codePoint > 0xFFFF) {
1688 // encode to utf16 (surrogate pair dance)
1689 codePoint -= 0x10000
1690 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1691 codePoint = 0xDC00 | codePoint & 0x3FF
1692 }
1693
1694 res.push(codePoint)
1695 i += bytesPerSequence
1696 }
1697
1698 return decodeCodePointsArray(res)
1699}
1700
1701// Based on http://stackoverflow.com/a/22747272/680742, the browser with
1702// the lowest limit is Chrome, with 0x10000 args.
1703// We go 1 magnitude less, for safety
1704var MAX_ARGUMENTS_LENGTH = 0x1000
1705
1706function decodeCodePointsArray (codePoints) {
1707 var len = codePoints.length
1708 if (len <= MAX_ARGUMENTS_LENGTH) {
1709 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1710 }
1711
1712 // Decode in chunks to avoid "call stack size exceeded".
1713 var res = ''
1714 var i = 0
1715 while (i < len) {
1716 res += String.fromCharCode.apply(
1717 String,
1718 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1719 )
1720 }
1721 return res
1722}
1723
1724function asciiSlice (buf, start, end) {
1725 var ret = ''
1726 end = Math.min(buf.length, end)
1727
1728 for (var i = start; i < end; ++i) {
1729 ret += String.fromCharCode(buf[i] & 0x7F)
1730 }
1731 return ret
1732}
1733
1734function latin1Slice (buf, start, end) {
1735 var ret = ''
1736 end = Math.min(buf.length, end)
1737
1738 for (var i = start; i < end; ++i) {
1739 ret += String.fromCharCode(buf[i])
1740 }
1741 return ret
1742}
1743
1744function hexSlice (buf, start, end) {
1745 var len = buf.length
1746
1747 if (!start || start < 0) start = 0
1748 if (!end || end < 0 || end > len) end = len
1749
1750 var out = ''
1751 for (var i = start; i < end; ++i) {
1752 out += hexSliceLookupTable[buf[i]]
1753 }
1754 return out
1755}
1756
1757function utf16leSlice (buf, start, end) {
1758 var bytes = buf.slice(start, end)
1759 var res = ''
1760 // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
1761 for (var i = 0; i < bytes.length - 1; i += 2) {
1762 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
1763 }
1764 return res
1765}
1766
1767Buffer.prototype.slice = function slice (start, end) {
1768 var len = this.length
1769 start = ~~start
1770 end = end === undefined ? len : ~~end
1771
1772 if (start < 0) {
1773 start += len
1774 if (start < 0) start = 0
1775 } else if (start > len) {
1776 start = len
1777 }
1778
1779 if (end < 0) {
1780 end += len
1781 if (end < 0) end = 0
1782 } else if (end > len) {
1783 end = len
1784 }
1785
1786 if (end < start) end = start
1787
1788 var newBuf = this.subarray(start, end)
1789 // Return an augmented `Uint8Array` instance
1790 Object.setPrototypeOf(newBuf, Buffer.prototype)
1791
1792 return newBuf
1793}
1794
1795/*
1796 * Need to make sure that buffer isn't trying to write out of bounds.
1797 */
1798function checkOffset (offset, ext, length) {
1799 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1800 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1801}
1802
1803Buffer.prototype.readUintLE =
1804Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1805 offset = offset >>> 0
1806 byteLength = byteLength >>> 0
1807 if (!noAssert) checkOffset(offset, byteLength, this.length)
1808
1809 var val = this[offset]
1810 var mul = 1
1811 var i = 0
1812 while (++i < byteLength && (mul *= 0x100)) {
1813 val += this[offset + i] * mul
1814 }
1815
1816 return val
1817}
1818
1819Buffer.prototype.readUintBE =
1820Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1821 offset = offset >>> 0
1822 byteLength = byteLength >>> 0
1823 if (!noAssert) {
1824 checkOffset(offset, byteLength, this.length)
1825 }
1826
1827 var val = this[offset + --byteLength]
1828 var mul = 1
1829 while (byteLength > 0 && (mul *= 0x100)) {
1830 val += this[offset + --byteLength] * mul
1831 }
1832
1833 return val
1834}
1835
1836Buffer.prototype.readUint8 =
1837Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1838 offset = offset >>> 0
1839 if (!noAssert) checkOffset(offset, 1, this.length)
1840 return this[offset]
1841}
1842
1843Buffer.prototype.readUint16LE =
1844Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1845 offset = offset >>> 0
1846 if (!noAssert) checkOffset(offset, 2, this.length)
1847 return this[offset] | (this[offset + 1] << 8)
1848}
1849
1850Buffer.prototype.readUint16BE =
1851Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1852 offset = offset >>> 0
1853 if (!noAssert) checkOffset(offset, 2, this.length)
1854 return (this[offset] << 8) | this[offset + 1]
1855}
1856
1857Buffer.prototype.readUint32LE =
1858Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1859 offset = offset >>> 0
1860 if (!noAssert) checkOffset(offset, 4, this.length)
1861
1862 return ((this[offset]) |
1863 (this[offset + 1] << 8) |
1864 (this[offset + 2] << 16)) +
1865 (this[offset + 3] * 0x1000000)
1866}
1867
1868Buffer.prototype.readUint32BE =
1869Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1870 offset = offset >>> 0
1871 if (!noAssert) checkOffset(offset, 4, this.length)
1872
1873 return (this[offset] * 0x1000000) +
1874 ((this[offset + 1] << 16) |
1875 (this[offset + 2] << 8) |
1876 this[offset + 3])
1877}
1878
1879Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1880 offset = offset >>> 0
1881 byteLength = byteLength >>> 0
1882 if (!noAssert) checkOffset(offset, byteLength, this.length)
1883
1884 var val = this[offset]
1885 var mul = 1
1886 var i = 0
1887 while (++i < byteLength && (mul *= 0x100)) {
1888 val += this[offset + i] * mul
1889 }
1890 mul *= 0x80
1891
1892 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1893
1894 return val
1895}
1896
1897Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1898 offset = offset >>> 0
1899 byteLength = byteLength >>> 0
1900 if (!noAssert) checkOffset(offset, byteLength, this.length)
1901
1902 var i = byteLength
1903 var mul = 1
1904 var val = this[offset + --i]
1905 while (i > 0 && (mul *= 0x100)) {
1906 val += this[offset + --i] * mul
1907 }
1908 mul *= 0x80
1909
1910 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1911
1912 return val
1913}
1914
1915Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1916 offset = offset >>> 0
1917 if (!noAssert) checkOffset(offset, 1, this.length)
1918 if (!(this[offset] & 0x80)) return (this[offset])
1919 return ((0xff - this[offset] + 1) * -1)
1920}
1921
1922Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1923 offset = offset >>> 0
1924 if (!noAssert) checkOffset(offset, 2, this.length)
1925 var val = this[offset] | (this[offset + 1] << 8)
1926 return (val & 0x8000) ? val | 0xFFFF0000 : val
1927}
1928
1929Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1930 offset = offset >>> 0
1931 if (!noAssert) checkOffset(offset, 2, this.length)
1932 var val = this[offset + 1] | (this[offset] << 8)
1933 return (val & 0x8000) ? val | 0xFFFF0000 : val
1934}
1935
1936Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1937 offset = offset >>> 0
1938 if (!noAssert) checkOffset(offset, 4, this.length)
1939
1940 return (this[offset]) |
1941 (this[offset + 1] << 8) |
1942 (this[offset + 2] << 16) |
1943 (this[offset + 3] << 24)
1944}
1945
1946Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1947 offset = offset >>> 0
1948 if (!noAssert) checkOffset(offset, 4, this.length)
1949
1950 return (this[offset] << 24) |
1951 (this[offset + 1] << 16) |
1952 (this[offset + 2] << 8) |
1953 (this[offset + 3])
1954}
1955
1956Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1957 offset = offset >>> 0
1958 if (!noAssert) checkOffset(offset, 4, this.length)
1959 return ieee754.read(this, offset, true, 23, 4)
1960}
1961
1962Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1963 offset = offset >>> 0
1964 if (!noAssert) checkOffset(offset, 4, this.length)
1965 return ieee754.read(this, offset, false, 23, 4)
1966}
1967
1968Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1969 offset = offset >>> 0
1970 if (!noAssert) checkOffset(offset, 8, this.length)
1971 return ieee754.read(this, offset, true, 52, 8)
1972}
1973
1974Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1975 offset = offset >>> 0
1976 if (!noAssert) checkOffset(offset, 8, this.length)
1977 return ieee754.read(this, offset, false, 52, 8)
1978}
1979
1980function checkInt (buf, value, offset, ext, max, min) {
1981 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1982 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1983 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1984}
1985
1986Buffer.prototype.writeUintLE =
1987Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1988 value = +value
1989 offset = offset >>> 0
1990 byteLength = byteLength >>> 0
1991 if (!noAssert) {
1992 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1993 checkInt(this, value, offset, byteLength, maxBytes, 0)
1994 }
1995
1996 var mul = 1
1997 var i = 0
1998 this[offset] = value & 0xFF
1999 while (++i < byteLength && (mul *= 0x100)) {
2000 this[offset + i] = (value / mul) & 0xFF
2001 }
2002
2003 return offset + byteLength
2004}
2005
2006Buffer.prototype.writeUintBE =
2007Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
2008 value = +value
2009 offset = offset >>> 0
2010 byteLength = byteLength >>> 0
2011 if (!noAssert) {
2012 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2013 checkInt(this, value, offset, byteLength, maxBytes, 0)
2014 }
2015
2016 var i = byteLength - 1
2017 var mul = 1
2018 this[offset + i] = value & 0xFF
2019 while (--i >= 0 && (mul *= 0x100)) {
2020 this[offset + i] = (value / mul) & 0xFF
2021 }
2022
2023 return offset + byteLength
2024}
2025
2026Buffer.prototype.writeUint8 =
2027Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
2028 value = +value
2029 offset = offset >>> 0
2030 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
2031 this[offset] = (value & 0xff)
2032 return offset + 1
2033}
2034
2035Buffer.prototype.writeUint16LE =
2036Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
2037 value = +value
2038 offset = offset >>> 0
2039 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2040 this[offset] = (value & 0xff)
2041 this[offset + 1] = (value >>> 8)
2042 return offset + 2
2043}
2044
2045Buffer.prototype.writeUint16BE =
2046Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
2047 value = +value
2048 offset = offset >>> 0
2049 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2050 this[offset] = (value >>> 8)
2051 this[offset + 1] = (value & 0xff)
2052 return offset + 2
2053}
2054
2055Buffer.prototype.writeUint32LE =
2056Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
2057 value = +value
2058 offset = offset >>> 0
2059 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2060 this[offset + 3] = (value >>> 24)
2061 this[offset + 2] = (value >>> 16)
2062 this[offset + 1] = (value >>> 8)
2063 this[offset] = (value & 0xff)
2064 return offset + 4
2065}
2066
2067Buffer.prototype.writeUint32BE =
2068Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
2069 value = +value
2070 offset = offset >>> 0
2071 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2072 this[offset] = (value >>> 24)
2073 this[offset + 1] = (value >>> 16)
2074 this[offset + 2] = (value >>> 8)
2075 this[offset + 3] = (value & 0xff)
2076 return offset + 4
2077}
2078
2079Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
2080 value = +value
2081 offset = offset >>> 0
2082 if (!noAssert) {
2083 var limit = Math.pow(2, (8 * byteLength) - 1)
2084
2085 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2086 }
2087
2088 var i = 0
2089 var mul = 1
2090 var sub = 0
2091 this[offset] = value & 0xFF
2092 while (++i < byteLength && (mul *= 0x100)) {
2093 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2094 sub = 1
2095 }
2096 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2097 }
2098
2099 return offset + byteLength
2100}
2101
2102Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2103 value = +value
2104 offset = offset >>> 0
2105 if (!noAssert) {
2106 var limit = Math.pow(2, (8 * byteLength) - 1)
2107
2108 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2109 }
2110
2111 var i = byteLength - 1
2112 var mul = 1
2113 var sub = 0
2114 this[offset + i] = value & 0xFF
2115 while (--i >= 0 && (mul *= 0x100)) {
2116 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2117 sub = 1
2118 }
2119 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2120 }
2121
2122 return offset + byteLength
2123}
2124
2125Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2126 value = +value
2127 offset = offset >>> 0
2128 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2129 if (value < 0) value = 0xff + value + 1
2130 this[offset] = (value & 0xff)
2131 return offset + 1
2132}
2133
2134Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2135 value = +value
2136 offset = offset >>> 0
2137 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2138 this[offset] = (value & 0xff)
2139 this[offset + 1] = (value >>> 8)
2140 return offset + 2
2141}
2142
2143Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2144 value = +value
2145 offset = offset >>> 0
2146 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2147 this[offset] = (value >>> 8)
2148 this[offset + 1] = (value & 0xff)
2149 return offset + 2
2150}
2151
2152Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2153 value = +value
2154 offset = offset >>> 0
2155 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2156 this[offset] = (value & 0xff)
2157 this[offset + 1] = (value >>> 8)
2158 this[offset + 2] = (value >>> 16)
2159 this[offset + 3] = (value >>> 24)
2160 return offset + 4
2161}
2162
2163Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2164 value = +value
2165 offset = offset >>> 0
2166 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2167 if (value < 0) value = 0xffffffff + value + 1
2168 this[offset] = (value >>> 24)
2169 this[offset + 1] = (value >>> 16)
2170 this[offset + 2] = (value >>> 8)
2171 this[offset + 3] = (value & 0xff)
2172 return offset + 4
2173}
2174
2175function checkIEEE754 (buf, value, offset, ext, max, min) {
2176 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2177 if (offset < 0) throw new RangeError('Index out of range')
2178}
2179
2180function writeFloat (buf, value, offset, littleEndian, noAssert) {
2181 value = +value
2182 offset = offset >>> 0
2183 if (!noAssert) {
2184 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2185 }
2186 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2187 return offset + 4
2188}
2189
2190Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2191 return writeFloat(this, value, offset, true, noAssert)
2192}
2193
2194Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2195 return writeFloat(this, value, offset, false, noAssert)
2196}
2197
2198function writeDouble (buf, value, offset, littleEndian, noAssert) {
2199 value = +value
2200 offset = offset >>> 0
2201 if (!noAssert) {
2202 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2203 }
2204 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2205 return offset + 8
2206}
2207
2208Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2209 return writeDouble(this, value, offset, true, noAssert)
2210}
2211
2212Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2213 return writeDouble(this, value, offset, false, noAssert)
2214}
2215
2216// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2217Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2218 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
2219 if (!start) start = 0
2220 if (!end && end !== 0) end = this.length
2221 if (targetStart >= target.length) targetStart = target.length
2222 if (!targetStart) targetStart = 0
2223 if (end > 0 && end < start) end = start
2224
2225 // Copy 0 bytes; we're done
2226 if (end === start) return 0
2227 if (target.length === 0 || this.length === 0) return 0
2228
2229 // Fatal error conditions
2230 if (targetStart < 0) {
2231 throw new RangeError('targetStart out of bounds')
2232 }
2233 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
2234 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2235
2236 // Are we oob?
2237 if (end > this.length) end = this.length
2238 if (target.length - targetStart < end - start) {
2239 end = target.length - targetStart + start
2240 }
2241
2242 var len = end - start
2243
2244 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
2245 // Use built-in when available, missing from IE11
2246 this.copyWithin(targetStart, start, end)
2247 } else {
2248 Uint8Array.prototype.set.call(
2249 target,
2250 this.subarray(start, end),
2251 targetStart
2252 )
2253 }
2254
2255 return len
2256}
2257
2258// Usage:
2259// buffer.fill(number[, offset[, end]])
2260// buffer.fill(buffer[, offset[, end]])
2261// buffer.fill(string[, offset[, end]][, encoding])
2262Buffer.prototype.fill = function fill (val, start, end, encoding) {
2263 // Handle string cases:
2264 if (typeof val === 'string') {
2265 if (typeof start === 'string') {
2266 encoding = start
2267 start = 0
2268 end = this.length
2269 } else if (typeof end === 'string') {
2270 encoding = end
2271 end = this.length
2272 }
2273 if (encoding !== undefined && typeof encoding !== 'string') {
2274 throw new TypeError('encoding must be a string')
2275 }
2276 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2277 throw new TypeError('Unknown encoding: ' + encoding)
2278 }
2279 if (val.length === 1) {
2280 var code = val.charCodeAt(0)
2281 if ((encoding === 'utf8' && code < 128) ||
2282 encoding === 'latin1') {
2283 // Fast path: If `val` fits into a single byte, use that numeric value.
2284 val = code
2285 }
2286 }
2287 } else if (typeof val === 'number') {
2288 val = val & 255
2289 } else if (typeof val === 'boolean') {
2290 val = Number(val)
2291 }
2292
2293 // Invalid ranges are not set to a default, so can range check early.
2294 if (start < 0 || this.length < start || this.length < end) {
2295 throw new RangeError('Out of range index')
2296 }
2297
2298 if (end <= start) {
2299 return this
2300 }
2301
2302 start = start >>> 0
2303 end = end === undefined ? this.length : end >>> 0
2304
2305 if (!val) val = 0
2306
2307 var i
2308 if (typeof val === 'number') {
2309 for (i = start; i < end; ++i) {
2310 this[i] = val
2311 }
2312 } else {
2313 var bytes = Buffer.isBuffer(val)
2314 ? val
2315 : Buffer.from(val, encoding)
2316 var len = bytes.length
2317 if (len === 0) {
2318 throw new TypeError('The value "' + val +
2319 '" is invalid for argument "value"')
2320 }
2321 for (i = 0; i < end - start; ++i) {
2322 this[i + start] = bytes[i % len]
2323 }
2324 }
2325
2326 return this
2327}
2328
2329// HELPER FUNCTIONS
2330// ================
2331
2332var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
2333
2334function base64clean (str) {
2335 // Node takes equal signs as end of the Base64 encoding
2336 str = str.split('=')[0]
2337 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2338 str = str.trim().replace(INVALID_BASE64_RE, '')
2339 // Node converts strings with length < 2 to ''
2340 if (str.length < 2) return ''
2341 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2342 while (str.length % 4 !== 0) {
2343 str = str + '='
2344 }
2345 return str
2346}
2347
2348function utf8ToBytes (string, units) {
2349 units = units || Infinity
2350 var codePoint
2351 var length = string.length
2352 var leadSurrogate = null
2353 var bytes = []
2354
2355 for (var i = 0; i < length; ++i) {
2356 codePoint = string.charCodeAt(i)
2357
2358 // is surrogate component
2359 if (codePoint > 0xD7FF && codePoint < 0xE000) {
2360 // last char was a lead
2361 if (!leadSurrogate) {
2362 // no lead yet
2363 if (codePoint > 0xDBFF) {
2364 // unexpected trail
2365 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2366 continue
2367 } else if (i + 1 === length) {
2368 // unpaired lead
2369 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2370 continue
2371 }
2372
2373 // valid lead
2374 leadSurrogate = codePoint
2375
2376 continue
2377 }
2378
2379 // 2 leads in a row
2380 if (codePoint < 0xDC00) {
2381 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2382 leadSurrogate = codePoint
2383 continue
2384 }
2385
2386 // valid surrogate pair
2387 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
2388 } else if (leadSurrogate) {
2389 // valid bmp char, but last char was a lead
2390 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2391 }
2392
2393 leadSurrogate = null
2394
2395 // encode utf8
2396 if (codePoint < 0x80) {
2397 if ((units -= 1) < 0) break
2398 bytes.push(codePoint)
2399 } else if (codePoint < 0x800) {
2400 if ((units -= 2) < 0) break
2401 bytes.push(
2402 codePoint >> 0x6 | 0xC0,
2403 codePoint & 0x3F | 0x80
2404 )
2405 } else if (codePoint < 0x10000) {
2406 if ((units -= 3) < 0) break
2407 bytes.push(
2408 codePoint >> 0xC | 0xE0,
2409 codePoint >> 0x6 & 0x3F | 0x80,
2410 codePoint & 0x3F | 0x80
2411 )
2412 } else if (codePoint < 0x110000) {
2413 if ((units -= 4) < 0) break
2414 bytes.push(
2415 codePoint >> 0x12 | 0xF0,
2416 codePoint >> 0xC & 0x3F | 0x80,
2417 codePoint >> 0x6 & 0x3F | 0x80,
2418 codePoint & 0x3F | 0x80
2419 )
2420 } else {
2421 throw new Error('Invalid code point')
2422 }
2423 }
2424
2425 return bytes
2426}
2427
2428function asciiToBytes (str) {
2429 var byteArray = []
2430 for (var i = 0; i < str.length; ++i) {
2431 // Node's code seems to be doing this and not & 0x7F..
2432 byteArray.push(str.charCodeAt(i) & 0xFF)
2433 }
2434 return byteArray
2435}
2436
2437function utf16leToBytes (str, units) {
2438 var c, hi, lo
2439 var byteArray = []
2440 for (var i = 0; i < str.length; ++i) {
2441 if ((units -= 2) < 0) break
2442
2443 c = str.charCodeAt(i)
2444 hi = c >> 8
2445 lo = c % 256
2446 byteArray.push(lo)
2447 byteArray.push(hi)
2448 }
2449
2450 return byteArray
2451}
2452
2453function base64ToBytes (str) {
2454 return base64.toByteArray(base64clean(str))
2455}
2456
2457function blitBuffer (src, dst, offset, length) {
2458 for (var i = 0; i < length; ++i) {
2459 if ((i + offset >= dst.length) || (i >= src.length)) break
2460 dst[i + offset] = src[i]
2461 }
2462 return i
2463}
2464
2465// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
2466// the `instanceof` check but they should be treated as of that type.
2467// See: https://github.com/feross/buffer/issues/166
2468function isInstance (obj, type) {
2469 return obj instanceof type ||
2470 (obj != null && obj.constructor != null && obj.constructor.name != null &&
2471 obj.constructor.name === type.name)
2472}
2473function numberIsNaN (obj) {
2474 // For IE11 support
2475 return obj !== obj // eslint-disable-line no-self-compare
2476}
2477
2478// Create lookup table for `toString('hex')`
2479// See: https://github.com/feross/buffer/issues/219
2480var hexSliceLookupTable = (function () {
2481 var alphabet = '0123456789abcdef'
2482 var table = new Array(256)
2483 for (var i = 0; i < 16; ++i) {
2484 var i16 = i * 16
2485 for (var j = 0; j < 16; ++j) {
2486 table[i16 + j] = alphabet[i] + alphabet[j]
2487 }
2488 }
2489 return table
2490})()
2491
2492}).call(this)}).call(this,_dereq_("buffer").Buffer)
2493},{"base64-js":2,"buffer":4,"ieee754":44}],5:[function(_dereq_,module,exports){
2494'use strict';
2495
2496var GetIntrinsic = _dereq_('get-intrinsic');
2497
2498var callBind = _dereq_('./');
2499
2500var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
2501
2502module.exports = function callBoundIntrinsic(name, allowMissing) {
2503 var intrinsic = GetIntrinsic(name, !!allowMissing);
2504 if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
2505 return callBind(intrinsic);
2506 }
2507 return intrinsic;
2508};
2509
2510},{"./":6,"get-intrinsic":37}],6:[function(_dereq_,module,exports){
2511'use strict';
2512
2513var bind = _dereq_('function-bind');
2514var GetIntrinsic = _dereq_('get-intrinsic');
2515var setFunctionLength = _dereq_('set-function-length');
2516
2517var $TypeError = _dereq_('es-errors/type');
2518var $apply = GetIntrinsic('%Function.prototype.apply%');
2519var $call = GetIntrinsic('%Function.prototype.call%');
2520var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
2521
2522var $defineProperty = _dereq_('es-define-property');
2523var $max = GetIntrinsic('%Math.max%');
2524
2525module.exports = function callBind(originalFunction) {
2526 if (typeof originalFunction !== 'function') {
2527 throw new $TypeError('a function is required');
2528 }
2529 var func = $reflectApply(bind, $call, arguments);
2530 return setFunctionLength(
2531 func,
2532 1 + $max(0, originalFunction.length - (arguments.length - 1)),
2533 true
2534 );
2535};
2536
2537var applyBind = function applyBind() {
2538 return $reflectApply(bind, $apply, arguments);
2539};
2540
2541if ($defineProperty) {
2542 $defineProperty(module.exports, 'apply', { value: applyBind });
2543} else {
2544 module.exports.apply = applyBind;
2545}
2546
2547},{"es-define-property":25,"es-errors/type":31,"function-bind":35,"get-intrinsic":37,"set-function-length":103}],7:[function(_dereq_,module,exports){
2548// Copyright Joyent, Inc. and other Node contributors.
2549//
2550// Permission is hereby granted, free of charge, to any person obtaining a
2551// copy of this software and associated documentation files (the
2552// "Software"), to deal in the Software without restriction, including
2553// without limitation the rights to use, copy, modify, merge, publish,
2554// distribute, sublicense, and/or sell copies of the Software, and to permit
2555// persons to whom the Software is furnished to do so, subject to the
2556// following conditions:
2557//
2558// The above copyright notice and this permission notice shall be included
2559// in all copies or substantial portions of the Software.
2560//
2561// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2562// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2563// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
2564// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2565// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2566// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2567// USE OR OTHER DEALINGS IN THE SOFTWARE.
2568
2569// NOTE: These type checking functions intentionally don't use `instanceof`
2570// because it is fragile and can be easily faked with `Object.create()`.
2571
2572function isArray(arg) {
2573 if (Array.isArray) {
2574 return Array.isArray(arg);
2575 }
2576 return objectToString(arg) === '[object Array]';
2577}
2578exports.isArray = isArray;
2579
2580function isBoolean(arg) {
2581 return typeof arg === 'boolean';
2582}
2583exports.isBoolean = isBoolean;
2584
2585function isNull(arg) {
2586 return arg === null;
2587}
2588exports.isNull = isNull;
2589
2590function isNullOrUndefined(arg) {
2591 return arg == null;
2592}
2593exports.isNullOrUndefined = isNullOrUndefined;
2594
2595function isNumber(arg) {
2596 return typeof arg === 'number';
2597}
2598exports.isNumber = isNumber;
2599
2600function isString(arg) {
2601 return typeof arg === 'string';
2602}
2603exports.isString = isString;
2604
2605function isSymbol(arg) {
2606 return typeof arg === 'symbol';
2607}
2608exports.isSymbol = isSymbol;
2609
2610function isUndefined(arg) {
2611 return arg === void 0;
2612}
2613exports.isUndefined = isUndefined;
2614
2615function isRegExp(re) {
2616 return objectToString(re) === '[object RegExp]';
2617}
2618exports.isRegExp = isRegExp;
2619
2620function isObject(arg) {
2621 return typeof arg === 'object' && arg !== null;
2622}
2623exports.isObject = isObject;
2624
2625function isDate(d) {
2626 return objectToString(d) === '[object Date]';
2627}
2628exports.isDate = isDate;
2629
2630function isError(e) {
2631 return (objectToString(e) === '[object Error]' || e instanceof Error);
2632}
2633exports.isError = isError;
2634
2635function isFunction(arg) {
2636 return typeof arg === 'function';
2637}
2638exports.isFunction = isFunction;
2639
2640function isPrimitive(arg) {
2641 return arg === null ||
2642 typeof arg === 'boolean' ||
2643 typeof arg === 'number' ||
2644 typeof arg === 'string' ||
2645 typeof arg === 'symbol' || // ES6 symbol
2646 typeof arg === 'undefined';
2647}
2648exports.isPrimitive = isPrimitive;
2649
2650exports.isBuffer = _dereq_('buffer').Buffer.isBuffer;
2651
2652function objectToString(o) {
2653 return Object.prototype.toString.call(o);
2654}
2655
2656},{"buffer":4}],8:[function(_dereq_,module,exports){
2657var AbstractIterator = _dereq_('abstract-leveldown').AbstractIterator
2658var inherits = _dereq_('inherits')
2659
2660function DeferredIterator (db, options) {
2661 AbstractIterator.call(this, db)
2662
2663 this._options = options
2664 this._iterator = null
2665 this._operations = []
2666}
2667
2668inherits(DeferredIterator, AbstractIterator)
2669
2670DeferredIterator.prototype.setDb = function (db) {
2671 var it = this._iterator = db.iterator(this._options)
2672 this._operations.forEach(function (op) {
2673 it[op.method].apply(it, op.args)
2674 })
2675}
2676
2677DeferredIterator.prototype._operation = function (method, args) {
2678 if (this._iterator) return this._iterator[method].apply(this._iterator, args)
2679 this._operations.push({ method: method, args: args })
2680}
2681
2682'next end'.split(' ').forEach(function (m) {
2683 DeferredIterator.prototype['_' + m] = function () {
2684 this._operation(m, arguments)
2685 }
2686})
2687
2688// Must defer seek() rather than _seek() because it requires db._serializeKey to be available
2689DeferredIterator.prototype.seek = function () {
2690 this._operation('seek', arguments)
2691}
2692
2693module.exports = DeferredIterator
2694
2695},{"abstract-leveldown":13,"inherits":45}],9:[function(_dereq_,module,exports){
2696var AbstractLevelDOWN = _dereq_('abstract-leveldown').AbstractLevelDOWN
2697var inherits = _dereq_('inherits')
2698var DeferredIterator = _dereq_('./deferred-iterator')
2699var deferrables = 'put get del batch clear'.split(' ')
2700var optionalDeferrables = 'approximateSize compactRange'.split(' ')
2701
2702function DeferredLevelDOWN (db) {
2703 AbstractLevelDOWN.call(this, db.supports || {})
2704
2705 // TODO (future major): remove this fallback; db must have manifest that
2706 // declares approximateSize and compactRange in additionalMethods.
2707 optionalDeferrables.forEach(function (m) {
2708 if (typeof db[m] === 'function' && !this.supports.additionalMethods[m]) {
2709 this.supports.additionalMethods[m] = true
2710 }
2711 }, this)
2712
2713 this._db = db
2714 this._operations = []
2715 closed(this)
2716}
2717
2718inherits(DeferredLevelDOWN, AbstractLevelDOWN)
2719
2720DeferredLevelDOWN.prototype.type = 'deferred-leveldown'
2721
2722DeferredLevelDOWN.prototype._open = function (options, callback) {
2723 var self = this
2724
2725 this._db.open(options, function (err) {
2726 if (err) return callback(err)
2727
2728 self._operations.forEach(function (op) {
2729 if (op.iterator) {
2730 op.iterator.setDb(self._db)
2731 } else {
2732 self._db[op.method].apply(self._db, op.args)
2733 }
2734 })
2735 self._operations = []
2736
2737 open(self)
2738 callback()
2739 })
2740}
2741
2742DeferredLevelDOWN.prototype._close = function (callback) {
2743 var self = this
2744
2745 this._db.close(function (err) {
2746 if (err) return callback(err)
2747 closed(self)
2748 callback()
2749 })
2750}
2751
2752function open (self) {
2753 deferrables.concat('iterator').forEach(function (m) {
2754 self['_' + m] = function () {
2755 return this._db[m].apply(this._db, arguments)
2756 }
2757 })
2758 Object.keys(self.supports.additionalMethods).forEach(function (m) {
2759 self[m] = function () {
2760 return this._db[m].apply(this._db, arguments)
2761 }
2762 })
2763}
2764
2765function closed (self) {
2766 deferrables.forEach(function (m) {
2767 self['_' + m] = function () {
2768 this._operations.push({ method: m, args: arguments })
2769 }
2770 })
2771 Object.keys(self.supports.additionalMethods).forEach(function (m) {
2772 self[m] = function () {
2773 this._operations.push({ method: m, args: arguments })
2774 }
2775 })
2776 self._iterator = function (options) {
2777 var it = new DeferredIterator(self, options)
2778 this._operations.push({ iterator: it })
2779 return it
2780 }
2781}
2782
2783DeferredLevelDOWN.prototype._serializeKey = function (key) {
2784 return key
2785}
2786
2787DeferredLevelDOWN.prototype._serializeValue = function (value) {
2788 return value
2789}
2790
2791module.exports = DeferredLevelDOWN
2792module.exports.DeferredIterator = DeferredIterator
2793
2794},{"./deferred-iterator":8,"abstract-leveldown":13,"inherits":45}],10:[function(_dereq_,module,exports){
2795var nextTick = _dereq_('./next-tick')
2796
2797function AbstractChainedBatch (db) {
2798 if (typeof db !== 'object' || db === null) {
2799 throw new TypeError('First argument must be an abstract-leveldown compliant store')
2800 }
2801
2802 this.db = db
2803 this._operations = []
2804 this._written = false
2805}
2806
2807AbstractChainedBatch.prototype._checkWritten = function () {
2808 if (this._written) {
2809 throw new Error('write() already called on this batch')
2810 }
2811}
2812
2813AbstractChainedBatch.prototype.put = function (key, value) {
2814 this._checkWritten()
2815
2816 var err = this.db._checkKey(key) || this.db._checkValue(value)
2817 if (err) throw err
2818
2819 key = this.db._serializeKey(key)
2820 value = this.db._serializeValue(value)
2821
2822 this._put(key, value)
2823
2824 return this
2825}
2826
2827AbstractChainedBatch.prototype._put = function (key, value) {
2828 this._operations.push({ type: 'put', key: key, value: value })
2829}
2830
2831AbstractChainedBatch.prototype.del = function (key) {
2832 this._checkWritten()
2833
2834 var err = this.db._checkKey(key)
2835 if (err) throw err
2836
2837 key = this.db._serializeKey(key)
2838 this._del(key)
2839
2840 return this
2841}
2842
2843AbstractChainedBatch.prototype._del = function (key) {
2844 this._operations.push({ type: 'del', key: key })
2845}
2846
2847AbstractChainedBatch.prototype.clear = function () {
2848 this._checkWritten()
2849 this._clear()
2850
2851 return this
2852}
2853
2854AbstractChainedBatch.prototype._clear = function () {
2855 this._operations = []
2856}
2857
2858AbstractChainedBatch.prototype.write = function (options, callback) {
2859 this._checkWritten()
2860
2861 if (typeof options === 'function') { callback = options }
2862 if (typeof callback !== 'function') {
2863 throw new Error('write() requires a callback argument')
2864 }
2865 if (typeof options !== 'object' || options === null) {
2866 options = {}
2867 }
2868
2869 this._written = true
2870 this._write(options, callback)
2871}
2872
2873AbstractChainedBatch.prototype._write = function (options, callback) {
2874 this.db._batch(this._operations, options, callback)
2875}
2876
2877// Expose browser-compatible nextTick for dependents
2878AbstractChainedBatch.prototype._nextTick = nextTick
2879
2880module.exports = AbstractChainedBatch
2881
2882},{"./next-tick":14}],11:[function(_dereq_,module,exports){
2883var nextTick = _dereq_('./next-tick')
2884
2885function AbstractIterator (db) {
2886 if (typeof db !== 'object' || db === null) {
2887 throw new TypeError('First argument must be an abstract-leveldown compliant store')
2888 }
2889
2890 this.db = db
2891 this._ended = false
2892 this._nexting = false
2893}
2894
2895AbstractIterator.prototype.next = function (callback) {
2896 var self = this
2897
2898 if (typeof callback !== 'function') {
2899 throw new Error('next() requires a callback argument')
2900 }
2901
2902 if (self._ended) {
2903 nextTick(callback, new Error('cannot call next() after end()'))
2904 return self
2905 }
2906
2907 if (self._nexting) {
2908 nextTick(callback, new Error('cannot call next() before previous next() has completed'))
2909 return self
2910 }
2911
2912 self._nexting = true
2913 self._next(function () {
2914 self._nexting = false
2915 callback.apply(null, arguments)
2916 })
2917
2918 return self
2919}
2920
2921AbstractIterator.prototype._next = function (callback) {
2922 nextTick(callback)
2923}
2924
2925AbstractIterator.prototype.seek = function (target) {
2926 if (this._ended) {
2927 throw new Error('cannot call seek() after end()')
2928 }
2929 if (this._nexting) {
2930 throw new Error('cannot call seek() before next() has completed')
2931 }
2932
2933 target = this.db._serializeKey(target)
2934 this._seek(target)
2935}
2936
2937AbstractIterator.prototype._seek = function (target) {}
2938
2939AbstractIterator.prototype.end = function (callback) {
2940 if (typeof callback !== 'function') {
2941 throw new Error('end() requires a callback argument')
2942 }
2943
2944 if (this._ended) {
2945 return nextTick(callback, new Error('end() already called on iterator'))
2946 }
2947
2948 this._ended = true
2949 this._end(callback)
2950}
2951
2952AbstractIterator.prototype._end = function (callback) {
2953 nextTick(callback)
2954}
2955
2956// Expose browser-compatible nextTick for dependents
2957AbstractIterator.prototype._nextTick = nextTick
2958
2959module.exports = AbstractIterator
2960
2961},{"./next-tick":14}],12:[function(_dereq_,module,exports){
2962var xtend = _dereq_('xtend')
2963var supports = _dereq_('level-supports')
2964var Buffer = _dereq_('buffer').Buffer
2965var AbstractIterator = _dereq_('./abstract-iterator')
2966var AbstractChainedBatch = _dereq_('./abstract-chained-batch')
2967var nextTick = _dereq_('./next-tick')
2968var hasOwnProperty = Object.prototype.hasOwnProperty
2969var rangeOptions = 'start end gt gte lt lte'.split(' ')
2970
2971function AbstractLevelDOWN (manifest) {
2972 this.status = 'new'
2973
2974 // TODO (next major): make this mandatory
2975 this.supports = supports(manifest, {
2976 status: true
2977 })
2978}
2979
2980AbstractLevelDOWN.prototype.open = function (options, callback) {
2981 var self = this
2982 var oldStatus = this.status
2983
2984 if (typeof options === 'function') callback = options
2985
2986 if (typeof callback !== 'function') {
2987 throw new Error('open() requires a callback argument')
2988 }
2989
2990 if (typeof options !== 'object' || options === null) options = {}
2991
2992 options.createIfMissing = options.createIfMissing !== false
2993 options.errorIfExists = !!options.errorIfExists
2994
2995 this.status = 'opening'
2996 this._open(options, function (err) {
2997 if (err) {
2998 self.status = oldStatus
2999 return callback(err)
3000 }
3001 self.status = 'open'
3002 callback()
3003 })
3004}
3005
3006AbstractLevelDOWN.prototype._open = function (options, callback) {
3007 nextTick(callback)
3008}
3009
3010AbstractLevelDOWN.prototype.close = function (callback) {
3011 var self = this
3012 var oldStatus = this.status
3013
3014 if (typeof callback !== 'function') {
3015 throw new Error('close() requires a callback argument')
3016 }
3017
3018 this.status = 'closing'
3019 this._close(function (err) {
3020 if (err) {
3021 self.status = oldStatus
3022 return callback(err)
3023 }
3024 self.status = 'closed'
3025 callback()
3026 })
3027}
3028
3029AbstractLevelDOWN.prototype._close = function (callback) {
3030 nextTick(callback)
3031}
3032
3033AbstractLevelDOWN.prototype.get = function (key, options, callback) {
3034 if (typeof options === 'function') callback = options
3035
3036 if (typeof callback !== 'function') {
3037 throw new Error('get() requires a callback argument')
3038 }
3039
3040 var err = this._checkKey(key)
3041 if (err) return nextTick(callback, err)
3042
3043 key = this._serializeKey(key)
3044
3045 if (typeof options !== 'object' || options === null) options = {}
3046
3047 options.asBuffer = options.asBuffer !== false
3048
3049 this._get(key, options, callback)
3050}
3051
3052AbstractLevelDOWN.prototype._get = function (key, options, callback) {
3053 nextTick(function () { callback(new Error('NotFound')) })
3054}
3055
3056AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
3057 if (typeof options === 'function') callback = options
3058
3059 if (typeof callback !== 'function') {
3060 throw new Error('put() requires a callback argument')
3061 }
3062
3063 var err = this._checkKey(key) || this._checkValue(value)
3064 if (err) return nextTick(callback, err)
3065
3066 key = this._serializeKey(key)
3067 value = this._serializeValue(value)
3068
3069 if (typeof options !== 'object' || options === null) options = {}
3070
3071 this._put(key, value, options, callback)
3072}
3073
3074AbstractLevelDOWN.prototype._put = function (key, value, options, callback) {
3075 nextTick(callback)
3076}
3077
3078AbstractLevelDOWN.prototype.del = function (key, options, callback) {
3079 if (typeof options === 'function') callback = options
3080
3081 if (typeof callback !== 'function') {
3082 throw new Error('del() requires a callback argument')
3083 }
3084
3085 var err = this._checkKey(key)
3086 if (err) return nextTick(callback, err)
3087
3088 key = this._serializeKey(key)
3089
3090 if (typeof options !== 'object' || options === null) options = {}
3091
3092 this._del(key, options, callback)
3093}
3094
3095AbstractLevelDOWN.prototype._del = function (key, options, callback) {
3096 nextTick(callback)
3097}
3098
3099AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
3100 if (!arguments.length) return this._chainedBatch()
3101
3102 if (typeof options === 'function') callback = options
3103
3104 if (typeof array === 'function') callback = array
3105
3106 if (typeof callback !== 'function') {
3107 throw new Error('batch(array) requires a callback argument')
3108 }
3109
3110 if (!Array.isArray(array)) {
3111 return nextTick(callback, new Error('batch(array) requires an array argument'))
3112 }
3113
3114 if (array.length === 0) {
3115 return nextTick(callback)
3116 }
3117
3118 if (typeof options !== 'object' || options === null) options = {}
3119
3120 var serialized = new Array(array.length)
3121
3122 for (var i = 0; i < array.length; i++) {
3123 if (typeof array[i] !== 'object' || array[i] === null) {
3124 return nextTick(callback, new Error('batch(array) element must be an object and not `null`'))
3125 }
3126
3127 var e = xtend(array[i])
3128
3129 if (e.type !== 'put' && e.type !== 'del') {
3130 return nextTick(callback, new Error("`type` must be 'put' or 'del'"))
3131 }
3132
3133 var err = this._checkKey(e.key)
3134 if (err) return nextTick(callback, err)
3135
3136 e.key = this._serializeKey(e.key)
3137
3138 if (e.type === 'put') {
3139 var valueErr = this._checkValue(e.value)
3140 if (valueErr) return nextTick(callback, valueErr)
3141
3142 e.value = this._serializeValue(e.value)
3143 }
3144
3145 serialized[i] = e
3146 }
3147
3148 this._batch(serialized, options, callback)
3149}
3150
3151AbstractLevelDOWN.prototype._batch = function (array, options, callback) {
3152 nextTick(callback)
3153}
3154
3155AbstractLevelDOWN.prototype.clear = function (options, callback) {
3156 if (typeof options === 'function') {
3157 callback = options
3158 } else if (typeof callback !== 'function') {
3159 throw new Error('clear() requires a callback argument')
3160 }
3161
3162 options = cleanRangeOptions(this, options)
3163 options.reverse = !!options.reverse
3164 options.limit = 'limit' in options ? options.limit : -1
3165
3166 this._clear(options, callback)
3167}
3168
3169AbstractLevelDOWN.prototype._clear = function (options, callback) {
3170 // Avoid setupIteratorOptions, would serialize range options a second time.
3171 options.keys = true
3172 options.values = false
3173 options.keyAsBuffer = true
3174 options.valueAsBuffer = true
3175
3176 var iterator = this._iterator(options)
3177 var emptyOptions = {}
3178 var self = this
3179
3180 var next = function (err) {
3181 if (err) {
3182 return iterator.end(function () {
3183 callback(err)
3184 })
3185 }
3186
3187 iterator.next(function (err, key) {
3188 if (err) return next(err)
3189 if (key === undefined) return iterator.end(callback)
3190
3191 // This could be optimized by using a batch, but the default _clear
3192 // is not meant to be fast. Implementations have more room to optimize
3193 // if they override _clear. Note: using _del bypasses key serialization.
3194 self._del(key, emptyOptions, next)
3195 })
3196 }
3197
3198 next()
3199}
3200
3201AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
3202 options = cleanRangeOptions(this, options)
3203
3204 options.reverse = !!options.reverse
3205 options.keys = options.keys !== false
3206 options.values = options.values !== false
3207 options.limit = 'limit' in options ? options.limit : -1
3208 options.keyAsBuffer = options.keyAsBuffer !== false
3209 options.valueAsBuffer = options.valueAsBuffer !== false
3210
3211 return options
3212}
3213
3214function cleanRangeOptions (db, options) {
3215 var result = {}
3216
3217 for (var k in options) {
3218 if (!hasOwnProperty.call(options, k)) continue
3219
3220 var opt = options[k]
3221
3222 if (isRangeOption(k)) {
3223 // Note that we don't reject nullish and empty options here. While
3224 // those types are invalid as keys, they are valid as range options.
3225 opt = db._serializeKey(opt)
3226 }
3227
3228 result[k] = opt
3229 }
3230
3231 return result
3232}
3233
3234function isRangeOption (k) {
3235 return rangeOptions.indexOf(k) !== -1
3236}
3237
3238AbstractLevelDOWN.prototype.iterator = function (options) {
3239 if (typeof options !== 'object' || options === null) options = {}
3240 options = this._setupIteratorOptions(options)
3241 return this._iterator(options)
3242}
3243
3244AbstractLevelDOWN.prototype._iterator = function (options) {
3245 return new AbstractIterator(this)
3246}
3247
3248AbstractLevelDOWN.prototype._chainedBatch = function () {
3249 return new AbstractChainedBatch(this)
3250}
3251
3252AbstractLevelDOWN.prototype._serializeKey = function (key) {
3253 return key
3254}
3255
3256AbstractLevelDOWN.prototype._serializeValue = function (value) {
3257 return value
3258}
3259
3260AbstractLevelDOWN.prototype._checkKey = function (key) {
3261 if (key === null || key === undefined) {
3262 return new Error('key cannot be `null` or `undefined`')
3263 } else if (Buffer.isBuffer(key) && key.length === 0) {
3264 return new Error('key cannot be an empty Buffer')
3265 } else if (key === '') {
3266 return new Error('key cannot be an empty String')
3267 } else if (Array.isArray(key) && key.length === 0) {
3268 return new Error('key cannot be an empty Array')
3269 }
3270}
3271
3272AbstractLevelDOWN.prototype._checkValue = function (value) {
3273 if (value === null || value === undefined) {
3274 return new Error('value cannot be `null` or `undefined`')
3275 }
3276}
3277
3278// Expose browser-compatible nextTick for dependents
3279AbstractLevelDOWN.prototype._nextTick = nextTick
3280
3281module.exports = AbstractLevelDOWN
3282
3283},{"./abstract-chained-batch":10,"./abstract-iterator":11,"./next-tick":14,"buffer":4,"level-supports":67,"xtend":160}],13:[function(_dereq_,module,exports){
3284exports.AbstractLevelDOWN = _dereq_('./abstract-leveldown')
3285exports.AbstractIterator = _dereq_('./abstract-iterator')
3286exports.AbstractChainedBatch = _dereq_('./abstract-chained-batch')
3287
3288},{"./abstract-chained-batch":10,"./abstract-iterator":11,"./abstract-leveldown":12}],14:[function(_dereq_,module,exports){
3289module.exports = _dereq_('immediate')
3290
3291},{"immediate":15}],15:[function(_dereq_,module,exports){
3292'use strict';
3293var types = [
3294 _dereq_('./nextTick'),
3295 _dereq_('./queueMicrotask'),
3296 _dereq_('./mutation.js'),
3297 _dereq_('./messageChannel'),
3298 _dereq_('./stateChange'),
3299 _dereq_('./timeout')
3300];
3301var draining;
3302var currentQueue;
3303var queueIndex = -1;
3304var queue = [];
3305var scheduled = false;
3306function cleanUpNextTick() {
3307 if (!draining || !currentQueue) {
3308 return;
3309 }
3310 draining = false;
3311 if (currentQueue.length) {
3312 queue = currentQueue.concat(queue);
3313 } else {
3314 queueIndex = -1;
3315 }
3316 if (queue.length) {
3317 nextTick();
3318 }
3319}
3320
3321//named nextTick for less confusing stack traces
3322function nextTick() {
3323 if (draining) {
3324 return;
3325 }
3326 scheduled = false;
3327 draining = true;
3328 var len = queue.length;
3329 var timeout = setTimeout(cleanUpNextTick);
3330 while (len) {
3331 currentQueue = queue;
3332 queue = [];
3333 while (currentQueue && ++queueIndex < len) {
3334 currentQueue[queueIndex].run();
3335 }
3336 queueIndex = -1;
3337 len = queue.length;
3338 }
3339 currentQueue = null;
3340 queueIndex = -1;
3341 draining = false;
3342 clearTimeout(timeout);
3343}
3344var scheduleDrain;
3345var i = -1;
3346var len = types.length;
3347while (++i < len) {
3348 if (types[i] && types[i].test && types[i].test()) {
3349 scheduleDrain = types[i].install(nextTick);
3350 break;
3351 }
3352}
3353// v8 likes predictible objects
3354function Item(fun, array) {
3355 this.fun = fun;
3356 this.array = array;
3357}
3358Item.prototype.run = function () {
3359 var fun = this.fun;
3360 var array = this.array;
3361 switch (array.length) {
3362 case 0:
3363 return fun();
3364 case 1:
3365 return fun(array[0]);
3366 case 2:
3367 return fun(array[0], array[1]);
3368 case 3:
3369 return fun(array[0], array[1], array[2]);
3370 default:
3371 return fun.apply(null, array);
3372 }
3373
3374};
3375module.exports = immediate;
3376function immediate(task) {
3377 var args = new Array(arguments.length - 1);
3378 if (arguments.length > 1) {
3379 for (var i = 1; i < arguments.length; i++) {
3380 args[i - 1] = arguments[i];
3381 }
3382 }
3383 queue.push(new Item(task, args));
3384 if (!scheduled && !draining) {
3385 scheduled = true;
3386 scheduleDrain();
3387 }
3388}
3389
3390},{"./messageChannel":16,"./mutation.js":17,"./nextTick":3,"./queueMicrotask":18,"./stateChange":19,"./timeout":20}],16:[function(_dereq_,module,exports){
3391(function (global){(function (){
3392'use strict';
3393
3394exports.test = function () {
3395 if (global.setImmediate) {
3396 // we can only get here in IE10
3397 // which doesn't handel postMessage well
3398 return false;
3399 }
3400 return typeof global.MessageChannel !== 'undefined';
3401};
3402
3403exports.install = function (func) {
3404 var channel = new global.MessageChannel();
3405 channel.port1.onmessage = func;
3406 return function () {
3407 channel.port2.postMessage(0);
3408 };
3409};
3410}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3411},{}],17:[function(_dereq_,module,exports){
3412(function (global){(function (){
3413'use strict';
3414//based off rsvp https://github.com/tildeio/rsvp.js
3415//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE
3416//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js
3417
3418var Mutation = global.MutationObserver || global.WebKitMutationObserver;
3419
3420exports.test = function () {
3421 return Mutation;
3422};
3423
3424exports.install = function (handle) {
3425 var called = 0;
3426 var observer = new Mutation(handle);
3427 var element = global.document.createTextNode('');
3428 observer.observe(element, {
3429 characterData: true
3430 });
3431 return function () {
3432 element.data = (called = ++called % 2);
3433 };
3434};
3435}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3436},{}],18:[function(_dereq_,module,exports){
3437(function (global){(function (){
3438'use strict';
3439exports.test = function () {
3440 return typeof global.queueMicrotask === 'function';
3441};
3442
3443exports.install = function (func) {
3444 return function () {
3445 global.queueMicrotask(func);
3446 };
3447};
3448
3449}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3450},{}],19:[function(_dereq_,module,exports){
3451(function (global){(function (){
3452'use strict';
3453
3454exports.test = function () {
3455 return 'document' in global && 'onreadystatechange' in global.document.createElement('script');
3456};
3457
3458exports.install = function (handle) {
3459 return function () {
3460
3461 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
3462 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
3463 var scriptEl = global.document.createElement('script');
3464 scriptEl.onreadystatechange = function () {
3465 handle();
3466
3467 scriptEl.onreadystatechange = null;
3468 scriptEl.parentNode.removeChild(scriptEl);
3469 scriptEl = null;
3470 };
3471 global.document.documentElement.appendChild(scriptEl);
3472
3473 return handle;
3474 };
3475};
3476}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3477},{}],20:[function(_dereq_,module,exports){
3478'use strict';
3479exports.test = function () {
3480 return true;
3481};
3482
3483exports.install = function (t) {
3484 return function () {
3485 setTimeout(t, 0);
3486 };
3487};
3488},{}],21:[function(_dereq_,module,exports){
3489'use strict';
3490
3491var $defineProperty = _dereq_('es-define-property');
3492
3493var $SyntaxError = _dereq_('es-errors/syntax');
3494var $TypeError = _dereq_('es-errors/type');
3495
3496var gopd = _dereq_('gopd');
3497
3498/** @type {import('.')} */
3499module.exports = function defineDataProperty(
3500 obj,
3501 property,
3502 value
3503) {
3504 if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
3505 throw new $TypeError('`obj` must be an object or a function`');
3506 }
3507 if (typeof property !== 'string' && typeof property !== 'symbol') {
3508 throw new $TypeError('`property` must be a string or a symbol`');
3509 }
3510 if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) {
3511 throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null');
3512 }
3513 if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) {
3514 throw new $TypeError('`nonWritable`, if provided, must be a boolean or null');
3515 }
3516 if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) {
3517 throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null');
3518 }
3519 if (arguments.length > 6 && typeof arguments[6] !== 'boolean') {
3520 throw new $TypeError('`loose`, if provided, must be a boolean');
3521 }
3522
3523 var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
3524 var nonWritable = arguments.length > 4 ? arguments[4] : null;
3525 var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
3526 var loose = arguments.length > 6 ? arguments[6] : false;
3527
3528 /* @type {false | TypedPropertyDescriptor<unknown>} */
3529 var desc = !!gopd && gopd(obj, property);
3530
3531 if ($defineProperty) {
3532 $defineProperty(obj, property, {
3533 configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable,
3534 enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable,
3535 value: value,
3536 writable: nonWritable === null && desc ? desc.writable : !nonWritable
3537 });
3538 } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) {
3539 // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable
3540 obj[property] = value; // eslint-disable-line no-param-reassign
3541 } else {
3542 throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.');
3543 }
3544};
3545
3546},{"es-define-property":25,"es-errors/syntax":30,"es-errors/type":31,"gopd":38}],22:[function(_dereq_,module,exports){
3547/**
3548 * Copyright (c) 2013 Petka Antonov
3549 *
3550 * Permission is hereby granted, free of charge, to any person obtaining a copy
3551 * of this software and associated documentation files (the "Software"), to deal
3552 * in the Software without restriction, including without limitation the rights
3553 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3554 * copies of the Software, and to permit persons to whom the Software is
3555 * furnished to do so, subject to the following conditions:</p>
3556 *
3557 * The above copyright notice and this permission notice shall be included in
3558 * all copies or substantial portions of the Software.
3559 *
3560 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3561 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3562 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3563 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3564 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3565 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3566 * THE SOFTWARE.
3567 */
3568"use strict";
3569function Deque(capacity) {
3570 this._capacity = getCapacity(capacity);
3571 this._length = 0;
3572 this._front = 0;
3573 if (isArray(capacity)) {
3574 var len = capacity.length;
3575 for (var i = 0; i < len; ++i) {
3576 this[i] = capacity[i];
3577 }
3578 this._length = len;
3579 }
3580}
3581
3582Deque.prototype.toArray = function Deque$toArray() {
3583 var len = this._length;
3584 var ret = new Array(len);
3585 var front = this._front;
3586 var capacity = this._capacity;
3587 for (var j = 0; j < len; ++j) {
3588 ret[j] = this[(front + j) & (capacity - 1)];
3589 }
3590 return ret;
3591};
3592
3593Deque.prototype.push = function Deque$push(item) {
3594 var argsLength = arguments.length;
3595 var length = this._length;
3596 if (argsLength > 1) {
3597 var capacity = this._capacity;
3598 if (length + argsLength > capacity) {
3599 for (var i = 0; i < argsLength; ++i) {
3600 this._checkCapacity(length + 1);
3601 var j = (this._front + length) & (this._capacity - 1);
3602 this[j] = arguments[i];
3603 length++;
3604 this._length = length;
3605 }
3606 return length;
3607 }
3608 else {
3609 var j = this._front;
3610 for (var i = 0; i < argsLength; ++i) {
3611 this[(j + length) & (capacity - 1)] = arguments[i];
3612 j++;
3613 }
3614 this._length = length + argsLength;
3615 return length + argsLength;
3616 }
3617
3618 }
3619
3620 if (argsLength === 0) return length;
3621
3622 this._checkCapacity(length + 1);
3623 var i = (this._front + length) & (this._capacity - 1);
3624 this[i] = item;
3625 this._length = length + 1;
3626 return length + 1;
3627};
3628
3629Deque.prototype.pop = function Deque$pop() {
3630 var length = this._length;
3631 if (length === 0) {
3632 return void 0;
3633 }
3634 var i = (this._front + length - 1) & (this._capacity - 1);
3635 var ret = this[i];
3636 this[i] = void 0;
3637 this._length = length - 1;
3638 return ret;
3639};
3640
3641Deque.prototype.shift = function Deque$shift() {
3642 var length = this._length;
3643 if (length === 0) {
3644 return void 0;
3645 }
3646 var front = this._front;
3647 var ret = this[front];
3648 this[front] = void 0;
3649 this._front = (front + 1) & (this._capacity - 1);
3650 this._length = length - 1;
3651 return ret;
3652};
3653
3654Deque.prototype.unshift = function Deque$unshift(item) {
3655 var length = this._length;
3656 var argsLength = arguments.length;
3657
3658
3659 if (argsLength > 1) {
3660 var capacity = this._capacity;
3661 if (length + argsLength > capacity) {
3662 for (var i = argsLength - 1; i >= 0; i--) {
3663 this._checkCapacity(length + 1);
3664 var capacity = this._capacity;
3665 var j = (((( this._front - 1 ) &
3666 ( capacity - 1) ) ^ capacity ) - capacity );
3667 this[j] = arguments[i];
3668 length++;
3669 this._length = length;
3670 this._front = j;
3671 }
3672 return length;
3673 }
3674 else {
3675 var front = this._front;
3676 for (var i = argsLength - 1; i >= 0; i--) {
3677 var j = (((( front - 1 ) &
3678 ( capacity - 1) ) ^ capacity ) - capacity );
3679 this[j] = arguments[i];
3680 front = j;
3681 }
3682 this._front = front;
3683 this._length = length + argsLength;
3684 return length + argsLength;
3685 }
3686 }
3687
3688 if (argsLength === 0) return length;
3689
3690 this._checkCapacity(length + 1);
3691 var capacity = this._capacity;
3692 var i = (((( this._front - 1 ) &
3693 ( capacity - 1) ) ^ capacity ) - capacity );
3694 this[i] = item;
3695 this._length = length + 1;
3696 this._front = i;
3697 return length + 1;
3698};
3699
3700Deque.prototype.peekBack = function Deque$peekBack() {
3701 var length = this._length;
3702 if (length === 0) {
3703 return void 0;
3704 }
3705 var index = (this._front + length - 1) & (this._capacity - 1);
3706 return this[index];
3707};
3708
3709Deque.prototype.peekFront = function Deque$peekFront() {
3710 if (this._length === 0) {
3711 return void 0;
3712 }
3713 return this[this._front];
3714};
3715
3716Deque.prototype.get = function Deque$get(index) {
3717 var i = index;
3718 if ((i !== (i | 0))) {
3719 return void 0;
3720 }
3721 var len = this._length;
3722 if (i < 0) {
3723 i = i + len;
3724 }
3725 if (i < 0 || i >= len) {
3726 return void 0;
3727 }
3728 return this[(this._front + i) & (this._capacity - 1)];
3729};
3730
3731Deque.prototype.isEmpty = function Deque$isEmpty() {
3732 return this._length === 0;
3733};
3734
3735Deque.prototype.clear = function Deque$clear() {
3736 var len = this._length;
3737 var front = this._front;
3738 var capacity = this._capacity;
3739 for (var j = 0; j < len; ++j) {
3740 this[(front + j) & (capacity - 1)] = void 0;
3741 }
3742 this._length = 0;
3743 this._front = 0;
3744};
3745
3746Deque.prototype.toString = function Deque$toString() {
3747 return this.toArray().toString();
3748};
3749
3750Deque.prototype.valueOf = Deque.prototype.toString;
3751Deque.prototype.removeFront = Deque.prototype.shift;
3752Deque.prototype.removeBack = Deque.prototype.pop;
3753Deque.prototype.insertFront = Deque.prototype.unshift;
3754Deque.prototype.insertBack = Deque.prototype.push;
3755Deque.prototype.enqueue = Deque.prototype.push;
3756Deque.prototype.dequeue = Deque.prototype.shift;
3757Deque.prototype.toJSON = Deque.prototype.toArray;
3758
3759Object.defineProperty(Deque.prototype, "length", {
3760 get: function() {
3761 return this._length;
3762 },
3763 set: function() {
3764 throw new RangeError("");
3765 }
3766});
3767
3768Deque.prototype._checkCapacity = function Deque$_checkCapacity(size) {
3769 if (this._capacity < size) {
3770 this._resizeTo(getCapacity(this._capacity * 1.5 + 16));
3771 }
3772};
3773
3774Deque.prototype._resizeTo = function Deque$_resizeTo(capacity) {
3775 var oldCapacity = this._capacity;
3776 this._capacity = capacity;
3777 var front = this._front;
3778 var length = this._length;
3779 if (front + length > oldCapacity) {
3780 var moveItemsCount = (front + length) & (oldCapacity - 1);
3781 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
3782 }
3783};
3784
3785
3786var isArray = Array.isArray;
3787
3788function arrayMove(src, srcIndex, dst, dstIndex, len) {
3789 for (var j = 0; j < len; ++j) {
3790 dst[j + dstIndex] = src[j + srcIndex];
3791 src[j + srcIndex] = void 0;
3792 }
3793}
3794
3795function pow2AtLeast(n) {
3796 n = n >>> 0;
3797 n = n - 1;
3798 n = n | (n >> 1);
3799 n = n | (n >> 2);
3800 n = n | (n >> 4);
3801 n = n | (n >> 8);
3802 n = n | (n >> 16);
3803 return n + 1;
3804}
3805
3806function getCapacity(capacity) {
3807 if (typeof capacity !== "number") {
3808 if (isArray(capacity)) {
3809 capacity = capacity.length;
3810 }
3811 else {
3812 return 16;
3813 }
3814 }
3815 return pow2AtLeast(
3816 Math.min(
3817 Math.max(16, capacity), 1073741824)
3818 );
3819}
3820
3821module.exports = Deque;
3822
3823},{}],23:[function(_dereq_,module,exports){
3824var prr = _dereq_('prr')
3825
3826function init (type, message, cause) {
3827 if (!!message && typeof message != 'string') {
3828 message = message.message || message.name
3829 }
3830 prr(this, {
3831 type : type
3832 , name : type
3833 // can be passed just a 'cause'
3834 , cause : typeof message != 'string' ? message : cause
3835 , message : message
3836 }, 'ewr')
3837}
3838
3839// generic prototype, not intended to be actually used - helpful for `instanceof`
3840function CustomError (message, cause) {
3841 Error.call(this)
3842 if (Error.captureStackTrace)
3843 Error.captureStackTrace(this, this.constructor)
3844 init.call(this, 'CustomError', message, cause)
3845}
3846
3847CustomError.prototype = new Error()
3848
3849function createError (errno, type, proto) {
3850 var err = function (message, cause) {
3851 init.call(this, type, message, cause)
3852 //TODO: the specificity here is stupid, errno should be available everywhere
3853 if (type == 'FilesystemError') {
3854 this.code = this.cause.code
3855 this.path = this.cause.path
3856 this.errno = this.cause.errno
3857 this.message =
3858 (errno.errno[this.cause.errno]
3859 ? errno.errno[this.cause.errno].description
3860 : this.cause.message)
3861 + (this.cause.path ? ' [' + this.cause.path + ']' : '')
3862 }
3863 Error.call(this)
3864 if (Error.captureStackTrace)
3865 Error.captureStackTrace(this, err)
3866 }
3867 err.prototype = !!proto ? new proto() : new CustomError()
3868 return err
3869}
3870
3871module.exports = function (errno) {
3872 var ce = function (type, proto) {
3873 return createError(errno, type, proto)
3874 }
3875 return {
3876 CustomError : CustomError
3877 , FilesystemError : ce('FilesystemError')
3878 , createError : ce
3879 }
3880}
3881
3882},{"prr":94}],24:[function(_dereq_,module,exports){
3883var all = module.exports.all = [
3884 {
3885 errno: -2,
3886 code: 'ENOENT',
3887 description: 'no such file or directory'
3888 },
3889 {
3890 errno: -1,
3891 code: 'UNKNOWN',
3892 description: 'unknown error'
3893 },
3894 {
3895 errno: 0,
3896 code: 'OK',
3897 description: 'success'
3898 },
3899 {
3900 errno: 1,
3901 code: 'EOF',
3902 description: 'end of file'
3903 },
3904 {
3905 errno: 2,
3906 code: 'EADDRINFO',
3907 description: 'getaddrinfo error'
3908 },
3909 {
3910 errno: 3,
3911 code: 'EACCES',
3912 description: 'permission denied'
3913 },
3914 {
3915 errno: 4,
3916 code: 'EAGAIN',
3917 description: 'resource temporarily unavailable'
3918 },
3919 {
3920 errno: 5,
3921 code: 'EADDRINUSE',
3922 description: 'address already in use'
3923 },
3924 {
3925 errno: 6,
3926 code: 'EADDRNOTAVAIL',
3927 description: 'address not available'
3928 },
3929 {
3930 errno: 7,
3931 code: 'EAFNOSUPPORT',
3932 description: 'address family not supported'
3933 },
3934 {
3935 errno: 8,
3936 code: 'EALREADY',
3937 description: 'connection already in progress'
3938 },
3939 {
3940 errno: 9,
3941 code: 'EBADF',
3942 description: 'bad file descriptor'
3943 },
3944 {
3945 errno: 10,
3946 code: 'EBUSY',
3947 description: 'resource busy or locked'
3948 },
3949 {
3950 errno: 11,
3951 code: 'ECONNABORTED',
3952 description: 'software caused connection abort'
3953 },
3954 {
3955 errno: 12,
3956 code: 'ECONNREFUSED',
3957 description: 'connection refused'
3958 },
3959 {
3960 errno: 13,
3961 code: 'ECONNRESET',
3962 description: 'connection reset by peer'
3963 },
3964 {
3965 errno: 14,
3966 code: 'EDESTADDRREQ',
3967 description: 'destination address required'
3968 },
3969 {
3970 errno: 15,
3971 code: 'EFAULT',
3972 description: 'bad address in system call argument'
3973 },
3974 {
3975 errno: 16,
3976 code: 'EHOSTUNREACH',
3977 description: 'host is unreachable'
3978 },
3979 {
3980 errno: 17,
3981 code: 'EINTR',
3982 description: 'interrupted system call'
3983 },
3984 {
3985 errno: 18,
3986 code: 'EINVAL',
3987 description: 'invalid argument'
3988 },
3989 {
3990 errno: 19,
3991 code: 'EISCONN',
3992 description: 'socket is already connected'
3993 },
3994 {
3995 errno: 20,
3996 code: 'EMFILE',
3997 description: 'too many open files'
3998 },
3999 {
4000 errno: 21,
4001 code: 'EMSGSIZE',
4002 description: 'message too long'
4003 },
4004 {
4005 errno: 22,
4006 code: 'ENETDOWN',
4007 description: 'network is down'
4008 },
4009 {
4010 errno: 23,
4011 code: 'ENETUNREACH',
4012 description: 'network is unreachable'
4013 },
4014 {
4015 errno: 24,
4016 code: 'ENFILE',
4017 description: 'file table overflow'
4018 },
4019 {
4020 errno: 25,
4021 code: 'ENOBUFS',
4022 description: 'no buffer space available'
4023 },
4024 {
4025 errno: 26,
4026 code: 'ENOMEM',
4027 description: 'not enough memory'
4028 },
4029 {
4030 errno: 27,
4031 code: 'ENOTDIR',
4032 description: 'not a directory'
4033 },
4034 {
4035 errno: 28,
4036 code: 'EISDIR',
4037 description: 'illegal operation on a directory'
4038 },
4039 {
4040 errno: 29,
4041 code: 'ENONET',
4042 description: 'machine is not on the network'
4043 },
4044 {
4045 errno: 31,
4046 code: 'ENOTCONN',
4047 description: 'socket is not connected'
4048 },
4049 {
4050 errno: 32,
4051 code: 'ENOTSOCK',
4052 description: 'socket operation on non-socket'
4053 },
4054 {
4055 errno: 33,
4056 code: 'ENOTSUP',
4057 description: 'operation not supported on socket'
4058 },
4059 {
4060 errno: 34,
4061 code: 'ENOENT',
4062 description: 'no such file or directory'
4063 },
4064 {
4065 errno: 35,
4066 code: 'ENOSYS',
4067 description: 'function not implemented'
4068 },
4069 {
4070 errno: 36,
4071 code: 'EPIPE',
4072 description: 'broken pipe'
4073 },
4074 {
4075 errno: 37,
4076 code: 'EPROTO',
4077 description: 'protocol error'
4078 },
4079 {
4080 errno: 38,
4081 code: 'EPROTONOSUPPORT',
4082 description: 'protocol not supported'
4083 },
4084 {
4085 errno: 39,
4086 code: 'EPROTOTYPE',
4087 description: 'protocol wrong type for socket'
4088 },
4089 {
4090 errno: 40,
4091 code: 'ETIMEDOUT',
4092 description: 'connection timed out'
4093 },
4094 {
4095 errno: 41,
4096 code: 'ECHARSET',
4097 description: 'invalid Unicode character'
4098 },
4099 {
4100 errno: 42,
4101 code: 'EAIFAMNOSUPPORT',
4102 description: 'address family for hostname not supported'
4103 },
4104 {
4105 errno: 44,
4106 code: 'EAISERVICE',
4107 description: 'servname not supported for ai_socktype'
4108 },
4109 {
4110 errno: 45,
4111 code: 'EAISOCKTYPE',
4112 description: 'ai_socktype not supported'
4113 },
4114 {
4115 errno: 46,
4116 code: 'ESHUTDOWN',
4117 description: 'cannot send after transport endpoint shutdown'
4118 },
4119 {
4120 errno: 47,
4121 code: 'EEXIST',
4122 description: 'file already exists'
4123 },
4124 {
4125 errno: 48,
4126 code: 'ESRCH',
4127 description: 'no such process'
4128 },
4129 {
4130 errno: 49,
4131 code: 'ENAMETOOLONG',
4132 description: 'name too long'
4133 },
4134 {
4135 errno: 50,
4136 code: 'EPERM',
4137 description: 'operation not permitted'
4138 },
4139 {
4140 errno: 51,
4141 code: 'ELOOP',
4142 description: 'too many symbolic links encountered'
4143 },
4144 {
4145 errno: 52,
4146 code: 'EXDEV',
4147 description: 'cross-device link not permitted'
4148 },
4149 {
4150 errno: 53,
4151 code: 'ENOTEMPTY',
4152 description: 'directory not empty'
4153 },
4154 {
4155 errno: 54,
4156 code: 'ENOSPC',
4157 description: 'no space left on device'
4158 },
4159 {
4160 errno: 55,
4161 code: 'EIO',
4162 description: 'i/o error'
4163 },
4164 {
4165 errno: 56,
4166 code: 'EROFS',
4167 description: 'read-only file system'
4168 },
4169 {
4170 errno: 57,
4171 code: 'ENODEV',
4172 description: 'no such device'
4173 },
4174 {
4175 errno: 58,
4176 code: 'ESPIPE',
4177 description: 'invalid seek'
4178 },
4179 {
4180 errno: 59,
4181 code: 'ECANCELED',
4182 description: 'operation canceled'
4183 }
4184]
4185
4186module.exports.errno = {}
4187module.exports.code = {}
4188
4189all.forEach(function (error) {
4190 module.exports.errno[error.errno] = error
4191 module.exports.code[error.code] = error
4192})
4193
4194module.exports.custom = _dereq_('./custom')(module.exports)
4195module.exports.create = module.exports.custom.createError
4196
4197},{"./custom":23}],25:[function(_dereq_,module,exports){
4198'use strict';
4199
4200var GetIntrinsic = _dereq_('get-intrinsic');
4201
4202/** @type {import('.')} */
4203var $defineProperty = GetIntrinsic('%Object.defineProperty%', true) || false;
4204if ($defineProperty) {
4205 try {
4206 $defineProperty({}, 'a', { value: 1 });
4207 } catch (e) {
4208 // IE 8 has a broken defineProperty
4209 $defineProperty = false;
4210 }
4211}
4212
4213module.exports = $defineProperty;
4214
4215},{"get-intrinsic":37}],26:[function(_dereq_,module,exports){
4216'use strict';
4217
4218/** @type {import('./eval')} */
4219module.exports = EvalError;
4220
4221},{}],27:[function(_dereq_,module,exports){
4222'use strict';
4223
4224/** @type {import('.')} */
4225module.exports = Error;
4226
4227},{}],28:[function(_dereq_,module,exports){
4228'use strict';
4229
4230/** @type {import('./range')} */
4231module.exports = RangeError;
4232
4233},{}],29:[function(_dereq_,module,exports){
4234'use strict';
4235
4236/** @type {import('./ref')} */
4237module.exports = ReferenceError;
4238
4239},{}],30:[function(_dereq_,module,exports){
4240'use strict';
4241
4242/** @type {import('./syntax')} */
4243module.exports = SyntaxError;
4244
4245},{}],31:[function(_dereq_,module,exports){
4246'use strict';
4247
4248/** @type {import('./type')} */
4249module.exports = TypeError;
4250
4251},{}],32:[function(_dereq_,module,exports){
4252'use strict';
4253
4254/** @type {import('./uri')} */
4255module.exports = URIError;
4256
4257},{}],33:[function(_dereq_,module,exports){
4258// Copyright Joyent, Inc. and other Node contributors.
4259//
4260// Permission is hereby granted, free of charge, to any person obtaining a
4261// copy of this software and associated documentation files (the
4262// "Software"), to deal in the Software without restriction, including
4263// without limitation the rights to use, copy, modify, merge, publish,
4264// distribute, sublicense, and/or sell copies of the Software, and to permit
4265// persons to whom the Software is furnished to do so, subject to the
4266// following conditions:
4267//
4268// The above copyright notice and this permission notice shall be included
4269// in all copies or substantial portions of the Software.
4270//
4271// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4272// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4273// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4274// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4275// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4276// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4277// USE OR OTHER DEALINGS IN THE SOFTWARE.
4278
4279var objectCreate = Object.create || objectCreatePolyfill
4280var objectKeys = Object.keys || objectKeysPolyfill
4281var bind = Function.prototype.bind || functionBindPolyfill
4282
4283function EventEmitter() {
4284 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
4285 this._events = objectCreate(null);
4286 this._eventsCount = 0;
4287 }
4288
4289 this._maxListeners = this._maxListeners || undefined;
4290}
4291module.exports = EventEmitter;
4292
4293// Backwards-compat with node 0.10.x
4294EventEmitter.EventEmitter = EventEmitter;
4295
4296EventEmitter.prototype._events = undefined;
4297EventEmitter.prototype._maxListeners = undefined;
4298
4299// By default EventEmitters will print a warning if more than 10 listeners are
4300// added to it. This is a useful default which helps finding memory leaks.
4301var defaultMaxListeners = 10;
4302
4303var hasDefineProperty;
4304try {
4305 var o = {};
4306 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
4307 hasDefineProperty = o.x === 0;
4308} catch (err) { hasDefineProperty = false }
4309if (hasDefineProperty) {
4310 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
4311 enumerable: true,
4312 get: function() {
4313 return defaultMaxListeners;
4314 },
4315 set: function(arg) {
4316 // check whether the input is a positive number (whose value is zero or
4317 // greater and not a NaN).
4318 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
4319 throw new TypeError('"defaultMaxListeners" must be a positive number');
4320 defaultMaxListeners = arg;
4321 }
4322 });
4323} else {
4324 EventEmitter.defaultMaxListeners = defaultMaxListeners;
4325}
4326
4327// Obviously not all Emitters should be limited to 10. This function allows
4328// that to be increased. Set to zero for unlimited.
4329EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
4330 if (typeof n !== 'number' || n < 0 || isNaN(n))
4331 throw new TypeError('"n" argument must be a positive number');
4332 this._maxListeners = n;
4333 return this;
4334};
4335
4336function $getMaxListeners(that) {
4337 if (that._maxListeners === undefined)
4338 return EventEmitter.defaultMaxListeners;
4339 return that._maxListeners;
4340}
4341
4342EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
4343 return $getMaxListeners(this);
4344};
4345
4346// These standalone emit* functions are used to optimize calling of event
4347// handlers for fast cases because emit() itself often has a variable number of
4348// arguments and can be deoptimized because of that. These functions always have
4349// the same number of arguments and thus do not get deoptimized, so the code
4350// inside them can execute faster.
4351function emitNone(handler, isFn, self) {
4352 if (isFn)
4353 handler.call(self);
4354 else {
4355 var len = handler.length;
4356 var listeners = arrayClone(handler, len);
4357 for (var i = 0; i < len; ++i)
4358 listeners[i].call(self);
4359 }
4360}
4361function emitOne(handler, isFn, self, arg1) {
4362 if (isFn)
4363 handler.call(self, arg1);
4364 else {
4365 var len = handler.length;
4366 var listeners = arrayClone(handler, len);
4367 for (var i = 0; i < len; ++i)
4368 listeners[i].call(self, arg1);
4369 }
4370}
4371function emitTwo(handler, isFn, self, arg1, arg2) {
4372 if (isFn)
4373 handler.call(self, arg1, arg2);
4374 else {
4375 var len = handler.length;
4376 var listeners = arrayClone(handler, len);
4377 for (var i = 0; i < len; ++i)
4378 listeners[i].call(self, arg1, arg2);
4379 }
4380}
4381function emitThree(handler, isFn, self, arg1, arg2, arg3) {
4382 if (isFn)
4383 handler.call(self, arg1, arg2, arg3);
4384 else {
4385 var len = handler.length;
4386 var listeners = arrayClone(handler, len);
4387 for (var i = 0; i < len; ++i)
4388 listeners[i].call(self, arg1, arg2, arg3);
4389 }
4390}
4391
4392function emitMany(handler, isFn, self, args) {
4393 if (isFn)
4394 handler.apply(self, args);
4395 else {
4396 var len = handler.length;
4397 var listeners = arrayClone(handler, len);
4398 for (var i = 0; i < len; ++i)
4399 listeners[i].apply(self, args);
4400 }
4401}
4402
4403EventEmitter.prototype.emit = function emit(type) {
4404 var er, handler, len, args, i, events;
4405 var doError = (type === 'error');
4406
4407 events = this._events;
4408 if (events)
4409 doError = (doError && events.error == null);
4410 else if (!doError)
4411 return false;
4412
4413 // If there is no 'error' event listener then throw.
4414 if (doError) {
4415 if (arguments.length > 1)
4416 er = arguments[1];
4417 if (er instanceof Error) {
4418 throw er; // Unhandled 'error' event
4419 } else {
4420 // At least give some kind of context to the user
4421 var err = new Error('Unhandled "error" event. (' + er + ')');
4422 err.context = er;
4423 throw err;
4424 }
4425 return false;
4426 }
4427
4428 handler = events[type];
4429
4430 if (!handler)
4431 return false;
4432
4433 var isFn = typeof handler === 'function';
4434 len = arguments.length;
4435 switch (len) {
4436 // fast cases
4437 case 1:
4438 emitNone(handler, isFn, this);
4439 break;
4440 case 2:
4441 emitOne(handler, isFn, this, arguments[1]);
4442 break;
4443 case 3:
4444 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
4445 break;
4446 case 4:
4447 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
4448 break;
4449 // slower
4450 default:
4451 args = new Array(len - 1);
4452 for (i = 1; i < len; i++)
4453 args[i - 1] = arguments[i];
4454 emitMany(handler, isFn, this, args);
4455 }
4456
4457 return true;
4458};
4459
4460function _addListener(target, type, listener, prepend) {
4461 var m;
4462 var events;
4463 var existing;
4464
4465 if (typeof listener !== 'function')
4466 throw new TypeError('"listener" argument must be a function');
4467
4468 events = target._events;
4469 if (!events) {
4470 events = target._events = objectCreate(null);
4471 target._eventsCount = 0;
4472 } else {
4473 // To avoid recursion in the case that type === "newListener"! Before
4474 // adding it to the listeners, first emit "newListener".
4475 if (events.newListener) {
4476 target.emit('newListener', type,
4477 listener.listener ? listener.listener : listener);
4478
4479 // Re-assign `events` because a newListener handler could have caused the
4480 // this._events to be assigned to a new object
4481 events = target._events;
4482 }
4483 existing = events[type];
4484 }
4485
4486 if (!existing) {
4487 // Optimize the case of one listener. Don't need the extra array object.
4488 existing = events[type] = listener;
4489 ++target._eventsCount;
4490 } else {
4491 if (typeof existing === 'function') {
4492 // Adding the second element, need to change to array.
4493 existing = events[type] =
4494 prepend ? [listener, existing] : [existing, listener];
4495 } else {
4496 // If we've already got an array, just append.
4497 if (prepend) {
4498 existing.unshift(listener);
4499 } else {
4500 existing.push(listener);
4501 }
4502 }
4503
4504 // Check for listener leak
4505 if (!existing.warned) {
4506 m = $getMaxListeners(target);
4507 if (m && m > 0 && existing.length > m) {
4508 existing.warned = true;
4509 var w = new Error('Possible EventEmitter memory leak detected. ' +
4510 existing.length + ' "' + String(type) + '" listeners ' +
4511 'added. Use emitter.setMaxListeners() to ' +
4512 'increase limit.');
4513 w.name = 'MaxListenersExceededWarning';
4514 w.emitter = target;
4515 w.type = type;
4516 w.count = existing.length;
4517 if (typeof console === 'object' && console.warn) {
4518 console.warn('%s: %s', w.name, w.message);
4519 }
4520 }
4521 }
4522 }
4523
4524 return target;
4525}
4526
4527EventEmitter.prototype.addListener = function addListener(type, listener) {
4528 return _addListener(this, type, listener, false);
4529};
4530
4531EventEmitter.prototype.on = EventEmitter.prototype.addListener;
4532
4533EventEmitter.prototype.prependListener =
4534 function prependListener(type, listener) {
4535 return _addListener(this, type, listener, true);
4536 };
4537
4538function onceWrapper() {
4539 if (!this.fired) {
4540 this.target.removeListener(this.type, this.wrapFn);
4541 this.fired = true;
4542 switch (arguments.length) {
4543 case 0:
4544 return this.listener.call(this.target);
4545 case 1:
4546 return this.listener.call(this.target, arguments[0]);
4547 case 2:
4548 return this.listener.call(this.target, arguments[0], arguments[1]);
4549 case 3:
4550 return this.listener.call(this.target, arguments[0], arguments[1],
4551 arguments[2]);
4552 default:
4553 var args = new Array(arguments.length);
4554 for (var i = 0; i < args.length; ++i)
4555 args[i] = arguments[i];
4556 this.listener.apply(this.target, args);
4557 }
4558 }
4559}
4560
4561function _onceWrap(target, type, listener) {
4562 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
4563 var wrapped = bind.call(onceWrapper, state);
4564 wrapped.listener = listener;
4565 state.wrapFn = wrapped;
4566 return wrapped;
4567}
4568
4569EventEmitter.prototype.once = function once(type, listener) {
4570 if (typeof listener !== 'function')
4571 throw new TypeError('"listener" argument must be a function');
4572 this.on(type, _onceWrap(this, type, listener));
4573 return this;
4574};
4575
4576EventEmitter.prototype.prependOnceListener =
4577 function prependOnceListener(type, listener) {
4578 if (typeof listener !== 'function')
4579 throw new TypeError('"listener" argument must be a function');
4580 this.prependListener(type, _onceWrap(this, type, listener));
4581 return this;
4582 };
4583
4584// Emits a 'removeListener' event if and only if the listener was removed.
4585EventEmitter.prototype.removeListener =
4586 function removeListener(type, listener) {
4587 var list, events, position, i, originalListener;
4588
4589 if (typeof listener !== 'function')
4590 throw new TypeError('"listener" argument must be a function');
4591
4592 events = this._events;
4593 if (!events)
4594 return this;
4595
4596 list = events[type];
4597 if (!list)
4598 return this;
4599
4600 if (list === listener || list.listener === listener) {
4601 if (--this._eventsCount === 0)
4602 this._events = objectCreate(null);
4603 else {
4604 delete events[type];
4605 if (events.removeListener)
4606 this.emit('removeListener', type, list.listener || listener);
4607 }
4608 } else if (typeof list !== 'function') {
4609 position = -1;
4610
4611 for (i = list.length - 1; i >= 0; i--) {
4612 if (list[i] === listener || list[i].listener === listener) {
4613 originalListener = list[i].listener;
4614 position = i;
4615 break;
4616 }
4617 }
4618
4619 if (position < 0)
4620 return this;
4621
4622 if (position === 0)
4623 list.shift();
4624 else
4625 spliceOne(list, position);
4626
4627 if (list.length === 1)
4628 events[type] = list[0];
4629
4630 if (events.removeListener)
4631 this.emit('removeListener', type, originalListener || listener);
4632 }
4633
4634 return this;
4635 };
4636
4637EventEmitter.prototype.removeAllListeners =
4638 function removeAllListeners(type) {
4639 var listeners, events, i;
4640
4641 events = this._events;
4642 if (!events)
4643 return this;
4644
4645 // not listening for removeListener, no need to emit
4646 if (!events.removeListener) {
4647 if (arguments.length === 0) {
4648 this._events = objectCreate(null);
4649 this._eventsCount = 0;
4650 } else if (events[type]) {
4651 if (--this._eventsCount === 0)
4652 this._events = objectCreate(null);
4653 else
4654 delete events[type];
4655 }
4656 return this;
4657 }
4658
4659 // emit removeListener for all listeners on all events
4660 if (arguments.length === 0) {
4661 var keys = objectKeys(events);
4662 var key;
4663 for (i = 0; i < keys.length; ++i) {
4664 key = keys[i];
4665 if (key === 'removeListener') continue;
4666 this.removeAllListeners(key);
4667 }
4668 this.removeAllListeners('removeListener');
4669 this._events = objectCreate(null);
4670 this._eventsCount = 0;
4671 return this;
4672 }
4673
4674 listeners = events[type];
4675
4676 if (typeof listeners === 'function') {
4677 this.removeListener(type, listeners);
4678 } else if (listeners) {
4679 // LIFO order
4680 for (i = listeners.length - 1; i >= 0; i--) {
4681 this.removeListener(type, listeners[i]);
4682 }
4683 }
4684
4685 return this;
4686 };
4687
4688function _listeners(target, type, unwrap) {
4689 var events = target._events;
4690
4691 if (!events)
4692 return [];
4693
4694 var evlistener = events[type];
4695 if (!evlistener)
4696 return [];
4697
4698 if (typeof evlistener === 'function')
4699 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
4700
4701 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
4702}
4703
4704EventEmitter.prototype.listeners = function listeners(type) {
4705 return _listeners(this, type, true);
4706};
4707
4708EventEmitter.prototype.rawListeners = function rawListeners(type) {
4709 return _listeners(this, type, false);
4710};
4711
4712EventEmitter.listenerCount = function(emitter, type) {
4713 if (typeof emitter.listenerCount === 'function') {
4714 return emitter.listenerCount(type);
4715 } else {
4716 return listenerCount.call(emitter, type);
4717 }
4718};
4719
4720EventEmitter.prototype.listenerCount = listenerCount;
4721function listenerCount(type) {
4722 var events = this._events;
4723
4724 if (events) {
4725 var evlistener = events[type];
4726
4727 if (typeof evlistener === 'function') {
4728 return 1;
4729 } else if (evlistener) {
4730 return evlistener.length;
4731 }
4732 }
4733
4734 return 0;
4735}
4736
4737EventEmitter.prototype.eventNames = function eventNames() {
4738 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
4739};
4740
4741// About 1.5x faster than the two-arg version of Array#splice().
4742function spliceOne(list, index) {
4743 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
4744 list[i] = list[k];
4745 list.pop();
4746}
4747
4748function arrayClone(arr, n) {
4749 var copy = new Array(n);
4750 for (var i = 0; i < n; ++i)
4751 copy[i] = arr[i];
4752 return copy;
4753}
4754
4755function unwrapListeners(arr) {
4756 var ret = new Array(arr.length);
4757 for (var i = 0; i < ret.length; ++i) {
4758 ret[i] = arr[i].listener || arr[i];
4759 }
4760 return ret;
4761}
4762
4763function objectCreatePolyfill(proto) {
4764 var F = function() {};
4765 F.prototype = proto;
4766 return new F;
4767}
4768function objectKeysPolyfill(obj) {
4769 var keys = [];
4770 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
4771 keys.push(k);
4772 }
4773 return k;
4774}
4775function functionBindPolyfill(context) {
4776 var fn = this;
4777 return function () {
4778 return fn.apply(context, arguments);
4779 };
4780}
4781
4782},{}],34:[function(_dereq_,module,exports){
4783'use strict';
4784
4785/* eslint no-invalid-this: 1 */
4786
4787var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
4788var toStr = Object.prototype.toString;
4789var max = Math.max;
4790var funcType = '[object Function]';
4791
4792var concatty = function concatty(a, b) {
4793 var arr = [];
4794
4795 for (var i = 0; i < a.length; i += 1) {
4796 arr[i] = a[i];
4797 }
4798 for (var j = 0; j < b.length; j += 1) {
4799 arr[j + a.length] = b[j];
4800 }
4801
4802 return arr;
4803};
4804
4805var slicy = function slicy(arrLike, offset) {
4806 var arr = [];
4807 for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
4808 arr[j] = arrLike[i];
4809 }
4810 return arr;
4811};
4812
4813var joiny = function (arr, joiner) {
4814 var str = '';
4815 for (var i = 0; i < arr.length; i += 1) {
4816 str += arr[i];
4817 if (i + 1 < arr.length) {
4818 str += joiner;
4819 }
4820 }
4821 return str;
4822};
4823
4824module.exports = function bind(that) {
4825 var target = this;
4826 if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
4827 throw new TypeError(ERROR_MESSAGE + target);
4828 }
4829 var args = slicy(arguments, 1);
4830
4831 var bound;
4832 var binder = function () {
4833 if (this instanceof bound) {
4834 var result = target.apply(
4835 this,
4836 concatty(args, arguments)
4837 );
4838 if (Object(result) === result) {
4839 return result;
4840 }
4841 return this;
4842 }
4843 return target.apply(
4844 that,
4845 concatty(args, arguments)
4846 );
4847
4848 };
4849
4850 var boundLength = max(0, target.length - args.length);
4851 var boundArgs = [];
4852 for (var i = 0; i < boundLength; i++) {
4853 boundArgs[i] = '$' + i;
4854 }
4855
4856 bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
4857
4858 if (target.prototype) {
4859 var Empty = function Empty() {};
4860 Empty.prototype = target.prototype;
4861 bound.prototype = new Empty();
4862 Empty.prototype = null;
4863 }
4864
4865 return bound;
4866};
4867
4868},{}],35:[function(_dereq_,module,exports){
4869'use strict';
4870
4871var implementation = _dereq_('./implementation');
4872
4873module.exports = Function.prototype.bind || implementation;
4874
4875},{"./implementation":34}],36:[function(_dereq_,module,exports){
4876"use strict"
4877
4878module.exports = createRBTree
4879
4880var RED = 0
4881var BLACK = 1
4882
4883function RBNode(color, key, value, left, right, count) {
4884 this._color = color
4885 this.key = key
4886 this.value = value
4887 this.left = left
4888 this.right = right
4889 this._count = count
4890}
4891
4892function cloneNode(node) {
4893 return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count)
4894}
4895
4896function repaint(color, node) {
4897 return new RBNode(color, node.key, node.value, node.left, node.right, node._count)
4898}
4899
4900function recount(node) {
4901 node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0)
4902}
4903
4904function RedBlackTree(compare, root) {
4905 this._compare = compare
4906 this.root = root
4907}
4908
4909var proto = RedBlackTree.prototype
4910
4911Object.defineProperty(proto, "keys", {
4912 get: function() {
4913 var result = []
4914 this.forEach(function(k,v) {
4915 result.push(k)
4916 })
4917 return result
4918 }
4919})
4920
4921Object.defineProperty(proto, "values", {
4922 get: function() {
4923 var result = []
4924 this.forEach(function(k,v) {
4925 result.push(v)
4926 })
4927 return result
4928 }
4929})
4930
4931//Returns the number of nodes in the tree
4932Object.defineProperty(proto, "length", {
4933 get: function() {
4934 if(this.root) {
4935 return this.root._count
4936 }
4937 return 0
4938 }
4939})
4940
4941//Insert a new item into the tree
4942proto.insert = function(key, value) {
4943 var cmp = this._compare
4944 //Find point to insert new node at
4945 var n = this.root
4946 var n_stack = []
4947 var d_stack = []
4948 while(n) {
4949 var d = cmp(key, n.key)
4950 n_stack.push(n)
4951 d_stack.push(d)
4952 if(d <= 0) {
4953 n = n.left
4954 } else {
4955 n = n.right
4956 }
4957 }
4958 //Rebuild path to leaf node
4959 n_stack.push(new RBNode(RED, key, value, null, null, 1))
4960 for(var s=n_stack.length-2; s>=0; --s) {
4961 var n = n_stack[s]
4962 if(d_stack[s] <= 0) {
4963 n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1)
4964 } else {
4965 n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1)
4966 }
4967 }
4968 //Rebalance tree using rotations
4969 //console.log("start insert", key, d_stack)
4970 for(var s=n_stack.length-1; s>1; --s) {
4971 var p = n_stack[s-1]
4972 var n = n_stack[s]
4973 if(p._color === BLACK || n._color === BLACK) {
4974 break
4975 }
4976 var pp = n_stack[s-2]
4977 if(pp.left === p) {
4978 if(p.left === n) {
4979 var y = pp.right
4980 if(y && y._color === RED) {
4981 //console.log("LLr")
4982 p._color = BLACK
4983 pp.right = repaint(BLACK, y)
4984 pp._color = RED
4985 s -= 1
4986 } else {
4987 //console.log("LLb")
4988 pp._color = RED
4989 pp.left = p.right
4990 p._color = BLACK
4991 p.right = pp
4992 n_stack[s-2] = p
4993 n_stack[s-1] = n
4994 recount(pp)
4995 recount(p)
4996 if(s >= 3) {
4997 var ppp = n_stack[s-3]
4998 if(ppp.left === pp) {
4999 ppp.left = p
5000 } else {
5001 ppp.right = p
5002 }
5003 }
5004 break
5005 }
5006 } else {
5007 var y = pp.right
5008 if(y && y._color === RED) {
5009 //console.log("LRr")
5010 p._color = BLACK
5011 pp.right = repaint(BLACK, y)
5012 pp._color = RED
5013 s -= 1
5014 } else {
5015 //console.log("LRb")
5016 p.right = n.left
5017 pp._color = RED
5018 pp.left = n.right
5019 n._color = BLACK
5020 n.left = p
5021 n.right = pp
5022 n_stack[s-2] = n
5023 n_stack[s-1] = p
5024 recount(pp)
5025 recount(p)
5026 recount(n)
5027 if(s >= 3) {
5028 var ppp = n_stack[s-3]
5029 if(ppp.left === pp) {
5030 ppp.left = n
5031 } else {
5032 ppp.right = n
5033 }
5034 }
5035 break
5036 }
5037 }
5038 } else {
5039 if(p.right === n) {
5040 var y = pp.left
5041 if(y && y._color === RED) {
5042 //console.log("RRr", y.key)
5043 p._color = BLACK
5044 pp.left = repaint(BLACK, y)
5045 pp._color = RED
5046 s -= 1
5047 } else {
5048 //console.log("RRb")
5049 pp._color = RED
5050 pp.right = p.left
5051 p._color = BLACK
5052 p.left = pp
5053 n_stack[s-2] = p
5054 n_stack[s-1] = n
5055 recount(pp)
5056 recount(p)
5057 if(s >= 3) {
5058 var ppp = n_stack[s-3]
5059 if(ppp.right === pp) {
5060 ppp.right = p
5061 } else {
5062 ppp.left = p
5063 }
5064 }
5065 break
5066 }
5067 } else {
5068 var y = pp.left
5069 if(y && y._color === RED) {
5070 //console.log("RLr")
5071 p._color = BLACK
5072 pp.left = repaint(BLACK, y)
5073 pp._color = RED
5074 s -= 1
5075 } else {
5076 //console.log("RLb")
5077 p.left = n.right
5078 pp._color = RED
5079 pp.right = n.left
5080 n._color = BLACK
5081 n.right = p
5082 n.left = pp
5083 n_stack[s-2] = n
5084 n_stack[s-1] = p
5085 recount(pp)
5086 recount(p)
5087 recount(n)
5088 if(s >= 3) {
5089 var ppp = n_stack[s-3]
5090 if(ppp.right === pp) {
5091 ppp.right = n
5092 } else {
5093 ppp.left = n
5094 }
5095 }
5096 break
5097 }
5098 }
5099 }
5100 }
5101 //Return new tree
5102 n_stack[0]._color = BLACK
5103 return new RedBlackTree(cmp, n_stack[0])
5104}
5105
5106
5107//Visit all nodes inorder
5108function doVisitFull(visit, node) {
5109 if(node.left) {
5110 var v = doVisitFull(visit, node.left)
5111 if(v) { return v }
5112 }
5113 var v = visit(node.key, node.value)
5114 if(v) { return v }
5115 if(node.right) {
5116 return doVisitFull(visit, node.right)
5117 }
5118}
5119
5120//Visit half nodes in order
5121function doVisitHalf(lo, compare, visit, node) {
5122 var l = compare(lo, node.key)
5123 if(l <= 0) {
5124 if(node.left) {
5125 var v = doVisitHalf(lo, compare, visit, node.left)
5126 if(v) { return v }
5127 }
5128 var v = visit(node.key, node.value)
5129 if(v) { return v }
5130 }
5131 if(node.right) {
5132 return doVisitHalf(lo, compare, visit, node.right)
5133 }
5134}
5135
5136//Visit all nodes within a range
5137function doVisit(lo, hi, compare, visit, node) {
5138 var l = compare(lo, node.key)
5139 var h = compare(hi, node.key)
5140 var v
5141 if(l <= 0) {
5142 if(node.left) {
5143 v = doVisit(lo, hi, compare, visit, node.left)
5144 if(v) { return v }
5145 }
5146 if(h > 0) {
5147 v = visit(node.key, node.value)
5148 if(v) { return v }
5149 }
5150 }
5151 if(h > 0 && node.right) {
5152 return doVisit(lo, hi, compare, visit, node.right)
5153 }
5154}
5155
5156
5157proto.forEach = function rbTreeForEach(visit, lo, hi) {
5158 if(!this.root) {
5159 return
5160 }
5161 switch(arguments.length) {
5162 case 1:
5163 return doVisitFull(visit, this.root)
5164 break
5165
5166 case 2:
5167 return doVisitHalf(lo, this._compare, visit, this.root)
5168 break
5169
5170 case 3:
5171 if(this._compare(lo, hi) >= 0) {
5172 return
5173 }
5174 return doVisit(lo, hi, this._compare, visit, this.root)
5175 break
5176 }
5177}
5178
5179//First item in list
5180Object.defineProperty(proto, "begin", {
5181 get: function() {
5182 var stack = []
5183 var n = this.root
5184 while(n) {
5185 stack.push(n)
5186 n = n.left
5187 }
5188 return new RedBlackTreeIterator(this, stack)
5189 }
5190})
5191
5192//Last item in list
5193Object.defineProperty(proto, "end", {
5194 get: function() {
5195 var stack = []
5196 var n = this.root
5197 while(n) {
5198 stack.push(n)
5199 n = n.right
5200 }
5201 return new RedBlackTreeIterator(this, stack)
5202 }
5203})
5204
5205//Find the ith item in the tree
5206proto.at = function(idx) {
5207 if(idx < 0) {
5208 return new RedBlackTreeIterator(this, [])
5209 }
5210 var n = this.root
5211 var stack = []
5212 while(true) {
5213 stack.push(n)
5214 if(n.left) {
5215 if(idx < n.left._count) {
5216 n = n.left
5217 continue
5218 }
5219 idx -= n.left._count
5220 }
5221 if(!idx) {
5222 return new RedBlackTreeIterator(this, stack)
5223 }
5224 idx -= 1
5225 if(n.right) {
5226 if(idx >= n.right._count) {
5227 break
5228 }
5229 n = n.right
5230 } else {
5231 break
5232 }
5233 }
5234 return new RedBlackTreeIterator(this, [])
5235}
5236
5237proto.ge = function(key) {
5238 var cmp = this._compare
5239 var n = this.root
5240 var stack = []
5241 var last_ptr = 0
5242 while(n) {
5243 var d = cmp(key, n.key)
5244 stack.push(n)
5245 if(d <= 0) {
5246 last_ptr = stack.length
5247 }
5248 if(d <= 0) {
5249 n = n.left
5250 } else {
5251 n = n.right
5252 }
5253 }
5254 stack.length = last_ptr
5255 return new RedBlackTreeIterator(this, stack)
5256}
5257
5258proto.gt = function(key) {
5259 var cmp = this._compare
5260 var n = this.root
5261 var stack = []
5262 var last_ptr = 0
5263 while(n) {
5264 var d = cmp(key, n.key)
5265 stack.push(n)
5266 if(d < 0) {
5267 last_ptr = stack.length
5268 }
5269 if(d < 0) {
5270 n = n.left
5271 } else {
5272 n = n.right
5273 }
5274 }
5275 stack.length = last_ptr
5276 return new RedBlackTreeIterator(this, stack)
5277}
5278
5279proto.lt = function(key) {
5280 var cmp = this._compare
5281 var n = this.root
5282 var stack = []
5283 var last_ptr = 0
5284 while(n) {
5285 var d = cmp(key, n.key)
5286 stack.push(n)
5287 if(d > 0) {
5288 last_ptr = stack.length
5289 }
5290 if(d <= 0) {
5291 n = n.left
5292 } else {
5293 n = n.right
5294 }
5295 }
5296 stack.length = last_ptr
5297 return new RedBlackTreeIterator(this, stack)
5298}
5299
5300proto.le = function(key) {
5301 var cmp = this._compare
5302 var n = this.root
5303 var stack = []
5304 var last_ptr = 0
5305 while(n) {
5306 var d = cmp(key, n.key)
5307 stack.push(n)
5308 if(d >= 0) {
5309 last_ptr = stack.length
5310 }
5311 if(d < 0) {
5312 n = n.left
5313 } else {
5314 n = n.right
5315 }
5316 }
5317 stack.length = last_ptr
5318 return new RedBlackTreeIterator(this, stack)
5319}
5320
5321//Finds the item with key if it exists
5322proto.find = function(key) {
5323 var cmp = this._compare
5324 var n = this.root
5325 var stack = []
5326 while(n) {
5327 var d = cmp(key, n.key)
5328 stack.push(n)
5329 if(d === 0) {
5330 return new RedBlackTreeIterator(this, stack)
5331 }
5332 if(d <= 0) {
5333 n = n.left
5334 } else {
5335 n = n.right
5336 }
5337 }
5338 return new RedBlackTreeIterator(this, [])
5339}
5340
5341//Removes item with key from tree
5342proto.remove = function(key) {
5343 var iter = this.find(key)
5344 if(iter) {
5345 return iter.remove()
5346 }
5347 return this
5348}
5349
5350//Returns the item at `key`
5351proto.get = function(key) {
5352 var cmp = this._compare
5353 var n = this.root
5354 while(n) {
5355 var d = cmp(key, n.key)
5356 if(d === 0) {
5357 return n.value
5358 }
5359 if(d <= 0) {
5360 n = n.left
5361 } else {
5362 n = n.right
5363 }
5364 }
5365 return
5366}
5367
5368//Iterator for red black tree
5369function RedBlackTreeIterator(tree, stack) {
5370 this.tree = tree
5371 this._stack = stack
5372}
5373
5374var iproto = RedBlackTreeIterator.prototype
5375
5376//Test if iterator is valid
5377Object.defineProperty(iproto, "valid", {
5378 get: function() {
5379 return this._stack.length > 0
5380 }
5381})
5382
5383//Node of the iterator
5384Object.defineProperty(iproto, "node", {
5385 get: function() {
5386 if(this._stack.length > 0) {
5387 return this._stack[this._stack.length-1]
5388 }
5389 return null
5390 },
5391 enumerable: true
5392})
5393
5394//Makes a copy of an iterator
5395iproto.clone = function() {
5396 return new RedBlackTreeIterator(this.tree, this._stack.slice())
5397}
5398
5399//Swaps two nodes
5400function swapNode(n, v) {
5401 n.key = v.key
5402 n.value = v.value
5403 n.left = v.left
5404 n.right = v.right
5405 n._color = v._color
5406 n._count = v._count
5407}
5408
5409//Fix up a double black node in a tree
5410function fixDoubleBlack(stack) {
5411 var n, p, s, z
5412 for(var i=stack.length-1; i>=0; --i) {
5413 n = stack[i]
5414 if(i === 0) {
5415 n._color = BLACK
5416 return
5417 }
5418 //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key)
5419 p = stack[i-1]
5420 if(p.left === n) {
5421 //console.log("left child")
5422 s = p.right
5423 if(s.right && s.right._color === RED) {
5424 //console.log("case 1: right sibling child red")
5425 s = p.right = cloneNode(s)
5426 z = s.right = cloneNode(s.right)
5427 p.right = s.left
5428 s.left = p
5429 s.right = z
5430 s._color = p._color
5431 n._color = BLACK
5432 p._color = BLACK
5433 z._color = BLACK
5434 recount(p)
5435 recount(s)
5436 if(i > 1) {
5437 var pp = stack[i-2]
5438 if(pp.left === p) {
5439 pp.left = s
5440 } else {
5441 pp.right = s
5442 }
5443 }
5444 stack[i-1] = s
5445 return
5446 } else if(s.left && s.left._color === RED) {
5447 //console.log("case 1: left sibling child red")
5448 s = p.right = cloneNode(s)
5449 z = s.left = cloneNode(s.left)
5450 p.right = z.left
5451 s.left = z.right
5452 z.left = p
5453 z.right = s
5454 z._color = p._color
5455 p._color = BLACK
5456 s._color = BLACK
5457 n._color = BLACK
5458 recount(p)
5459 recount(s)
5460 recount(z)
5461 if(i > 1) {
5462 var pp = stack[i-2]
5463 if(pp.left === p) {
5464 pp.left = z
5465 } else {
5466 pp.right = z
5467 }
5468 }
5469 stack[i-1] = z
5470 return
5471 }
5472 if(s._color === BLACK) {
5473 if(p._color === RED) {
5474 //console.log("case 2: black sibling, red parent", p.right.value)
5475 p._color = BLACK
5476 p.right = repaint(RED, s)
5477 return
5478 } else {
5479 //console.log("case 2: black sibling, black parent", p.right.value)
5480 p.right = repaint(RED, s)
5481 continue
5482 }
5483 } else {
5484 //console.log("case 3: red sibling")
5485 s = cloneNode(s)
5486 p.right = s.left
5487 s.left = p
5488 s._color = p._color
5489 p._color = RED
5490 recount(p)
5491 recount(s)
5492 if(i > 1) {
5493 var pp = stack[i-2]
5494 if(pp.left === p) {
5495 pp.left = s
5496 } else {
5497 pp.right = s
5498 }
5499 }
5500 stack[i-1] = s
5501 stack[i] = p
5502 if(i+1 < stack.length) {
5503 stack[i+1] = n
5504 } else {
5505 stack.push(n)
5506 }
5507 i = i+2
5508 }
5509 } else {
5510 //console.log("right child")
5511 s = p.left
5512 if(s.left && s.left._color === RED) {
5513 //console.log("case 1: left sibling child red", p.value, p._color)
5514 s = p.left = cloneNode(s)
5515 z = s.left = cloneNode(s.left)
5516 p.left = s.right
5517 s.right = p
5518 s.left = z
5519 s._color = p._color
5520 n._color = BLACK
5521 p._color = BLACK
5522 z._color = BLACK
5523 recount(p)
5524 recount(s)
5525 if(i > 1) {
5526 var pp = stack[i-2]
5527 if(pp.right === p) {
5528 pp.right = s
5529 } else {
5530 pp.left = s
5531 }
5532 }
5533 stack[i-1] = s
5534 return
5535 } else if(s.right && s.right._color === RED) {
5536 //console.log("case 1: right sibling child red")
5537 s = p.left = cloneNode(s)
5538 z = s.right = cloneNode(s.right)
5539 p.left = z.right
5540 s.right = z.left
5541 z.right = p
5542 z.left = s
5543 z._color = p._color
5544 p._color = BLACK
5545 s._color = BLACK
5546 n._color = BLACK
5547 recount(p)
5548 recount(s)
5549 recount(z)
5550 if(i > 1) {
5551 var pp = stack[i-2]
5552 if(pp.right === p) {
5553 pp.right = z
5554 } else {
5555 pp.left = z
5556 }
5557 }
5558 stack[i-1] = z
5559 return
5560 }
5561 if(s._color === BLACK) {
5562 if(p._color === RED) {
5563 //console.log("case 2: black sibling, red parent")
5564 p._color = BLACK
5565 p.left = repaint(RED, s)
5566 return
5567 } else {
5568 //console.log("case 2: black sibling, black parent")
5569 p.left = repaint(RED, s)
5570 continue
5571 }
5572 } else {
5573 //console.log("case 3: red sibling")
5574 s = cloneNode(s)
5575 p.left = s.right
5576 s.right = p
5577 s._color = p._color
5578 p._color = RED
5579 recount(p)
5580 recount(s)
5581 if(i > 1) {
5582 var pp = stack[i-2]
5583 if(pp.right === p) {
5584 pp.right = s
5585 } else {
5586 pp.left = s
5587 }
5588 }
5589 stack[i-1] = s
5590 stack[i] = p
5591 if(i+1 < stack.length) {
5592 stack[i+1] = n
5593 } else {
5594 stack.push(n)
5595 }
5596 i = i+2
5597 }
5598 }
5599 }
5600}
5601
5602//Removes item at iterator from tree
5603iproto.remove = function() {
5604 var stack = this._stack
5605 if(stack.length === 0) {
5606 return this.tree
5607 }
5608 //First copy path to node
5609 var cstack = new Array(stack.length)
5610 var n = stack[stack.length-1]
5611 cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count)
5612 for(var i=stack.length-2; i>=0; --i) {
5613 var n = stack[i]
5614 if(n.left === stack[i+1]) {
5615 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
5616 } else {
5617 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5618 }
5619 }
5620
5621 //Get node
5622 n = cstack[cstack.length-1]
5623 //console.log("start remove: ", n.value)
5624
5625 //If not leaf, then swap with previous node
5626 if(n.left && n.right) {
5627 //console.log("moving to leaf")
5628
5629 //First walk to previous leaf
5630 var split = cstack.length
5631 n = n.left
5632 while(n.right) {
5633 cstack.push(n)
5634 n = n.right
5635 }
5636 //Copy path to leaf
5637 var v = cstack[split-1]
5638 cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count))
5639 cstack[split-1].key = n.key
5640 cstack[split-1].value = n.value
5641
5642 //Fix up stack
5643 for(var i=cstack.length-2; i>=split; --i) {
5644 n = cstack[i]
5645 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5646 }
5647 cstack[split-1].left = cstack[split]
5648 }
5649 //console.log("stack=", cstack.map(function(v) { return v.value }))
5650
5651 //Remove leaf node
5652 n = cstack[cstack.length-1]
5653 if(n._color === RED) {
5654 //Easy case: removing red leaf
5655 //console.log("RED leaf")
5656 var p = cstack[cstack.length-2]
5657 if(p.left === n) {
5658 p.left = null
5659 } else if(p.right === n) {
5660 p.right = null
5661 }
5662 cstack.pop()
5663 for(var i=0; i<cstack.length; ++i) {
5664 cstack[i]._count--
5665 }
5666 return new RedBlackTree(this.tree._compare, cstack[0])
5667 } else {
5668 if(n.left || n.right) {
5669 //Second easy case: Single child black parent
5670 //console.log("BLACK single child")
5671 if(n.left) {
5672 swapNode(n, n.left)
5673 } else if(n.right) {
5674 swapNode(n, n.right)
5675 }
5676 //Child must be red, so repaint it black to balance color
5677 n._color = BLACK
5678 for(var i=0; i<cstack.length-1; ++i) {
5679 cstack[i]._count--
5680 }
5681 return new RedBlackTree(this.tree._compare, cstack[0])
5682 } else if(cstack.length === 1) {
5683 //Third easy case: root
5684 //console.log("ROOT")
5685 return new RedBlackTree(this.tree._compare, null)
5686 } else {
5687 //Hard case: Repaint n, and then do some nasty stuff
5688 //console.log("BLACK leaf no children")
5689 for(var i=0; i<cstack.length; ++i) {
5690 cstack[i]._count--
5691 }
5692 var parent = cstack[cstack.length-2]
5693 fixDoubleBlack(cstack)
5694 //Fix up links
5695 if(parent.left === n) {
5696 parent.left = null
5697 } else {
5698 parent.right = null
5699 }
5700 }
5701 }
5702 return new RedBlackTree(this.tree._compare, cstack[0])
5703}
5704
5705//Returns key
5706Object.defineProperty(iproto, "key", {
5707 get: function() {
5708 if(this._stack.length > 0) {
5709 return this._stack[this._stack.length-1].key
5710 }
5711 return
5712 },
5713 enumerable: true
5714})
5715
5716//Returns value
5717Object.defineProperty(iproto, "value", {
5718 get: function() {
5719 if(this._stack.length > 0) {
5720 return this._stack[this._stack.length-1].value
5721 }
5722 return
5723 },
5724 enumerable: true
5725})
5726
5727
5728//Returns the position of this iterator in the sorted list
5729Object.defineProperty(iproto, "index", {
5730 get: function() {
5731 var idx = 0
5732 var stack = this._stack
5733 if(stack.length === 0) {
5734 var r = this.tree.root
5735 if(r) {
5736 return r._count
5737 }
5738 return 0
5739 } else if(stack[stack.length-1].left) {
5740 idx = stack[stack.length-1].left._count
5741 }
5742 for(var s=stack.length-2; s>=0; --s) {
5743 if(stack[s+1] === stack[s].right) {
5744 ++idx
5745 if(stack[s].left) {
5746 idx += stack[s].left._count
5747 }
5748 }
5749 }
5750 return idx
5751 },
5752 enumerable: true
5753})
5754
5755//Advances iterator to next element in list
5756iproto.next = function() {
5757 var stack = this._stack
5758 if(stack.length === 0) {
5759 return
5760 }
5761 var n = stack[stack.length-1]
5762 if(n.right) {
5763 n = n.right
5764 while(n) {
5765 stack.push(n)
5766 n = n.left
5767 }
5768 } else {
5769 stack.pop()
5770 while(stack.length > 0 && stack[stack.length-1].right === n) {
5771 n = stack[stack.length-1]
5772 stack.pop()
5773 }
5774 }
5775}
5776
5777//Checks if iterator is at end of tree
5778Object.defineProperty(iproto, "hasNext", {
5779 get: function() {
5780 var stack = this._stack
5781 if(stack.length === 0) {
5782 return false
5783 }
5784 if(stack[stack.length-1].right) {
5785 return true
5786 }
5787 for(var s=stack.length-1; s>0; --s) {
5788 if(stack[s-1].left === stack[s]) {
5789 return true
5790 }
5791 }
5792 return false
5793 }
5794})
5795
5796//Update value
5797iproto.update = function(value) {
5798 var stack = this._stack
5799 if(stack.length === 0) {
5800 throw new Error("Can't update empty node!")
5801 }
5802 var cstack = new Array(stack.length)
5803 var n = stack[stack.length-1]
5804 cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count)
5805 for(var i=stack.length-2; i>=0; --i) {
5806 n = stack[i]
5807 if(n.left === stack[i+1]) {
5808 cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
5809 } else {
5810 cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
5811 }
5812 }
5813 return new RedBlackTree(this.tree._compare, cstack[0])
5814}
5815
5816//Moves iterator backward one element
5817iproto.prev = function() {
5818 var stack = this._stack
5819 if(stack.length === 0) {
5820 return
5821 }
5822 var n = stack[stack.length-1]
5823 if(n.left) {
5824 n = n.left
5825 while(n) {
5826 stack.push(n)
5827 n = n.right
5828 }
5829 } else {
5830 stack.pop()
5831 while(stack.length > 0 && stack[stack.length-1].left === n) {
5832 n = stack[stack.length-1]
5833 stack.pop()
5834 }
5835 }
5836}
5837
5838//Checks if iterator is at start of tree
5839Object.defineProperty(iproto, "hasPrev", {
5840 get: function() {
5841 var stack = this._stack
5842 if(stack.length === 0) {
5843 return false
5844 }
5845 if(stack[stack.length-1].left) {
5846 return true
5847 }
5848 for(var s=stack.length-1; s>0; --s) {
5849 if(stack[s-1].right === stack[s]) {
5850 return true
5851 }
5852 }
5853 return false
5854 }
5855})
5856
5857//Default comparison function
5858function defaultCompare(a, b) {
5859 if(a < b) {
5860 return -1
5861 }
5862 if(a > b) {
5863 return 1
5864 }
5865 return 0
5866}
5867
5868//Build a tree
5869function createRBTree(compare) {
5870 return new RedBlackTree(compare || defaultCompare, null)
5871}
5872},{}],37:[function(_dereq_,module,exports){
5873'use strict';
5874
5875var undefined;
5876
5877var $Error = _dereq_('es-errors');
5878var $EvalError = _dereq_('es-errors/eval');
5879var $RangeError = _dereq_('es-errors/range');
5880var $ReferenceError = _dereq_('es-errors/ref');
5881var $SyntaxError = _dereq_('es-errors/syntax');
5882var $TypeError = _dereq_('es-errors/type');
5883var $URIError = _dereq_('es-errors/uri');
5884
5885var $Function = Function;
5886
5887// eslint-disable-next-line consistent-return
5888var getEvalledConstructor = function (expressionSyntax) {
5889 try {
5890 return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
5891 } catch (e) {}
5892};
5893
5894var $gOPD = Object.getOwnPropertyDescriptor;
5895if ($gOPD) {
5896 try {
5897 $gOPD({}, '');
5898 } catch (e) {
5899 $gOPD = null; // this is IE 8, which has a broken gOPD
5900 }
5901}
5902
5903var throwTypeError = function () {
5904 throw new $TypeError();
5905};
5906var ThrowTypeError = $gOPD
5907 ? (function () {
5908 try {
5909 // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
5910 arguments.callee; // IE 8 does not throw here
5911 return throwTypeError;
5912 } catch (calleeThrows) {
5913 try {
5914 // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
5915 return $gOPD(arguments, 'callee').get;
5916 } catch (gOPDthrows) {
5917 return throwTypeError;
5918 }
5919 }
5920 }())
5921 : throwTypeError;
5922
5923var hasSymbols = _dereq_('has-symbols')();
5924var hasProto = _dereq_('has-proto')();
5925
5926var getProto = Object.getPrototypeOf || (
5927 hasProto
5928 ? function (x) { return x.__proto__; } // eslint-disable-line no-proto
5929 : null
5930);
5931
5932var needsEval = {};
5933
5934var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
5935
5936var INTRINSICS = {
5937 __proto__: null,
5938 '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
5939 '%Array%': Array,
5940 '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
5941 '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
5942 '%AsyncFromSyncIteratorPrototype%': undefined,
5943 '%AsyncFunction%': needsEval,
5944 '%AsyncGenerator%': needsEval,
5945 '%AsyncGeneratorFunction%': needsEval,
5946 '%AsyncIteratorPrototype%': needsEval,
5947 '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
5948 '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
5949 '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
5950 '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
5951 '%Boolean%': Boolean,
5952 '%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
5953 '%Date%': Date,
5954 '%decodeURI%': decodeURI,
5955 '%decodeURIComponent%': decodeURIComponent,
5956 '%encodeURI%': encodeURI,
5957 '%encodeURIComponent%': encodeURIComponent,
5958 '%Error%': $Error,
5959 '%eval%': eval, // eslint-disable-line no-eval
5960 '%EvalError%': $EvalError,
5961 '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
5962 '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
5963 '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
5964 '%Function%': $Function,
5965 '%GeneratorFunction%': needsEval,
5966 '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
5967 '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
5968 '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
5969 '%isFinite%': isFinite,
5970 '%isNaN%': isNaN,
5971 '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
5972 '%JSON%': typeof JSON === 'object' ? JSON : undefined,
5973 '%Map%': typeof Map === 'undefined' ? undefined : Map,
5974 '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
5975 '%Math%': Math,
5976 '%Number%': Number,
5977 '%Object%': Object,
5978 '%parseFloat%': parseFloat,
5979 '%parseInt%': parseInt,
5980 '%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
5981 '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
5982 '%RangeError%': $RangeError,
5983 '%ReferenceError%': $ReferenceError,
5984 '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
5985 '%RegExp%': RegExp,
5986 '%Set%': typeof Set === 'undefined' ? undefined : Set,
5987 '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
5988 '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
5989 '%String%': String,
5990 '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
5991 '%Symbol%': hasSymbols ? Symbol : undefined,
5992 '%SyntaxError%': $SyntaxError,
5993 '%ThrowTypeError%': ThrowTypeError,
5994 '%TypedArray%': TypedArray,
5995 '%TypeError%': $TypeError,
5996 '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
5997 '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
5998 '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
5999 '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
6000 '%URIError%': $URIError,
6001 '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
6002 '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
6003 '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
6004};
6005
6006if (getProto) {
6007 try {
6008 null.error; // eslint-disable-line no-unused-expressions
6009 } catch (e) {
6010 // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
6011 var errorProto = getProto(getProto(e));
6012 INTRINSICS['%Error.prototype%'] = errorProto;
6013 }
6014}
6015
6016var doEval = function doEval(name) {
6017 var value;
6018 if (name === '%AsyncFunction%') {
6019 value = getEvalledConstructor('async function () {}');
6020 } else if (name === '%GeneratorFunction%') {
6021 value = getEvalledConstructor('function* () {}');
6022 } else if (name === '%AsyncGeneratorFunction%') {
6023 value = getEvalledConstructor('async function* () {}');
6024 } else if (name === '%AsyncGenerator%') {
6025 var fn = doEval('%AsyncGeneratorFunction%');
6026 if (fn) {
6027 value = fn.prototype;
6028 }
6029 } else if (name === '%AsyncIteratorPrototype%') {
6030 var gen = doEval('%AsyncGenerator%');
6031 if (gen && getProto) {
6032 value = getProto(gen.prototype);
6033 }
6034 }
6035
6036 INTRINSICS[name] = value;
6037
6038 return value;
6039};
6040
6041var LEGACY_ALIASES = {
6042 __proto__: null,
6043 '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
6044 '%ArrayPrototype%': ['Array', 'prototype'],
6045 '%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
6046 '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
6047 '%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
6048 '%ArrayProto_values%': ['Array', 'prototype', 'values'],
6049 '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
6050 '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
6051 '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
6052 '%BooleanPrototype%': ['Boolean', 'prototype'],
6053 '%DataViewPrototype%': ['DataView', 'prototype'],
6054 '%DatePrototype%': ['Date', 'prototype'],
6055 '%ErrorPrototype%': ['Error', 'prototype'],
6056 '%EvalErrorPrototype%': ['EvalError', 'prototype'],
6057 '%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
6058 '%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
6059 '%FunctionPrototype%': ['Function', 'prototype'],
6060 '%Generator%': ['GeneratorFunction', 'prototype'],
6061 '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
6062 '%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
6063 '%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
6064 '%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
6065 '%JSONParse%': ['JSON', 'parse'],
6066 '%JSONStringify%': ['JSON', 'stringify'],
6067 '%MapPrototype%': ['Map', 'prototype'],
6068 '%NumberPrototype%': ['Number', 'prototype'],
6069 '%ObjectPrototype%': ['Object', 'prototype'],
6070 '%ObjProto_toString%': ['Object', 'prototype', 'toString'],
6071 '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
6072 '%PromisePrototype%': ['Promise', 'prototype'],
6073 '%PromiseProto_then%': ['Promise', 'prototype', 'then'],
6074 '%Promise_all%': ['Promise', 'all'],
6075 '%Promise_reject%': ['Promise', 'reject'],
6076 '%Promise_resolve%': ['Promise', 'resolve'],
6077 '%RangeErrorPrototype%': ['RangeError', 'prototype'],
6078 '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
6079 '%RegExpPrototype%': ['RegExp', 'prototype'],
6080 '%SetPrototype%': ['Set', 'prototype'],
6081 '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
6082 '%StringPrototype%': ['String', 'prototype'],
6083 '%SymbolPrototype%': ['Symbol', 'prototype'],
6084 '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
6085 '%TypedArrayPrototype%': ['TypedArray', 'prototype'],
6086 '%TypeErrorPrototype%': ['TypeError', 'prototype'],
6087 '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
6088 '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
6089 '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
6090 '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
6091 '%URIErrorPrototype%': ['URIError', 'prototype'],
6092 '%WeakMapPrototype%': ['WeakMap', 'prototype'],
6093 '%WeakSetPrototype%': ['WeakSet', 'prototype']
6094};
6095
6096var bind = _dereq_('function-bind');
6097var hasOwn = _dereq_('hasown');
6098var $concat = bind.call(Function.call, Array.prototype.concat);
6099var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
6100var $replace = bind.call(Function.call, String.prototype.replace);
6101var $strSlice = bind.call(Function.call, String.prototype.slice);
6102var $exec = bind.call(Function.call, RegExp.prototype.exec);
6103
6104/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
6105var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
6106var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
6107var stringToPath = function stringToPath(string) {
6108 var first = $strSlice(string, 0, 1);
6109 var last = $strSlice(string, -1);
6110 if (first === '%' && last !== '%') {
6111 throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
6112 } else if (last === '%' && first !== '%') {
6113 throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
6114 }
6115 var result = [];
6116 $replace(string, rePropName, function (match, number, quote, subString) {
6117 result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
6118 });
6119 return result;
6120};
6121/* end adaptation */
6122
6123var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
6124 var intrinsicName = name;
6125 var alias;
6126 if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
6127 alias = LEGACY_ALIASES[intrinsicName];
6128 intrinsicName = '%' + alias[0] + '%';
6129 }
6130
6131 if (hasOwn(INTRINSICS, intrinsicName)) {
6132 var value = INTRINSICS[intrinsicName];
6133 if (value === needsEval) {
6134 value = doEval(intrinsicName);
6135 }
6136 if (typeof value === 'undefined' && !allowMissing) {
6137 throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
6138 }
6139
6140 return {
6141 alias: alias,
6142 name: intrinsicName,
6143 value: value
6144 };
6145 }
6146
6147 throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
6148};
6149
6150module.exports = function GetIntrinsic(name, allowMissing) {
6151 if (typeof name !== 'string' || name.length === 0) {
6152 throw new $TypeError('intrinsic name must be a non-empty string');
6153 }
6154 if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
6155 throw new $TypeError('"allowMissing" argument must be a boolean');
6156 }
6157
6158 if ($exec(/^%?[^%]*%?$/, name) === null) {
6159 throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
6160 }
6161 var parts = stringToPath(name);
6162 var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
6163
6164 var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
6165 var intrinsicRealName = intrinsic.name;
6166 var value = intrinsic.value;
6167 var skipFurtherCaching = false;
6168
6169 var alias = intrinsic.alias;
6170 if (alias) {
6171 intrinsicBaseName = alias[0];
6172 $spliceApply(parts, $concat([0, 1], alias));
6173 }
6174
6175 for (var i = 1, isOwn = true; i < parts.length; i += 1) {
6176 var part = parts[i];
6177 var first = $strSlice(part, 0, 1);
6178 var last = $strSlice(part, -1);
6179 if (
6180 (
6181 (first === '"' || first === "'" || first === '`')
6182 || (last === '"' || last === "'" || last === '`')
6183 )
6184 && first !== last
6185 ) {
6186 throw new $SyntaxError('property names with quotes must have matching quotes');
6187 }
6188 if (part === 'constructor' || !isOwn) {
6189 skipFurtherCaching = true;
6190 }
6191
6192 intrinsicBaseName += '.' + part;
6193 intrinsicRealName = '%' + intrinsicBaseName + '%';
6194
6195 if (hasOwn(INTRINSICS, intrinsicRealName)) {
6196 value = INTRINSICS[intrinsicRealName];
6197 } else if (value != null) {
6198 if (!(part in value)) {
6199 if (!allowMissing) {
6200 throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
6201 }
6202 return void undefined;
6203 }
6204 if ($gOPD && (i + 1) >= parts.length) {
6205 var desc = $gOPD(value, part);
6206 isOwn = !!desc;
6207
6208 // By convention, when a data property is converted to an accessor
6209 // property to emulate a data property that does not suffer from
6210 // the override mistake, that accessor's getter is marked with
6211 // an `originalValue` property. Here, when we detect this, we
6212 // uphold the illusion by pretending to see that original data
6213 // property, i.e., returning the value rather than the getter
6214 // itself.
6215 if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
6216 value = desc.get;
6217 } else {
6218 value = value[part];
6219 }
6220 } else {
6221 isOwn = hasOwn(value, part);
6222 value = value[part];
6223 }
6224
6225 if (isOwn && !skipFurtherCaching) {
6226 INTRINSICS[intrinsicRealName] = value;
6227 }
6228 }
6229 }
6230 return value;
6231};
6232
6233},{"es-errors":27,"es-errors/eval":26,"es-errors/range":28,"es-errors/ref":29,"es-errors/syntax":30,"es-errors/type":31,"es-errors/uri":32,"function-bind":35,"has-proto":40,"has-symbols":41,"hasown":43}],38:[function(_dereq_,module,exports){
6234'use strict';
6235
6236var GetIntrinsic = _dereq_('get-intrinsic');
6237
6238var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
6239
6240if ($gOPD) {
6241 try {
6242 $gOPD([], 'length');
6243 } catch (e) {
6244 // IE 8 has a broken gOPD
6245 $gOPD = null;
6246 }
6247}
6248
6249module.exports = $gOPD;
6250
6251},{"get-intrinsic":37}],39:[function(_dereq_,module,exports){
6252'use strict';
6253
6254var $defineProperty = _dereq_('es-define-property');
6255
6256var hasPropertyDescriptors = function hasPropertyDescriptors() {
6257 return !!$defineProperty;
6258};
6259
6260hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
6261 // node v0.6 has a bug where array lengths can be Set but not Defined
6262 if (!$defineProperty) {
6263 return null;
6264 }
6265 try {
6266 return $defineProperty([], 'length', { value: 1 }).length !== 1;
6267 } catch (e) {
6268 // In Firefox 4-22, defining length on an array throws an exception.
6269 return true;
6270 }
6271};
6272
6273module.exports = hasPropertyDescriptors;
6274
6275},{"es-define-property":25}],40:[function(_dereq_,module,exports){
6276'use strict';
6277
6278var test = {
6279 __proto__: null,
6280 foo: {}
6281};
6282
6283var $Object = Object;
6284
6285/** @type {import('.')} */
6286module.exports = function hasProto() {
6287 // @ts-expect-error: TS errors on an inherited property for some reason
6288 return { __proto__: test }.foo === test.foo
6289 && !(test instanceof $Object);
6290};
6291
6292},{}],41:[function(_dereq_,module,exports){
6293'use strict';
6294
6295var origSymbol = typeof Symbol !== 'undefined' && Symbol;
6296var hasSymbolSham = _dereq_('./shams');
6297
6298module.exports = function hasNativeSymbols() {
6299 if (typeof origSymbol !== 'function') { return false; }
6300 if (typeof Symbol !== 'function') { return false; }
6301 if (typeof origSymbol('foo') !== 'symbol') { return false; }
6302 if (typeof Symbol('bar') !== 'symbol') { return false; }
6303
6304 return hasSymbolSham();
6305};
6306
6307},{"./shams":42}],42:[function(_dereq_,module,exports){
6308'use strict';
6309
6310/* eslint complexity: [2, 18], max-statements: [2, 33] */
6311module.exports = function hasSymbols() {
6312 if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
6313 if (typeof Symbol.iterator === 'symbol') { return true; }
6314
6315 var obj = {};
6316 var sym = Symbol('test');
6317 var symObj = Object(sym);
6318 if (typeof sym === 'string') { return false; }
6319
6320 if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
6321 if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
6322
6323 // temp disabled per https://github.com/ljharb/object.assign/issues/17
6324 // if (sym instanceof Symbol) { return false; }
6325 // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
6326 // if (!(symObj instanceof Symbol)) { return false; }
6327
6328 // if (typeof Symbol.prototype.toString !== 'function') { return false; }
6329 // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
6330
6331 var symVal = 42;
6332 obj[sym] = symVal;
6333 for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
6334 if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
6335
6336 if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
6337
6338 var syms = Object.getOwnPropertySymbols(obj);
6339 if (syms.length !== 1 || syms[0] !== sym) { return false; }
6340
6341 if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
6342
6343 if (typeof Object.getOwnPropertyDescriptor === 'function') {
6344 var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
6345 if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
6346 }
6347
6348 return true;
6349};
6350
6351},{}],43:[function(_dereq_,module,exports){
6352'use strict';
6353
6354var call = Function.prototype.call;
6355var $hasOwn = Object.prototype.hasOwnProperty;
6356var bind = _dereq_('function-bind');
6357
6358/** @type {import('.')} */
6359module.exports = bind.call(call, $hasOwn);
6360
6361},{"function-bind":35}],44:[function(_dereq_,module,exports){
6362/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
6363exports.read = function (buffer, offset, isLE, mLen, nBytes) {
6364 var e, m
6365 var eLen = (nBytes * 8) - mLen - 1
6366 var eMax = (1 << eLen) - 1
6367 var eBias = eMax >> 1
6368 var nBits = -7
6369 var i = isLE ? (nBytes - 1) : 0
6370 var d = isLE ? -1 : 1
6371 var s = buffer[offset + i]
6372
6373 i += d
6374
6375 e = s & ((1 << (-nBits)) - 1)
6376 s >>= (-nBits)
6377 nBits += eLen
6378 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
6379
6380 m = e & ((1 << (-nBits)) - 1)
6381 e >>= (-nBits)
6382 nBits += mLen
6383 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
6384
6385 if (e === 0) {
6386 e = 1 - eBias
6387 } else if (e === eMax) {
6388 return m ? NaN : ((s ? -1 : 1) * Infinity)
6389 } else {
6390 m = m + Math.pow(2, mLen)
6391 e = e - eBias
6392 }
6393 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
6394}
6395
6396exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
6397 var e, m, c
6398 var eLen = (nBytes * 8) - mLen - 1
6399 var eMax = (1 << eLen) - 1
6400 var eBias = eMax >> 1
6401 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
6402 var i = isLE ? 0 : (nBytes - 1)
6403 var d = isLE ? 1 : -1
6404 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
6405
6406 value = Math.abs(value)
6407
6408 if (isNaN(value) || value === Infinity) {
6409 m = isNaN(value) ? 1 : 0
6410 e = eMax
6411 } else {
6412 e = Math.floor(Math.log(value) / Math.LN2)
6413 if (value * (c = Math.pow(2, -e)) < 1) {
6414 e--
6415 c *= 2
6416 }
6417 if (e + eBias >= 1) {
6418 value += rt / c
6419 } else {
6420 value += rt * Math.pow(2, 1 - eBias)
6421 }
6422 if (value * c >= 2) {
6423 e++
6424 c /= 2
6425 }
6426
6427 if (e + eBias >= eMax) {
6428 m = 0
6429 e = eMax
6430 } else if (e + eBias >= 1) {
6431 m = ((value * c) - 1) * Math.pow(2, mLen)
6432 e = e + eBias
6433 } else {
6434 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
6435 e = 0
6436 }
6437 }
6438
6439 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
6440
6441 e = (e << mLen) | m
6442 eLen += mLen
6443 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
6444
6445 buffer[offset + i - d] |= s * 128
6446}
6447
6448},{}],45:[function(_dereq_,module,exports){
6449if (typeof Object.create === 'function') {
6450 // implementation from standard node.js 'util' module
6451 module.exports = function inherits(ctor, superCtor) {
6452 if (superCtor) {
6453 ctor.super_ = superCtor
6454 ctor.prototype = Object.create(superCtor.prototype, {
6455 constructor: {
6456 value: ctor,
6457 enumerable: false,
6458 writable: true,
6459 configurable: true
6460 }
6461 })
6462 }
6463 };
6464} else {
6465 // old school shim for old browsers
6466 module.exports = function inherits(ctor, superCtor) {
6467 if (superCtor) {
6468 ctor.super_ = superCtor
6469 var TempCtor = function () {}
6470 TempCtor.prototype = superCtor.prototype
6471 ctor.prototype = new TempCtor()
6472 ctor.prototype.constructor = ctor
6473 }
6474 }
6475}
6476
6477},{}],46:[function(_dereq_,module,exports){
6478/*!
6479 * Determine if an object is a Buffer
6480 *
6481 * @author Feross Aboukhadijeh <https://feross.org>
6482 * @license MIT
6483 */
6484
6485// The _isBuffer check is for Safari 5-7 support, because it's missing
6486// Object.prototype.constructor. Remove this eventually
6487module.exports = function (obj) {
6488 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
6489}
6490
6491function isBuffer (obj) {
6492 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
6493}
6494
6495// For Node v0.10 support. Remove this eventually.
6496function isSlowBuffer (obj) {
6497 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
6498}
6499
6500},{}],47:[function(_dereq_,module,exports){
6501module.exports = Array.isArray || function (arr) {
6502 return Object.prototype.toString.call(arr) == '[object Array]';
6503};
6504
6505},{}],48:[function(_dereq_,module,exports){
6506var encodings = _dereq_('./lib/encodings')
6507
6508module.exports = Codec
6509
6510function Codec (opts) {
6511 if (!(this instanceof Codec)) {
6512 return new Codec(opts)
6513 }
6514 this.opts = opts || {}
6515 this.encodings = encodings
6516}
6517
6518Codec.prototype._encoding = function (encoding) {
6519 if (typeof encoding === 'string') encoding = encodings[encoding]
6520 if (!encoding) encoding = encodings.id
6521 return encoding
6522}
6523
6524Codec.prototype._keyEncoding = function (opts, batchOpts) {
6525 return this._encoding((batchOpts && batchOpts.keyEncoding) ||
6526 (opts && opts.keyEncoding) ||
6527 this.opts.keyEncoding)
6528}
6529
6530Codec.prototype._valueEncoding = function (opts, batchOpts) {
6531 return this._encoding((batchOpts && (batchOpts.valueEncoding || batchOpts.encoding)) ||
6532 (opts && (opts.valueEncoding || opts.encoding)) ||
6533 (this.opts.valueEncoding || this.opts.encoding))
6534}
6535
6536Codec.prototype.encodeKey = function (key, opts, batchOpts) {
6537 return this._keyEncoding(opts, batchOpts).encode(key)
6538}
6539
6540Codec.prototype.encodeValue = function (value, opts, batchOpts) {
6541 return this._valueEncoding(opts, batchOpts).encode(value)
6542}
6543
6544Codec.prototype.decodeKey = function (key, opts) {
6545 return this._keyEncoding(opts).decode(key)
6546}
6547
6548Codec.prototype.decodeValue = function (value, opts) {
6549 return this._valueEncoding(opts).decode(value)
6550}
6551
6552Codec.prototype.encodeBatch = function (ops, opts) {
6553 var self = this
6554
6555 return ops.map(function (_op) {
6556 var op = {
6557 type: _op.type,
6558 key: self.encodeKey(_op.key, opts, _op)
6559 }
6560 if (self.keyAsBuffer(opts, _op)) op.keyEncoding = 'binary'
6561 if (_op.prefix) op.prefix = _op.prefix
6562 if ('value' in _op) {
6563 op.value = self.encodeValue(_op.value, opts, _op)
6564 if (self.valueAsBuffer(opts, _op)) op.valueEncoding = 'binary'
6565 }
6566 return op
6567 })
6568}
6569
6570var ltgtKeys = ['lt', 'gt', 'lte', 'gte', 'start', 'end']
6571
6572Codec.prototype.encodeLtgt = function (ltgt) {
6573 var self = this
6574 var ret = {}
6575 Object.keys(ltgt).forEach(function (key) {
6576 ret[key] = ltgtKeys.indexOf(key) > -1
6577 ? self.encodeKey(ltgt[key], ltgt)
6578 : ltgt[key]
6579 })
6580 return ret
6581}
6582
6583Codec.prototype.createStreamDecoder = function (opts) {
6584 var self = this
6585
6586 if (opts.keys && opts.values) {
6587 return function (key, value) {
6588 return {
6589 key: self.decodeKey(key, opts),
6590 value: self.decodeValue(value, opts)
6591 }
6592 }
6593 } else if (opts.keys) {
6594 return function (key) {
6595 return self.decodeKey(key, opts)
6596 }
6597 } else if (opts.values) {
6598 return function (_, value) {
6599 return self.decodeValue(value, opts)
6600 }
6601 } else {
6602 return function () {}
6603 }
6604}
6605
6606Codec.prototype.keyAsBuffer = function (opts) {
6607 return this._keyEncoding(opts).buffer
6608}
6609
6610Codec.prototype.valueAsBuffer = function (opts) {
6611 return this._valueEncoding(opts).buffer
6612}
6613
6614},{"./lib/encodings":49}],49:[function(_dereq_,module,exports){
6615var Buffer = _dereq_('buffer').Buffer
6616
6617exports.utf8 = exports['utf-8'] = {
6618 encode: function (data) {
6619 return isBinary(data) ? data : String(data)
6620 },
6621 decode: identity,
6622 buffer: false,
6623 type: 'utf8'
6624}
6625
6626exports.json = {
6627 encode: JSON.stringify,
6628 decode: JSON.parse,
6629 buffer: false,
6630 type: 'json'
6631}
6632
6633exports.binary = {
6634 encode: function (data) {
6635 return isBinary(data) ? data : Buffer.from(data)
6636 },
6637 decode: identity,
6638 buffer: true,
6639 type: 'binary'
6640}
6641
6642exports.none = {
6643 encode: identity,
6644 decode: identity,
6645 buffer: false,
6646 type: 'id'
6647}
6648
6649exports.id = exports.none
6650
6651var bufferEncodings = [
6652 'hex',
6653 'ascii',
6654 'base64',
6655 'ucs2',
6656 'ucs-2',
6657 'utf16le',
6658 'utf-16le'
6659]
6660
6661bufferEncodings.forEach(function (type) {
6662 exports[type] = {
6663 encode: function (data) {
6664 return isBinary(data) ? data : Buffer.from(data, type)
6665 },
6666 decode: function (buffer) {
6667 return buffer.toString(type)
6668 },
6669 buffer: true,
6670 type: type
6671 }
6672})
6673
6674function identity (value) {
6675 return value
6676}
6677
6678function isBinary (data) {
6679 return data === undefined || data === null || Buffer.isBuffer(data)
6680}
6681
6682},{"buffer":4}],50:[function(_dereq_,module,exports){
6683var createError = _dereq_('errno').create
6684var LevelUPError = createError('LevelUPError')
6685var NotFoundError = createError('NotFoundError', LevelUPError)
6686
6687NotFoundError.prototype.notFound = true
6688NotFoundError.prototype.status = 404
6689
6690module.exports = {
6691 LevelUPError: LevelUPError,
6692 InitializationError: createError('InitializationError', LevelUPError),
6693 OpenError: createError('OpenError', LevelUPError),
6694 ReadError: createError('ReadError', LevelUPError),
6695 WriteError: createError('WriteError', LevelUPError),
6696 NotFoundError: NotFoundError,
6697 EncodingError: createError('EncodingError', LevelUPError)
6698}
6699
6700},{"errno":24}],51:[function(_dereq_,module,exports){
6701var inherits = _dereq_('inherits')
6702var Readable = _dereq_('readable-stream').Readable
6703var extend = _dereq_('xtend')
6704
6705module.exports = ReadStream
6706inherits(ReadStream, Readable)
6707
6708function ReadStream (iterator, options) {
6709 if (!(this instanceof ReadStream)) return new ReadStream(iterator, options)
6710 options = options || {}
6711 Readable.call(this, extend(options, {
6712 objectMode: true
6713 }))
6714 this._iterator = iterator
6715 this._options = options
6716 this.on('end', this.destroy.bind(this, null, null))
6717}
6718
6719ReadStream.prototype._read = function () {
6720 var self = this
6721 var options = this._options
6722 if (this.destroyed) return
6723
6724 this._iterator.next(function (err, key, value) {
6725 if (self.destroyed) return
6726 if (err) return self.destroy(err)
6727
6728 if (key === undefined && value === undefined) {
6729 self.push(null)
6730 } else if (options.keys !== false && options.values === false) {
6731 self.push(key)
6732 } else if (options.keys === false && options.values !== false) {
6733 self.push(value)
6734 } else {
6735 self.push({ key: key, value: value })
6736 }
6737 })
6738}
6739
6740ReadStream.prototype._destroy = function (err, callback) {
6741 this._iterator.end(function (err2) {
6742 callback(err || err2)
6743 })
6744}
6745
6746},{"inherits":45,"readable-stream":66,"xtend":160}],52:[function(_dereq_,module,exports){
6747'use strict';
6748
6749function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
6750
6751var codes = {};
6752
6753function createErrorType(code, message, Base) {
6754 if (!Base) {
6755 Base = Error;
6756 }
6757
6758 function getMessage(arg1, arg2, arg3) {
6759 if (typeof message === 'string') {
6760 return message;
6761 } else {
6762 return message(arg1, arg2, arg3);
6763 }
6764 }
6765
6766 var NodeError =
6767 /*#__PURE__*/
6768 function (_Base) {
6769 _inheritsLoose(NodeError, _Base);
6770
6771 function NodeError(arg1, arg2, arg3) {
6772 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
6773 }
6774
6775 return NodeError;
6776 }(Base);
6777
6778 NodeError.prototype.name = Base.name;
6779 NodeError.prototype.code = code;
6780 codes[code] = NodeError;
6781} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
6782
6783
6784function oneOf(expected, thing) {
6785 if (Array.isArray(expected)) {
6786 var len = expected.length;
6787 expected = expected.map(function (i) {
6788 return String(i);
6789 });
6790
6791 if (len > 2) {
6792 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
6793 } else if (len === 2) {
6794 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
6795 } else {
6796 return "of ".concat(thing, " ").concat(expected[0]);
6797 }
6798 } else {
6799 return "of ".concat(thing, " ").concat(String(expected));
6800 }
6801} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
6802
6803
6804function startsWith(str, search, pos) {
6805 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
6806} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
6807
6808
6809function endsWith(str, search, this_len) {
6810 if (this_len === undefined || this_len > str.length) {
6811 this_len = str.length;
6812 }
6813
6814 return str.substring(this_len - search.length, this_len) === search;
6815} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
6816
6817
6818function includes(str, search, start) {
6819 if (typeof start !== 'number') {
6820 start = 0;
6821 }
6822
6823 if (start + search.length > str.length) {
6824 return false;
6825 } else {
6826 return str.indexOf(search, start) !== -1;
6827 }
6828}
6829
6830createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
6831 return 'The value "' + value + '" is invalid for option "' + name + '"';
6832}, TypeError);
6833createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
6834 // determiner: 'must be' or 'must not be'
6835 var determiner;
6836
6837 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
6838 determiner = 'must not be';
6839 expected = expected.replace(/^not /, '');
6840 } else {
6841 determiner = 'must be';
6842 }
6843
6844 var msg;
6845
6846 if (endsWith(name, ' argument')) {
6847 // For cases like 'first argument'
6848 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6849 } else {
6850 var type = includes(name, '.') ? 'property' : 'argument';
6851 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
6852 }
6853
6854 msg += ". Received type ".concat(typeof actual);
6855 return msg;
6856}, TypeError);
6857createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
6858createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
6859 return 'The ' + name + ' method is not implemented';
6860});
6861createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
6862createErrorType('ERR_STREAM_DESTROYED', function (name) {
6863 return 'Cannot call ' + name + ' after a stream was destroyed';
6864});
6865createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
6866createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
6867createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
6868createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
6869createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
6870 return 'Unknown encoding: ' + arg;
6871}, TypeError);
6872createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
6873module.exports.codes = codes;
6874
6875},{}],53:[function(_dereq_,module,exports){
6876(function (process){(function (){
6877// Copyright Joyent, Inc. and other Node contributors.
6878//
6879// Permission is hereby granted, free of charge, to any person obtaining a
6880// copy of this software and associated documentation files (the
6881// "Software"), to deal in the Software without restriction, including
6882// without limitation the rights to use, copy, modify, merge, publish,
6883// distribute, sublicense, and/or sell copies of the Software, and to permit
6884// persons to whom the Software is furnished to do so, subject to the
6885// following conditions:
6886//
6887// The above copyright notice and this permission notice shall be included
6888// in all copies or substantial portions of the Software.
6889//
6890// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6891// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6892// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6893// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6894// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6895// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6896// USE OR OTHER DEALINGS IN THE SOFTWARE.
6897
6898// a duplex stream is just a stream that is both readable and writable.
6899// Since JS doesn't have multiple prototypal inheritance, this class
6900// prototypally inherits from Readable, and then parasitically from
6901// Writable.
6902
6903'use strict';
6904
6905/*<replacement>*/
6906var objectKeys = Object.keys || function (obj) {
6907 var keys = [];
6908 for (var key in obj) keys.push(key);
6909 return keys;
6910};
6911/*</replacement>*/
6912
6913module.exports = Duplex;
6914var Readable = _dereq_('./_stream_readable');
6915var Writable = _dereq_('./_stream_writable');
6916_dereq_('inherits')(Duplex, Readable);
6917{
6918 // Allow the keys array to be GC'ed.
6919 var keys = objectKeys(Writable.prototype);
6920 for (var v = 0; v < keys.length; v++) {
6921 var method = keys[v];
6922 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
6923 }
6924}
6925function Duplex(options) {
6926 if (!(this instanceof Duplex)) return new Duplex(options);
6927 Readable.call(this, options);
6928 Writable.call(this, options);
6929 this.allowHalfOpen = true;
6930 if (options) {
6931 if (options.readable === false) this.readable = false;
6932 if (options.writable === false) this.writable = false;
6933 if (options.allowHalfOpen === false) {
6934 this.allowHalfOpen = false;
6935 this.once('end', onend);
6936 }
6937 }
6938}
6939Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
6940 // making it explicit this property is not enumerable
6941 // because otherwise some prototype manipulation in
6942 // userland will fail
6943 enumerable: false,
6944 get: function get() {
6945 return this._writableState.highWaterMark;
6946 }
6947});
6948Object.defineProperty(Duplex.prototype, 'writableBuffer', {
6949 // making it explicit this property is not enumerable
6950 // because otherwise some prototype manipulation in
6951 // userland will fail
6952 enumerable: false,
6953 get: function get() {
6954 return this._writableState && this._writableState.getBuffer();
6955 }
6956});
6957Object.defineProperty(Duplex.prototype, 'writableLength', {
6958 // making it explicit this property is not enumerable
6959 // because otherwise some prototype manipulation in
6960 // userland will fail
6961 enumerable: false,
6962 get: function get() {
6963 return this._writableState.length;
6964 }
6965});
6966
6967// the no-half-open enforcer
6968function onend() {
6969 // If the writable side ended, then we're ok.
6970 if (this._writableState.ended) return;
6971
6972 // no more data can be written.
6973 // But allow more writes to happen in this tick.
6974 process.nextTick(onEndNT, this);
6975}
6976function onEndNT(self) {
6977 self.end();
6978}
6979Object.defineProperty(Duplex.prototype, 'destroyed', {
6980 // making it explicit this property is not enumerable
6981 // because otherwise some prototype manipulation in
6982 // userland will fail
6983 enumerable: false,
6984 get: function get() {
6985 if (this._readableState === undefined || this._writableState === undefined) {
6986 return false;
6987 }
6988 return this._readableState.destroyed && this._writableState.destroyed;
6989 },
6990 set: function set(value) {
6991 // we ignore the value if the stream
6992 // has not been initialized yet
6993 if (this._readableState === undefined || this._writableState === undefined) {
6994 return;
6995 }
6996
6997 // backward compatibility, the user is explicitly
6998 // managing destroyed
6999 this._readableState.destroyed = value;
7000 this._writableState.destroyed = value;
7001 }
7002});
7003}).call(this)}).call(this,_dereq_('_process'))
7004},{"./_stream_readable":55,"./_stream_writable":57,"_process":93,"inherits":45}],54:[function(_dereq_,module,exports){
7005// Copyright Joyent, Inc. and other Node contributors.
7006//
7007// Permission is hereby granted, free of charge, to any person obtaining a
7008// copy of this software and associated documentation files (the
7009// "Software"), to deal in the Software without restriction, including
7010// without limitation the rights to use, copy, modify, merge, publish,
7011// distribute, sublicense, and/or sell copies of the Software, and to permit
7012// persons to whom the Software is furnished to do so, subject to the
7013// following conditions:
7014//
7015// The above copyright notice and this permission notice shall be included
7016// in all copies or substantial portions of the Software.
7017//
7018// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7019// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7020// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7021// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7022// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7023// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7024// USE OR OTHER DEALINGS IN THE SOFTWARE.
7025
7026// a passthrough stream.
7027// basically just the most minimal sort of Transform stream.
7028// Every written chunk gets output as-is.
7029
7030'use strict';
7031
7032module.exports = PassThrough;
7033var Transform = _dereq_('./_stream_transform');
7034_dereq_('inherits')(PassThrough, Transform);
7035function PassThrough(options) {
7036 if (!(this instanceof PassThrough)) return new PassThrough(options);
7037 Transform.call(this, options);
7038}
7039PassThrough.prototype._transform = function (chunk, encoding, cb) {
7040 cb(null, chunk);
7041};
7042},{"./_stream_transform":56,"inherits":45}],55:[function(_dereq_,module,exports){
7043(function (process,global){(function (){
7044// Copyright Joyent, Inc. and other Node contributors.
7045//
7046// Permission is hereby granted, free of charge, to any person obtaining a
7047// copy of this software and associated documentation files (the
7048// "Software"), to deal in the Software without restriction, including
7049// without limitation the rights to use, copy, modify, merge, publish,
7050// distribute, sublicense, and/or sell copies of the Software, and to permit
7051// persons to whom the Software is furnished to do so, subject to the
7052// following conditions:
7053//
7054// The above copyright notice and this permission notice shall be included
7055// in all copies or substantial portions of the Software.
7056//
7057// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7058// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7059// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7060// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7061// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7062// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7063// USE OR OTHER DEALINGS IN THE SOFTWARE.
7064
7065'use strict';
7066
7067module.exports = Readable;
7068
7069/*<replacement>*/
7070var Duplex;
7071/*</replacement>*/
7072
7073Readable.ReadableState = ReadableState;
7074
7075/*<replacement>*/
7076var EE = _dereq_('events').EventEmitter;
7077var EElistenerCount = function EElistenerCount(emitter, type) {
7078 return emitter.listeners(type).length;
7079};
7080/*</replacement>*/
7081
7082/*<replacement>*/
7083var Stream = _dereq_('./internal/streams/stream');
7084/*</replacement>*/
7085
7086var Buffer = _dereq_('buffer').Buffer;
7087var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
7088function _uint8ArrayToBuffer(chunk) {
7089 return Buffer.from(chunk);
7090}
7091function _isUint8Array(obj) {
7092 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
7093}
7094
7095/*<replacement>*/
7096var debugUtil = _dereq_('util');
7097var debug;
7098if (debugUtil && debugUtil.debuglog) {
7099 debug = debugUtil.debuglog('stream');
7100} else {
7101 debug = function debug() {};
7102}
7103/*</replacement>*/
7104
7105var BufferList = _dereq_('./internal/streams/buffer_list');
7106var destroyImpl = _dereq_('./internal/streams/destroy');
7107var _require = _dereq_('./internal/streams/state'),
7108 getHighWaterMark = _require.getHighWaterMark;
7109var _require$codes = _dereq_('../errors').codes,
7110 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
7111 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
7112 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
7113 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
7114
7115// Lazy loaded to improve the startup performance.
7116var StringDecoder;
7117var createReadableStreamAsyncIterator;
7118var from;
7119_dereq_('inherits')(Readable, Stream);
7120var errorOrDestroy = destroyImpl.errorOrDestroy;
7121var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
7122function prependListener(emitter, event, fn) {
7123 // Sadly this is not cacheable as some libraries bundle their own
7124 // event emitter implementation with them.
7125 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
7126
7127 // This is a hack to make sure that our error handler is attached before any
7128 // userland ones. NEVER DO THIS. This is here only because this code needs
7129 // to continue to work with older versions of Node.js that do not include
7130 // the prependListener() method. The goal is to eventually remove this hack.
7131 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
7132}
7133function ReadableState(options, stream, isDuplex) {
7134 Duplex = Duplex || _dereq_('./_stream_duplex');
7135 options = options || {};
7136
7137 // Duplex streams are both readable and writable, but share
7138 // the same options object.
7139 // However, some cases require setting options to different
7140 // values for the readable and the writable sides of the duplex stream.
7141 // These options can be provided separately as readableXXX and writableXXX.
7142 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
7143
7144 // object stream flag. Used to make read(n) ignore n and to
7145 // make all the buffer merging and length checks go away
7146 this.objectMode = !!options.objectMode;
7147 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
7148
7149 // the point at which it stops calling _read() to fill the buffer
7150 // Note: 0 is a valid value, means "don't call _read preemptively ever"
7151 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex);
7152
7153 // A linked list is used to store data chunks instead of an array because the
7154 // linked list can remove elements from the beginning faster than
7155 // array.shift()
7156 this.buffer = new BufferList();
7157 this.length = 0;
7158 this.pipes = null;
7159 this.pipesCount = 0;
7160 this.flowing = null;
7161 this.ended = false;
7162 this.endEmitted = false;
7163 this.reading = false;
7164
7165 // a flag to be able to tell if the event 'readable'/'data' is emitted
7166 // immediately, or on a later tick. We set this to true at first, because
7167 // any actions that shouldn't happen until "later" should generally also
7168 // not happen before the first read call.
7169 this.sync = true;
7170
7171 // whenever we return null, then we set a flag to say
7172 // that we're awaiting a 'readable' event emission.
7173 this.needReadable = false;
7174 this.emittedReadable = false;
7175 this.readableListening = false;
7176 this.resumeScheduled = false;
7177 this.paused = true;
7178
7179 // Should close be emitted on destroy. Defaults to true.
7180 this.emitClose = options.emitClose !== false;
7181
7182 // Should .destroy() be called after 'end' (and potentially 'finish')
7183 this.autoDestroy = !!options.autoDestroy;
7184
7185 // has it been destroyed
7186 this.destroyed = false;
7187
7188 // Crypto is kind of old and crusty. Historically, its default string
7189 // encoding is 'binary' so we have to make this configurable.
7190 // Everything else in the universe uses 'utf8', though.
7191 this.defaultEncoding = options.defaultEncoding || 'utf8';
7192
7193 // the number of writers that are awaiting a drain event in .pipe()s
7194 this.awaitDrain = 0;
7195
7196 // if true, a maybeReadMore has been scheduled
7197 this.readingMore = false;
7198 this.decoder = null;
7199 this.encoding = null;
7200 if (options.encoding) {
7201 if (!StringDecoder) StringDecoder = _dereq_('string_decoder/').StringDecoder;
7202 this.decoder = new StringDecoder(options.encoding);
7203 this.encoding = options.encoding;
7204 }
7205}
7206function Readable(options) {
7207 Duplex = Duplex || _dereq_('./_stream_duplex');
7208 if (!(this instanceof Readable)) return new Readable(options);
7209
7210 // Checking for a Stream.Duplex instance is faster here instead of inside
7211 // the ReadableState constructor, at least with V8 6.5
7212 var isDuplex = this instanceof Duplex;
7213 this._readableState = new ReadableState(options, this, isDuplex);
7214
7215 // legacy
7216 this.readable = true;
7217 if (options) {
7218 if (typeof options.read === 'function') this._read = options.read;
7219 if (typeof options.destroy === 'function') this._destroy = options.destroy;
7220 }
7221 Stream.call(this);
7222}
7223Object.defineProperty(Readable.prototype, 'destroyed', {
7224 // making it explicit this property is not enumerable
7225 // because otherwise some prototype manipulation in
7226 // userland will fail
7227 enumerable: false,
7228 get: function get() {
7229 if (this._readableState === undefined) {
7230 return false;
7231 }
7232 return this._readableState.destroyed;
7233 },
7234 set: function set(value) {
7235 // we ignore the value if the stream
7236 // has not been initialized yet
7237 if (!this._readableState) {
7238 return;
7239 }
7240
7241 // backward compatibility, the user is explicitly
7242 // managing destroyed
7243 this._readableState.destroyed = value;
7244 }
7245});
7246Readable.prototype.destroy = destroyImpl.destroy;
7247Readable.prototype._undestroy = destroyImpl.undestroy;
7248Readable.prototype._destroy = function (err, cb) {
7249 cb(err);
7250};
7251
7252// Manually shove something into the read() buffer.
7253// This returns true if the highWaterMark has not been hit yet,
7254// similar to how Writable.write() returns true if you should
7255// write() some more.
7256Readable.prototype.push = function (chunk, encoding) {
7257 var state = this._readableState;
7258 var skipChunkCheck;
7259 if (!state.objectMode) {
7260 if (typeof chunk === 'string') {
7261 encoding = encoding || state.defaultEncoding;
7262 if (encoding !== state.encoding) {
7263 chunk = Buffer.from(chunk, encoding);
7264 encoding = '';
7265 }
7266 skipChunkCheck = true;
7267 }
7268 } else {
7269 skipChunkCheck = true;
7270 }
7271 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
7272};
7273
7274// Unshift should *always* be something directly out of read()
7275Readable.prototype.unshift = function (chunk) {
7276 return readableAddChunk(this, chunk, null, true, false);
7277};
7278function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
7279 debug('readableAddChunk', chunk);
7280 var state = stream._readableState;
7281 if (chunk === null) {
7282 state.reading = false;
7283 onEofChunk(stream, state);
7284 } else {
7285 var er;
7286 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
7287 if (er) {
7288 errorOrDestroy(stream, er);
7289 } else if (state.objectMode || chunk && chunk.length > 0) {
7290 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
7291 chunk = _uint8ArrayToBuffer(chunk);
7292 }
7293 if (addToFront) {
7294 if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
7295 } else if (state.ended) {
7296 errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
7297 } else if (state.destroyed) {
7298 return false;
7299 } else {
7300 state.reading = false;
7301 if (state.decoder && !encoding) {
7302 chunk = state.decoder.write(chunk);
7303 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
7304 } else {
7305 addChunk(stream, state, chunk, false);
7306 }
7307 }
7308 } else if (!addToFront) {
7309 state.reading = false;
7310 maybeReadMore(stream, state);
7311 }
7312 }
7313
7314 // We can push more data if we are below the highWaterMark.
7315 // Also, if we have no data yet, we can stand some more bytes.
7316 // This is to work around cases where hwm=0, such as the repl.
7317 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
7318}
7319function addChunk(stream, state, chunk, addToFront) {
7320 if (state.flowing && state.length === 0 && !state.sync) {
7321 state.awaitDrain = 0;
7322 stream.emit('data', chunk);
7323 } else {
7324 // update the buffer info.
7325 state.length += state.objectMode ? 1 : chunk.length;
7326 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
7327 if (state.needReadable) emitReadable(stream);
7328 }
7329 maybeReadMore(stream, state);
7330}
7331function chunkInvalid(state, chunk) {
7332 var er;
7333 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
7334 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
7335 }
7336 return er;
7337}
7338Readable.prototype.isPaused = function () {
7339 return this._readableState.flowing === false;
7340};
7341
7342// backwards compatibility.
7343Readable.prototype.setEncoding = function (enc) {
7344 if (!StringDecoder) StringDecoder = _dereq_('string_decoder/').StringDecoder;
7345 var decoder = new StringDecoder(enc);
7346 this._readableState.decoder = decoder;
7347 // If setEncoding(null), decoder.encoding equals utf8
7348 this._readableState.encoding = this._readableState.decoder.encoding;
7349
7350 // Iterate over current buffer to convert already stored Buffers:
7351 var p = this._readableState.buffer.head;
7352 var content = '';
7353 while (p !== null) {
7354 content += decoder.write(p.data);
7355 p = p.next;
7356 }
7357 this._readableState.buffer.clear();
7358 if (content !== '') this._readableState.buffer.push(content);
7359 this._readableState.length = content.length;
7360 return this;
7361};
7362
7363// Don't raise the hwm > 1GB
7364var MAX_HWM = 0x40000000;
7365function computeNewHighWaterMark(n) {
7366 if (n >= MAX_HWM) {
7367 // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
7368 n = MAX_HWM;
7369 } else {
7370 // Get the next highest power of 2 to prevent increasing hwm excessively in
7371 // tiny amounts
7372 n--;
7373 n |= n >>> 1;
7374 n |= n >>> 2;
7375 n |= n >>> 4;
7376 n |= n >>> 8;
7377 n |= n >>> 16;
7378 n++;
7379 }
7380 return n;
7381}
7382
7383// This function is designed to be inlinable, so please take care when making
7384// changes to the function body.
7385function howMuchToRead(n, state) {
7386 if (n <= 0 || state.length === 0 && state.ended) return 0;
7387 if (state.objectMode) return 1;
7388 if (n !== n) {
7389 // Only flow one buffer at a time
7390 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
7391 }
7392 // If we're asking for more than the current hwm, then raise the hwm.
7393 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
7394 if (n <= state.length) return n;
7395 // Don't have enough
7396 if (!state.ended) {
7397 state.needReadable = true;
7398 return 0;
7399 }
7400 return state.length;
7401}
7402
7403// you can override either this method, or the async _read(n) below.
7404Readable.prototype.read = function (n) {
7405 debug('read', n);
7406 n = parseInt(n, 10);
7407 var state = this._readableState;
7408 var nOrig = n;
7409 if (n !== 0) state.emittedReadable = false;
7410
7411 // if we're doing read(0) to trigger a readable event, but we
7412 // already have a bunch of data in the buffer, then just trigger
7413 // the 'readable' event and move on.
7414 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
7415 debug('read: emitReadable', state.length, state.ended);
7416 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
7417 return null;
7418 }
7419 n = howMuchToRead(n, state);
7420
7421 // if we've ended, and we're now clear, then finish it up.
7422 if (n === 0 && state.ended) {
7423 if (state.length === 0) endReadable(this);
7424 return null;
7425 }
7426
7427 // All the actual chunk generation logic needs to be
7428 // *below* the call to _read. The reason is that in certain
7429 // synthetic stream cases, such as passthrough streams, _read
7430 // may be a completely synchronous operation which may change
7431 // the state of the read buffer, providing enough data when
7432 // before there was *not* enough.
7433 //
7434 // So, the steps are:
7435 // 1. Figure out what the state of things will be after we do
7436 // a read from the buffer.
7437 //
7438 // 2. If that resulting state will trigger a _read, then call _read.
7439 // Note that this may be asynchronous, or synchronous. Yes, it is
7440 // deeply ugly to write APIs this way, but that still doesn't mean
7441 // that the Readable class should behave improperly, as streams are
7442 // designed to be sync/async agnostic.
7443 // Take note if the _read call is sync or async (ie, if the read call
7444 // has returned yet), so that we know whether or not it's safe to emit
7445 // 'readable' etc.
7446 //
7447 // 3. Actually pull the requested chunks out of the buffer and return.
7448
7449 // if we need a readable event, then we need to do some reading.
7450 var doRead = state.needReadable;
7451 debug('need readable', doRead);
7452
7453 // if we currently have less than the highWaterMark, then also read some
7454 if (state.length === 0 || state.length - n < state.highWaterMark) {
7455 doRead = true;
7456 debug('length less than watermark', doRead);
7457 }
7458
7459 // however, if we've ended, then there's no point, and if we're already
7460 // reading, then it's unnecessary.
7461 if (state.ended || state.reading) {
7462 doRead = false;
7463 debug('reading or ended', doRead);
7464 } else if (doRead) {
7465 debug('do read');
7466 state.reading = true;
7467 state.sync = true;
7468 // if the length is currently zero, then we *need* a readable event.
7469 if (state.length === 0) state.needReadable = true;
7470 // call internal read method
7471 this._read(state.highWaterMark);
7472 state.sync = false;
7473 // If _read pushed data synchronously, then `reading` will be false,
7474 // and we need to re-evaluate how much data we can return to the user.
7475 if (!state.reading) n = howMuchToRead(nOrig, state);
7476 }
7477 var ret;
7478 if (n > 0) ret = fromList(n, state);else ret = null;
7479 if (ret === null) {
7480 state.needReadable = state.length <= state.highWaterMark;
7481 n = 0;
7482 } else {
7483 state.length -= n;
7484 state.awaitDrain = 0;
7485 }
7486 if (state.length === 0) {
7487 // If we have nothing in the buffer, then we want to know
7488 // as soon as we *do* get something into the buffer.
7489 if (!state.ended) state.needReadable = true;
7490
7491 // If we tried to read() past the EOF, then emit end on the next tick.
7492 if (nOrig !== n && state.ended) endReadable(this);
7493 }
7494 if (ret !== null) this.emit('data', ret);
7495 return ret;
7496};
7497function onEofChunk(stream, state) {
7498 debug('onEofChunk');
7499 if (state.ended) return;
7500 if (state.decoder) {
7501 var chunk = state.decoder.end();
7502 if (chunk && chunk.length) {
7503 state.buffer.push(chunk);
7504 state.length += state.objectMode ? 1 : chunk.length;
7505 }
7506 }
7507 state.ended = true;
7508 if (state.sync) {
7509 // if we are sync, wait until next tick to emit the data.
7510 // Otherwise we risk emitting data in the flow()
7511 // the readable code triggers during a read() call
7512 emitReadable(stream);
7513 } else {
7514 // emit 'readable' now to make sure it gets picked up.
7515 state.needReadable = false;
7516 if (!state.emittedReadable) {
7517 state.emittedReadable = true;
7518 emitReadable_(stream);
7519 }
7520 }
7521}
7522
7523// Don't emit readable right away in sync mode, because this can trigger
7524// another read() call => stack overflow. This way, it might trigger
7525// a nextTick recursion warning, but that's not so bad.
7526function emitReadable(stream) {
7527 var state = stream._readableState;
7528 debug('emitReadable', state.needReadable, state.emittedReadable);
7529 state.needReadable = false;
7530 if (!state.emittedReadable) {
7531 debug('emitReadable', state.flowing);
7532 state.emittedReadable = true;
7533 process.nextTick(emitReadable_, stream);
7534 }
7535}
7536function emitReadable_(stream) {
7537 var state = stream._readableState;
7538 debug('emitReadable_', state.destroyed, state.length, state.ended);
7539 if (!state.destroyed && (state.length || state.ended)) {
7540 stream.emit('readable');
7541 state.emittedReadable = false;
7542 }
7543
7544 // The stream needs another readable event if
7545 // 1. It is not flowing, as the flow mechanism will take
7546 // care of it.
7547 // 2. It is not ended.
7548 // 3. It is below the highWaterMark, so we can schedule
7549 // another readable later.
7550 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
7551 flow(stream);
7552}
7553
7554// at this point, the user has presumably seen the 'readable' event,
7555// and called read() to consume some data. that may have triggered
7556// in turn another _read(n) call, in which case reading = true if
7557// it's in progress.
7558// However, if we're not ended, or reading, and the length < hwm,
7559// then go ahead and try to read some more preemptively.
7560function maybeReadMore(stream, state) {
7561 if (!state.readingMore) {
7562 state.readingMore = true;
7563 process.nextTick(maybeReadMore_, stream, state);
7564 }
7565}
7566function maybeReadMore_(stream, state) {
7567 // Attempt to read more data if we should.
7568 //
7569 // The conditions for reading more data are (one of):
7570 // - Not enough data buffered (state.length < state.highWaterMark). The loop
7571 // is responsible for filling the buffer with enough data if such data
7572 // is available. If highWaterMark is 0 and we are not in the flowing mode
7573 // we should _not_ attempt to buffer any extra data. We'll get more data
7574 // when the stream consumer calls read() instead.
7575 // - No data in the buffer, and the stream is in flowing mode. In this mode
7576 // the loop below is responsible for ensuring read() is called. Failing to
7577 // call read here would abort the flow and there's no other mechanism for
7578 // continuing the flow if the stream consumer has just subscribed to the
7579 // 'data' event.
7580 //
7581 // In addition to the above conditions to keep reading data, the following
7582 // conditions prevent the data from being read:
7583 // - The stream has ended (state.ended).
7584 // - There is already a pending 'read' operation (state.reading). This is a
7585 // case where the the stream has called the implementation defined _read()
7586 // method, but they are processing the call asynchronously and have _not_
7587 // called push() with new data. In this case we skip performing more
7588 // read()s. The execution ends in this method again after the _read() ends
7589 // up calling push() with more data.
7590 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
7591 var len = state.length;
7592 debug('maybeReadMore read 0');
7593 stream.read(0);
7594 if (len === state.length)
7595 // didn't get any data, stop spinning.
7596 break;
7597 }
7598 state.readingMore = false;
7599}
7600
7601// abstract method. to be overridden in specific implementation classes.
7602// call cb(er, data) where data is <= n in length.
7603// for virtual (non-string, non-buffer) streams, "length" is somewhat
7604// arbitrary, and perhaps not very meaningful.
7605Readable.prototype._read = function (n) {
7606 errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
7607};
7608Readable.prototype.pipe = function (dest, pipeOpts) {
7609 var src = this;
7610 var state = this._readableState;
7611 switch (state.pipesCount) {
7612 case 0:
7613 state.pipes = dest;
7614 break;
7615 case 1:
7616 state.pipes = [state.pipes, dest];
7617 break;
7618 default:
7619 state.pipes.push(dest);
7620 break;
7621 }
7622 state.pipesCount += 1;
7623 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
7624 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
7625 var endFn = doEnd ? onend : unpipe;
7626 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
7627 dest.on('unpipe', onunpipe);
7628 function onunpipe(readable, unpipeInfo) {
7629 debug('onunpipe');
7630 if (readable === src) {
7631 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
7632 unpipeInfo.hasUnpiped = true;
7633 cleanup();
7634 }
7635 }
7636 }
7637 function onend() {
7638 debug('onend');
7639 dest.end();
7640 }
7641
7642 // when the dest drains, it reduces the awaitDrain counter
7643 // on the source. This would be more elegant with a .once()
7644 // handler in flow(), but adding and removing repeatedly is
7645 // too slow.
7646 var ondrain = pipeOnDrain(src);
7647 dest.on('drain', ondrain);
7648 var cleanedUp = false;
7649 function cleanup() {
7650 debug('cleanup');
7651 // cleanup event handlers once the pipe is broken
7652 dest.removeListener('close', onclose);
7653 dest.removeListener('finish', onfinish);
7654 dest.removeListener('drain', ondrain);
7655 dest.removeListener('error', onerror);
7656 dest.removeListener('unpipe', onunpipe);
7657 src.removeListener('end', onend);
7658 src.removeListener('end', unpipe);
7659 src.removeListener('data', ondata);
7660 cleanedUp = true;
7661
7662 // if the reader is waiting for a drain event from this
7663 // specific writer, then it would cause it to never start
7664 // flowing again.
7665 // So, if this is awaiting a drain, then we just call it now.
7666 // If we don't know, then assume that we are waiting for one.
7667 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
7668 }
7669 src.on('data', ondata);
7670 function ondata(chunk) {
7671 debug('ondata');
7672 var ret = dest.write(chunk);
7673 debug('dest.write', ret);
7674 if (ret === false) {
7675 // If the user unpiped during `dest.write()`, it is possible
7676 // to get stuck in a permanently paused state if that write
7677 // also returned false.
7678 // => Check whether `dest` is still a piping destination.
7679 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
7680 debug('false write response, pause', state.awaitDrain);
7681 state.awaitDrain++;
7682 }
7683 src.pause();
7684 }
7685 }
7686
7687 // if the dest has an error, then stop piping into it.
7688 // however, don't suppress the throwing behavior for this.
7689 function onerror(er) {
7690 debug('onerror', er);
7691 unpipe();
7692 dest.removeListener('error', onerror);
7693 if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
7694 }
7695
7696 // Make sure our error handler is attached before userland ones.
7697 prependListener(dest, 'error', onerror);
7698
7699 // Both close and finish should trigger unpipe, but only once.
7700 function onclose() {
7701 dest.removeListener('finish', onfinish);
7702 unpipe();
7703 }
7704 dest.once('close', onclose);
7705 function onfinish() {
7706 debug('onfinish');
7707 dest.removeListener('close', onclose);
7708 unpipe();
7709 }
7710 dest.once('finish', onfinish);
7711 function unpipe() {
7712 debug('unpipe');
7713 src.unpipe(dest);
7714 }
7715
7716 // tell the dest that it's being piped to
7717 dest.emit('pipe', src);
7718
7719 // start the flow if it hasn't been started already.
7720 if (!state.flowing) {
7721 debug('pipe resume');
7722 src.resume();
7723 }
7724 return dest;
7725};
7726function pipeOnDrain(src) {
7727 return function pipeOnDrainFunctionResult() {
7728 var state = src._readableState;
7729 debug('pipeOnDrain', state.awaitDrain);
7730 if (state.awaitDrain) state.awaitDrain--;
7731 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
7732 state.flowing = true;
7733 flow(src);
7734 }
7735 };
7736}
7737Readable.prototype.unpipe = function (dest) {
7738 var state = this._readableState;
7739 var unpipeInfo = {
7740 hasUnpiped: false
7741 };
7742
7743 // if we're not piping anywhere, then do nothing.
7744 if (state.pipesCount === 0) return this;
7745
7746 // just one destination. most common case.
7747 if (state.pipesCount === 1) {
7748 // passed in one, but it's not the right one.
7749 if (dest && dest !== state.pipes) return this;
7750 if (!dest) dest = state.pipes;
7751
7752 // got a match.
7753 state.pipes = null;
7754 state.pipesCount = 0;
7755 state.flowing = false;
7756 if (dest) dest.emit('unpipe', this, unpipeInfo);
7757 return this;
7758 }
7759
7760 // slow case. multiple pipe destinations.
7761
7762 if (!dest) {
7763 // remove all.
7764 var dests = state.pipes;
7765 var len = state.pipesCount;
7766 state.pipes = null;
7767 state.pipesCount = 0;
7768 state.flowing = false;
7769 for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, {
7770 hasUnpiped: false
7771 });
7772 return this;
7773 }
7774
7775 // try to find the right one.
7776 var index = indexOf(state.pipes, dest);
7777 if (index === -1) return this;
7778 state.pipes.splice(index, 1);
7779 state.pipesCount -= 1;
7780 if (state.pipesCount === 1) state.pipes = state.pipes[0];
7781 dest.emit('unpipe', this, unpipeInfo);
7782 return this;
7783};
7784
7785// set up data events if they are asked for
7786// Ensure readable listeners eventually get something
7787Readable.prototype.on = function (ev, fn) {
7788 var res = Stream.prototype.on.call(this, ev, fn);
7789 var state = this._readableState;
7790 if (ev === 'data') {
7791 // update readableListening so that resume() may be a no-op
7792 // a few lines down. This is needed to support once('readable').
7793 state.readableListening = this.listenerCount('readable') > 0;
7794
7795 // Try start flowing on next tick if stream isn't explicitly paused
7796 if (state.flowing !== false) this.resume();
7797 } else if (ev === 'readable') {
7798 if (!state.endEmitted && !state.readableListening) {
7799 state.readableListening = state.needReadable = true;
7800 state.flowing = false;
7801 state.emittedReadable = false;
7802 debug('on readable', state.length, state.reading);
7803 if (state.length) {
7804 emitReadable(this);
7805 } else if (!state.reading) {
7806 process.nextTick(nReadingNextTick, this);
7807 }
7808 }
7809 }
7810 return res;
7811};
7812Readable.prototype.addListener = Readable.prototype.on;
7813Readable.prototype.removeListener = function (ev, fn) {
7814 var res = Stream.prototype.removeListener.call(this, ev, fn);
7815 if (ev === 'readable') {
7816 // We need to check if there is someone still listening to
7817 // readable and reset the state. However this needs to happen
7818 // after readable has been emitted but before I/O (nextTick) to
7819 // support once('readable', fn) cycles. This means that calling
7820 // resume within the same tick will have no
7821 // effect.
7822 process.nextTick(updateReadableListening, this);
7823 }
7824 return res;
7825};
7826Readable.prototype.removeAllListeners = function (ev) {
7827 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
7828 if (ev === 'readable' || ev === undefined) {
7829 // We need to check if there is someone still listening to
7830 // readable and reset the state. However this needs to happen
7831 // after readable has been emitted but before I/O (nextTick) to
7832 // support once('readable', fn) cycles. This means that calling
7833 // resume within the same tick will have no
7834 // effect.
7835 process.nextTick(updateReadableListening, this);
7836 }
7837 return res;
7838};
7839function updateReadableListening(self) {
7840 var state = self._readableState;
7841 state.readableListening = self.listenerCount('readable') > 0;
7842 if (state.resumeScheduled && !state.paused) {
7843 // flowing needs to be set to true now, otherwise
7844 // the upcoming resume will not flow.
7845 state.flowing = true;
7846
7847 // crude way to check if we should resume
7848 } else if (self.listenerCount('data') > 0) {
7849 self.resume();
7850 }
7851}
7852function nReadingNextTick(self) {
7853 debug('readable nexttick read 0');
7854 self.read(0);
7855}
7856
7857// pause() and resume() are remnants of the legacy readable stream API
7858// If the user uses them, then switch into old mode.
7859Readable.prototype.resume = function () {
7860 var state = this._readableState;
7861 if (!state.flowing) {
7862 debug('resume');
7863 // we flow only if there is no one listening
7864 // for readable, but we still have to call
7865 // resume()
7866 state.flowing = !state.readableListening;
7867 resume(this, state);
7868 }
7869 state.paused = false;
7870 return this;
7871};
7872function resume(stream, state) {
7873 if (!state.resumeScheduled) {
7874 state.resumeScheduled = true;
7875 process.nextTick(resume_, stream, state);
7876 }
7877}
7878function resume_(stream, state) {
7879 debug('resume', state.reading);
7880 if (!state.reading) {
7881 stream.read(0);
7882 }
7883 state.resumeScheduled = false;
7884 stream.emit('resume');
7885 flow(stream);
7886 if (state.flowing && !state.reading) stream.read(0);
7887}
7888Readable.prototype.pause = function () {
7889 debug('call pause flowing=%j', this._readableState.flowing);
7890 if (this._readableState.flowing !== false) {
7891 debug('pause');
7892 this._readableState.flowing = false;
7893 this.emit('pause');
7894 }
7895 this._readableState.paused = true;
7896 return this;
7897};
7898function flow(stream) {
7899 var state = stream._readableState;
7900 debug('flow', state.flowing);
7901 while (state.flowing && stream.read() !== null);
7902}
7903
7904// wrap an old-style stream as the async data source.
7905// This is *not* part of the readable stream interface.
7906// It is an ugly unfortunate mess of history.
7907Readable.prototype.wrap = function (stream) {
7908 var _this = this;
7909 var state = this._readableState;
7910 var paused = false;
7911 stream.on('end', function () {
7912 debug('wrapped end');
7913 if (state.decoder && !state.ended) {
7914 var chunk = state.decoder.end();
7915 if (chunk && chunk.length) _this.push(chunk);
7916 }
7917 _this.push(null);
7918 });
7919 stream.on('data', function (chunk) {
7920 debug('wrapped data');
7921 if (state.decoder) chunk = state.decoder.write(chunk);
7922
7923 // don't skip over falsy values in objectMode
7924 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
7925 var ret = _this.push(chunk);
7926 if (!ret) {
7927 paused = true;
7928 stream.pause();
7929 }
7930 });
7931
7932 // proxy all the other methods.
7933 // important when wrapping filters and duplexes.
7934 for (var i in stream) {
7935 if (this[i] === undefined && typeof stream[i] === 'function') {
7936 this[i] = function methodWrap(method) {
7937 return function methodWrapReturnFunction() {
7938 return stream[method].apply(stream, arguments);
7939 };
7940 }(i);
7941 }
7942 }
7943
7944 // proxy certain important events.
7945 for (var n = 0; n < kProxyEvents.length; n++) {
7946 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
7947 }
7948
7949 // when we try to consume some more bytes, simply unpause the
7950 // underlying stream.
7951 this._read = function (n) {
7952 debug('wrapped _read', n);
7953 if (paused) {
7954 paused = false;
7955 stream.resume();
7956 }
7957 };
7958 return this;
7959};
7960if (typeof Symbol === 'function') {
7961 Readable.prototype[Symbol.asyncIterator] = function () {
7962 if (createReadableStreamAsyncIterator === undefined) {
7963 createReadableStreamAsyncIterator = _dereq_('./internal/streams/async_iterator');
7964 }
7965 return createReadableStreamAsyncIterator(this);
7966 };
7967}
7968Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
7969 // making it explicit this property is not enumerable
7970 // because otherwise some prototype manipulation in
7971 // userland will fail
7972 enumerable: false,
7973 get: function get() {
7974 return this._readableState.highWaterMark;
7975 }
7976});
7977Object.defineProperty(Readable.prototype, 'readableBuffer', {
7978 // making it explicit this property is not enumerable
7979 // because otherwise some prototype manipulation in
7980 // userland will fail
7981 enumerable: false,
7982 get: function get() {
7983 return this._readableState && this._readableState.buffer;
7984 }
7985});
7986Object.defineProperty(Readable.prototype, 'readableFlowing', {
7987 // making it explicit this property is not enumerable
7988 // because otherwise some prototype manipulation in
7989 // userland will fail
7990 enumerable: false,
7991 get: function get() {
7992 return this._readableState.flowing;
7993 },
7994 set: function set(state) {
7995 if (this._readableState) {
7996 this._readableState.flowing = state;
7997 }
7998 }
7999});
8000
8001// exposed for testing purposes only.
8002Readable._fromList = fromList;
8003Object.defineProperty(Readable.prototype, 'readableLength', {
8004 // making it explicit this property is not enumerable
8005 // because otherwise some prototype manipulation in
8006 // userland will fail
8007 enumerable: false,
8008 get: function get() {
8009 return this._readableState.length;
8010 }
8011});
8012
8013// Pluck off n bytes from an array of buffers.
8014// Length is the combined lengths of all the buffers in the list.
8015// This function is designed to be inlinable, so please take care when making
8016// changes to the function body.
8017function fromList(n, state) {
8018 // nothing buffered
8019 if (state.length === 0) return null;
8020 var ret;
8021 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
8022 // read it all, truncate the list
8023 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
8024 state.buffer.clear();
8025 } else {
8026 // read part of list
8027 ret = state.buffer.consume(n, state.decoder);
8028 }
8029 return ret;
8030}
8031function endReadable(stream) {
8032 var state = stream._readableState;
8033 debug('endReadable', state.endEmitted);
8034 if (!state.endEmitted) {
8035 state.ended = true;
8036 process.nextTick(endReadableNT, state, stream);
8037 }
8038}
8039function endReadableNT(state, stream) {
8040 debug('endReadableNT', state.endEmitted, state.length);
8041
8042 // Check that we didn't get one last unshift.
8043 if (!state.endEmitted && state.length === 0) {
8044 state.endEmitted = true;
8045 stream.readable = false;
8046 stream.emit('end');
8047 if (state.autoDestroy) {
8048 // In case of duplex streams we need a way to detect
8049 // if the writable side is ready for autoDestroy as well
8050 var wState = stream._writableState;
8051 if (!wState || wState.autoDestroy && wState.finished) {
8052 stream.destroy();
8053 }
8054 }
8055 }
8056}
8057if (typeof Symbol === 'function') {
8058 Readable.from = function (iterable, opts) {
8059 if (from === undefined) {
8060 from = _dereq_('./internal/streams/from');
8061 }
8062 return from(Readable, iterable, opts);
8063 };
8064}
8065function indexOf(xs, x) {
8066 for (var i = 0, l = xs.length; i < l; i++) {
8067 if (xs[i] === x) return i;
8068 }
8069 return -1;
8070}
8071}).call(this)}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8072},{"../errors":52,"./_stream_duplex":53,"./internal/streams/async_iterator":58,"./internal/streams/buffer_list":59,"./internal/streams/destroy":60,"./internal/streams/from":62,"./internal/streams/state":64,"./internal/streams/stream":65,"_process":93,"buffer":4,"events":33,"inherits":45,"string_decoder/":122,"util":3}],56:[function(_dereq_,module,exports){
8073// Copyright Joyent, Inc. and other Node contributors.
8074//
8075// Permission is hereby granted, free of charge, to any person obtaining a
8076// copy of this software and associated documentation files (the
8077// "Software"), to deal in the Software without restriction, including
8078// without limitation the rights to use, copy, modify, merge, publish,
8079// distribute, sublicense, and/or sell copies of the Software, and to permit
8080// persons to whom the Software is furnished to do so, subject to the
8081// following conditions:
8082//
8083// The above copyright notice and this permission notice shall be included
8084// in all copies or substantial portions of the Software.
8085//
8086// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8087// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8088// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
8089// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
8090// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
8091// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
8092// USE OR OTHER DEALINGS IN THE SOFTWARE.
8093
8094// a transform stream is a readable/writable stream where you do
8095// something with the data. Sometimes it's called a "filter",
8096// but that's not a great name for it, since that implies a thing where
8097// some bits pass through, and others are simply ignored. (That would
8098// be a valid example of a transform, of course.)
8099//
8100// While the output is causally related to the input, it's not a
8101// necessarily symmetric or synchronous transformation. For example,
8102// a zlib stream might take multiple plain-text writes(), and then
8103// emit a single compressed chunk some time in the future.
8104//
8105// Here's how this works:
8106//
8107// The Transform stream has all the aspects of the readable and writable
8108// stream classes. When you write(chunk), that calls _write(chunk,cb)
8109// internally, and returns false if there's a lot of pending writes
8110// buffered up. When you call read(), that calls _read(n) until
8111// there's enough pending readable data buffered up.
8112//
8113// In a transform stream, the written data is placed in a buffer. When
8114// _read(n) is called, it transforms the queued up data, calling the
8115// buffered _write cb's as it consumes chunks. If consuming a single
8116// written chunk would result in multiple output chunks, then the first
8117// outputted bit calls the readcb, and subsequent chunks just go into
8118// the read buffer, and will cause it to emit 'readable' if necessary.
8119//
8120// This way, back-pressure is actually determined by the reading side,
8121// since _read has to be called to start processing a new chunk. However,
8122// a pathological inflate type of transform can cause excessive buffering
8123// here. For example, imagine a stream where every byte of input is
8124// interpreted as an integer from 0-255, and then results in that many
8125// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
8126// 1kb of data being output. In this case, you could write a very small
8127// amount of input, and end up with a very large amount of output. In
8128// such a pathological inflating mechanism, there'd be no way to tell
8129// the system to stop doing the transform. A single 4MB write could
8130// cause the system to run out of memory.
8131//
8132// However, even in such a pathological case, only a single written chunk
8133// would be consumed, and then the rest would wait (un-transformed) until
8134// the results of the previous transformed chunk were consumed.
8135
8136'use strict';
8137
8138module.exports = Transform;
8139var _require$codes = _dereq_('../errors').codes,
8140 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
8141 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
8142 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
8143 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
8144var Duplex = _dereq_('./_stream_duplex');
8145_dereq_('inherits')(Transform, Duplex);
8146function afterTransform(er, data) {
8147 var ts = this._transformState;
8148 ts.transforming = false;
8149 var cb = ts.writecb;
8150 if (cb === null) {
8151 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
8152 }
8153 ts.writechunk = null;
8154 ts.writecb = null;
8155 if (data != null)
8156 // single equals check for both `null` and `undefined`
8157 this.push(data);
8158 cb(er);
8159 var rs = this._readableState;
8160 rs.reading = false;
8161 if (rs.needReadable || rs.length < rs.highWaterMark) {
8162 this._read(rs.highWaterMark);
8163 }
8164}
8165function Transform(options) {
8166 if (!(this instanceof Transform)) return new Transform(options);
8167 Duplex.call(this, options);
8168 this._transformState = {
8169 afterTransform: afterTransform.bind(this),
8170 needTransform: false,
8171 transforming: false,
8172 writecb: null,
8173 writechunk: null,
8174 writeencoding: null
8175 };
8176
8177 // start out asking for a readable event once data is transformed.
8178 this._readableState.needReadable = true;
8179
8180 // we have implemented the _read method, and done the other things
8181 // that Readable wants before the first _read call, so unset the
8182 // sync guard flag.
8183 this._readableState.sync = false;
8184 if (options) {
8185 if (typeof options.transform === 'function') this._transform = options.transform;
8186 if (typeof options.flush === 'function') this._flush = options.flush;
8187 }
8188
8189 // When the writable side finishes, then flush out anything remaining.
8190 this.on('prefinish', prefinish);
8191}
8192function prefinish() {
8193 var _this = this;
8194 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
8195 this._flush(function (er, data) {
8196 done(_this, er, data);
8197 });
8198 } else {
8199 done(this, null, null);
8200 }
8201}
8202Transform.prototype.push = function (chunk, encoding) {
8203 this._transformState.needTransform = false;
8204 return Duplex.prototype.push.call(this, chunk, encoding);
8205};
8206
8207// This is the part where you do stuff!
8208// override this function in implementation classes.
8209// 'chunk' is an input chunk.
8210//
8211// Call `push(newChunk)` to pass along transformed output
8212// to the readable side. You may call 'push' zero or more times.
8213//
8214// Call `cb(err)` when you are done with this chunk. If you pass
8215// an error, then that'll put the hurt on the whole operation. If you
8216// never call cb(), then you'll never get another chunk.
8217Transform.prototype._transform = function (chunk, encoding, cb) {
8218 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
8219};
8220Transform.prototype._write = function (chunk, encoding, cb) {
8221 var ts = this._transformState;
8222 ts.writecb = cb;
8223 ts.writechunk = chunk;
8224 ts.writeencoding = encoding;
8225 if (!ts.transforming) {
8226 var rs = this._readableState;
8227 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
8228 }
8229};
8230
8231// Doesn't matter what the args are here.
8232// _transform does all the work.
8233// That we got here means that the readable side wants more data.
8234Transform.prototype._read = function (n) {
8235 var ts = this._transformState;
8236 if (ts.writechunk !== null && !ts.transforming) {
8237 ts.transforming = true;
8238 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
8239 } else {
8240 // mark that we need a transform, so that any data that comes in
8241 // will get processed, now that we've asked for it.
8242 ts.needTransform = true;
8243 }
8244};
8245Transform.prototype._destroy = function (err, cb) {
8246 Duplex.prototype._destroy.call(this, err, function (err2) {
8247 cb(err2);
8248 });
8249};
8250function done(stream, er, data) {
8251 if (er) return stream.emit('error', er);
8252 if (data != null)
8253 // single equals check for both `null` and `undefined`
8254 stream.push(data);
8255
8256 // TODO(BridgeAR): Write a test for these two error cases
8257 // if there's nothing in the write buffer, then that means
8258 // that nothing more will ever be provided
8259 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
8260 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
8261 return stream.push(null);
8262}
8263},{"../errors":52,"./_stream_duplex":53,"inherits":45}],57:[function(_dereq_,module,exports){
8264(function (process,global){(function (){
8265// Copyright Joyent, Inc. and other Node contributors.
8266//
8267// Permission is hereby granted, free of charge, to any person obtaining a
8268// copy of this software and associated documentation files (the
8269// "Software"), to deal in the Software without restriction, including
8270// without limitation the rights to use, copy, modify, merge, publish,
8271// distribute, sublicense, and/or sell copies of the Software, and to permit
8272// persons to whom the Software is furnished to do so, subject to the
8273// following conditions:
8274//
8275// The above copyright notice and this permission notice shall be included
8276// in all copies or substantial portions of the Software.
8277//
8278// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8279// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8280// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
8281// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
8282// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
8283// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
8284// USE OR OTHER DEALINGS IN THE SOFTWARE.
8285
8286// A bit simpler than readable streams.
8287// Implement an async ._write(chunk, encoding, cb), and it'll handle all
8288// the drain event emission and buffering.
8289
8290'use strict';
8291
8292module.exports = Writable;
8293
8294/* <replacement> */
8295function WriteReq(chunk, encoding, cb) {
8296 this.chunk = chunk;
8297 this.encoding = encoding;
8298 this.callback = cb;
8299 this.next = null;
8300}
8301
8302// It seems a linked list but it is not
8303// there will be only 2 of these for each stream
8304function CorkedRequest(state) {
8305 var _this = this;
8306 this.next = null;
8307 this.entry = null;
8308 this.finish = function () {
8309 onCorkedFinish(_this, state);
8310 };
8311}
8312/* </replacement> */
8313
8314/*<replacement>*/
8315var Duplex;
8316/*</replacement>*/
8317
8318Writable.WritableState = WritableState;
8319
8320/*<replacement>*/
8321var internalUtil = {
8322 deprecate: _dereq_('util-deprecate')
8323};
8324/*</replacement>*/
8325
8326/*<replacement>*/
8327var Stream = _dereq_('./internal/streams/stream');
8328/*</replacement>*/
8329
8330var Buffer = _dereq_('buffer').Buffer;
8331var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
8332function _uint8ArrayToBuffer(chunk) {
8333 return Buffer.from(chunk);
8334}
8335function _isUint8Array(obj) {
8336 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
8337}
8338var destroyImpl = _dereq_('./internal/streams/destroy');
8339var _require = _dereq_('./internal/streams/state'),
8340 getHighWaterMark = _require.getHighWaterMark;
8341var _require$codes = _dereq_('../errors').codes,
8342 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
8343 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
8344 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
8345 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
8346 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
8347 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
8348 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
8349 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
8350var errorOrDestroy = destroyImpl.errorOrDestroy;
8351_dereq_('inherits')(Writable, Stream);
8352function nop() {}
8353function WritableState(options, stream, isDuplex) {
8354 Duplex = Duplex || _dereq_('./_stream_duplex');
8355 options = options || {};
8356
8357 // Duplex streams are both readable and writable, but share
8358 // the same options object.
8359 // However, some cases require setting options to different
8360 // values for the readable and the writable sides of the duplex stream,
8361 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
8362 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
8363
8364 // object stream flag to indicate whether or not this stream
8365 // contains buffers or objects.
8366 this.objectMode = !!options.objectMode;
8367 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
8368
8369 // the point at which write() starts returning false
8370 // Note: 0 is a valid value, means that we always return false if
8371 // the entire buffer is not flushed immediately on write()
8372 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex);
8373
8374 // if _final has been called
8375 this.finalCalled = false;
8376
8377 // drain event flag.
8378 this.needDrain = false;
8379 // at the start of calling end()
8380 this.ending = false;
8381 // when end() has been called, and returned
8382 this.ended = false;
8383 // when 'finish' is emitted
8384 this.finished = false;
8385
8386 // has it been destroyed
8387 this.destroyed = false;
8388
8389 // should we decode strings into buffers before passing to _write?
8390 // this is here so that some node-core streams can optimize string
8391 // handling at a lower level.
8392 var noDecode = options.decodeStrings === false;
8393 this.decodeStrings = !noDecode;
8394
8395 // Crypto is kind of old and crusty. Historically, its default string
8396 // encoding is 'binary' so we have to make this configurable.
8397 // Everything else in the universe uses 'utf8', though.
8398 this.defaultEncoding = options.defaultEncoding || 'utf8';
8399
8400 // not an actual buffer we keep track of, but a measurement
8401 // of how much we're waiting to get pushed to some underlying
8402 // socket or file.
8403 this.length = 0;
8404
8405 // a flag to see when we're in the middle of a write.
8406 this.writing = false;
8407
8408 // when true all writes will be buffered until .uncork() call
8409 this.corked = 0;
8410
8411 // a flag to be able to tell if the onwrite cb is called immediately,
8412 // or on a later tick. We set this to true at first, because any
8413 // actions that shouldn't happen until "later" should generally also
8414 // not happen before the first write call.
8415 this.sync = true;
8416
8417 // a flag to know if we're processing previously buffered items, which
8418 // may call the _write() callback in the same tick, so that we don't
8419 // end up in an overlapped onwrite situation.
8420 this.bufferProcessing = false;
8421
8422 // the callback that's passed to _write(chunk,cb)
8423 this.onwrite = function (er) {
8424 onwrite(stream, er);
8425 };
8426
8427 // the callback that the user supplies to write(chunk,encoding,cb)
8428 this.writecb = null;
8429
8430 // the amount that is being written when _write is called.
8431 this.writelen = 0;
8432 this.bufferedRequest = null;
8433 this.lastBufferedRequest = null;
8434
8435 // number of pending user-supplied write callbacks
8436 // this must be 0 before 'finish' can be emitted
8437 this.pendingcb = 0;
8438
8439 // emit prefinish if the only thing we're waiting for is _write cbs
8440 // This is relevant for synchronous Transform streams
8441 this.prefinished = false;
8442
8443 // True if the error was already emitted and should not be thrown again
8444 this.errorEmitted = false;
8445
8446 // Should close be emitted on destroy. Defaults to true.
8447 this.emitClose = options.emitClose !== false;
8448
8449 // Should .destroy() be called after 'finish' (and potentially 'end')
8450 this.autoDestroy = !!options.autoDestroy;
8451
8452 // count buffered requests
8453 this.bufferedRequestCount = 0;
8454
8455 // allocate the first CorkedRequest, there is always
8456 // one allocated and free to use, and we maintain at most two
8457 this.corkedRequestsFree = new CorkedRequest(this);
8458}
8459WritableState.prototype.getBuffer = function getBuffer() {
8460 var current = this.bufferedRequest;
8461 var out = [];
8462 while (current) {
8463 out.push(current);
8464 current = current.next;
8465 }
8466 return out;
8467};
8468(function () {
8469 try {
8470 Object.defineProperty(WritableState.prototype, 'buffer', {
8471 get: internalUtil.deprecate(function writableStateBufferGetter() {
8472 return this.getBuffer();
8473 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
8474 });
8475 } catch (_) {}
8476})();
8477
8478// Test _writableState for inheritance to account for Duplex streams,
8479// whose prototype chain only points to Readable.
8480var realHasInstance;
8481if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
8482 realHasInstance = Function.prototype[Symbol.hasInstance];
8483 Object.defineProperty(Writable, Symbol.hasInstance, {
8484 value: function value(object) {
8485 if (realHasInstance.call(this, object)) return true;
8486 if (this !== Writable) return false;
8487 return object && object._writableState instanceof WritableState;
8488 }
8489 });
8490} else {
8491 realHasInstance = function realHasInstance(object) {
8492 return object instanceof this;
8493 };
8494}
8495function Writable(options) {
8496 Duplex = Duplex || _dereq_('./_stream_duplex');
8497
8498 // Writable ctor is applied to Duplexes, too.
8499 // `realHasInstance` is necessary because using plain `instanceof`
8500 // would return false, as no `_writableState` property is attached.
8501
8502 // Trying to use the custom `instanceof` for Writable here will also break the
8503 // Node.js LazyTransform implementation, which has a non-trivial getter for
8504 // `_writableState` that would lead to infinite recursion.
8505
8506 // Checking for a Stream.Duplex instance is faster here instead of inside
8507 // the WritableState constructor, at least with V8 6.5
8508 var isDuplex = this instanceof Duplex;
8509 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
8510 this._writableState = new WritableState(options, this, isDuplex);
8511
8512 // legacy.
8513 this.writable = true;
8514 if (options) {
8515 if (typeof options.write === 'function') this._write = options.write;
8516 if (typeof options.writev === 'function') this._writev = options.writev;
8517 if (typeof options.destroy === 'function') this._destroy = options.destroy;
8518 if (typeof options.final === 'function') this._final = options.final;
8519 }
8520 Stream.call(this);
8521}
8522
8523// Otherwise people can pipe Writable streams, which is just wrong.
8524Writable.prototype.pipe = function () {
8525 errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
8526};
8527function writeAfterEnd(stream, cb) {
8528 var er = new ERR_STREAM_WRITE_AFTER_END();
8529 // TODO: defer error events consistently everywhere, not just the cb
8530 errorOrDestroy(stream, er);
8531 process.nextTick(cb, er);
8532}
8533
8534// Checks that a user-supplied chunk is valid, especially for the particular
8535// mode the stream is in. Currently this means that `null` is never accepted
8536// and undefined/non-string values are only allowed in object mode.
8537function validChunk(stream, state, chunk, cb) {
8538 var er;
8539 if (chunk === null) {
8540 er = new ERR_STREAM_NULL_VALUES();
8541 } else if (typeof chunk !== 'string' && !state.objectMode) {
8542 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
8543 }
8544 if (er) {
8545 errorOrDestroy(stream, er);
8546 process.nextTick(cb, er);
8547 return false;
8548 }
8549 return true;
8550}
8551Writable.prototype.write = function (chunk, encoding, cb) {
8552 var state = this._writableState;
8553 var ret = false;
8554 var isBuf = !state.objectMode && _isUint8Array(chunk);
8555 if (isBuf && !Buffer.isBuffer(chunk)) {
8556 chunk = _uint8ArrayToBuffer(chunk);
8557 }
8558 if (typeof encoding === 'function') {
8559 cb = encoding;
8560 encoding = null;
8561 }
8562 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
8563 if (typeof cb !== 'function') cb = nop;
8564 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
8565 state.pendingcb++;
8566 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
8567 }
8568 return ret;
8569};
8570Writable.prototype.cork = function () {
8571 this._writableState.corked++;
8572};
8573Writable.prototype.uncork = function () {
8574 var state = this._writableState;
8575 if (state.corked) {
8576 state.corked--;
8577 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
8578 }
8579};
8580Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
8581 // node::ParseEncoding() requires lower case.
8582 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
8583 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
8584 this._writableState.defaultEncoding = encoding;
8585 return this;
8586};
8587Object.defineProperty(Writable.prototype, 'writableBuffer', {
8588 // making it explicit this property is not enumerable
8589 // because otherwise some prototype manipulation in
8590 // userland will fail
8591 enumerable: false,
8592 get: function get() {
8593 return this._writableState && this._writableState.getBuffer();
8594 }
8595});
8596function decodeChunk(state, chunk, encoding) {
8597 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
8598 chunk = Buffer.from(chunk, encoding);
8599 }
8600 return chunk;
8601}
8602Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
8603 // making it explicit this property is not enumerable
8604 // because otherwise some prototype manipulation in
8605 // userland will fail
8606 enumerable: false,
8607 get: function get() {
8608 return this._writableState.highWaterMark;
8609 }
8610});
8611
8612// if we're already writing something, then just put this
8613// in the queue, and wait our turn. Otherwise, call _write
8614// If we return false, then we need a drain event, so set that flag.
8615function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
8616 if (!isBuf) {
8617 var newChunk = decodeChunk(state, chunk, encoding);
8618 if (chunk !== newChunk) {
8619 isBuf = true;
8620 encoding = 'buffer';
8621 chunk = newChunk;
8622 }
8623 }
8624 var len = state.objectMode ? 1 : chunk.length;
8625 state.length += len;
8626 var ret = state.length < state.highWaterMark;
8627 // we must ensure that previous needDrain will not be reset to false.
8628 if (!ret) state.needDrain = true;
8629 if (state.writing || state.corked) {
8630 var last = state.lastBufferedRequest;
8631 state.lastBufferedRequest = {
8632 chunk: chunk,
8633 encoding: encoding,
8634 isBuf: isBuf,
8635 callback: cb,
8636 next: null
8637 };
8638 if (last) {
8639 last.next = state.lastBufferedRequest;
8640 } else {
8641 state.bufferedRequest = state.lastBufferedRequest;
8642 }
8643 state.bufferedRequestCount += 1;
8644 } else {
8645 doWrite(stream, state, false, len, chunk, encoding, cb);
8646 }
8647 return ret;
8648}
8649function doWrite(stream, state, writev, len, chunk, encoding, cb) {
8650 state.writelen = len;
8651 state.writecb = cb;
8652 state.writing = true;
8653 state.sync = true;
8654 if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
8655 state.sync = false;
8656}
8657function onwriteError(stream, state, sync, er, cb) {
8658 --state.pendingcb;
8659 if (sync) {
8660 // defer the callback if we are being called synchronously
8661 // to avoid piling up things on the stack
8662 process.nextTick(cb, er);
8663 // this can emit finish, and it will always happen
8664 // after error
8665 process.nextTick(finishMaybe, stream, state);
8666 stream._writableState.errorEmitted = true;
8667 errorOrDestroy(stream, er);
8668 } else {
8669 // the caller expect this to happen before if
8670 // it is async
8671 cb(er);
8672 stream._writableState.errorEmitted = true;
8673 errorOrDestroy(stream, er);
8674 // this can emit finish, but finish must
8675 // always follow error
8676 finishMaybe(stream, state);
8677 }
8678}
8679function onwriteStateUpdate(state) {
8680 state.writing = false;
8681 state.writecb = null;
8682 state.length -= state.writelen;
8683 state.writelen = 0;
8684}
8685function onwrite(stream, er) {
8686 var state = stream._writableState;
8687 var sync = state.sync;
8688 var cb = state.writecb;
8689 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
8690 onwriteStateUpdate(state);
8691 if (er) onwriteError(stream, state, sync, er, cb);else {
8692 // Check if we're actually ready to finish, but don't emit yet
8693 var finished = needFinish(state) || stream.destroyed;
8694 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
8695 clearBuffer(stream, state);
8696 }
8697 if (sync) {
8698 process.nextTick(afterWrite, stream, state, finished, cb);
8699 } else {
8700 afterWrite(stream, state, finished, cb);
8701 }
8702 }
8703}
8704function afterWrite(stream, state, finished, cb) {
8705 if (!finished) onwriteDrain(stream, state);
8706 state.pendingcb--;
8707 cb();
8708 finishMaybe(stream, state);
8709}
8710
8711// Must force callback to be called on nextTick, so that we don't
8712// emit 'drain' before the write() consumer gets the 'false' return
8713// value, and has a chance to attach a 'drain' listener.
8714function onwriteDrain(stream, state) {
8715 if (state.length === 0 && state.needDrain) {
8716 state.needDrain = false;
8717 stream.emit('drain');
8718 }
8719}
8720
8721// if there's something in the buffer waiting, then process it
8722function clearBuffer(stream, state) {
8723 state.bufferProcessing = true;
8724 var entry = state.bufferedRequest;
8725 if (stream._writev && entry && entry.next) {
8726 // Fast case, write everything using _writev()
8727 var l = state.bufferedRequestCount;
8728 var buffer = new Array(l);
8729 var holder = state.corkedRequestsFree;
8730 holder.entry = entry;
8731 var count = 0;
8732 var allBuffers = true;
8733 while (entry) {
8734 buffer[count] = entry;
8735 if (!entry.isBuf) allBuffers = false;
8736 entry = entry.next;
8737 count += 1;
8738 }
8739 buffer.allBuffers = allBuffers;
8740 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
8741
8742 // doWrite is almost always async, defer these to save a bit of time
8743 // as the hot path ends with doWrite
8744 state.pendingcb++;
8745 state.lastBufferedRequest = null;
8746 if (holder.next) {
8747 state.corkedRequestsFree = holder.next;
8748 holder.next = null;
8749 } else {
8750 state.corkedRequestsFree = new CorkedRequest(state);
8751 }
8752 state.bufferedRequestCount = 0;
8753 } else {
8754 // Slow case, write chunks one-by-one
8755 while (entry) {
8756 var chunk = entry.chunk;
8757 var encoding = entry.encoding;
8758 var cb = entry.callback;
8759 var len = state.objectMode ? 1 : chunk.length;
8760 doWrite(stream, state, false, len, chunk, encoding, cb);
8761 entry = entry.next;
8762 state.bufferedRequestCount--;
8763 // if we didn't call the onwrite immediately, then
8764 // it means that we need to wait until it does.
8765 // also, that means that the chunk and cb are currently
8766 // being processed, so move the buffer counter past them.
8767 if (state.writing) {
8768 break;
8769 }
8770 }
8771 if (entry === null) state.lastBufferedRequest = null;
8772 }
8773 state.bufferedRequest = entry;
8774 state.bufferProcessing = false;
8775}
8776Writable.prototype._write = function (chunk, encoding, cb) {
8777 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
8778};
8779Writable.prototype._writev = null;
8780Writable.prototype.end = function (chunk, encoding, cb) {
8781 var state = this._writableState;
8782 if (typeof chunk === 'function') {
8783 cb = chunk;
8784 chunk = null;
8785 encoding = null;
8786 } else if (typeof encoding === 'function') {
8787 cb = encoding;
8788 encoding = null;
8789 }
8790 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
8791
8792 // .end() fully uncorks
8793 if (state.corked) {
8794 state.corked = 1;
8795 this.uncork();
8796 }
8797
8798 // ignore unnecessary end() calls.
8799 if (!state.ending) endWritable(this, state, cb);
8800 return this;
8801};
8802Object.defineProperty(Writable.prototype, 'writableLength', {
8803 // making it explicit this property is not enumerable
8804 // because otherwise some prototype manipulation in
8805 // userland will fail
8806 enumerable: false,
8807 get: function get() {
8808 return this._writableState.length;
8809 }
8810});
8811function needFinish(state) {
8812 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
8813}
8814function callFinal(stream, state) {
8815 stream._final(function (err) {
8816 state.pendingcb--;
8817 if (err) {
8818 errorOrDestroy(stream, err);
8819 }
8820 state.prefinished = true;
8821 stream.emit('prefinish');
8822 finishMaybe(stream, state);
8823 });
8824}
8825function prefinish(stream, state) {
8826 if (!state.prefinished && !state.finalCalled) {
8827 if (typeof stream._final === 'function' && !state.destroyed) {
8828 state.pendingcb++;
8829 state.finalCalled = true;
8830 process.nextTick(callFinal, stream, state);
8831 } else {
8832 state.prefinished = true;
8833 stream.emit('prefinish');
8834 }
8835 }
8836}
8837function finishMaybe(stream, state) {
8838 var need = needFinish(state);
8839 if (need) {
8840 prefinish(stream, state);
8841 if (state.pendingcb === 0) {
8842 state.finished = true;
8843 stream.emit('finish');
8844 if (state.autoDestroy) {
8845 // In case of duplex streams we need a way to detect
8846 // if the readable side is ready for autoDestroy as well
8847 var rState = stream._readableState;
8848 if (!rState || rState.autoDestroy && rState.endEmitted) {
8849 stream.destroy();
8850 }
8851 }
8852 }
8853 }
8854 return need;
8855}
8856function endWritable(stream, state, cb) {
8857 state.ending = true;
8858 finishMaybe(stream, state);
8859 if (cb) {
8860 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
8861 }
8862 state.ended = true;
8863 stream.writable = false;
8864}
8865function onCorkedFinish(corkReq, state, err) {
8866 var entry = corkReq.entry;
8867 corkReq.entry = null;
8868 while (entry) {
8869 var cb = entry.callback;
8870 state.pendingcb--;
8871 cb(err);
8872 entry = entry.next;
8873 }
8874
8875 // reuse the free corkReq.
8876 state.corkedRequestsFree.next = corkReq;
8877}
8878Object.defineProperty(Writable.prototype, 'destroyed', {
8879 // making it explicit this property is not enumerable
8880 // because otherwise some prototype manipulation in
8881 // userland will fail
8882 enumerable: false,
8883 get: function get() {
8884 if (this._writableState === undefined) {
8885 return false;
8886 }
8887 return this._writableState.destroyed;
8888 },
8889 set: function set(value) {
8890 // we ignore the value if the stream
8891 // has not been initialized yet
8892 if (!this._writableState) {
8893 return;
8894 }
8895
8896 // backward compatibility, the user is explicitly
8897 // managing destroyed
8898 this._writableState.destroyed = value;
8899 }
8900});
8901Writable.prototype.destroy = destroyImpl.destroy;
8902Writable.prototype._undestroy = destroyImpl.undestroy;
8903Writable.prototype._destroy = function (err, cb) {
8904 cb(err);
8905};
8906}).call(this)}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8907},{"../errors":52,"./_stream_duplex":53,"./internal/streams/destroy":60,"./internal/streams/state":64,"./internal/streams/stream":65,"_process":93,"buffer":4,"inherits":45,"util-deprecate":140}],58:[function(_dereq_,module,exports){
8908(function (process){(function (){
8909'use strict';
8910
8911var _Object$setPrototypeO;
8912function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
8913function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
8914function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
8915var finished = _dereq_('./end-of-stream');
8916var kLastResolve = Symbol('lastResolve');
8917var kLastReject = Symbol('lastReject');
8918var kError = Symbol('error');
8919var kEnded = Symbol('ended');
8920var kLastPromise = Symbol('lastPromise');
8921var kHandlePromise = Symbol('handlePromise');
8922var kStream = Symbol('stream');
8923function createIterResult(value, done) {
8924 return {
8925 value: value,
8926 done: done
8927 };
8928}
8929function readAndResolve(iter) {
8930 var resolve = iter[kLastResolve];
8931 if (resolve !== null) {
8932 var data = iter[kStream].read();
8933 // we defer if data is null
8934 // we can be expecting either 'end' or
8935 // 'error'
8936 if (data !== null) {
8937 iter[kLastPromise] = null;
8938 iter[kLastResolve] = null;
8939 iter[kLastReject] = null;
8940 resolve(createIterResult(data, false));
8941 }
8942 }
8943}
8944function onReadable(iter) {
8945 // we wait for the next tick, because it might
8946 // emit an error with process.nextTick
8947 process.nextTick(readAndResolve, iter);
8948}
8949function wrapForNext(lastPromise, iter) {
8950 return function (resolve, reject) {
8951 lastPromise.then(function () {
8952 if (iter[kEnded]) {
8953 resolve(createIterResult(undefined, true));
8954 return;
8955 }
8956 iter[kHandlePromise](resolve, reject);
8957 }, reject);
8958 };
8959}
8960var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
8961var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
8962 get stream() {
8963 return this[kStream];
8964 },
8965 next: function next() {
8966 var _this = this;
8967 // if we have detected an error in the meanwhile
8968 // reject straight away
8969 var error = this[kError];
8970 if (error !== null) {
8971 return Promise.reject(error);
8972 }
8973 if (this[kEnded]) {
8974 return Promise.resolve(createIterResult(undefined, true));
8975 }
8976 if (this[kStream].destroyed) {
8977 // We need to defer via nextTick because if .destroy(err) is
8978 // called, the error will be emitted via nextTick, and
8979 // we cannot guarantee that there is no error lingering around
8980 // waiting to be emitted.
8981 return new Promise(function (resolve, reject) {
8982 process.nextTick(function () {
8983 if (_this[kError]) {
8984 reject(_this[kError]);
8985 } else {
8986 resolve(createIterResult(undefined, true));
8987 }
8988 });
8989 });
8990 }
8991
8992 // if we have multiple next() calls
8993 // we will wait for the previous Promise to finish
8994 // this logic is optimized to support for await loops,
8995 // where next() is only called once at a time
8996 var lastPromise = this[kLastPromise];
8997 var promise;
8998 if (lastPromise) {
8999 promise = new Promise(wrapForNext(lastPromise, this));
9000 } else {
9001 // fast path needed to support multiple this.push()
9002 // without triggering the next() queue
9003 var data = this[kStream].read();
9004 if (data !== null) {
9005 return Promise.resolve(createIterResult(data, false));
9006 }
9007 promise = new Promise(this[kHandlePromise]);
9008 }
9009 this[kLastPromise] = promise;
9010 return promise;
9011 }
9012}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
9013 return this;
9014}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
9015 var _this2 = this;
9016 // destroy(err, cb) is a private API
9017 // we can guarantee we have that here, because we control the
9018 // Readable class this is attached to
9019 return new Promise(function (resolve, reject) {
9020 _this2[kStream].destroy(null, function (err) {
9021 if (err) {
9022 reject(err);
9023 return;
9024 }
9025 resolve(createIterResult(undefined, true));
9026 });
9027 });
9028}), _Object$setPrototypeO), AsyncIteratorPrototype);
9029var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
9030 var _Object$create;
9031 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
9032 value: stream,
9033 writable: true
9034 }), _defineProperty(_Object$create, kLastResolve, {
9035 value: null,
9036 writable: true
9037 }), _defineProperty(_Object$create, kLastReject, {
9038 value: null,
9039 writable: true
9040 }), _defineProperty(_Object$create, kError, {
9041 value: null,
9042 writable: true
9043 }), _defineProperty(_Object$create, kEnded, {
9044 value: stream._readableState.endEmitted,
9045 writable: true
9046 }), _defineProperty(_Object$create, kHandlePromise, {
9047 value: function value(resolve, reject) {
9048 var data = iterator[kStream].read();
9049 if (data) {
9050 iterator[kLastPromise] = null;
9051 iterator[kLastResolve] = null;
9052 iterator[kLastReject] = null;
9053 resolve(createIterResult(data, false));
9054 } else {
9055 iterator[kLastResolve] = resolve;
9056 iterator[kLastReject] = reject;
9057 }
9058 },
9059 writable: true
9060 }), _Object$create));
9061 iterator[kLastPromise] = null;
9062 finished(stream, function (err) {
9063 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
9064 var reject = iterator[kLastReject];
9065 // reject if we are waiting for data in the Promise
9066 // returned by next() and store the error
9067 if (reject !== null) {
9068 iterator[kLastPromise] = null;
9069 iterator[kLastResolve] = null;
9070 iterator[kLastReject] = null;
9071 reject(err);
9072 }
9073 iterator[kError] = err;
9074 return;
9075 }
9076 var resolve = iterator[kLastResolve];
9077 if (resolve !== null) {
9078 iterator[kLastPromise] = null;
9079 iterator[kLastResolve] = null;
9080 iterator[kLastReject] = null;
9081 resolve(createIterResult(undefined, true));
9082 }
9083 iterator[kEnded] = true;
9084 });
9085 stream.on('readable', onReadable.bind(null, iterator));
9086 return iterator;
9087};
9088module.exports = createReadableStreamAsyncIterator;
9089}).call(this)}).call(this,_dereq_('_process'))
9090},{"./end-of-stream":61,"_process":93}],59:[function(_dereq_,module,exports){
9091'use strict';
9092
9093function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
9094function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
9095function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
9096function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
9097function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
9098function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
9099function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
9100function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
9101var _require = _dereq_('buffer'),
9102 Buffer = _require.Buffer;
9103var _require2 = _dereq_('util'),
9104 inspect = _require2.inspect;
9105var custom = inspect && inspect.custom || 'inspect';
9106function copyBuffer(src, target, offset) {
9107 Buffer.prototype.copy.call(src, target, offset);
9108}
9109module.exports = /*#__PURE__*/function () {
9110 function BufferList() {
9111 _classCallCheck(this, BufferList);
9112 this.head = null;
9113 this.tail = null;
9114 this.length = 0;
9115 }
9116 _createClass(BufferList, [{
9117 key: "push",
9118 value: function push(v) {
9119 var entry = {
9120 data: v,
9121 next: null
9122 };
9123 if (this.length > 0) this.tail.next = entry;else this.head = entry;
9124 this.tail = entry;
9125 ++this.length;
9126 }
9127 }, {
9128 key: "unshift",
9129 value: function unshift(v) {
9130 var entry = {
9131 data: v,
9132 next: this.head
9133 };
9134 if (this.length === 0) this.tail = entry;
9135 this.head = entry;
9136 ++this.length;
9137 }
9138 }, {
9139 key: "shift",
9140 value: function shift() {
9141 if (this.length === 0) return;
9142 var ret = this.head.data;
9143 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
9144 --this.length;
9145 return ret;
9146 }
9147 }, {
9148 key: "clear",
9149 value: function clear() {
9150 this.head = this.tail = null;
9151 this.length = 0;
9152 }
9153 }, {
9154 key: "join",
9155 value: function join(s) {
9156 if (this.length === 0) return '';
9157 var p = this.head;
9158 var ret = '' + p.data;
9159 while (p = p.next) ret += s + p.data;
9160 return ret;
9161 }
9162 }, {
9163 key: "concat",
9164 value: function concat(n) {
9165 if (this.length === 0) return Buffer.alloc(0);
9166 var ret = Buffer.allocUnsafe(n >>> 0);
9167 var p = this.head;
9168 var i = 0;
9169 while (p) {
9170 copyBuffer(p.data, ret, i);
9171 i += p.data.length;
9172 p = p.next;
9173 }
9174 return ret;
9175 }
9176
9177 // Consumes a specified amount of bytes or characters from the buffered data.
9178 }, {
9179 key: "consume",
9180 value: function consume(n, hasStrings) {
9181 var ret;
9182 if (n < this.head.data.length) {
9183 // `slice` is the same for buffers and strings.
9184 ret = this.head.data.slice(0, n);
9185 this.head.data = this.head.data.slice(n);
9186 } else if (n === this.head.data.length) {
9187 // First chunk is a perfect match.
9188 ret = this.shift();
9189 } else {
9190 // Result spans more than one buffer.
9191 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
9192 }
9193 return ret;
9194 }
9195 }, {
9196 key: "first",
9197 value: function first() {
9198 return this.head.data;
9199 }
9200
9201 // Consumes a specified amount of characters from the buffered data.
9202 }, {
9203 key: "_getString",
9204 value: function _getString(n) {
9205 var p = this.head;
9206 var c = 1;
9207 var ret = p.data;
9208 n -= ret.length;
9209 while (p = p.next) {
9210 var str = p.data;
9211 var nb = n > str.length ? str.length : n;
9212 if (nb === str.length) ret += str;else ret += str.slice(0, n);
9213 n -= nb;
9214 if (n === 0) {
9215 if (nb === str.length) {
9216 ++c;
9217 if (p.next) this.head = p.next;else this.head = this.tail = null;
9218 } else {
9219 this.head = p;
9220 p.data = str.slice(nb);
9221 }
9222 break;
9223 }
9224 ++c;
9225 }
9226 this.length -= c;
9227 return ret;
9228 }
9229
9230 // Consumes a specified amount of bytes from the buffered data.
9231 }, {
9232 key: "_getBuffer",
9233 value: function _getBuffer(n) {
9234 var ret = Buffer.allocUnsafe(n);
9235 var p = this.head;
9236 var c = 1;
9237 p.data.copy(ret);
9238 n -= p.data.length;
9239 while (p = p.next) {
9240 var buf = p.data;
9241 var nb = n > buf.length ? buf.length : n;
9242 buf.copy(ret, ret.length - n, 0, nb);
9243 n -= nb;
9244 if (n === 0) {
9245 if (nb === buf.length) {
9246 ++c;
9247 if (p.next) this.head = p.next;else this.head = this.tail = null;
9248 } else {
9249 this.head = p;
9250 p.data = buf.slice(nb);
9251 }
9252 break;
9253 }
9254 ++c;
9255 }
9256 this.length -= c;
9257 return ret;
9258 }
9259
9260 // Make sure the linked list only shows the minimal necessary information.
9261 }, {
9262 key: custom,
9263 value: function value(_, options) {
9264 return inspect(this, _objectSpread(_objectSpread({}, options), {}, {
9265 // Only inspect one level.
9266 depth: 0,
9267 // It should not recurse.
9268 customInspect: false
9269 }));
9270 }
9271 }]);
9272 return BufferList;
9273}();
9274},{"buffer":4,"util":3}],60:[function(_dereq_,module,exports){
9275(function (process){(function (){
9276'use strict';
9277
9278// undocumented cb() API, needed for core, not for public API
9279function destroy(err, cb) {
9280 var _this = this;
9281 var readableDestroyed = this._readableState && this._readableState.destroyed;
9282 var writableDestroyed = this._writableState && this._writableState.destroyed;
9283 if (readableDestroyed || writableDestroyed) {
9284 if (cb) {
9285 cb(err);
9286 } else if (err) {
9287 if (!this._writableState) {
9288 process.nextTick(emitErrorNT, this, err);
9289 } else if (!this._writableState.errorEmitted) {
9290 this._writableState.errorEmitted = true;
9291 process.nextTick(emitErrorNT, this, err);
9292 }
9293 }
9294 return this;
9295 }
9296
9297 // we set destroyed to true before firing error callbacks in order
9298 // to make it re-entrance safe in case destroy() is called within callbacks
9299
9300 if (this._readableState) {
9301 this._readableState.destroyed = true;
9302 }
9303
9304 // if this is a duplex stream mark the writable part as destroyed as well
9305 if (this._writableState) {
9306 this._writableState.destroyed = true;
9307 }
9308 this._destroy(err || null, function (err) {
9309 if (!cb && err) {
9310 if (!_this._writableState) {
9311 process.nextTick(emitErrorAndCloseNT, _this, err);
9312 } else if (!_this._writableState.errorEmitted) {
9313 _this._writableState.errorEmitted = true;
9314 process.nextTick(emitErrorAndCloseNT, _this, err);
9315 } else {
9316 process.nextTick(emitCloseNT, _this);
9317 }
9318 } else if (cb) {
9319 process.nextTick(emitCloseNT, _this);
9320 cb(err);
9321 } else {
9322 process.nextTick(emitCloseNT, _this);
9323 }
9324 });
9325 return this;
9326}
9327function emitErrorAndCloseNT(self, err) {
9328 emitErrorNT(self, err);
9329 emitCloseNT(self);
9330}
9331function emitCloseNT(self) {
9332 if (self._writableState && !self._writableState.emitClose) return;
9333 if (self._readableState && !self._readableState.emitClose) return;
9334 self.emit('close');
9335}
9336function undestroy() {
9337 if (this._readableState) {
9338 this._readableState.destroyed = false;
9339 this._readableState.reading = false;
9340 this._readableState.ended = false;
9341 this._readableState.endEmitted = false;
9342 }
9343 if (this._writableState) {
9344 this._writableState.destroyed = false;
9345 this._writableState.ended = false;
9346 this._writableState.ending = false;
9347 this._writableState.finalCalled = false;
9348 this._writableState.prefinished = false;
9349 this._writableState.finished = false;
9350 this._writableState.errorEmitted = false;
9351 }
9352}
9353function emitErrorNT(self, err) {
9354 self.emit('error', err);
9355}
9356function errorOrDestroy(stream, err) {
9357 // We have tests that rely on errors being emitted
9358 // in the same tick, so changing this is semver major.
9359 // For now when you opt-in to autoDestroy we allow
9360 // the error to be emitted nextTick. In a future
9361 // semver major update we should change the default to this.
9362
9363 var rState = stream._readableState;
9364 var wState = stream._writableState;
9365 if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
9366}
9367module.exports = {
9368 destroy: destroy,
9369 undestroy: undestroy,
9370 errorOrDestroy: errorOrDestroy
9371};
9372}).call(this)}).call(this,_dereq_('_process'))
9373},{"_process":93}],61:[function(_dereq_,module,exports){
9374// Ported from https://github.com/mafintosh/end-of-stream with
9375// permission from the author, Mathias Buus (@mafintosh).
9376
9377'use strict';
9378
9379var ERR_STREAM_PREMATURE_CLOSE = _dereq_('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
9380function once(callback) {
9381 var called = false;
9382 return function () {
9383 if (called) return;
9384 called = true;
9385 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
9386 args[_key] = arguments[_key];
9387 }
9388 callback.apply(this, args);
9389 };
9390}
9391function noop() {}
9392function isRequest(stream) {
9393 return stream.setHeader && typeof stream.abort === 'function';
9394}
9395function eos(stream, opts, callback) {
9396 if (typeof opts === 'function') return eos(stream, null, opts);
9397 if (!opts) opts = {};
9398 callback = once(callback || noop);
9399 var readable = opts.readable || opts.readable !== false && stream.readable;
9400 var writable = opts.writable || opts.writable !== false && stream.writable;
9401 var onlegacyfinish = function onlegacyfinish() {
9402 if (!stream.writable) onfinish();
9403 };
9404 var writableEnded = stream._writableState && stream._writableState.finished;
9405 var onfinish = function onfinish() {
9406 writable = false;
9407 writableEnded = true;
9408 if (!readable) callback.call(stream);
9409 };
9410 var readableEnded = stream._readableState && stream._readableState.endEmitted;
9411 var onend = function onend() {
9412 readable = false;
9413 readableEnded = true;
9414 if (!writable) callback.call(stream);
9415 };
9416 var onerror = function onerror(err) {
9417 callback.call(stream, err);
9418 };
9419 var onclose = function onclose() {
9420 var err;
9421 if (readable && !readableEnded) {
9422 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9423 return callback.call(stream, err);
9424 }
9425 if (writable && !writableEnded) {
9426 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
9427 return callback.call(stream, err);
9428 }
9429 };
9430 var onrequest = function onrequest() {
9431 stream.req.on('finish', onfinish);
9432 };
9433 if (isRequest(stream)) {
9434 stream.on('complete', onfinish);
9435 stream.on('abort', onclose);
9436 if (stream.req) onrequest();else stream.on('request', onrequest);
9437 } else if (writable && !stream._writableState) {
9438 // legacy streams
9439 stream.on('end', onlegacyfinish);
9440 stream.on('close', onlegacyfinish);
9441 }
9442 stream.on('end', onend);
9443 stream.on('finish', onfinish);
9444 if (opts.error !== false) stream.on('error', onerror);
9445 stream.on('close', onclose);
9446 return function () {
9447 stream.removeListener('complete', onfinish);
9448 stream.removeListener('abort', onclose);
9449 stream.removeListener('request', onrequest);
9450 if (stream.req) stream.req.removeListener('finish', onfinish);
9451 stream.removeListener('end', onlegacyfinish);
9452 stream.removeListener('close', onlegacyfinish);
9453 stream.removeListener('finish', onfinish);
9454 stream.removeListener('end', onend);
9455 stream.removeListener('error', onerror);
9456 stream.removeListener('close', onclose);
9457 };
9458}
9459module.exports = eos;
9460},{"../../../errors":52}],62:[function(_dereq_,module,exports){
9461module.exports = function () {
9462 throw new Error('Readable.from is not available in the browser')
9463};
9464
9465},{}],63:[function(_dereq_,module,exports){
9466// Ported from https://github.com/mafintosh/pump with
9467// permission from the author, Mathias Buus (@mafintosh).
9468
9469'use strict';
9470
9471var eos;
9472function once(callback) {
9473 var called = false;
9474 return function () {
9475 if (called) return;
9476 called = true;
9477 callback.apply(void 0, arguments);
9478 };
9479}
9480var _require$codes = _dereq_('../../../errors').codes,
9481 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
9482 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
9483function noop(err) {
9484 // Rethrow the error if it exists to avoid swallowing it
9485 if (err) throw err;
9486}
9487function isRequest(stream) {
9488 return stream.setHeader && typeof stream.abort === 'function';
9489}
9490function destroyer(stream, reading, writing, callback) {
9491 callback = once(callback);
9492 var closed = false;
9493 stream.on('close', function () {
9494 closed = true;
9495 });
9496 if (eos === undefined) eos = _dereq_('./end-of-stream');
9497 eos(stream, {
9498 readable: reading,
9499 writable: writing
9500 }, function (err) {
9501 if (err) return callback(err);
9502 closed = true;
9503 callback();
9504 });
9505 var destroyed = false;
9506 return function (err) {
9507 if (closed) return;
9508 if (destroyed) return;
9509 destroyed = true;
9510
9511 // request.destroy just do .end - .abort is what we want
9512 if (isRequest(stream)) return stream.abort();
9513 if (typeof stream.destroy === 'function') return stream.destroy();
9514 callback(err || new ERR_STREAM_DESTROYED('pipe'));
9515 };
9516}
9517function call(fn) {
9518 fn();
9519}
9520function pipe(from, to) {
9521 return from.pipe(to);
9522}
9523function popCallback(streams) {
9524 if (!streams.length) return noop;
9525 if (typeof streams[streams.length - 1] !== 'function') return noop;
9526 return streams.pop();
9527}
9528function pipeline() {
9529 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
9530 streams[_key] = arguments[_key];
9531 }
9532 var callback = popCallback(streams);
9533 if (Array.isArray(streams[0])) streams = streams[0];
9534 if (streams.length < 2) {
9535 throw new ERR_MISSING_ARGS('streams');
9536 }
9537 var error;
9538 var destroys = streams.map(function (stream, i) {
9539 var reading = i < streams.length - 1;
9540 var writing = i > 0;
9541 return destroyer(stream, reading, writing, function (err) {
9542 if (!error) error = err;
9543 if (err) destroys.forEach(call);
9544 if (reading) return;
9545 destroys.forEach(call);
9546 callback(error);
9547 });
9548 });
9549 return streams.reduce(pipe);
9550}
9551module.exports = pipeline;
9552},{"../../../errors":52,"./end-of-stream":61}],64:[function(_dereq_,module,exports){
9553'use strict';
9554
9555var ERR_INVALID_OPT_VALUE = _dereq_('../../../errors').codes.ERR_INVALID_OPT_VALUE;
9556function highWaterMarkFrom(options, isDuplex, duplexKey) {
9557 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
9558}
9559function getHighWaterMark(state, options, duplexKey, isDuplex) {
9560 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
9561 if (hwm != null) {
9562 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
9563 var name = isDuplex ? duplexKey : 'highWaterMark';
9564 throw new ERR_INVALID_OPT_VALUE(name, hwm);
9565 }
9566 return Math.floor(hwm);
9567 }
9568
9569 // Default value
9570 return state.objectMode ? 16 : 16 * 1024;
9571}
9572module.exports = {
9573 getHighWaterMark: getHighWaterMark
9574};
9575},{"../../../errors":52}],65:[function(_dereq_,module,exports){
9576module.exports = _dereq_('events').EventEmitter;
9577
9578},{"events":33}],66:[function(_dereq_,module,exports){
9579exports = module.exports = _dereq_('./lib/_stream_readable.js');
9580exports.Stream = exports;
9581exports.Readable = exports;
9582exports.Writable = _dereq_('./lib/_stream_writable.js');
9583exports.Duplex = _dereq_('./lib/_stream_duplex.js');
9584exports.Transform = _dereq_('./lib/_stream_transform.js');
9585exports.PassThrough = _dereq_('./lib/_stream_passthrough.js');
9586exports.finished = _dereq_('./lib/internal/streams/end-of-stream.js');
9587exports.pipeline = _dereq_('./lib/internal/streams/pipeline.js');
9588
9589},{"./lib/_stream_duplex.js":53,"./lib/_stream_passthrough.js":54,"./lib/_stream_readable.js":55,"./lib/_stream_transform.js":56,"./lib/_stream_writable.js":57,"./lib/internal/streams/end-of-stream.js":61,"./lib/internal/streams/pipeline.js":63}],67:[function(_dereq_,module,exports){
9590'use strict'
9591
9592// For (old) browser support
9593var xtend = _dereq_('xtend')
9594var assign = _dereq_('xtend/mutable')
9595
9596module.exports = function supports () {
9597 var manifest = xtend.apply(null, arguments)
9598
9599 return assign(manifest, {
9600 // Features of abstract-leveldown
9601 bufferKeys: manifest.bufferKeys || false,
9602 snapshots: manifest.snapshots || false,
9603 permanence: manifest.permanence || false,
9604 seek: manifest.seek || false,
9605 clear: manifest.clear || false,
9606
9607 // Features of abstract-leveldown that levelup doesn't have
9608 status: manifest.status || false,
9609
9610 // Features of disk-based implementations
9611 createIfMissing: manifest.createIfMissing || false,
9612 errorIfExists: manifest.errorIfExists || false,
9613
9614 // Features of level(up) that abstract-leveldown doesn't have yet
9615 deferredOpen: manifest.deferredOpen || false,
9616 openCallback: manifest.openCallback || false,
9617 promises: manifest.promises || false,
9618 streams: manifest.streams || false,
9619 encodings: manifest.encodings || false,
9620
9621 // Methods that are not part of abstract-leveldown or levelup
9622 additionalMethods: xtend(manifest.additionalMethods)
9623 })
9624}
9625
9626},{"xtend":160,"xtend/mutable":161}],68:[function(_dereq_,module,exports){
9627var WriteError = _dereq_('level-errors').WriteError
9628var promisify = _dereq_('./promisify')
9629var getCallback = _dereq_('./common').getCallback
9630var getOptions = _dereq_('./common').getOptions
9631
9632function Batch (levelup) {
9633 // TODO (next major): remove this._levelup alias
9634 this.db = this._levelup = levelup
9635 this.batch = levelup.db.batch()
9636 this.ops = []
9637 this.length = 0
9638}
9639
9640Batch.prototype.put = function (key, value) {
9641 try {
9642 this.batch.put(key, value)
9643 } catch (e) {
9644 throw new WriteError(e)
9645 }
9646
9647 this.ops.push({ type: 'put', key: key, value: value })
9648 this.length++
9649
9650 return this
9651}
9652
9653Batch.prototype.del = function (key) {
9654 try {
9655 this.batch.del(key)
9656 } catch (err) {
9657 throw new WriteError(err)
9658 }
9659
9660 this.ops.push({ type: 'del', key: key })
9661 this.length++
9662
9663 return this
9664}
9665
9666Batch.prototype.clear = function () {
9667 try {
9668 this.batch.clear()
9669 } catch (err) {
9670 throw new WriteError(err)
9671 }
9672
9673 this.ops = []
9674 this.length = 0
9675
9676 return this
9677}
9678
9679Batch.prototype.write = function (options, callback) {
9680 var levelup = this._levelup
9681 var ops = this.ops
9682 var promise
9683
9684 callback = getCallback(options, callback)
9685
9686 if (!callback) {
9687 callback = promisify()
9688 promise = callback.promise
9689 }
9690
9691 options = getOptions(options)
9692
9693 try {
9694 this.batch.write(options, function (err) {
9695 if (err) { return callback(new WriteError(err)) }
9696 levelup.emit('batch', ops)
9697 callback()
9698 })
9699 } catch (err) {
9700 throw new WriteError(err)
9701 }
9702
9703 return promise
9704}
9705
9706module.exports = Batch
9707
9708},{"./common":69,"./promisify":71,"level-errors":50}],69:[function(_dereq_,module,exports){
9709exports.getCallback = function (options, callback) {
9710 return typeof options === 'function' ? options : callback
9711}
9712
9713exports.getOptions = function (options) {
9714 return typeof options === 'object' && options !== null ? options : {}
9715}
9716
9717},{}],70:[function(_dereq_,module,exports){
9718(function (process){(function (){
9719var EventEmitter = _dereq_('events').EventEmitter
9720var inherits = _dereq_('util').inherits
9721var extend = _dereq_('xtend')
9722var DeferredLevelDOWN = _dereq_('deferred-leveldown')
9723var IteratorStream = _dereq_('level-iterator-stream')
9724var Batch = _dereq_('./batch')
9725var errors = _dereq_('level-errors')
9726var supports = _dereq_('level-supports')
9727var assert = _dereq_('assert')
9728var promisify = _dereq_('./promisify')
9729var getCallback = _dereq_('./common').getCallback
9730var getOptions = _dereq_('./common').getOptions
9731
9732var WriteError = errors.WriteError
9733var ReadError = errors.ReadError
9734var NotFoundError = errors.NotFoundError
9735var OpenError = errors.OpenError
9736var InitializationError = errors.InitializationError
9737
9738// Possible AbstractLevelDOWN#status values:
9739// - 'new' - newly created, not opened or closed
9740// - 'opening' - waiting for the database to be opened, post open()
9741// - 'open' - successfully opened the database, available for use
9742// - 'closing' - waiting for the database to be closed, post close()
9743// - 'closed' - database has been successfully closed, should not be
9744// used except for another open() operation
9745
9746function LevelUP (db, options, callback) {
9747 if (!(this instanceof LevelUP)) {
9748 return new LevelUP(db, options, callback)
9749 }
9750
9751 var error
9752 var self = this
9753
9754 EventEmitter.call(this)
9755 this.setMaxListeners(Infinity)
9756
9757 if (typeof options === 'function') {
9758 callback = options
9759 options = {}
9760 }
9761
9762 options = options || {}
9763
9764 if (!db || typeof db !== 'object') {
9765 error = new InitializationError('First argument must be an abstract-leveldown compliant store')
9766 if (typeof callback === 'function') {
9767 return process.nextTick(callback, error)
9768 }
9769 throw error
9770 }
9771
9772 assert.strictEqual(typeof db.status, 'string', '.status required, old abstract-leveldown')
9773
9774 this.options = getOptions(options)
9775 this._db = db
9776 this.db = new DeferredLevelDOWN(db)
9777 this.open(callback || function (err) {
9778 if (err) self.emit('error', err)
9779 })
9780
9781 // Create manifest based on deferred-leveldown's
9782 this.supports = supports(this.db.supports, {
9783 status: false,
9784 deferredOpen: true,
9785 openCallback: true,
9786 promises: true,
9787 streams: true
9788 })
9789
9790 // Experimental: enrich levelup interface
9791 Object.keys(this.supports.additionalMethods).forEach(function (method) {
9792 if (this[method] != null) return
9793
9794 // Don't do this.db[method].bind() because this.db is dynamic.
9795 this[method] = function () {
9796 return this.db[method].apply(this.db, arguments)
9797 }
9798 }, this)
9799}
9800
9801LevelUP.prototype.emit = EventEmitter.prototype.emit
9802LevelUP.prototype.once = EventEmitter.prototype.once
9803inherits(LevelUP, EventEmitter)
9804
9805LevelUP.prototype.open = function (opts, callback) {
9806 var self = this
9807 var promise
9808
9809 if (typeof opts === 'function') {
9810 callback = opts
9811 opts = null
9812 }
9813
9814 if (!callback) {
9815 callback = promisify()
9816 promise = callback.promise
9817 }
9818
9819 if (!opts) {
9820 opts = this.options
9821 }
9822
9823 if (this.isOpen()) {
9824 process.nextTick(callback, null, self)
9825 return promise
9826 }
9827
9828 if (this._isOpening()) {
9829 this.once('open', function () { callback(null, self) })
9830 return promise
9831 }
9832
9833 this.emit('opening')
9834
9835 this.db.open(opts, function (err) {
9836 if (err) {
9837 return callback(new OpenError(err))
9838 }
9839 self.db = self._db
9840 callback(null, self)
9841 self.emit('open')
9842 self.emit('ready')
9843 })
9844
9845 return promise
9846}
9847
9848LevelUP.prototype.close = function (callback) {
9849 var self = this
9850 var promise
9851
9852 if (!callback) {
9853 callback = promisify()
9854 promise = callback.promise
9855 }
9856
9857 if (this.isOpen()) {
9858 this.db.close(function () {
9859 self.emit('closed')
9860 callback.apply(null, arguments)
9861 })
9862 this.emit('closing')
9863 this.db = new DeferredLevelDOWN(this._db)
9864 } else if (this.isClosed()) {
9865 process.nextTick(callback)
9866 } else if (this.db.status === 'closing') {
9867 this.once('closed', callback)
9868 } else if (this._isOpening()) {
9869 this.once('open', function () {
9870 self.close(callback)
9871 })
9872 }
9873
9874 return promise
9875}
9876
9877LevelUP.prototype.isOpen = function () {
9878 return this.db.status === 'open'
9879}
9880
9881LevelUP.prototype._isOpening = function () {
9882 return this.db.status === 'opening'
9883}
9884
9885LevelUP.prototype.isClosed = function () {
9886 return (/^clos|new/).test(this.db.status)
9887}
9888
9889LevelUP.prototype.get = function (key, options, callback) {
9890 var promise
9891
9892 callback = getCallback(options, callback)
9893
9894 if (!callback) {
9895 callback = promisify()
9896 promise = callback.promise
9897 }
9898
9899 if (maybeError(this, callback)) { return promise }
9900
9901 options = getOptions(options)
9902
9903 this.db.get(key, options, function (err, value) {
9904 if (err) {
9905 if ((/notfound/i).test(err) || err.notFound) {
9906 err = new NotFoundError('Key not found in database [' + key + ']', err)
9907 } else {
9908 err = new ReadError(err)
9909 }
9910 return callback(err)
9911 }
9912 callback(null, value)
9913 })
9914
9915 return promise
9916}
9917
9918LevelUP.prototype.put = function (key, value, options, callback) {
9919 var self = this
9920 var promise
9921
9922 callback = getCallback(options, callback)
9923
9924 if (!callback) {
9925 callback = promisify()
9926 promise = callback.promise
9927 }
9928
9929 if (maybeError(this, callback)) { return promise }
9930
9931 options = getOptions(options)
9932
9933 this.db.put(key, value, options, function (err) {
9934 if (err) {
9935 return callback(new WriteError(err))
9936 }
9937 self.emit('put', key, value)
9938 callback()
9939 })
9940
9941 return promise
9942}
9943
9944LevelUP.prototype.del = function (key, options, callback) {
9945 var self = this
9946 var promise
9947
9948 callback = getCallback(options, callback)
9949
9950 if (!callback) {
9951 callback = promisify()
9952 promise = callback.promise
9953 }
9954
9955 if (maybeError(this, callback)) { return promise }
9956
9957 options = getOptions(options)
9958
9959 this.db.del(key, options, function (err) {
9960 if (err) {
9961 return callback(new WriteError(err))
9962 }
9963 self.emit('del', key)
9964 callback()
9965 })
9966
9967 return promise
9968}
9969
9970LevelUP.prototype.batch = function (arr, options, callback) {
9971 if (!arguments.length) {
9972 return new Batch(this)
9973 }
9974
9975 var self = this
9976 var promise
9977
9978 if (typeof arr === 'function') callback = arr
9979 else callback = getCallback(options, callback)
9980
9981 if (!callback) {
9982 callback = promisify()
9983 promise = callback.promise
9984 }
9985
9986 if (maybeError(this, callback)) { return promise }
9987
9988 options = getOptions(options)
9989
9990 this.db.batch(arr, options, function (err) {
9991 if (err) {
9992 return callback(new WriteError(err))
9993 }
9994 self.emit('batch', arr)
9995 callback()
9996 })
9997
9998 return promise
9999}
10000
10001LevelUP.prototype.iterator = function (options) {
10002 return this.db.iterator(options)
10003}
10004
10005LevelUP.prototype.clear = function (options, callback) {
10006 var self = this
10007 var promise
10008
10009 callback = getCallback(options, callback)
10010 options = getOptions(options)
10011
10012 if (!callback) {
10013 callback = promisify()
10014 promise = callback.promise
10015 }
10016
10017 if (maybeError(this, callback)) {
10018 return promise
10019 }
10020
10021 this.db.clear(options, function (err) {
10022 if (err) {
10023 return callback(new WriteError(err))
10024 }
10025 self.emit('clear', options)
10026 callback()
10027 })
10028
10029 return promise
10030}
10031
10032LevelUP.prototype.readStream =
10033LevelUP.prototype.createReadStream = function (options) {
10034 options = extend({ keys: true, values: true }, options)
10035 if (typeof options.limit !== 'number') { options.limit = -1 }
10036 return new IteratorStream(this.db.iterator(options), options)
10037}
10038
10039LevelUP.prototype.keyStream =
10040LevelUP.prototype.createKeyStream = function (options) {
10041 return this.createReadStream(extend(options, { keys: true, values: false }))
10042}
10043
10044LevelUP.prototype.valueStream =
10045LevelUP.prototype.createValueStream = function (options) {
10046 return this.createReadStream(extend(options, { keys: false, values: true }))
10047}
10048
10049LevelUP.prototype.toString = function () {
10050 return 'LevelUP'
10051}
10052
10053LevelUP.prototype.type = 'levelup'
10054
10055function maybeError (db, callback) {
10056 if (!db._isOpening() && !db.isOpen()) {
10057 process.nextTick(callback, new ReadError('Database is not open'))
10058 return true
10059 }
10060}
10061
10062LevelUP.errors = errors
10063module.exports = LevelUP.default = LevelUP
10064
10065}).call(this)}).call(this,_dereq_('_process'))
10066},{"./batch":68,"./common":69,"./promisify":71,"_process":93,"assert":1,"deferred-leveldown":9,"events":33,"level-errors":50,"level-iterator-stream":51,"level-supports":67,"util":143,"xtend":160}],71:[function(_dereq_,module,exports){
10067function promisify () {
10068 var callback
10069 var promise = new Promise(function (resolve, reject) {
10070 callback = function callback (err, value) {
10071 if (err) reject(err)
10072 else resolve(value)
10073 }
10074 })
10075 callback.promise = promise
10076 return callback
10077}
10078
10079module.exports = promisify
10080
10081},{}],72:[function(_dereq_,module,exports){
10082(function (Buffer){(function (){
10083
10084exports.compare = function (a, b) {
10085
10086 if(Buffer.isBuffer(a)) {
10087 var l = Math.min(a.length, b.length)
10088 for(var i = 0; i < l; i++) {
10089 var cmp = a[i] - b[i]
10090 if(cmp) return cmp
10091 }
10092 return a.length - b.length
10093 }
10094
10095 return a < b ? -1 : a > b ? 1 : 0
10096}
10097
10098// to be compatible with the current abstract-leveldown tests
10099// nullish or empty strings.
10100// I could use !!val but I want to permit numbers and booleans,
10101// if possible.
10102
10103function isDef (val) {
10104 return val !== undefined && val !== ''
10105}
10106
10107function has (range, name) {
10108 return Object.hasOwnProperty.call(range, name)
10109}
10110
10111function hasKey(range, name) {
10112 return Object.hasOwnProperty.call(range, name) && name
10113}
10114
10115var lowerBoundKey = exports.lowerBoundKey = function (range) {
10116 return (
10117 hasKey(range, 'gt')
10118 || hasKey(range, 'gte')
10119 || hasKey(range, 'min')
10120 || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
10121 || undefined
10122 )
10123}
10124
10125var lowerBound = exports.lowerBound = function (range, def) {
10126 var k = lowerBoundKey(range)
10127 return k ? range[k] : def
10128}
10129
10130var lowerBoundInclusive = exports.lowerBoundInclusive = function (range) {
10131 return has(range, 'gt') ? false : true
10132}
10133
10134var upperBoundInclusive = exports.upperBoundInclusive =
10135 function (range) {
10136 return (has(range, 'lt') /*&& !range.maxEx*/) ? false : true
10137 }
10138
10139var lowerBoundExclusive = exports.lowerBoundExclusive =
10140 function (range) {
10141 return !lowerBoundInclusive(range)
10142 }
10143
10144var upperBoundExclusive = exports.upperBoundExclusive =
10145 function (range) {
10146 return !upperBoundInclusive(range)
10147 }
10148
10149var upperBoundKey = exports.upperBoundKey = function (range) {
10150 return (
10151 hasKey(range, 'lt')
10152 || hasKey(range, 'lte')
10153 || hasKey(range, 'max')
10154 || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
10155 || undefined
10156 )
10157}
10158
10159var upperBound = exports.upperBound = function (range, def) {
10160 var k = upperBoundKey(range)
10161 return k ? range[k] : def
10162}
10163
10164exports.start = function (range, def) {
10165 return range.reverse ? upperBound(range, def) : lowerBound(range, def)
10166}
10167exports.end = function (range, def) {
10168 return range.reverse ? lowerBound(range, def) : upperBound(range, def)
10169}
10170exports.startInclusive = function (range) {
10171 return (
10172 range.reverse
10173 ? upperBoundInclusive(range)
10174 : lowerBoundInclusive(range)
10175 )
10176}
10177exports.endInclusive = function (range) {
10178 return (
10179 range.reverse
10180 ? lowerBoundInclusive(range)
10181 : upperBoundInclusive(range)
10182 )
10183}
10184
10185function id (e) { return e }
10186
10187exports.toLtgt = function (range, _range, map, lower, upper) {
10188 _range = _range || {}
10189 map = map || id
10190 var defaults = arguments.length > 3
10191 var lb = exports.lowerBoundKey(range)
10192 var ub = exports.upperBoundKey(range)
10193 if(lb) {
10194 if(lb === 'gt') _range.gt = map(range.gt, false)
10195 else _range.gte = map(range[lb], false)
10196 }
10197 else if(defaults)
10198 _range.gte = map(lower, false)
10199
10200 if(ub) {
10201 if(ub === 'lt') _range.lt = map(range.lt, true)
10202 else _range.lte = map(range[ub], true)
10203 }
10204 else if(defaults)
10205 _range.lte = map(upper, true)
10206
10207 if(range.reverse != null)
10208 _range.reverse = !!range.reverse
10209
10210 //if range was used mutably
10211 //(in level-sublevel it's part of an options object
10212 //that has more properties on it.)
10213 if(has(_range, 'max')) delete _range.max
10214 if(has(_range, 'min')) delete _range.min
10215 if(has(_range, 'start')) delete _range.start
10216 if(has(_range, 'end')) delete _range.end
10217
10218 return _range
10219}
10220
10221exports.contains = function (range, key, compare) {
10222 compare = compare || exports.compare
10223
10224 var lb = lowerBound(range)
10225 if(isDef(lb)) {
10226 var cmp = compare(key, lb)
10227 if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
10228 return false
10229 }
10230
10231 var ub = upperBound(range)
10232 if(isDef(ub)) {
10233 var cmp = compare(key, ub)
10234 if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
10235 return false
10236 }
10237
10238 return true
10239}
10240
10241exports.filter = function (range, compare) {
10242 return function (key) {
10243 return exports.contains(range, key, compare)
10244 }
10245}
10246
10247
10248
10249}).call(this)}).call(this,{"isBuffer":_dereq_("../is-buffer/index.js")})
10250},{"../is-buffer/index.js":46}],73:[function(_dereq_,module,exports){
10251arguments[4][14][0].apply(exports,arguments)
10252},{"dup":14,"immediate":80}],74:[function(_dereq_,module,exports){
10253var inherits = _dereq_('inherits')
10254var AbstractLevelDOWN = _dereq_('abstract-leveldown').AbstractLevelDOWN
10255var AbstractIterator = _dereq_('abstract-leveldown').AbstractIterator
10256var ltgt = _dereq_('ltgt')
10257var createRBT = _dereq_('functional-red-black-tree')
10258var Buffer = _dereq_('safe-buffer').Buffer
10259var globalStore = {}
10260
10261// In Node, use global.setImmediate. In the browser, use a consistent
10262// microtask library to give consistent microtask experience to all browsers
10263var setImmediate = _dereq_('./immediate')
10264
10265function gt (value) {
10266 return ltgt.compare(value, this._end) > 0
10267}
10268
10269function gte (value) {
10270 return ltgt.compare(value, this._end) >= 0
10271}
10272
10273function lt (value) {
10274 return ltgt.compare(value, this._end) < 0
10275}
10276
10277function lte (value) {
10278 return ltgt.compare(value, this._end) <= 0
10279}
10280
10281function MemIterator (db, options) {
10282 AbstractIterator.call(this, db)
10283 this._limit = options.limit
10284
10285 if (this._limit === -1) this._limit = Infinity
10286
10287 var tree = db._store[db._location]
10288
10289 this.keyAsBuffer = options.keyAsBuffer !== false
10290 this.valueAsBuffer = options.valueAsBuffer !== false
10291 this._reverse = options.reverse
10292 this._options = options
10293 this._done = 0
10294
10295 if (!this._reverse) {
10296 this._incr = 'next'
10297 this._start = ltgt.lowerBound(options)
10298 this._end = ltgt.upperBound(options)
10299
10300 if (typeof this._start === 'undefined') {
10301 this._tree = tree.begin
10302 } else if (ltgt.lowerBoundInclusive(options)) {
10303 this._tree = tree.ge(this._start)
10304 } else {
10305 this._tree = tree.gt(this._start)
10306 }
10307
10308 if (this._end) {
10309 if (ltgt.upperBoundInclusive(options)) {
10310 this._test = lte
10311 } else {
10312 this._test = lt
10313 }
10314 }
10315 } else {
10316 this._incr = 'prev'
10317 this._start = ltgt.upperBound(options)
10318 this._end = ltgt.lowerBound(options)
10319
10320 if (typeof this._start === 'undefined') {
10321 this._tree = tree.end
10322 } else if (ltgt.upperBoundInclusive(options)) {
10323 this._tree = tree.le(this._start)
10324 } else {
10325 this._tree = tree.lt(this._start)
10326 }
10327
10328 if (this._end) {
10329 if (ltgt.lowerBoundInclusive(options)) {
10330 this._test = gte
10331 } else {
10332 this._test = gt
10333 }
10334 }
10335 }
10336}
10337
10338inherits(MemIterator, AbstractIterator)
10339
10340MemIterator.prototype._next = function (callback) {
10341 var key
10342 var value
10343
10344 if (this._done++ >= this._limit) return setImmediate(callback)
10345 if (!this._tree.valid) return setImmediate(callback)
10346
10347 key = this._tree.key
10348 value = this._tree.value
10349
10350 if (!this._test(key)) return setImmediate(callback)
10351
10352 if (this.keyAsBuffer) key = Buffer.from(key)
10353 if (this.valueAsBuffer) value = Buffer.from(value)
10354
10355 this._tree[this._incr]()
10356
10357 setImmediate(function callNext () {
10358 callback(null, key, value)
10359 })
10360}
10361
10362MemIterator.prototype._test = function () {
10363 return true
10364}
10365
10366function MemDOWN (location) {
10367 if (!(this instanceof MemDOWN)) return new MemDOWN(location)
10368
10369 AbstractLevelDOWN.call(this, typeof location === 'string' ? location : '')
10370
10371 this._location = this.location ? '$' + this.location : '_tree'
10372 this._store = this.location ? globalStore : this
10373 this._store[this._location] =
10374 this._store[this._location] || createRBT(ltgt.compare)
10375}
10376
10377MemDOWN.clearGlobalStore = function (strict) {
10378 if (strict) {
10379 Object.keys(globalStore).forEach(function (key) {
10380 delete globalStore[key]
10381 })
10382 } else {
10383 globalStore = {}
10384 }
10385}
10386
10387inherits(MemDOWN, AbstractLevelDOWN)
10388
10389MemDOWN.prototype._open = function (options, callback) {
10390 var self = this
10391 setImmediate(function callNext () {
10392 callback(null, self)
10393 })
10394}
10395
10396MemDOWN.prototype._put = function (key, value, options, callback) {
10397 if (typeof value === 'undefined' || value === null) value = ''
10398
10399 var iter = this._store[this._location].find(key)
10400
10401 if (iter.valid) {
10402 this._store[this._location] = iter.update(value)
10403 } else {
10404 this._store[this._location] = this._store[this._location].insert(key, value)
10405 }
10406
10407 setImmediate(callback)
10408}
10409
10410MemDOWN.prototype._get = function (key, options, callback) {
10411 var value = this._store[this._location].get(key)
10412
10413 if (typeof value === 'undefined') {
10414 // 'NotFound' error, consistent with LevelDOWN API
10415 return setImmediate(function callNext () {
10416 callback(new Error('NotFound'))
10417 })
10418 }
10419
10420 if (options.asBuffer !== false && !this._isBuffer(value)) {
10421 value = Buffer.from(String(value))
10422 }
10423
10424 setImmediate(function callNext () {
10425 callback(null, value)
10426 })
10427}
10428
10429MemDOWN.prototype._del = function (key, options, callback) {
10430 this._store[this._location] = this._store[this._location].remove(key)
10431 setImmediate(callback)
10432}
10433
10434MemDOWN.prototype._batch = function (array, options, callback) {
10435 var i = -1
10436 var key
10437 var value
10438 var iter
10439 var len = array.length
10440 var tree = this._store[this._location]
10441
10442 while (++i < len) {
10443 if (!array[i]) continue
10444
10445 key = this._isBuffer(array[i].key) ? array[i].key : String(array[i].key)
10446 iter = tree.find(key)
10447
10448 if (array[i].type === 'put') {
10449 value = this._isBuffer(array[i].value)
10450 ? array[i].value
10451 : String(array[i].value)
10452 tree = iter.valid ? iter.update(value) : tree.insert(key, value)
10453 } else {
10454 tree = iter.remove()
10455 }
10456 }
10457
10458 this._store[this._location] = tree
10459
10460 setImmediate(callback)
10461}
10462
10463MemDOWN.prototype._iterator = function (options) {
10464 return new MemIterator(this, options)
10465}
10466
10467MemDOWN.prototype._isBuffer = function (obj) {
10468 return Buffer.isBuffer(obj)
10469}
10470
10471MemDOWN.destroy = function (name, callback) {
10472 var key = '$' + name
10473
10474 if (key in globalStore) {
10475 delete globalStore[key]
10476 }
10477
10478 setImmediate(callback)
10479}
10480
10481module.exports = MemDOWN.default = MemDOWN
10482
10483},{"./immediate":73,"abstract-leveldown":78,"functional-red-black-tree":36,"inherits":45,"ltgt":72,"safe-buffer":86}],75:[function(_dereq_,module,exports){
10484(function (process){(function (){
10485/* Copyright (c) 2017 Rod Vagg, MIT License */
10486
10487function AbstractChainedBatch (db) {
10488 this._db = db
10489 this._operations = []
10490 this._written = false
10491}
10492
10493AbstractChainedBatch.prototype._serializeKey = function (key) {
10494 return this._db._serializeKey(key)
10495}
10496
10497AbstractChainedBatch.prototype._serializeValue = function (value) {
10498 return this._db._serializeValue(value)
10499}
10500
10501AbstractChainedBatch.prototype._checkWritten = function () {
10502 if (this._written)
10503 throw new Error('write() already called on this batch')
10504}
10505
10506AbstractChainedBatch.prototype.put = function (key, value) {
10507 this._checkWritten()
10508
10509 var err = this._db._checkKey(key, 'key', this._db._isBuffer)
10510 if (err)
10511 throw err
10512
10513 key = this._serializeKey(key)
10514 value = this._serializeValue(value)
10515
10516 if (typeof this._put == 'function' )
10517 this._put(key, value)
10518 else
10519 this._operations.push({ type: 'put', key: key, value: value })
10520
10521 return this
10522}
10523
10524AbstractChainedBatch.prototype.del = function (key) {
10525 this._checkWritten()
10526
10527 var err = this._db._checkKey(key, 'key', this._db._isBuffer)
10528 if (err) throw err
10529
10530 key = this._serializeKey(key)
10531
10532 if (typeof this._del == 'function' )
10533 this._del(key)
10534 else
10535 this._operations.push({ type: 'del', key: key })
10536
10537 return this
10538}
10539
10540AbstractChainedBatch.prototype.clear = function () {
10541 this._checkWritten()
10542
10543 this._operations = []
10544
10545 if (typeof this._clear == 'function' )
10546 this._clear()
10547
10548 return this
10549}
10550
10551AbstractChainedBatch.prototype.write = function (options, callback) {
10552 this._checkWritten()
10553
10554 if (typeof options == 'function')
10555 callback = options
10556 if (typeof callback != 'function')
10557 throw new Error('write() requires a callback argument')
10558 if (typeof options != 'object')
10559 options = {}
10560
10561 this._written = true
10562
10563 if (typeof this._write == 'function' )
10564 return this._write(callback)
10565
10566 if (typeof this._db._batch == 'function')
10567 return this._db._batch(this._operations, options, callback)
10568
10569 process.nextTick(callback)
10570}
10571
10572module.exports = AbstractChainedBatch
10573
10574}).call(this)}).call(this,_dereq_('_process'))
10575},{"_process":93}],76:[function(_dereq_,module,exports){
10576(function (process){(function (){
10577/* Copyright (c) 2017 Rod Vagg, MIT License */
10578
10579function AbstractIterator (db) {
10580 this.db = db
10581 this._ended = false
10582 this._nexting = false
10583}
10584
10585AbstractIterator.prototype.next = function (callback) {
10586 var self = this
10587
10588 if (typeof callback != 'function')
10589 throw new Error('next() requires a callback argument')
10590
10591 if (self._ended)
10592 return callback(new Error('cannot call next() after end()'))
10593 if (self._nexting)
10594 return callback(new Error('cannot call next() before previous next() has completed'))
10595
10596 self._nexting = true
10597 if (typeof self._next == 'function') {
10598 return self._next(function () {
10599 self._nexting = false
10600 callback.apply(null, arguments)
10601 })
10602 }
10603
10604 process.nextTick(function () {
10605 self._nexting = false
10606 callback()
10607 })
10608}
10609
10610AbstractIterator.prototype.end = function (callback) {
10611 if (typeof callback != 'function')
10612 throw new Error('end() requires a callback argument')
10613
10614 if (this._ended)
10615 return callback(new Error('end() already called on iterator'))
10616
10617 this._ended = true
10618
10619 if (typeof this._end == 'function')
10620 return this._end(callback)
10621
10622 process.nextTick(callback)
10623}
10624
10625module.exports = AbstractIterator
10626
10627}).call(this)}).call(this,_dereq_('_process'))
10628},{"_process":93}],77:[function(_dereq_,module,exports){
10629(function (Buffer,process){(function (){
10630/* Copyright (c) 2017 Rod Vagg, MIT License */
10631
10632var xtend = _dereq_('xtend')
10633 , AbstractIterator = _dereq_('./abstract-iterator')
10634 , AbstractChainedBatch = _dereq_('./abstract-chained-batch')
10635
10636function AbstractLevelDOWN (location) {
10637 if (!arguments.length || location === undefined)
10638 throw new Error('constructor requires at least a location argument')
10639
10640 if (typeof location != 'string')
10641 throw new Error('constructor requires a location string argument')
10642
10643 this.location = location
10644 this.status = 'new'
10645}
10646
10647AbstractLevelDOWN.prototype.open = function (options, callback) {
10648 var self = this
10649 , oldStatus = this.status
10650
10651 if (typeof options == 'function')
10652 callback = options
10653
10654 if (typeof callback != 'function')
10655 throw new Error('open() requires a callback argument')
10656
10657 if (typeof options != 'object')
10658 options = {}
10659
10660 options.createIfMissing = options.createIfMissing != false
10661 options.errorIfExists = !!options.errorIfExists
10662
10663 if (typeof this._open == 'function') {
10664 this.status = 'opening'
10665 this._open(options, function (err) {
10666 if (err) {
10667 self.status = oldStatus
10668 return callback(err)
10669 }
10670 self.status = 'open'
10671 callback()
10672 })
10673 } else {
10674 this.status = 'open'
10675 process.nextTick(callback)
10676 }
10677}
10678
10679AbstractLevelDOWN.prototype.close = function (callback) {
10680 var self = this
10681 , oldStatus = this.status
10682
10683 if (typeof callback != 'function')
10684 throw new Error('close() requires a callback argument')
10685
10686 if (typeof this._close == 'function') {
10687 this.status = 'closing'
10688 this._close(function (err) {
10689 if (err) {
10690 self.status = oldStatus
10691 return callback(err)
10692 }
10693 self.status = 'closed'
10694 callback()
10695 })
10696 } else {
10697 this.status = 'closed'
10698 process.nextTick(callback)
10699 }
10700}
10701
10702AbstractLevelDOWN.prototype.get = function (key, options, callback) {
10703 var err
10704
10705 if (typeof options == 'function')
10706 callback = options
10707
10708 if (typeof callback != 'function')
10709 throw new Error('get() requires a callback argument')
10710
10711 if (err = this._checkKey(key, 'key'))
10712 return callback(err)
10713
10714 key = this._serializeKey(key)
10715
10716 if (typeof options != 'object')
10717 options = {}
10718
10719 options.asBuffer = options.asBuffer != false
10720
10721 if (typeof this._get == 'function')
10722 return this._get(key, options, callback)
10723
10724 process.nextTick(function () { callback(new Error('NotFound')) })
10725}
10726
10727AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
10728 var err
10729
10730 if (typeof options == 'function')
10731 callback = options
10732
10733 if (typeof callback != 'function')
10734 throw new Error('put() requires a callback argument')
10735
10736 if (err = this._checkKey(key, 'key'))
10737 return callback(err)
10738
10739 key = this._serializeKey(key)
10740 value = this._serializeValue(value)
10741
10742 if (typeof options != 'object')
10743 options = {}
10744
10745 if (typeof this._put == 'function')
10746 return this._put(key, value, options, callback)
10747
10748 process.nextTick(callback)
10749}
10750
10751AbstractLevelDOWN.prototype.del = function (key, options, callback) {
10752 var err
10753
10754 if (typeof options == 'function')
10755 callback = options
10756
10757 if (typeof callback != 'function')
10758 throw new Error('del() requires a callback argument')
10759
10760 if (err = this._checkKey(key, 'key'))
10761 return callback(err)
10762
10763 key = this._serializeKey(key)
10764
10765 if (typeof options != 'object')
10766 options = {}
10767
10768 if (typeof this._del == 'function')
10769 return this._del(key, options, callback)
10770
10771 process.nextTick(callback)
10772}
10773
10774AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
10775 if (!arguments.length)
10776 return this._chainedBatch()
10777
10778 if (typeof options == 'function')
10779 callback = options
10780
10781 if (typeof array == 'function')
10782 callback = array
10783
10784 if (typeof callback != 'function')
10785 throw new Error('batch(array) requires a callback argument')
10786
10787 if (!Array.isArray(array))
10788 return callback(new Error('batch(array) requires an array argument'))
10789
10790 if (!options || typeof options != 'object')
10791 options = {}
10792
10793 var i = 0
10794 , l = array.length
10795 , e
10796 , err
10797
10798 for (; i < l; i++) {
10799 e = array[i]
10800 if (typeof e != 'object')
10801 continue
10802
10803 if (err = this._checkKey(e.type, 'type'))
10804 return callback(err)
10805
10806 if (err = this._checkKey(e.key, 'key'))
10807 return callback(err)
10808 }
10809
10810 if (typeof this._batch == 'function')
10811 return this._batch(array, options, callback)
10812
10813 process.nextTick(callback)
10814}
10815
10816//TODO: remove from here, not a necessary primitive
10817AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
10818 if ( start == null
10819 || end == null
10820 || typeof start == 'function'
10821 || typeof end == 'function') {
10822 throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
10823 }
10824
10825 if (typeof callback != 'function')
10826 throw new Error('approximateSize() requires a callback argument')
10827
10828 start = this._serializeKey(start)
10829 end = this._serializeKey(end)
10830
10831 if (typeof this._approximateSize == 'function')
10832 return this._approximateSize(start, end, callback)
10833
10834 process.nextTick(function () {
10835 callback(null, 0)
10836 })
10837}
10838
10839AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
10840 var self = this
10841
10842 options = xtend(options)
10843
10844 ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
10845 if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
10846 delete options[o]
10847 })
10848
10849 options.reverse = !!options.reverse
10850 options.keys = options.keys != false
10851 options.values = options.values != false
10852 options.limit = 'limit' in options ? options.limit : -1
10853 options.keyAsBuffer = options.keyAsBuffer != false
10854 options.valueAsBuffer = options.valueAsBuffer != false
10855
10856 return options
10857}
10858
10859AbstractLevelDOWN.prototype.iterator = function (options) {
10860 if (typeof options != 'object')
10861 options = {}
10862
10863 options = this._setupIteratorOptions(options)
10864
10865 if (typeof this._iterator == 'function')
10866 return this._iterator(options)
10867
10868 return new AbstractIterator(this)
10869}
10870
10871AbstractLevelDOWN.prototype._chainedBatch = function () {
10872 return new AbstractChainedBatch(this)
10873}
10874
10875AbstractLevelDOWN.prototype._isBuffer = function (obj) {
10876 return Buffer.isBuffer(obj)
10877}
10878
10879AbstractLevelDOWN.prototype._serializeKey = function (key) {
10880 return this._isBuffer(key)
10881 ? key
10882 : String(key)
10883}
10884
10885AbstractLevelDOWN.prototype._serializeValue = function (value) {
10886 if (value == null) return ''
10887 return this._isBuffer(value) || process.browser ? value : String(value)
10888}
10889
10890AbstractLevelDOWN.prototype._checkKey = function (obj, type) {
10891 if (obj === null || obj === undefined)
10892 return new Error(type + ' cannot be `null` or `undefined`')
10893
10894 if (this._isBuffer(obj) && obj.length === 0)
10895 return new Error(type + ' cannot be an empty Buffer')
10896 else if (String(obj) === '')
10897 return new Error(type + ' cannot be an empty String')
10898}
10899
10900module.exports = AbstractLevelDOWN
10901
10902}).call(this)}).call(this,{"isBuffer":_dereq_("../../../is-buffer/index.js")},_dereq_('_process'))
10903},{"../../../is-buffer/index.js":46,"./abstract-chained-batch":75,"./abstract-iterator":76,"_process":93,"xtend":160}],78:[function(_dereq_,module,exports){
10904exports.AbstractLevelDOWN = _dereq_('./abstract-leveldown')
10905exports.AbstractIterator = _dereq_('./abstract-iterator')
10906exports.AbstractChainedBatch = _dereq_('./abstract-chained-batch')
10907exports.isLevelDOWN = _dereq_('./is-leveldown')
10908
10909},{"./abstract-chained-batch":75,"./abstract-iterator":76,"./abstract-leveldown":77,"./is-leveldown":79}],79:[function(_dereq_,module,exports){
10910var AbstractLevelDOWN = _dereq_('./abstract-leveldown')
10911
10912function isLevelDOWN (db) {
10913 if (!db || typeof db !== 'object')
10914 return false
10915 return Object.keys(AbstractLevelDOWN.prototype).filter(function (name) {
10916 // TODO remove approximateSize check when method is gone
10917 return name[0] != '_' && name != 'approximateSize'
10918 }).every(function (name) {
10919 return typeof db[name] == 'function'
10920 })
10921}
10922
10923module.exports = isLevelDOWN
10924
10925},{"./abstract-leveldown":77}],80:[function(_dereq_,module,exports){
10926arguments[4][15][0].apply(exports,arguments)
10927},{"./messageChannel":81,"./mutation.js":82,"./nextTick":3,"./queueMicrotask":83,"./stateChange":84,"./timeout":85,"dup":15}],81:[function(_dereq_,module,exports){
10928arguments[4][16][0].apply(exports,arguments)
10929},{"dup":16}],82:[function(_dereq_,module,exports){
10930arguments[4][17][0].apply(exports,arguments)
10931},{"dup":17}],83:[function(_dereq_,module,exports){
10932arguments[4][18][0].apply(exports,arguments)
10933},{"dup":18}],84:[function(_dereq_,module,exports){
10934arguments[4][19][0].apply(exports,arguments)
10935},{"dup":19}],85:[function(_dereq_,module,exports){
10936arguments[4][20][0].apply(exports,arguments)
10937},{"dup":20}],86:[function(_dereq_,module,exports){
10938/* eslint-disable node/no-deprecated-api */
10939var buffer = _dereq_('buffer')
10940var Buffer = buffer.Buffer
10941
10942// alternative to using Object.keys for old browsers
10943function copyProps (src, dst) {
10944 for (var key in src) {
10945 dst[key] = src[key]
10946 }
10947}
10948if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
10949 module.exports = buffer
10950} else {
10951 // Copy properties from require('buffer')
10952 copyProps(buffer, exports)
10953 exports.Buffer = SafeBuffer
10954}
10955
10956function SafeBuffer (arg, encodingOrOffset, length) {
10957 return Buffer(arg, encodingOrOffset, length)
10958}
10959
10960// Copy static methods from Buffer
10961copyProps(Buffer, SafeBuffer)
10962
10963SafeBuffer.from = function (arg, encodingOrOffset, length) {
10964 if (typeof arg === 'number') {
10965 throw new TypeError('Argument must not be a number')
10966 }
10967 return Buffer(arg, encodingOrOffset, length)
10968}
10969
10970SafeBuffer.alloc = function (size, fill, encoding) {
10971 if (typeof size !== 'number') {
10972 throw new TypeError('Argument must be a number')
10973 }
10974 var buf = Buffer(size)
10975 if (fill !== undefined) {
10976 if (typeof encoding === 'string') {
10977 buf.fill(fill, encoding)
10978 } else {
10979 buf.fill(fill)
10980 }
10981 } else {
10982 buf.fill(0)
10983 }
10984 return buf
10985}
10986
10987SafeBuffer.allocUnsafe = function (size) {
10988 if (typeof size !== 'number') {
10989 throw new TypeError('Argument must be a number')
10990 }
10991 return Buffer(size)
10992}
10993
10994SafeBuffer.allocUnsafeSlow = function (size) {
10995 if (typeof size !== 'number') {
10996 throw new TypeError('Argument must be a number')
10997 }
10998 return buffer.SlowBuffer(size)
10999}
11000
11001},{"buffer":4}],87:[function(_dereq_,module,exports){
11002'use strict';
11003
11004var keysShim;
11005if (!Object.keys) {
11006 // modified from https://github.com/es-shims/es5-shim
11007 var has = Object.prototype.hasOwnProperty;
11008 var toStr = Object.prototype.toString;
11009 var isArgs = _dereq_('./isArguments'); // eslint-disable-line global-require
11010 var isEnumerable = Object.prototype.propertyIsEnumerable;
11011 var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
11012 var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
11013 var dontEnums = [
11014 'toString',
11015 'toLocaleString',
11016 'valueOf',
11017 'hasOwnProperty',
11018 'isPrototypeOf',
11019 'propertyIsEnumerable',
11020 'constructor'
11021 ];
11022 var equalsConstructorPrototype = function (o) {
11023 var ctor = o.constructor;
11024 return ctor && ctor.prototype === o;
11025 };
11026 var excludedKeys = {
11027 $applicationCache: true,
11028 $console: true,
11029 $external: true,
11030 $frame: true,
11031 $frameElement: true,
11032 $frames: true,
11033 $innerHeight: true,
11034 $innerWidth: true,
11035 $onmozfullscreenchange: true,
11036 $onmozfullscreenerror: true,
11037 $outerHeight: true,
11038 $outerWidth: true,
11039 $pageXOffset: true,
11040 $pageYOffset: true,
11041 $parent: true,
11042 $scrollLeft: true,
11043 $scrollTop: true,
11044 $scrollX: true,
11045 $scrollY: true,
11046 $self: true,
11047 $webkitIndexedDB: true,
11048 $webkitStorageInfo: true,
11049 $window: true
11050 };
11051 var hasAutomationEqualityBug = (function () {
11052 /* global window */
11053 if (typeof window === 'undefined') { return false; }
11054 for (var k in window) {
11055 try {
11056 if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
11057 try {
11058 equalsConstructorPrototype(window[k]);
11059 } catch (e) {
11060 return true;
11061 }
11062 }
11063 } catch (e) {
11064 return true;
11065 }
11066 }
11067 return false;
11068 }());
11069 var equalsConstructorPrototypeIfNotBuggy = function (o) {
11070 /* global window */
11071 if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
11072 return equalsConstructorPrototype(o);
11073 }
11074 try {
11075 return equalsConstructorPrototype(o);
11076 } catch (e) {
11077 return false;
11078 }
11079 };
11080
11081 keysShim = function keys(object) {
11082 var isObject = object !== null && typeof object === 'object';
11083 var isFunction = toStr.call(object) === '[object Function]';
11084 var isArguments = isArgs(object);
11085 var isString = isObject && toStr.call(object) === '[object String]';
11086 var theKeys = [];
11087
11088 if (!isObject && !isFunction && !isArguments) {
11089 throw new TypeError('Object.keys called on a non-object');
11090 }
11091
11092 var skipProto = hasProtoEnumBug && isFunction;
11093 if (isString && object.length > 0 && !has.call(object, 0)) {
11094 for (var i = 0; i < object.length; ++i) {
11095 theKeys.push(String(i));
11096 }
11097 }
11098
11099 if (isArguments && object.length > 0) {
11100 for (var j = 0; j < object.length; ++j) {
11101 theKeys.push(String(j));
11102 }
11103 } else {
11104 for (var name in object) {
11105 if (!(skipProto && name === 'prototype') && has.call(object, name)) {
11106 theKeys.push(String(name));
11107 }
11108 }
11109 }
11110
11111 if (hasDontEnumBug) {
11112 var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
11113
11114 for (var k = 0; k < dontEnums.length; ++k) {
11115 if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
11116 theKeys.push(dontEnums[k]);
11117 }
11118 }
11119 }
11120 return theKeys;
11121 };
11122}
11123module.exports = keysShim;
11124
11125},{"./isArguments":89}],88:[function(_dereq_,module,exports){
11126'use strict';
11127
11128var slice = Array.prototype.slice;
11129var isArgs = _dereq_('./isArguments');
11130
11131var origKeys = Object.keys;
11132var keysShim = origKeys ? function keys(o) { return origKeys(o); } : _dereq_('./implementation');
11133
11134var originalKeys = Object.keys;
11135
11136keysShim.shim = function shimObjectKeys() {
11137 if (Object.keys) {
11138 var keysWorksWithArguments = (function () {
11139 // Safari 5.0 bug
11140 var args = Object.keys(arguments);
11141 return args && args.length === arguments.length;
11142 }(1, 2));
11143 if (!keysWorksWithArguments) {
11144 Object.keys = function keys(object) { // eslint-disable-line func-name-matching
11145 if (isArgs(object)) {
11146 return originalKeys(slice.call(object));
11147 }
11148 return originalKeys(object);
11149 };
11150 }
11151 } else {
11152 Object.keys = keysShim;
11153 }
11154 return Object.keys || keysShim;
11155};
11156
11157module.exports = keysShim;
11158
11159},{"./implementation":87,"./isArguments":89}],89:[function(_dereq_,module,exports){
11160'use strict';
11161
11162var toStr = Object.prototype.toString;
11163
11164module.exports = function isArguments(value) {
11165 var str = toStr.call(value);
11166 var isArgs = str === '[object Arguments]';
11167 if (!isArgs) {
11168 isArgs = str !== '[object Array]' &&
11169 value !== null &&
11170 typeof value === 'object' &&
11171 typeof value.length === 'number' &&
11172 value.length >= 0 &&
11173 toStr.call(value.callee) === '[object Function]';
11174 }
11175 return isArgs;
11176};
11177
11178},{}],90:[function(_dereq_,module,exports){
11179'use strict';
11180
11181// modified from https://github.com/es-shims/es6-shim
11182var objectKeys = _dereq_('object-keys');
11183var hasSymbols = _dereq_('has-symbols/shams')();
11184var callBound = _dereq_('call-bind/callBound');
11185var toObject = Object;
11186var $push = callBound('Array.prototype.push');
11187var $propIsEnumerable = callBound('Object.prototype.propertyIsEnumerable');
11188var originalGetSymbols = hasSymbols ? Object.getOwnPropertySymbols : null;
11189
11190// eslint-disable-next-line no-unused-vars
11191module.exports = function assign(target, source1) {
11192 if (target == null) { throw new TypeError('target must be an object'); }
11193 var to = toObject(target); // step 1
11194 if (arguments.length === 1) {
11195 return to; // step 2
11196 }
11197 for (var s = 1; s < arguments.length; ++s) {
11198 var from = toObject(arguments[s]); // step 3.a.i
11199
11200 // step 3.a.ii:
11201 var keys = objectKeys(from);
11202 var getSymbols = hasSymbols && (Object.getOwnPropertySymbols || originalGetSymbols);
11203 if (getSymbols) {
11204 var syms = getSymbols(from);
11205 for (var j = 0; j < syms.length; ++j) {
11206 var key = syms[j];
11207 if ($propIsEnumerable(from, key)) {
11208 $push(keys, key);
11209 }
11210 }
11211 }
11212
11213 // step 3.a.iii:
11214 for (var i = 0; i < keys.length; ++i) {
11215 var nextKey = keys[i];
11216 if ($propIsEnumerable(from, nextKey)) { // step 3.a.iii.2
11217 var propValue = from[nextKey]; // step 3.a.iii.2.a
11218 to[nextKey] = propValue; // step 3.a.iii.2.b
11219 }
11220 }
11221 }
11222
11223 return to; // step 4
11224};
11225
11226},{"call-bind/callBound":5,"has-symbols/shams":42,"object-keys":88}],91:[function(_dereq_,module,exports){
11227'use strict';
11228
11229var implementation = _dereq_('./implementation');
11230
11231var lacksProperEnumerationOrder = function () {
11232 if (!Object.assign) {
11233 return false;
11234 }
11235 /*
11236 * v8, specifically in node 4.x, has a bug with incorrect property enumeration order
11237 * note: this does not detect the bug unless there's 20 characters
11238 */
11239 var str = 'abcdefghijklmnopqrst';
11240 var letters = str.split('');
11241 var map = {};
11242 for (var i = 0; i < letters.length; ++i) {
11243 map[letters[i]] = letters[i];
11244 }
11245 var obj = Object.assign({}, map);
11246 var actual = '';
11247 for (var k in obj) {
11248 actual += k;
11249 }
11250 return str !== actual;
11251};
11252
11253var assignHasPendingExceptions = function () {
11254 if (!Object.assign || !Object.preventExtensions) {
11255 return false;
11256 }
11257 /*
11258 * Firefox 37 still has "pending exception" logic in its Object.assign implementation,
11259 * which is 72% slower than our shim, and Firefox 40's native implementation.
11260 */
11261 var thrower = Object.preventExtensions({ 1: 2 });
11262 try {
11263 Object.assign(thrower, 'xy');
11264 } catch (e) {
11265 return thrower[1] === 'y';
11266 }
11267 return false;
11268};
11269
11270module.exports = function getPolyfill() {
11271 if (!Object.assign) {
11272 return implementation;
11273 }
11274 if (lacksProperEnumerationOrder()) {
11275 return implementation;
11276 }
11277 if (assignHasPendingExceptions()) {
11278 return implementation;
11279 }
11280 return Object.assign;
11281};
11282
11283},{"./implementation":90}],92:[function(_dereq_,module,exports){
11284(function (process){(function (){
11285'use strict';
11286
11287if (typeof process === 'undefined' ||
11288 !process.version ||
11289 process.version.indexOf('v0.') === 0 ||
11290 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
11291 module.exports = { nextTick: nextTick };
11292} else {
11293 module.exports = process
11294}
11295
11296function nextTick(fn, arg1, arg2, arg3) {
11297 if (typeof fn !== 'function') {
11298 throw new TypeError('"callback" argument must be a function');
11299 }
11300 var len = arguments.length;
11301 var args, i;
11302 switch (len) {
11303 case 0:
11304 case 1:
11305 return process.nextTick(fn);
11306 case 2:
11307 return process.nextTick(function afterTickOne() {
11308 fn.call(null, arg1);
11309 });
11310 case 3:
11311 return process.nextTick(function afterTickTwo() {
11312 fn.call(null, arg1, arg2);
11313 });
11314 case 4:
11315 return process.nextTick(function afterTickThree() {
11316 fn.call(null, arg1, arg2, arg3);
11317 });
11318 default:
11319 args = new Array(len - 1);
11320 i = 0;
11321 while (i < args.length) {
11322 args[i++] = arguments[i];
11323 }
11324 return process.nextTick(function afterTick() {
11325 fn.apply(null, args);
11326 });
11327 }
11328}
11329
11330
11331}).call(this)}).call(this,_dereq_('_process'))
11332},{"_process":93}],93:[function(_dereq_,module,exports){
11333// shim for using process in browser
11334var process = module.exports = {};
11335
11336// cached from whatever global is present so that test runners that stub it
11337// don't break things. But we need to wrap it in a try catch in case it is
11338// wrapped in strict mode code which doesn't define any globals. It's inside a
11339// function because try/catches deoptimize in certain engines.
11340
11341var cachedSetTimeout;
11342var cachedClearTimeout;
11343
11344function defaultSetTimout() {
11345 throw new Error('setTimeout has not been defined');
11346}
11347function defaultClearTimeout () {
11348 throw new Error('clearTimeout has not been defined');
11349}
11350(function () {
11351 try {
11352 if (typeof setTimeout === 'function') {
11353 cachedSetTimeout = setTimeout;
11354 } else {
11355 cachedSetTimeout = defaultSetTimout;
11356 }
11357 } catch (e) {
11358 cachedSetTimeout = defaultSetTimout;
11359 }
11360 try {
11361 if (typeof clearTimeout === 'function') {
11362 cachedClearTimeout = clearTimeout;
11363 } else {
11364 cachedClearTimeout = defaultClearTimeout;
11365 }
11366 } catch (e) {
11367 cachedClearTimeout = defaultClearTimeout;
11368 }
11369} ())
11370function runTimeout(fun) {
11371 if (cachedSetTimeout === setTimeout) {
11372 //normal enviroments in sane situations
11373 return setTimeout(fun, 0);
11374 }
11375 // if setTimeout wasn't available but was latter defined
11376 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
11377 cachedSetTimeout = setTimeout;
11378 return setTimeout(fun, 0);
11379 }
11380 try {
11381 // when when somebody has screwed with setTimeout but no I.E. maddness
11382 return cachedSetTimeout(fun, 0);
11383 } catch(e){
11384 try {
11385 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11386 return cachedSetTimeout.call(null, fun, 0);
11387 } catch(e){
11388 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
11389 return cachedSetTimeout.call(this, fun, 0);
11390 }
11391 }
11392
11393
11394}
11395function runClearTimeout(marker) {
11396 if (cachedClearTimeout === clearTimeout) {
11397 //normal enviroments in sane situations
11398 return clearTimeout(marker);
11399 }
11400 // if clearTimeout wasn't available but was latter defined
11401 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
11402 cachedClearTimeout = clearTimeout;
11403 return clearTimeout(marker);
11404 }
11405 try {
11406 // when when somebody has screwed with setTimeout but no I.E. maddness
11407 return cachedClearTimeout(marker);
11408 } catch (e){
11409 try {
11410 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
11411 return cachedClearTimeout.call(null, marker);
11412 } catch (e){
11413 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
11414 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
11415 return cachedClearTimeout.call(this, marker);
11416 }
11417 }
11418
11419
11420
11421}
11422var queue = [];
11423var draining = false;
11424var currentQueue;
11425var queueIndex = -1;
11426
11427function cleanUpNextTick() {
11428 if (!draining || !currentQueue) {
11429 return;
11430 }
11431 draining = false;
11432 if (currentQueue.length) {
11433 queue = currentQueue.concat(queue);
11434 } else {
11435 queueIndex = -1;
11436 }
11437 if (queue.length) {
11438 drainQueue();
11439 }
11440}
11441
11442function drainQueue() {
11443 if (draining) {
11444 return;
11445 }
11446 var timeout = runTimeout(cleanUpNextTick);
11447 draining = true;
11448
11449 var len = queue.length;
11450 while(len) {
11451 currentQueue = queue;
11452 queue = [];
11453 while (++queueIndex < len) {
11454 if (currentQueue) {
11455 currentQueue[queueIndex].run();
11456 }
11457 }
11458 queueIndex = -1;
11459 len = queue.length;
11460 }
11461 currentQueue = null;
11462 draining = false;
11463 runClearTimeout(timeout);
11464}
11465
11466process.nextTick = function (fun) {
11467 var args = new Array(arguments.length - 1);
11468 if (arguments.length > 1) {
11469 for (var i = 1; i < arguments.length; i++) {
11470 args[i - 1] = arguments[i];
11471 }
11472 }
11473 queue.push(new Item(fun, args));
11474 if (queue.length === 1 && !draining) {
11475 runTimeout(drainQueue);
11476 }
11477};
11478
11479// v8 likes predictible objects
11480function Item(fun, array) {
11481 this.fun = fun;
11482 this.array = array;
11483}
11484Item.prototype.run = function () {
11485 this.fun.apply(null, this.array);
11486};
11487process.title = 'browser';
11488process.browser = true;
11489process.env = {};
11490process.argv = [];
11491process.version = ''; // empty string to avoid regexp issues
11492process.versions = {};
11493
11494function noop() {}
11495
11496process.on = noop;
11497process.addListener = noop;
11498process.once = noop;
11499process.off = noop;
11500process.removeListener = noop;
11501process.removeAllListeners = noop;
11502process.emit = noop;
11503process.prependListener = noop;
11504process.prependOnceListener = noop;
11505
11506process.listeners = function (name) { return [] }
11507
11508process.binding = function (name) {
11509 throw new Error('process.binding is not supported');
11510};
11511
11512process.cwd = function () { return '/' };
11513process.chdir = function (dir) {
11514 throw new Error('process.chdir is not supported');
11515};
11516process.umask = function() { return 0; };
11517
11518},{}],94:[function(_dereq_,module,exports){
11519/*!
11520 * prr
11521 * (c) 2013 Rod Vagg <rod@vagg.org>
11522 * https://github.com/rvagg/prr
11523 * License: MIT
11524 */
11525
11526(function (name, context, definition) {
11527 if (typeof module != 'undefined' && module.exports)
11528 module.exports = definition()
11529 else
11530 context[name] = definition()
11531})('prr', this, function() {
11532
11533 var setProperty = typeof Object.defineProperty == 'function'
11534 ? function (obj, key, options) {
11535 Object.defineProperty(obj, key, options)
11536 return obj
11537 }
11538 : function (obj, key, options) { // < es5
11539 obj[key] = options.value
11540 return obj
11541 }
11542
11543 , makeOptions = function (value, options) {
11544 var oo = typeof options == 'object'
11545 , os = !oo && typeof options == 'string'
11546 , op = function (p) {
11547 return oo
11548 ? !!options[p]
11549 : os
11550 ? options.indexOf(p[0]) > -1
11551 : false
11552 }
11553
11554 return {
11555 enumerable : op('enumerable')
11556 , configurable : op('configurable')
11557 , writable : op('writable')
11558 , value : value
11559 }
11560 }
11561
11562 , prr = function (obj, key, value, options) {
11563 var k
11564
11565 options = makeOptions(value, options)
11566
11567 if (typeof key == 'object') {
11568 for (k in key) {
11569 if (Object.hasOwnProperty.call(key, k)) {
11570 options.value = key[k]
11571 setProperty(obj, k, options)
11572 }
11573 }
11574 return obj
11575 }
11576
11577 return setProperty(obj, key, options)
11578 }
11579
11580 return prr
11581})
11582},{}],95:[function(_dereq_,module,exports){
11583(function (process){(function (){
11584// Copyright Joyent, Inc. and other Node contributors.
11585//
11586// Permission is hereby granted, free of charge, to any person obtaining a
11587// copy of this software and associated documentation files (the
11588// "Software"), to deal in the Software without restriction, including
11589// without limitation the rights to use, copy, modify, merge, publish,
11590// distribute, sublicense, and/or sell copies of the Software, and to permit
11591// persons to whom the Software is furnished to do so, subject to the
11592// following conditions:
11593//
11594// The above copyright notice and this permission notice shall be included
11595// in all copies or substantial portions of the Software.
11596//
11597// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11598// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11599// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11600// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11601// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11602// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11603// USE OR OTHER DEALINGS IN THE SOFTWARE.
11604
11605// a duplex stream is just a stream that is both readable and writable.
11606// Since JS doesn't have multiple prototypal inheritance, this class
11607// prototypally inherits from Readable, and then parasitically from
11608// Writable.
11609
11610module.exports = Duplex;
11611
11612/*<replacement>*/
11613var objectKeys = Object.keys || function (obj) {
11614 var keys = [];
11615 for (var key in obj) keys.push(key);
11616 return keys;
11617}
11618/*</replacement>*/
11619
11620
11621/*<replacement>*/
11622var util = _dereq_('core-util-is');
11623util.inherits = _dereq_('inherits');
11624/*</replacement>*/
11625
11626var Readable = _dereq_('./_stream_readable');
11627var Writable = _dereq_('./_stream_writable');
11628
11629util.inherits(Duplex, Readable);
11630
11631forEach(objectKeys(Writable.prototype), function(method) {
11632 if (!Duplex.prototype[method])
11633 Duplex.prototype[method] = Writable.prototype[method];
11634});
11635
11636function Duplex(options) {
11637 if (!(this instanceof Duplex))
11638 return new Duplex(options);
11639
11640 Readable.call(this, options);
11641 Writable.call(this, options);
11642
11643 if (options && options.readable === false)
11644 this.readable = false;
11645
11646 if (options && options.writable === false)
11647 this.writable = false;
11648
11649 this.allowHalfOpen = true;
11650 if (options && options.allowHalfOpen === false)
11651 this.allowHalfOpen = false;
11652
11653 this.once('end', onend);
11654}
11655
11656// the no-half-open enforcer
11657function onend() {
11658 // if we allow half-open state, or if the writable side ended,
11659 // then we're ok.
11660 if (this.allowHalfOpen || this._writableState.ended)
11661 return;
11662
11663 // no more data can be written.
11664 // But allow more writes to happen in this tick.
11665 process.nextTick(this.end.bind(this));
11666}
11667
11668function forEach (xs, f) {
11669 for (var i = 0, l = xs.length; i < l; i++) {
11670 f(xs[i], i);
11671 }
11672}
11673
11674}).call(this)}).call(this,_dereq_('_process'))
11675},{"./_stream_readable":97,"./_stream_writable":99,"_process":93,"core-util-is":7,"inherits":45}],96:[function(_dereq_,module,exports){
11676// Copyright Joyent, Inc. and other Node contributors.
11677//
11678// Permission is hereby granted, free of charge, to any person obtaining a
11679// copy of this software and associated documentation files (the
11680// "Software"), to deal in the Software without restriction, including
11681// without limitation the rights to use, copy, modify, merge, publish,
11682// distribute, sublicense, and/or sell copies of the Software, and to permit
11683// persons to whom the Software is furnished to do so, subject to the
11684// following conditions:
11685//
11686// The above copyright notice and this permission notice shall be included
11687// in all copies or substantial portions of the Software.
11688//
11689// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11690// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11691// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11692// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11693// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11694// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11695// USE OR OTHER DEALINGS IN THE SOFTWARE.
11696
11697// a passthrough stream.
11698// basically just the most minimal sort of Transform stream.
11699// Every written chunk gets output as-is.
11700
11701module.exports = PassThrough;
11702
11703var Transform = _dereq_('./_stream_transform');
11704
11705/*<replacement>*/
11706var util = _dereq_('core-util-is');
11707util.inherits = _dereq_('inherits');
11708/*</replacement>*/
11709
11710util.inherits(PassThrough, Transform);
11711
11712function PassThrough(options) {
11713 if (!(this instanceof PassThrough))
11714 return new PassThrough(options);
11715
11716 Transform.call(this, options);
11717}
11718
11719PassThrough.prototype._transform = function(chunk, encoding, cb) {
11720 cb(null, chunk);
11721};
11722
11723},{"./_stream_transform":98,"core-util-is":7,"inherits":45}],97:[function(_dereq_,module,exports){
11724(function (process){(function (){
11725// Copyright Joyent, Inc. and other Node contributors.
11726//
11727// Permission is hereby granted, free of charge, to any person obtaining a
11728// copy of this software and associated documentation files (the
11729// "Software"), to deal in the Software without restriction, including
11730// without limitation the rights to use, copy, modify, merge, publish,
11731// distribute, sublicense, and/or sell copies of the Software, and to permit
11732// persons to whom the Software is furnished to do so, subject to the
11733// following conditions:
11734//
11735// The above copyright notice and this permission notice shall be included
11736// in all copies or substantial portions of the Software.
11737//
11738// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11739// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11740// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11741// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11742// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11743// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11744// USE OR OTHER DEALINGS IN THE SOFTWARE.
11745
11746module.exports = Readable;
11747
11748/*<replacement>*/
11749var isArray = _dereq_('isarray');
11750/*</replacement>*/
11751
11752
11753/*<replacement>*/
11754var Buffer = _dereq_('buffer').Buffer;
11755/*</replacement>*/
11756
11757Readable.ReadableState = ReadableState;
11758
11759var EE = _dereq_('events').EventEmitter;
11760
11761/*<replacement>*/
11762if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
11763 return emitter.listeners(type).length;
11764};
11765/*</replacement>*/
11766
11767var Stream = _dereq_('stream');
11768
11769/*<replacement>*/
11770var util = _dereq_('core-util-is');
11771util.inherits = _dereq_('inherits');
11772/*</replacement>*/
11773
11774var StringDecoder;
11775
11776
11777/*<replacement>*/
11778var debug = _dereq_('util');
11779if (debug && debug.debuglog) {
11780 debug = debug.debuglog('stream');
11781} else {
11782 debug = function () {};
11783}
11784/*</replacement>*/
11785
11786
11787util.inherits(Readable, Stream);
11788
11789function ReadableState(options, stream) {
11790 var Duplex = _dereq_('./_stream_duplex');
11791
11792 options = options || {};
11793
11794 // the point at which it stops calling _read() to fill the buffer
11795 // Note: 0 is a valid value, means "don't call _read preemptively ever"
11796 var hwm = options.highWaterMark;
11797 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
11798 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
11799
11800 // cast to ints.
11801 this.highWaterMark = ~~this.highWaterMark;
11802
11803 this.buffer = [];
11804 this.length = 0;
11805 this.pipes = null;
11806 this.pipesCount = 0;
11807 this.flowing = null;
11808 this.ended = false;
11809 this.endEmitted = false;
11810 this.reading = false;
11811
11812 // a flag to be able to tell if the onwrite cb is called immediately,
11813 // or on a later tick. We set this to true at first, because any
11814 // actions that shouldn't happen until "later" should generally also
11815 // not happen before the first write call.
11816 this.sync = true;
11817
11818 // whenever we return null, then we set a flag to say
11819 // that we're awaiting a 'readable' event emission.
11820 this.needReadable = false;
11821 this.emittedReadable = false;
11822 this.readableListening = false;
11823
11824
11825 // object stream flag. Used to make read(n) ignore n and to
11826 // make all the buffer merging and length checks go away
11827 this.objectMode = !!options.objectMode;
11828
11829 if (stream instanceof Duplex)
11830 this.objectMode = this.objectMode || !!options.readableObjectMode;
11831
11832 // Crypto is kind of old and crusty. Historically, its default string
11833 // encoding is 'binary' so we have to make this configurable.
11834 // Everything else in the universe uses 'utf8', though.
11835 this.defaultEncoding = options.defaultEncoding || 'utf8';
11836
11837 // when piping, we only care about 'readable' events that happen
11838 // after read()ing all the bytes and not getting any pushback.
11839 this.ranOut = false;
11840
11841 // the number of writers that are awaiting a drain event in .pipe()s
11842 this.awaitDrain = 0;
11843
11844 // if true, a maybeReadMore has been scheduled
11845 this.readingMore = false;
11846
11847 this.decoder = null;
11848 this.encoding = null;
11849 if (options.encoding) {
11850 if (!StringDecoder)
11851 StringDecoder = _dereq_('string_decoder/').StringDecoder;
11852 this.decoder = new StringDecoder(options.encoding);
11853 this.encoding = options.encoding;
11854 }
11855}
11856
11857function Readable(options) {
11858 var Duplex = _dereq_('./_stream_duplex');
11859
11860 if (!(this instanceof Readable))
11861 return new Readable(options);
11862
11863 this._readableState = new ReadableState(options, this);
11864
11865 // legacy
11866 this.readable = true;
11867
11868 Stream.call(this);
11869}
11870
11871// Manually shove something into the read() buffer.
11872// This returns true if the highWaterMark has not been hit yet,
11873// similar to how Writable.write() returns true if you should
11874// write() some more.
11875Readable.prototype.push = function(chunk, encoding) {
11876 var state = this._readableState;
11877
11878 if (util.isString(chunk) && !state.objectMode) {
11879 encoding = encoding || state.defaultEncoding;
11880 if (encoding !== state.encoding) {
11881 chunk = new Buffer(chunk, encoding);
11882 encoding = '';
11883 }
11884 }
11885
11886 return readableAddChunk(this, state, chunk, encoding, false);
11887};
11888
11889// Unshift should *always* be something directly out of read()
11890Readable.prototype.unshift = function(chunk) {
11891 var state = this._readableState;
11892 return readableAddChunk(this, state, chunk, '', true);
11893};
11894
11895function readableAddChunk(stream, state, chunk, encoding, addToFront) {
11896 var er = chunkInvalid(state, chunk);
11897 if (er) {
11898 stream.emit('error', er);
11899 } else if (util.isNullOrUndefined(chunk)) {
11900 state.reading = false;
11901 if (!state.ended)
11902 onEofChunk(stream, state);
11903 } else if (state.objectMode || chunk && chunk.length > 0) {
11904 if (state.ended && !addToFront) {
11905 var e = new Error('stream.push() after EOF');
11906 stream.emit('error', e);
11907 } else if (state.endEmitted && addToFront) {
11908 var e = new Error('stream.unshift() after end event');
11909 stream.emit('error', e);
11910 } else {
11911 if (state.decoder && !addToFront && !encoding)
11912 chunk = state.decoder.write(chunk);
11913
11914 if (!addToFront)
11915 state.reading = false;
11916
11917 // if we want the data now, just emit it.
11918 if (state.flowing && state.length === 0 && !state.sync) {
11919 stream.emit('data', chunk);
11920 stream.read(0);
11921 } else {
11922 // update the buffer info.
11923 state.length += state.objectMode ? 1 : chunk.length;
11924 if (addToFront)
11925 state.buffer.unshift(chunk);
11926 else
11927 state.buffer.push(chunk);
11928
11929 if (state.needReadable)
11930 emitReadable(stream);
11931 }
11932
11933 maybeReadMore(stream, state);
11934 }
11935 } else if (!addToFront) {
11936 state.reading = false;
11937 }
11938
11939 return needMoreData(state);
11940}
11941
11942
11943
11944// if it's past the high water mark, we can push in some more.
11945// Also, if we have no data yet, we can stand some
11946// more bytes. This is to work around cases where hwm=0,
11947// such as the repl. Also, if the push() triggered a
11948// readable event, and the user called read(largeNumber) such that
11949// needReadable was set, then we ought to push more, so that another
11950// 'readable' event will be triggered.
11951function needMoreData(state) {
11952 return !state.ended &&
11953 (state.needReadable ||
11954 state.length < state.highWaterMark ||
11955 state.length === 0);
11956}
11957
11958// backwards compatibility.
11959Readable.prototype.setEncoding = function(enc) {
11960 if (!StringDecoder)
11961 StringDecoder = _dereq_('string_decoder/').StringDecoder;
11962 this._readableState.decoder = new StringDecoder(enc);
11963 this._readableState.encoding = enc;
11964 return this;
11965};
11966
11967// Don't raise the hwm > 128MB
11968var MAX_HWM = 0x800000;
11969function roundUpToNextPowerOf2(n) {
11970 if (n >= MAX_HWM) {
11971 n = MAX_HWM;
11972 } else {
11973 // Get the next highest power of 2
11974 n--;
11975 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
11976 n++;
11977 }
11978 return n;
11979}
11980
11981function howMuchToRead(n, state) {
11982 if (state.length === 0 && state.ended)
11983 return 0;
11984
11985 if (state.objectMode)
11986 return n === 0 ? 0 : 1;
11987
11988 if (isNaN(n) || util.isNull(n)) {
11989 // only flow one buffer at a time
11990 if (state.flowing && state.buffer.length)
11991 return state.buffer[0].length;
11992 else
11993 return state.length;
11994 }
11995
11996 if (n <= 0)
11997 return 0;
11998
11999 // If we're asking for more than the target buffer level,
12000 // then raise the water mark. Bump up to the next highest
12001 // power of 2, to prevent increasing it excessively in tiny
12002 // amounts.
12003 if (n > state.highWaterMark)
12004 state.highWaterMark = roundUpToNextPowerOf2(n);
12005
12006 // don't have that much. return null, unless we've ended.
12007 if (n > state.length) {
12008 if (!state.ended) {
12009 state.needReadable = true;
12010 return 0;
12011 } else
12012 return state.length;
12013 }
12014
12015 return n;
12016}
12017
12018// you can override either this method, or the async _read(n) below.
12019Readable.prototype.read = function(n) {
12020 debug('read', n);
12021 var state = this._readableState;
12022 var nOrig = n;
12023
12024 if (!util.isNumber(n) || n > 0)
12025 state.emittedReadable = false;
12026
12027 // if we're doing read(0) to trigger a readable event, but we
12028 // already have a bunch of data in the buffer, then just trigger
12029 // the 'readable' event and move on.
12030 if (n === 0 &&
12031 state.needReadable &&
12032 (state.length >= state.highWaterMark || state.ended)) {
12033 debug('read: emitReadable', state.length, state.ended);
12034 if (state.length === 0 && state.ended)
12035 endReadable(this);
12036 else
12037 emitReadable(this);
12038 return null;
12039 }
12040
12041 n = howMuchToRead(n, state);
12042
12043 // if we've ended, and we're now clear, then finish it up.
12044 if (n === 0 && state.ended) {
12045 if (state.length === 0)
12046 endReadable(this);
12047 return null;
12048 }
12049
12050 // All the actual chunk generation logic needs to be
12051 // *below* the call to _read. The reason is that in certain
12052 // synthetic stream cases, such as passthrough streams, _read
12053 // may be a completely synchronous operation which may change
12054 // the state of the read buffer, providing enough data when
12055 // before there was *not* enough.
12056 //
12057 // So, the steps are:
12058 // 1. Figure out what the state of things will be after we do
12059 // a read from the buffer.
12060 //
12061 // 2. If that resulting state will trigger a _read, then call _read.
12062 // Note that this may be asynchronous, or synchronous. Yes, it is
12063 // deeply ugly to write APIs this way, but that still doesn't mean
12064 // that the Readable class should behave improperly, as streams are
12065 // designed to be sync/async agnostic.
12066 // Take note if the _read call is sync or async (ie, if the read call
12067 // has returned yet), so that we know whether or not it's safe to emit
12068 // 'readable' etc.
12069 //
12070 // 3. Actually pull the requested chunks out of the buffer and return.
12071
12072 // if we need a readable event, then we need to do some reading.
12073 var doRead = state.needReadable;
12074 debug('need readable', doRead);
12075
12076 // if we currently have less than the highWaterMark, then also read some
12077 if (state.length === 0 || state.length - n < state.highWaterMark) {
12078 doRead = true;
12079 debug('length less than watermark', doRead);
12080 }
12081
12082 // however, if we've ended, then there's no point, and if we're already
12083 // reading, then it's unnecessary.
12084 if (state.ended || state.reading) {
12085 doRead = false;
12086 debug('reading or ended', doRead);
12087 }
12088
12089 if (doRead) {
12090 debug('do read');
12091 state.reading = true;
12092 state.sync = true;
12093 // if the length is currently zero, then we *need* a readable event.
12094 if (state.length === 0)
12095 state.needReadable = true;
12096 // call internal read method
12097 this._read(state.highWaterMark);
12098 state.sync = false;
12099 }
12100
12101 // If _read pushed data synchronously, then `reading` will be false,
12102 // and we need to re-evaluate how much data we can return to the user.
12103 if (doRead && !state.reading)
12104 n = howMuchToRead(nOrig, state);
12105
12106 var ret;
12107 if (n > 0)
12108 ret = fromList(n, state);
12109 else
12110 ret = null;
12111
12112 if (util.isNull(ret)) {
12113 state.needReadable = true;
12114 n = 0;
12115 }
12116
12117 state.length -= n;
12118
12119 // If we have nothing in the buffer, then we want to know
12120 // as soon as we *do* get something into the buffer.
12121 if (state.length === 0 && !state.ended)
12122 state.needReadable = true;
12123
12124 // If we tried to read() past the EOF, then emit end on the next tick.
12125 if (nOrig !== n && state.ended && state.length === 0)
12126 endReadable(this);
12127
12128 if (!util.isNull(ret))
12129 this.emit('data', ret);
12130
12131 return ret;
12132};
12133
12134function chunkInvalid(state, chunk) {
12135 var er = null;
12136 if (!util.isBuffer(chunk) &&
12137 !util.isString(chunk) &&
12138 !util.isNullOrUndefined(chunk) &&
12139 !state.objectMode) {
12140 er = new TypeError('Invalid non-string/buffer chunk');
12141 }
12142 return er;
12143}
12144
12145
12146function onEofChunk(stream, state) {
12147 if (state.decoder && !state.ended) {
12148 var chunk = state.decoder.end();
12149 if (chunk && chunk.length) {
12150 state.buffer.push(chunk);
12151 state.length += state.objectMode ? 1 : chunk.length;
12152 }
12153 }
12154 state.ended = true;
12155
12156 // emit 'readable' now to make sure it gets picked up.
12157 emitReadable(stream);
12158}
12159
12160// Don't emit readable right away in sync mode, because this can trigger
12161// another read() call => stack overflow. This way, it might trigger
12162// a nextTick recursion warning, but that's not so bad.
12163function emitReadable(stream) {
12164 var state = stream._readableState;
12165 state.needReadable = false;
12166 if (!state.emittedReadable) {
12167 debug('emitReadable', state.flowing);
12168 state.emittedReadable = true;
12169 if (state.sync)
12170 process.nextTick(function() {
12171 emitReadable_(stream);
12172 });
12173 else
12174 emitReadable_(stream);
12175 }
12176}
12177
12178function emitReadable_(stream) {
12179 debug('emit readable');
12180 stream.emit('readable');
12181 flow(stream);
12182}
12183
12184
12185// at this point, the user has presumably seen the 'readable' event,
12186// and called read() to consume some data. that may have triggered
12187// in turn another _read(n) call, in which case reading = true if
12188// it's in progress.
12189// However, if we're not ended, or reading, and the length < hwm,
12190// then go ahead and try to read some more preemptively.
12191function maybeReadMore(stream, state) {
12192 if (!state.readingMore) {
12193 state.readingMore = true;
12194 process.nextTick(function() {
12195 maybeReadMore_(stream, state);
12196 });
12197 }
12198}
12199
12200function maybeReadMore_(stream, state) {
12201 var len = state.length;
12202 while (!state.reading && !state.flowing && !state.ended &&
12203 state.length < state.highWaterMark) {
12204 debug('maybeReadMore read 0');
12205 stream.read(0);
12206 if (len === state.length)
12207 // didn't get any data, stop spinning.
12208 break;
12209 else
12210 len = state.length;
12211 }
12212 state.readingMore = false;
12213}
12214
12215// abstract method. to be overridden in specific implementation classes.
12216// call cb(er, data) where data is <= n in length.
12217// for virtual (non-string, non-buffer) streams, "length" is somewhat
12218// arbitrary, and perhaps not very meaningful.
12219Readable.prototype._read = function(n) {
12220 this.emit('error', new Error('not implemented'));
12221};
12222
12223Readable.prototype.pipe = function(dest, pipeOpts) {
12224 var src = this;
12225 var state = this._readableState;
12226
12227 switch (state.pipesCount) {
12228 case 0:
12229 state.pipes = dest;
12230 break;
12231 case 1:
12232 state.pipes = [state.pipes, dest];
12233 break;
12234 default:
12235 state.pipes.push(dest);
12236 break;
12237 }
12238 state.pipesCount += 1;
12239 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
12240
12241 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
12242 dest !== process.stdout &&
12243 dest !== process.stderr;
12244
12245 var endFn = doEnd ? onend : cleanup;
12246 if (state.endEmitted)
12247 process.nextTick(endFn);
12248 else
12249 src.once('end', endFn);
12250
12251 dest.on('unpipe', onunpipe);
12252 function onunpipe(readable) {
12253 debug('onunpipe');
12254 if (readable === src) {
12255 cleanup();
12256 }
12257 }
12258
12259 function onend() {
12260 debug('onend');
12261 dest.end();
12262 }
12263
12264 // when the dest drains, it reduces the awaitDrain counter
12265 // on the source. This would be more elegant with a .once()
12266 // handler in flow(), but adding and removing repeatedly is
12267 // too slow.
12268 var ondrain = pipeOnDrain(src);
12269 dest.on('drain', ondrain);
12270
12271 function cleanup() {
12272 debug('cleanup');
12273 // cleanup event handlers once the pipe is broken
12274 dest.removeListener('close', onclose);
12275 dest.removeListener('finish', onfinish);
12276 dest.removeListener('drain', ondrain);
12277 dest.removeListener('error', onerror);
12278 dest.removeListener('unpipe', onunpipe);
12279 src.removeListener('end', onend);
12280 src.removeListener('end', cleanup);
12281 src.removeListener('data', ondata);
12282
12283 // if the reader is waiting for a drain event from this
12284 // specific writer, then it would cause it to never start
12285 // flowing again.
12286 // So, if this is awaiting a drain, then we just call it now.
12287 // If we don't know, then assume that we are waiting for one.
12288 if (state.awaitDrain &&
12289 (!dest._writableState || dest._writableState.needDrain))
12290 ondrain();
12291 }
12292
12293 src.on('data', ondata);
12294 function ondata(chunk) {
12295 debug('ondata');
12296 var ret = dest.write(chunk);
12297 if (false === ret) {
12298 debug('false write response, pause',
12299 src._readableState.awaitDrain);
12300 src._readableState.awaitDrain++;
12301 src.pause();
12302 }
12303 }
12304
12305 // if the dest has an error, then stop piping into it.
12306 // however, don't suppress the throwing behavior for this.
12307 function onerror(er) {
12308 debug('onerror', er);
12309 unpipe();
12310 dest.removeListener('error', onerror);
12311 if (EE.listenerCount(dest, 'error') === 0)
12312 dest.emit('error', er);
12313 }
12314 // This is a brutally ugly hack to make sure that our error handler
12315 // is attached before any userland ones. NEVER DO THIS.
12316 if (!dest._events || !dest._events.error)
12317 dest.on('error', onerror);
12318 else if (isArray(dest._events.error))
12319 dest._events.error.unshift(onerror);
12320 else
12321 dest._events.error = [onerror, dest._events.error];
12322
12323
12324
12325 // Both close and finish should trigger unpipe, but only once.
12326 function onclose() {
12327 dest.removeListener('finish', onfinish);
12328 unpipe();
12329 }
12330 dest.once('close', onclose);
12331 function onfinish() {
12332 debug('onfinish');
12333 dest.removeListener('close', onclose);
12334 unpipe();
12335 }
12336 dest.once('finish', onfinish);
12337
12338 function unpipe() {
12339 debug('unpipe');
12340 src.unpipe(dest);
12341 }
12342
12343 // tell the dest that it's being piped to
12344 dest.emit('pipe', src);
12345
12346 // start the flow if it hasn't been started already.
12347 if (!state.flowing) {
12348 debug('pipe resume');
12349 src.resume();
12350 }
12351
12352 return dest;
12353};
12354
12355function pipeOnDrain(src) {
12356 return function() {
12357 var state = src._readableState;
12358 debug('pipeOnDrain', state.awaitDrain);
12359 if (state.awaitDrain)
12360 state.awaitDrain--;
12361 if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
12362 state.flowing = true;
12363 flow(src);
12364 }
12365 };
12366}
12367
12368
12369Readable.prototype.unpipe = function(dest) {
12370 var state = this._readableState;
12371
12372 // if we're not piping anywhere, then do nothing.
12373 if (state.pipesCount === 0)
12374 return this;
12375
12376 // just one destination. most common case.
12377 if (state.pipesCount === 1) {
12378 // passed in one, but it's not the right one.
12379 if (dest && dest !== state.pipes)
12380 return this;
12381
12382 if (!dest)
12383 dest = state.pipes;
12384
12385 // got a match.
12386 state.pipes = null;
12387 state.pipesCount = 0;
12388 state.flowing = false;
12389 if (dest)
12390 dest.emit('unpipe', this);
12391 return this;
12392 }
12393
12394 // slow case. multiple pipe destinations.
12395
12396 if (!dest) {
12397 // remove all.
12398 var dests = state.pipes;
12399 var len = state.pipesCount;
12400 state.pipes = null;
12401 state.pipesCount = 0;
12402 state.flowing = false;
12403
12404 for (var i = 0; i < len; i++)
12405 dests[i].emit('unpipe', this);
12406 return this;
12407 }
12408
12409 // try to find the right one.
12410 var i = indexOf(state.pipes, dest);
12411 if (i === -1)
12412 return this;
12413
12414 state.pipes.splice(i, 1);
12415 state.pipesCount -= 1;
12416 if (state.pipesCount === 1)
12417 state.pipes = state.pipes[0];
12418
12419 dest.emit('unpipe', this);
12420
12421 return this;
12422};
12423
12424// set up data events if they are asked for
12425// Ensure readable listeners eventually get something
12426Readable.prototype.on = function(ev, fn) {
12427 var res = Stream.prototype.on.call(this, ev, fn);
12428
12429 // If listening to data, and it has not explicitly been paused,
12430 // then call resume to start the flow of data on the next tick.
12431 if (ev === 'data' && false !== this._readableState.flowing) {
12432 this.resume();
12433 }
12434
12435 if (ev === 'readable' && this.readable) {
12436 var state = this._readableState;
12437 if (!state.readableListening) {
12438 state.readableListening = true;
12439 state.emittedReadable = false;
12440 state.needReadable = true;
12441 if (!state.reading) {
12442 var self = this;
12443 process.nextTick(function() {
12444 debug('readable nexttick read 0');
12445 self.read(0);
12446 });
12447 } else if (state.length) {
12448 emitReadable(this, state);
12449 }
12450 }
12451 }
12452
12453 return res;
12454};
12455Readable.prototype.addListener = Readable.prototype.on;
12456
12457// pause() and resume() are remnants of the legacy readable stream API
12458// If the user uses them, then switch into old mode.
12459Readable.prototype.resume = function() {
12460 var state = this._readableState;
12461 if (!state.flowing) {
12462 debug('resume');
12463 state.flowing = true;
12464 if (!state.reading) {
12465 debug('resume read 0');
12466 this.read(0);
12467 }
12468 resume(this, state);
12469 }
12470 return this;
12471};
12472
12473function resume(stream, state) {
12474 if (!state.resumeScheduled) {
12475 state.resumeScheduled = true;
12476 process.nextTick(function() {
12477 resume_(stream, state);
12478 });
12479 }
12480}
12481
12482function resume_(stream, state) {
12483 state.resumeScheduled = false;
12484 stream.emit('resume');
12485 flow(stream);
12486 if (state.flowing && !state.reading)
12487 stream.read(0);
12488}
12489
12490Readable.prototype.pause = function() {
12491 debug('call pause flowing=%j', this._readableState.flowing);
12492 if (false !== this._readableState.flowing) {
12493 debug('pause');
12494 this._readableState.flowing = false;
12495 this.emit('pause');
12496 }
12497 return this;
12498};
12499
12500function flow(stream) {
12501 var state = stream._readableState;
12502 debug('flow', state.flowing);
12503 if (state.flowing) {
12504 do {
12505 var chunk = stream.read();
12506 } while (null !== chunk && state.flowing);
12507 }
12508}
12509
12510// wrap an old-style stream as the async data source.
12511// This is *not* part of the readable stream interface.
12512// It is an ugly unfortunate mess of history.
12513Readable.prototype.wrap = function(stream) {
12514 var state = this._readableState;
12515 var paused = false;
12516
12517 var self = this;
12518 stream.on('end', function() {
12519 debug('wrapped end');
12520 if (state.decoder && !state.ended) {
12521 var chunk = state.decoder.end();
12522 if (chunk && chunk.length)
12523 self.push(chunk);
12524 }
12525
12526 self.push(null);
12527 });
12528
12529 stream.on('data', function(chunk) {
12530 debug('wrapped data');
12531 if (state.decoder)
12532 chunk = state.decoder.write(chunk);
12533 if (!chunk || !state.objectMode && !chunk.length)
12534 return;
12535
12536 var ret = self.push(chunk);
12537 if (!ret) {
12538 paused = true;
12539 stream.pause();
12540 }
12541 });
12542
12543 // proxy all the other methods.
12544 // important when wrapping filters and duplexes.
12545 for (var i in stream) {
12546 if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
12547 this[i] = function(method) { return function() {
12548 return stream[method].apply(stream, arguments);
12549 }}(i);
12550 }
12551 }
12552
12553 // proxy certain important events.
12554 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
12555 forEach(events, function(ev) {
12556 stream.on(ev, self.emit.bind(self, ev));
12557 });
12558
12559 // when we try to consume some more bytes, simply unpause the
12560 // underlying stream.
12561 self._read = function(n) {
12562 debug('wrapped _read', n);
12563 if (paused) {
12564 paused = false;
12565 stream.resume();
12566 }
12567 };
12568
12569 return self;
12570};
12571
12572
12573
12574// exposed for testing purposes only.
12575Readable._fromList = fromList;
12576
12577// Pluck off n bytes from an array of buffers.
12578// Length is the combined lengths of all the buffers in the list.
12579function fromList(n, state) {
12580 var list = state.buffer;
12581 var length = state.length;
12582 var stringMode = !!state.decoder;
12583 var objectMode = !!state.objectMode;
12584 var ret;
12585
12586 // nothing in the list, definitely empty.
12587 if (list.length === 0)
12588 return null;
12589
12590 if (length === 0)
12591 ret = null;
12592 else if (objectMode)
12593 ret = list.shift();
12594 else if (!n || n >= length) {
12595 // read it all, truncate the array.
12596 if (stringMode)
12597 ret = list.join('');
12598 else
12599 ret = Buffer.concat(list, length);
12600 list.length = 0;
12601 } else {
12602 // read just some of it.
12603 if (n < list[0].length) {
12604 // just take a part of the first list item.
12605 // slice is the same for buffers and strings.
12606 var buf = list[0];
12607 ret = buf.slice(0, n);
12608 list[0] = buf.slice(n);
12609 } else if (n === list[0].length) {
12610 // first list is a perfect match
12611 ret = list.shift();
12612 } else {
12613 // complex case.
12614 // we have enough to cover it, but it spans past the first buffer.
12615 if (stringMode)
12616 ret = '';
12617 else
12618 ret = new Buffer(n);
12619
12620 var c = 0;
12621 for (var i = 0, l = list.length; i < l && c < n; i++) {
12622 var buf = list[0];
12623 var cpy = Math.min(n - c, buf.length);
12624
12625 if (stringMode)
12626 ret += buf.slice(0, cpy);
12627 else
12628 buf.copy(ret, c, 0, cpy);
12629
12630 if (cpy < buf.length)
12631 list[0] = buf.slice(cpy);
12632 else
12633 list.shift();
12634
12635 c += cpy;
12636 }
12637 }
12638 }
12639
12640 return ret;
12641}
12642
12643function endReadable(stream) {
12644 var state = stream._readableState;
12645
12646 // If we get here before consuming all the bytes, then that is a
12647 // bug in node. Should never happen.
12648 if (state.length > 0)
12649 throw new Error('endReadable called on non-empty stream');
12650
12651 if (!state.endEmitted) {
12652 state.ended = true;
12653 process.nextTick(function() {
12654 // Check that we didn't get one last unshift.
12655 if (!state.endEmitted && state.length === 0) {
12656 state.endEmitted = true;
12657 stream.readable = false;
12658 stream.emit('end');
12659 }
12660 });
12661 }
12662}
12663
12664function forEach (xs, f) {
12665 for (var i = 0, l = xs.length; i < l; i++) {
12666 f(xs[i], i);
12667 }
12668}
12669
12670function indexOf (xs, x) {
12671 for (var i = 0, l = xs.length; i < l; i++) {
12672 if (xs[i] === x) return i;
12673 }
12674 return -1;
12675}
12676
12677}).call(this)}).call(this,_dereq_('_process'))
12678},{"./_stream_duplex":95,"_process":93,"buffer":4,"core-util-is":7,"events":33,"inherits":45,"isarray":47,"stream":105,"string_decoder/":100,"util":3}],98:[function(_dereq_,module,exports){
12679// Copyright Joyent, Inc. and other Node contributors.
12680//
12681// Permission is hereby granted, free of charge, to any person obtaining a
12682// copy of this software and associated documentation files (the
12683// "Software"), to deal in the Software without restriction, including
12684// without limitation the rights to use, copy, modify, merge, publish,
12685// distribute, sublicense, and/or sell copies of the Software, and to permit
12686// persons to whom the Software is furnished to do so, subject to the
12687// following conditions:
12688//
12689// The above copyright notice and this permission notice shall be included
12690// in all copies or substantial portions of the Software.
12691//
12692// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12693// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12694// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12695// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12696// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12697// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12698// USE OR OTHER DEALINGS IN THE SOFTWARE.
12699
12700
12701// a transform stream is a readable/writable stream where you do
12702// something with the data. Sometimes it's called a "filter",
12703// but that's not a great name for it, since that implies a thing where
12704// some bits pass through, and others are simply ignored. (That would
12705// be a valid example of a transform, of course.)
12706//
12707// While the output is causally related to the input, it's not a
12708// necessarily symmetric or synchronous transformation. For example,
12709// a zlib stream might take multiple plain-text writes(), and then
12710// emit a single compressed chunk some time in the future.
12711//
12712// Here's how this works:
12713//
12714// The Transform stream has all the aspects of the readable and writable
12715// stream classes. When you write(chunk), that calls _write(chunk,cb)
12716// internally, and returns false if there's a lot of pending writes
12717// buffered up. When you call read(), that calls _read(n) until
12718// there's enough pending readable data buffered up.
12719//
12720// In a transform stream, the written data is placed in a buffer. When
12721// _read(n) is called, it transforms the queued up data, calling the
12722// buffered _write cb's as it consumes chunks. If consuming a single
12723// written chunk would result in multiple output chunks, then the first
12724// outputted bit calls the readcb, and subsequent chunks just go into
12725// the read buffer, and will cause it to emit 'readable' if necessary.
12726//
12727// This way, back-pressure is actually determined by the reading side,
12728// since _read has to be called to start processing a new chunk. However,
12729// a pathological inflate type of transform can cause excessive buffering
12730// here. For example, imagine a stream where every byte of input is
12731// interpreted as an integer from 0-255, and then results in that many
12732// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
12733// 1kb of data being output. In this case, you could write a very small
12734// amount of input, and end up with a very large amount of output. In
12735// such a pathological inflating mechanism, there'd be no way to tell
12736// the system to stop doing the transform. A single 4MB write could
12737// cause the system to run out of memory.
12738//
12739// However, even in such a pathological case, only a single written chunk
12740// would be consumed, and then the rest would wait (un-transformed) until
12741// the results of the previous transformed chunk were consumed.
12742
12743module.exports = Transform;
12744
12745var Duplex = _dereq_('./_stream_duplex');
12746
12747/*<replacement>*/
12748var util = _dereq_('core-util-is');
12749util.inherits = _dereq_('inherits');
12750/*</replacement>*/
12751
12752util.inherits(Transform, Duplex);
12753
12754
12755function TransformState(options, stream) {
12756 this.afterTransform = function(er, data) {
12757 return afterTransform(stream, er, data);
12758 };
12759
12760 this.needTransform = false;
12761 this.transforming = false;
12762 this.writecb = null;
12763 this.writechunk = null;
12764}
12765
12766function afterTransform(stream, er, data) {
12767 var ts = stream._transformState;
12768 ts.transforming = false;
12769
12770 var cb = ts.writecb;
12771
12772 if (!cb)
12773 return stream.emit('error', new Error('no writecb in Transform class'));
12774
12775 ts.writechunk = null;
12776 ts.writecb = null;
12777
12778 if (!util.isNullOrUndefined(data))
12779 stream.push(data);
12780
12781 if (cb)
12782 cb(er);
12783
12784 var rs = stream._readableState;
12785 rs.reading = false;
12786 if (rs.needReadable || rs.length < rs.highWaterMark) {
12787 stream._read(rs.highWaterMark);
12788 }
12789}
12790
12791
12792function Transform(options) {
12793 if (!(this instanceof Transform))
12794 return new Transform(options);
12795
12796 Duplex.call(this, options);
12797
12798 this._transformState = new TransformState(options, this);
12799
12800 // when the writable side finishes, then flush out anything remaining.
12801 var stream = this;
12802
12803 // start out asking for a readable event once data is transformed.
12804 this._readableState.needReadable = true;
12805
12806 // we have implemented the _read method, and done the other things
12807 // that Readable wants before the first _read call, so unset the
12808 // sync guard flag.
12809 this._readableState.sync = false;
12810
12811 this.once('prefinish', function() {
12812 if (util.isFunction(this._flush))
12813 this._flush(function(er) {
12814 done(stream, er);
12815 });
12816 else
12817 done(stream);
12818 });
12819}
12820
12821Transform.prototype.push = function(chunk, encoding) {
12822 this._transformState.needTransform = false;
12823 return Duplex.prototype.push.call(this, chunk, encoding);
12824};
12825
12826// This is the part where you do stuff!
12827// override this function in implementation classes.
12828// 'chunk' is an input chunk.
12829//
12830// Call `push(newChunk)` to pass along transformed output
12831// to the readable side. You may call 'push' zero or more times.
12832//
12833// Call `cb(err)` when you are done with this chunk. If you pass
12834// an error, then that'll put the hurt on the whole operation. If you
12835// never call cb(), then you'll never get another chunk.
12836Transform.prototype._transform = function(chunk, encoding, cb) {
12837 throw new Error('not implemented');
12838};
12839
12840Transform.prototype._write = function(chunk, encoding, cb) {
12841 var ts = this._transformState;
12842 ts.writecb = cb;
12843 ts.writechunk = chunk;
12844 ts.writeencoding = encoding;
12845 if (!ts.transforming) {
12846 var rs = this._readableState;
12847 if (ts.needTransform ||
12848 rs.needReadable ||
12849 rs.length < rs.highWaterMark)
12850 this._read(rs.highWaterMark);
12851 }
12852};
12853
12854// Doesn't matter what the args are here.
12855// _transform does all the work.
12856// That we got here means that the readable side wants more data.
12857Transform.prototype._read = function(n) {
12858 var ts = this._transformState;
12859
12860 if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
12861 ts.transforming = true;
12862 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
12863 } else {
12864 // mark that we need a transform, so that any data that comes in
12865 // will get processed, now that we've asked for it.
12866 ts.needTransform = true;
12867 }
12868};
12869
12870
12871function done(stream, er) {
12872 if (er)
12873 return stream.emit('error', er);
12874
12875 // if there's nothing in the write buffer, then that means
12876 // that nothing more will ever be provided
12877 var ws = stream._writableState;
12878 var ts = stream._transformState;
12879
12880 if (ws.length)
12881 throw new Error('calling transform done when ws.length != 0');
12882
12883 if (ts.transforming)
12884 throw new Error('calling transform done when still transforming');
12885
12886 return stream.push(null);
12887}
12888
12889},{"./_stream_duplex":95,"core-util-is":7,"inherits":45}],99:[function(_dereq_,module,exports){
12890(function (process){(function (){
12891// Copyright Joyent, Inc. and other Node contributors.
12892//
12893// Permission is hereby granted, free of charge, to any person obtaining a
12894// copy of this software and associated documentation files (the
12895// "Software"), to deal in the Software without restriction, including
12896// without limitation the rights to use, copy, modify, merge, publish,
12897// distribute, sublicense, and/or sell copies of the Software, and to permit
12898// persons to whom the Software is furnished to do so, subject to the
12899// following conditions:
12900//
12901// The above copyright notice and this permission notice shall be included
12902// in all copies or substantial portions of the Software.
12903//
12904// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12905// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12906// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12907// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12908// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12909// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12910// USE OR OTHER DEALINGS IN THE SOFTWARE.
12911
12912// A bit simpler than readable streams.
12913// Implement an async ._write(chunk, cb), and it'll handle all
12914// the drain event emission and buffering.
12915
12916module.exports = Writable;
12917
12918/*<replacement>*/
12919var Buffer = _dereq_('buffer').Buffer;
12920/*</replacement>*/
12921
12922Writable.WritableState = WritableState;
12923
12924
12925/*<replacement>*/
12926var util = _dereq_('core-util-is');
12927util.inherits = _dereq_('inherits');
12928/*</replacement>*/
12929
12930var Stream = _dereq_('stream');
12931
12932util.inherits(Writable, Stream);
12933
12934function WriteReq(chunk, encoding, cb) {
12935 this.chunk = chunk;
12936 this.encoding = encoding;
12937 this.callback = cb;
12938}
12939
12940function WritableState(options, stream) {
12941 var Duplex = _dereq_('./_stream_duplex');
12942
12943 options = options || {};
12944
12945 // the point at which write() starts returning false
12946 // Note: 0 is a valid value, means that we always return false if
12947 // the entire buffer is not flushed immediately on write()
12948 var hwm = options.highWaterMark;
12949 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
12950 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
12951
12952 // object stream flag to indicate whether or not this stream
12953 // contains buffers or objects.
12954 this.objectMode = !!options.objectMode;
12955
12956 if (stream instanceof Duplex)
12957 this.objectMode = this.objectMode || !!options.writableObjectMode;
12958
12959 // cast to ints.
12960 this.highWaterMark = ~~this.highWaterMark;
12961
12962 this.needDrain = false;
12963 // at the start of calling end()
12964 this.ending = false;
12965 // when end() has been called, and returned
12966 this.ended = false;
12967 // when 'finish' is emitted
12968 this.finished = false;
12969
12970 // should we decode strings into buffers before passing to _write?
12971 // this is here so that some node-core streams can optimize string
12972 // handling at a lower level.
12973 var noDecode = options.decodeStrings === false;
12974 this.decodeStrings = !noDecode;
12975
12976 // Crypto is kind of old and crusty. Historically, its default string
12977 // encoding is 'binary' so we have to make this configurable.
12978 // Everything else in the universe uses 'utf8', though.
12979 this.defaultEncoding = options.defaultEncoding || 'utf8';
12980
12981 // not an actual buffer we keep track of, but a measurement
12982 // of how much we're waiting to get pushed to some underlying
12983 // socket or file.
12984 this.length = 0;
12985
12986 // a flag to see when we're in the middle of a write.
12987 this.writing = false;
12988
12989 // when true all writes will be buffered until .uncork() call
12990 this.corked = 0;
12991
12992 // a flag to be able to tell if the onwrite cb is called immediately,
12993 // or on a later tick. We set this to true at first, because any
12994 // actions that shouldn't happen until "later" should generally also
12995 // not happen before the first write call.
12996 this.sync = true;
12997
12998 // a flag to know if we're processing previously buffered items, which
12999 // may call the _write() callback in the same tick, so that we don't
13000 // end up in an overlapped onwrite situation.
13001 this.bufferProcessing = false;
13002
13003 // the callback that's passed to _write(chunk,cb)
13004 this.onwrite = function(er) {
13005 onwrite(stream, er);
13006 };
13007
13008 // the callback that the user supplies to write(chunk,encoding,cb)
13009 this.writecb = null;
13010
13011 // the amount that is being written when _write is called.
13012 this.writelen = 0;
13013
13014 this.buffer = [];
13015
13016 // number of pending user-supplied write callbacks
13017 // this must be 0 before 'finish' can be emitted
13018 this.pendingcb = 0;
13019
13020 // emit prefinish if the only thing we're waiting for is _write cbs
13021 // This is relevant for synchronous Transform streams
13022 this.prefinished = false;
13023
13024 // True if the error was already emitted and should not be thrown again
13025 this.errorEmitted = false;
13026}
13027
13028function Writable(options) {
13029 var Duplex = _dereq_('./_stream_duplex');
13030
13031 // Writable ctor is applied to Duplexes, though they're not
13032 // instanceof Writable, they're instanceof Readable.
13033 if (!(this instanceof Writable) && !(this instanceof Duplex))
13034 return new Writable(options);
13035
13036 this._writableState = new WritableState(options, this);
13037
13038 // legacy.
13039 this.writable = true;
13040
13041 Stream.call(this);
13042}
13043
13044// Otherwise people can pipe Writable streams, which is just wrong.
13045Writable.prototype.pipe = function() {
13046 this.emit('error', new Error('Cannot pipe. Not readable.'));
13047};
13048
13049
13050function writeAfterEnd(stream, state, cb) {
13051 var er = new Error('write after end');
13052 // TODO: defer error events consistently everywhere, not just the cb
13053 stream.emit('error', er);
13054 process.nextTick(function() {
13055 cb(er);
13056 });
13057}
13058
13059// If we get something that is not a buffer, string, null, or undefined,
13060// and we're not in objectMode, then that's an error.
13061// Otherwise stream chunks are all considered to be of length=1, and the
13062// watermarks determine how many objects to keep in the buffer, rather than
13063// how many bytes or characters.
13064function validChunk(stream, state, chunk, cb) {
13065 var valid = true;
13066 if (!util.isBuffer(chunk) &&
13067 !util.isString(chunk) &&
13068 !util.isNullOrUndefined(chunk) &&
13069 !state.objectMode) {
13070 var er = new TypeError('Invalid non-string/buffer chunk');
13071 stream.emit('error', er);
13072 process.nextTick(function() {
13073 cb(er);
13074 });
13075 valid = false;
13076 }
13077 return valid;
13078}
13079
13080Writable.prototype.write = function(chunk, encoding, cb) {
13081 var state = this._writableState;
13082 var ret = false;
13083
13084 if (util.isFunction(encoding)) {
13085 cb = encoding;
13086 encoding = null;
13087 }
13088
13089 if (util.isBuffer(chunk))
13090 encoding = 'buffer';
13091 else if (!encoding)
13092 encoding = state.defaultEncoding;
13093
13094 if (!util.isFunction(cb))
13095 cb = function() {};
13096
13097 if (state.ended)
13098 writeAfterEnd(this, state, cb);
13099 else if (validChunk(this, state, chunk, cb)) {
13100 state.pendingcb++;
13101 ret = writeOrBuffer(this, state, chunk, encoding, cb);
13102 }
13103
13104 return ret;
13105};
13106
13107Writable.prototype.cork = function() {
13108 var state = this._writableState;
13109
13110 state.corked++;
13111};
13112
13113Writable.prototype.uncork = function() {
13114 var state = this._writableState;
13115
13116 if (state.corked) {
13117 state.corked--;
13118
13119 if (!state.writing &&
13120 !state.corked &&
13121 !state.finished &&
13122 !state.bufferProcessing &&
13123 state.buffer.length)
13124 clearBuffer(this, state);
13125 }
13126};
13127
13128function decodeChunk(state, chunk, encoding) {
13129 if (!state.objectMode &&
13130 state.decodeStrings !== false &&
13131 util.isString(chunk)) {
13132 chunk = new Buffer(chunk, encoding);
13133 }
13134 return chunk;
13135}
13136
13137// if we're already writing something, then just put this
13138// in the queue, and wait our turn. Otherwise, call _write
13139// If we return false, then we need a drain event, so set that flag.
13140function writeOrBuffer(stream, state, chunk, encoding, cb) {
13141 chunk = decodeChunk(state, chunk, encoding);
13142 if (util.isBuffer(chunk))
13143 encoding = 'buffer';
13144 var len = state.objectMode ? 1 : chunk.length;
13145
13146 state.length += len;
13147
13148 var ret = state.length < state.highWaterMark;
13149 // we must ensure that previous needDrain will not be reset to false.
13150 if (!ret)
13151 state.needDrain = true;
13152
13153 if (state.writing || state.corked)
13154 state.buffer.push(new WriteReq(chunk, encoding, cb));
13155 else
13156 doWrite(stream, state, false, len, chunk, encoding, cb);
13157
13158 return ret;
13159}
13160
13161function doWrite(stream, state, writev, len, chunk, encoding, cb) {
13162 state.writelen = len;
13163 state.writecb = cb;
13164 state.writing = true;
13165 state.sync = true;
13166 if (writev)
13167 stream._writev(chunk, state.onwrite);
13168 else
13169 stream._write(chunk, encoding, state.onwrite);
13170 state.sync = false;
13171}
13172
13173function onwriteError(stream, state, sync, er, cb) {
13174 if (sync)
13175 process.nextTick(function() {
13176 state.pendingcb--;
13177 cb(er);
13178 });
13179 else {
13180 state.pendingcb--;
13181 cb(er);
13182 }
13183
13184 stream._writableState.errorEmitted = true;
13185 stream.emit('error', er);
13186}
13187
13188function onwriteStateUpdate(state) {
13189 state.writing = false;
13190 state.writecb = null;
13191 state.length -= state.writelen;
13192 state.writelen = 0;
13193}
13194
13195function onwrite(stream, er) {
13196 var state = stream._writableState;
13197 var sync = state.sync;
13198 var cb = state.writecb;
13199
13200 onwriteStateUpdate(state);
13201
13202 if (er)
13203 onwriteError(stream, state, sync, er, cb);
13204 else {
13205 // Check if we're actually ready to finish, but don't emit yet
13206 var finished = needFinish(stream, state);
13207
13208 if (!finished &&
13209 !state.corked &&
13210 !state.bufferProcessing &&
13211 state.buffer.length) {
13212 clearBuffer(stream, state);
13213 }
13214
13215 if (sync) {
13216 process.nextTick(function() {
13217 afterWrite(stream, state, finished, cb);
13218 });
13219 } else {
13220 afterWrite(stream, state, finished, cb);
13221 }
13222 }
13223}
13224
13225function afterWrite(stream, state, finished, cb) {
13226 if (!finished)
13227 onwriteDrain(stream, state);
13228 state.pendingcb--;
13229 cb();
13230 finishMaybe(stream, state);
13231}
13232
13233// Must force callback to be called on nextTick, so that we don't
13234// emit 'drain' before the write() consumer gets the 'false' return
13235// value, and has a chance to attach a 'drain' listener.
13236function onwriteDrain(stream, state) {
13237 if (state.length === 0 && state.needDrain) {
13238 state.needDrain = false;
13239 stream.emit('drain');
13240 }
13241}
13242
13243
13244// if there's something in the buffer waiting, then process it
13245function clearBuffer(stream, state) {
13246 state.bufferProcessing = true;
13247
13248 if (stream._writev && state.buffer.length > 1) {
13249 // Fast case, write everything using _writev()
13250 var cbs = [];
13251 for (var c = 0; c < state.buffer.length; c++)
13252 cbs.push(state.buffer[c].callback);
13253
13254 // count the one we are adding, as well.
13255 // TODO(isaacs) clean this up
13256 state.pendingcb++;
13257 doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
13258 for (var i = 0; i < cbs.length; i++) {
13259 state.pendingcb--;
13260 cbs[i](err);
13261 }
13262 });
13263
13264 // Clear buffer
13265 state.buffer = [];
13266 } else {
13267 // Slow case, write chunks one-by-one
13268 for (var c = 0; c < state.buffer.length; c++) {
13269 var entry = state.buffer[c];
13270 var chunk = entry.chunk;
13271 var encoding = entry.encoding;
13272 var cb = entry.callback;
13273 var len = state.objectMode ? 1 : chunk.length;
13274
13275 doWrite(stream, state, false, len, chunk, encoding, cb);
13276
13277 // if we didn't call the onwrite immediately, then
13278 // it means that we need to wait until it does.
13279 // also, that means that the chunk and cb are currently
13280 // being processed, so move the buffer counter past them.
13281 if (state.writing) {
13282 c++;
13283 break;
13284 }
13285 }
13286
13287 if (c < state.buffer.length)
13288 state.buffer = state.buffer.slice(c);
13289 else
13290 state.buffer.length = 0;
13291 }
13292
13293 state.bufferProcessing = false;
13294}
13295
13296Writable.prototype._write = function(chunk, encoding, cb) {
13297 cb(new Error('not implemented'));
13298
13299};
13300
13301Writable.prototype._writev = null;
13302
13303Writable.prototype.end = function(chunk, encoding, cb) {
13304 var state = this._writableState;
13305
13306 if (util.isFunction(chunk)) {
13307 cb = chunk;
13308 chunk = null;
13309 encoding = null;
13310 } else if (util.isFunction(encoding)) {
13311 cb = encoding;
13312 encoding = null;
13313 }
13314
13315 if (!util.isNullOrUndefined(chunk))
13316 this.write(chunk, encoding);
13317
13318 // .end() fully uncorks
13319 if (state.corked) {
13320 state.corked = 1;
13321 this.uncork();
13322 }
13323
13324 // ignore unnecessary end() calls.
13325 if (!state.ending && !state.finished)
13326 endWritable(this, state, cb);
13327};
13328
13329
13330function needFinish(stream, state) {
13331 return (state.ending &&
13332 state.length === 0 &&
13333 !state.finished &&
13334 !state.writing);
13335}
13336
13337function prefinish(stream, state) {
13338 if (!state.prefinished) {
13339 state.prefinished = true;
13340 stream.emit('prefinish');
13341 }
13342}
13343
13344function finishMaybe(stream, state) {
13345 var need = needFinish(stream, state);
13346 if (need) {
13347 if (state.pendingcb === 0) {
13348 prefinish(stream, state);
13349 state.finished = true;
13350 stream.emit('finish');
13351 } else
13352 prefinish(stream, state);
13353 }
13354 return need;
13355}
13356
13357function endWritable(stream, state, cb) {
13358 state.ending = true;
13359 finishMaybe(stream, state);
13360 if (cb) {
13361 if (state.finished)
13362 process.nextTick(cb);
13363 else
13364 stream.once('finish', cb);
13365 }
13366 state.ended = true;
13367}
13368
13369}).call(this)}).call(this,_dereq_('_process'))
13370},{"./_stream_duplex":95,"_process":93,"buffer":4,"core-util-is":7,"inherits":45,"stream":105}],100:[function(_dereq_,module,exports){
13371// Copyright Joyent, Inc. and other Node contributors.
13372//
13373// Permission is hereby granted, free of charge, to any person obtaining a
13374// copy of this software and associated documentation files (the
13375// "Software"), to deal in the Software without restriction, including
13376// without limitation the rights to use, copy, modify, merge, publish,
13377// distribute, sublicense, and/or sell copies of the Software, and to permit
13378// persons to whom the Software is furnished to do so, subject to the
13379// following conditions:
13380//
13381// The above copyright notice and this permission notice shall be included
13382// in all copies or substantial portions of the Software.
13383//
13384// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
13385// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13386// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
13387// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
13388// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
13389// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
13390// USE OR OTHER DEALINGS IN THE SOFTWARE.
13391
13392var Buffer = _dereq_('buffer').Buffer;
13393
13394var isBufferEncoding = Buffer.isEncoding
13395 || function(encoding) {
13396 switch (encoding && encoding.toLowerCase()) {
13397 case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
13398 default: return false;
13399 }
13400 }
13401
13402
13403function assertEncoding(encoding) {
13404 if (encoding && !isBufferEncoding(encoding)) {
13405 throw new Error('Unknown encoding: ' + encoding);
13406 }
13407}
13408
13409// StringDecoder provides an interface for efficiently splitting a series of
13410// buffers into a series of JS strings without breaking apart multi-byte
13411// characters. CESU-8 is handled as part of the UTF-8 encoding.
13412//
13413// @TODO Handling all encodings inside a single object makes it very difficult
13414// to reason about this code, so it should be split up in the future.
13415// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
13416// points as used by CESU-8.
13417var StringDecoder = exports.StringDecoder = function(encoding) {
13418 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
13419 assertEncoding(encoding);
13420 switch (this.encoding) {
13421 case 'utf8':
13422 // CESU-8 represents each of Surrogate Pair by 3-bytes
13423 this.surrogateSize = 3;
13424 break;
13425 case 'ucs2':
13426 case 'utf16le':
13427 // UTF-16 represents each of Surrogate Pair by 2-bytes
13428 this.surrogateSize = 2;
13429 this.detectIncompleteChar = utf16DetectIncompleteChar;
13430 break;
13431 case 'base64':
13432 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
13433 this.surrogateSize = 3;
13434 this.detectIncompleteChar = base64DetectIncompleteChar;
13435 break;
13436 default:
13437 this.write = passThroughWrite;
13438 return;
13439 }
13440
13441 // Enough space to store all bytes of a single character. UTF-8 needs 4
13442 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
13443 this.charBuffer = new Buffer(6);
13444 // Number of bytes received for the current incomplete multi-byte character.
13445 this.charReceived = 0;
13446 // Number of bytes expected for the current incomplete multi-byte character.
13447 this.charLength = 0;
13448};
13449
13450
13451// write decodes the given buffer and returns it as JS string that is
13452// guaranteed to not contain any partial multi-byte characters. Any partial
13453// character found at the end of the buffer is buffered up, and will be
13454// returned when calling write again with the remaining bytes.
13455//
13456// Note: Converting a Buffer containing an orphan surrogate to a String
13457// currently works, but converting a String to a Buffer (via `new Buffer`, or
13458// Buffer#write) will replace incomplete surrogates with the unicode
13459// replacement character. See https://codereview.chromium.org/121173009/ .
13460StringDecoder.prototype.write = function(buffer) {
13461 var charStr = '';
13462 // if our last write ended with an incomplete multibyte character
13463 while (this.charLength) {
13464 // determine how many remaining bytes this buffer has to offer for this char
13465 var available = (buffer.length >= this.charLength - this.charReceived) ?
13466 this.charLength - this.charReceived :
13467 buffer.length;
13468
13469 // add the new bytes to the char buffer
13470 buffer.copy(this.charBuffer, this.charReceived, 0, available);
13471 this.charReceived += available;
13472
13473 if (this.charReceived < this.charLength) {
13474 // still not enough chars in this buffer? wait for more ...
13475 return '';
13476 }
13477
13478 // remove bytes belonging to the current character from the buffer
13479 buffer = buffer.slice(available, buffer.length);
13480
13481 // get the character that was split
13482 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
13483
13484 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13485 var charCode = charStr.charCodeAt(charStr.length - 1);
13486 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13487 this.charLength += this.surrogateSize;
13488 charStr = '';
13489 continue;
13490 }
13491 this.charReceived = this.charLength = 0;
13492
13493 // if there are no more bytes in this buffer, just emit our char
13494 if (buffer.length === 0) {
13495 return charStr;
13496 }
13497 break;
13498 }
13499
13500 // determine and set charLength / charReceived
13501 this.detectIncompleteChar(buffer);
13502
13503 var end = buffer.length;
13504 if (this.charLength) {
13505 // buffer the incomplete character bytes we got
13506 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
13507 end -= this.charReceived;
13508 }
13509
13510 charStr += buffer.toString(this.encoding, 0, end);
13511
13512 var end = charStr.length - 1;
13513 var charCode = charStr.charCodeAt(end);
13514 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
13515 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
13516 var size = this.surrogateSize;
13517 this.charLength += size;
13518 this.charReceived += size;
13519 this.charBuffer.copy(this.charBuffer, size, 0, size);
13520 buffer.copy(this.charBuffer, 0, 0, size);
13521 return charStr.substring(0, end);
13522 }
13523
13524 // or just emit the charStr
13525 return charStr;
13526};
13527
13528// detectIncompleteChar determines if there is an incomplete UTF-8 character at
13529// the end of the given buffer. If so, it sets this.charLength to the byte
13530// length that character, and sets this.charReceived to the number of bytes
13531// that are available for this character.
13532StringDecoder.prototype.detectIncompleteChar = function(buffer) {
13533 // determine how many bytes we have to check at the end of this buffer
13534 var i = (buffer.length >= 3) ? 3 : buffer.length;
13535
13536 // Figure out if one of the last i bytes of our buffer announces an
13537 // incomplete char.
13538 for (; i > 0; i--) {
13539 var c = buffer[buffer.length - i];
13540
13541 // See http://en.wikipedia.org/wiki/UTF-8#Description
13542
13543 // 110XXXXX
13544 if (i == 1 && c >> 5 == 0x06) {
13545 this.charLength = 2;
13546 break;
13547 }
13548
13549 // 1110XXXX
13550 if (i <= 2 && c >> 4 == 0x0E) {
13551 this.charLength = 3;
13552 break;
13553 }
13554
13555 // 11110XXX
13556 if (i <= 3 && c >> 3 == 0x1E) {
13557 this.charLength = 4;
13558 break;
13559 }
13560 }
13561 this.charReceived = i;
13562};
13563
13564StringDecoder.prototype.end = function(buffer) {
13565 var res = '';
13566 if (buffer && buffer.length)
13567 res = this.write(buffer);
13568
13569 if (this.charReceived) {
13570 var cr = this.charReceived;
13571 var buf = this.charBuffer;
13572 var enc = this.encoding;
13573 res += buf.slice(0, cr).toString(enc);
13574 }
13575
13576 return res;
13577};
13578
13579function passThroughWrite(buffer) {
13580 return buffer.toString(this.encoding);
13581}
13582
13583function utf16DetectIncompleteChar(buffer) {
13584 this.charReceived = buffer.length % 2;
13585 this.charLength = this.charReceived ? 2 : 0;
13586}
13587
13588function base64DetectIncompleteChar(buffer) {
13589 this.charReceived = buffer.length % 3;
13590 this.charLength = this.charReceived ? 3 : 0;
13591}
13592
13593},{"buffer":4}],101:[function(_dereq_,module,exports){
13594(function (process){(function (){
13595exports = module.exports = _dereq_('./lib/_stream_readable.js');
13596exports.Stream = _dereq_('stream');
13597exports.Readable = exports;
13598exports.Writable = _dereq_('./lib/_stream_writable.js');
13599exports.Duplex = _dereq_('./lib/_stream_duplex.js');
13600exports.Transform = _dereq_('./lib/_stream_transform.js');
13601exports.PassThrough = _dereq_('./lib/_stream_passthrough.js');
13602if (!process.browser && process.env.READABLE_STREAM === 'disable') {
13603 module.exports = _dereq_('stream');
13604}
13605
13606}).call(this)}).call(this,_dereq_('_process'))
13607},{"./lib/_stream_duplex.js":95,"./lib/_stream_passthrough.js":96,"./lib/_stream_readable.js":97,"./lib/_stream_transform.js":98,"./lib/_stream_writable.js":99,"_process":93,"stream":105}],102:[function(_dereq_,module,exports){
13608/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
13609/* eslint-disable node/no-deprecated-api */
13610var buffer = _dereq_('buffer')
13611var Buffer = buffer.Buffer
13612
13613// alternative to using Object.keys for old browsers
13614function copyProps (src, dst) {
13615 for (var key in src) {
13616 dst[key] = src[key]
13617 }
13618}
13619if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
13620 module.exports = buffer
13621} else {
13622 // Copy properties from require('buffer')
13623 copyProps(buffer, exports)
13624 exports.Buffer = SafeBuffer
13625}
13626
13627function SafeBuffer (arg, encodingOrOffset, length) {
13628 return Buffer(arg, encodingOrOffset, length)
13629}
13630
13631SafeBuffer.prototype = Object.create(Buffer.prototype)
13632
13633// Copy static methods from Buffer
13634copyProps(Buffer, SafeBuffer)
13635
13636SafeBuffer.from = function (arg, encodingOrOffset, length) {
13637 if (typeof arg === 'number') {
13638 throw new TypeError('Argument must not be a number')
13639 }
13640 return Buffer(arg, encodingOrOffset, length)
13641}
13642
13643SafeBuffer.alloc = function (size, fill, encoding) {
13644 if (typeof size !== 'number') {
13645 throw new TypeError('Argument must be a number')
13646 }
13647 var buf = Buffer(size)
13648 if (fill !== undefined) {
13649 if (typeof encoding === 'string') {
13650 buf.fill(fill, encoding)
13651 } else {
13652 buf.fill(fill)
13653 }
13654 } else {
13655 buf.fill(0)
13656 }
13657 return buf
13658}
13659
13660SafeBuffer.allocUnsafe = function (size) {
13661 if (typeof size !== 'number') {
13662 throw new TypeError('Argument must be a number')
13663 }
13664 return Buffer(size)
13665}
13666
13667SafeBuffer.allocUnsafeSlow = function (size) {
13668 if (typeof size !== 'number') {
13669 throw new TypeError('Argument must be a number')
13670 }
13671 return buffer.SlowBuffer(size)
13672}
13673
13674},{"buffer":4}],103:[function(_dereq_,module,exports){
13675'use strict';
13676
13677var GetIntrinsic = _dereq_('get-intrinsic');
13678var define = _dereq_('define-data-property');
13679var hasDescriptors = _dereq_('has-property-descriptors')();
13680var gOPD = _dereq_('gopd');
13681
13682var $TypeError = _dereq_('es-errors/type');
13683var $floor = GetIntrinsic('%Math.floor%');
13684
13685/** @type {import('.')} */
13686module.exports = function setFunctionLength(fn, length) {
13687 if (typeof fn !== 'function') {
13688 throw new $TypeError('`fn` is not a function');
13689 }
13690 if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) {
13691 throw new $TypeError('`length` must be a positive 32-bit integer');
13692 }
13693
13694 var loose = arguments.length > 2 && !!arguments[2];
13695
13696 var functionLengthIsConfigurable = true;
13697 var functionLengthIsWritable = true;
13698 if ('length' in fn && gOPD) {
13699 var desc = gOPD(fn, 'length');
13700 if (desc && !desc.configurable) {
13701 functionLengthIsConfigurable = false;
13702 }
13703 if (desc && !desc.writable) {
13704 functionLengthIsWritable = false;
13705 }
13706 }
13707
13708 if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) {
13709 if (hasDescriptors) {
13710 define(/** @type {Parameters<define>[0]} */ (fn), 'length', length, true, true);
13711 } else {
13712 define(/** @type {Parameters<define>[0]} */ (fn), 'length', length);
13713 }
13714 }
13715 return fn;
13716};
13717
13718},{"define-data-property":21,"es-errors/type":31,"get-intrinsic":37,"gopd":38,"has-property-descriptors":39}],104:[function(_dereq_,module,exports){
13719(function (factory) {
13720 if (typeof exports === 'object') {
13721 // Node/CommonJS
13722 module.exports = factory();
13723 } else if (typeof define === 'function' && define.amd) {
13724 // AMD
13725 define(factory);
13726 } else {
13727 // Browser globals (with support for web workers)
13728 var glob;
13729
13730 try {
13731 glob = window;
13732 } catch (e) {
13733 glob = self;
13734 }
13735
13736 glob.SparkMD5 = factory();
13737 }
13738}(function (undefined) {
13739
13740 'use strict';
13741
13742 /*
13743 * Fastest md5 implementation around (JKM md5).
13744 * Credits: Joseph Myers
13745 *
13746 * @see http://www.myersdaily.org/joseph/javascript/md5-text.html
13747 * @see http://jsperf.com/md5-shootout/7
13748 */
13749
13750 /* this function is much faster,
13751 so if possible we use it. Some IEs
13752 are the only ones I know of that
13753 need the idiotic second function,
13754 generated by an if clause. */
13755 var add32 = function (a, b) {
13756 return (a + b) & 0xFFFFFFFF;
13757 },
13758 hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
13759
13760
13761 function cmn(q, a, b, x, s, t) {
13762 a = add32(add32(a, q), add32(x, t));
13763 return add32((a << s) | (a >>> (32 - s)), b);
13764 }
13765
13766 function md5cycle(x, k) {
13767 var a = x[0],
13768 b = x[1],
13769 c = x[2],
13770 d = x[3];
13771
13772 a += (b & c | ~b & d) + k[0] - 680876936 | 0;
13773 a = (a << 7 | a >>> 25) + b | 0;
13774 d += (a & b | ~a & c) + k[1] - 389564586 | 0;
13775 d = (d << 12 | d >>> 20) + a | 0;
13776 c += (d & a | ~d & b) + k[2] + 606105819 | 0;
13777 c = (c << 17 | c >>> 15) + d | 0;
13778 b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
13779 b = (b << 22 | b >>> 10) + c | 0;
13780 a += (b & c | ~b & d) + k[4] - 176418897 | 0;
13781 a = (a << 7 | a >>> 25) + b | 0;
13782 d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
13783 d = (d << 12 | d >>> 20) + a | 0;
13784 c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
13785 c = (c << 17 | c >>> 15) + d | 0;
13786 b += (c & d | ~c & a) + k[7] - 45705983 | 0;
13787 b = (b << 22 | b >>> 10) + c | 0;
13788 a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
13789 a = (a << 7 | a >>> 25) + b | 0;
13790 d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
13791 d = (d << 12 | d >>> 20) + a | 0;
13792 c += (d & a | ~d & b) + k[10] - 42063 | 0;
13793 c = (c << 17 | c >>> 15) + d | 0;
13794 b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
13795 b = (b << 22 | b >>> 10) + c | 0;
13796 a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
13797 a = (a << 7 | a >>> 25) + b | 0;
13798 d += (a & b | ~a & c) + k[13] - 40341101 | 0;
13799 d = (d << 12 | d >>> 20) + a | 0;
13800 c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
13801 c = (c << 17 | c >>> 15) + d | 0;
13802 b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
13803 b = (b << 22 | b >>> 10) + c | 0;
13804
13805 a += (b & d | c & ~d) + k[1] - 165796510 | 0;
13806 a = (a << 5 | a >>> 27) + b | 0;
13807 d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
13808 d = (d << 9 | d >>> 23) + a | 0;
13809 c += (d & b | a & ~b) + k[11] + 643717713 | 0;
13810 c = (c << 14 | c >>> 18) + d | 0;
13811 b += (c & a | d & ~a) + k[0] - 373897302 | 0;
13812 b = (b << 20 | b >>> 12) + c | 0;
13813 a += (b & d | c & ~d) + k[5] - 701558691 | 0;
13814 a = (a << 5 | a >>> 27) + b | 0;
13815 d += (a & c | b & ~c) + k[10] + 38016083 | 0;
13816 d = (d << 9 | d >>> 23) + a | 0;
13817 c += (d & b | a & ~b) + k[15] - 660478335 | 0;
13818 c = (c << 14 | c >>> 18) + d | 0;
13819 b += (c & a | d & ~a) + k[4] - 405537848 | 0;
13820 b = (b << 20 | b >>> 12) + c | 0;
13821 a += (b & d | c & ~d) + k[9] + 568446438 | 0;
13822 a = (a << 5 | a >>> 27) + b | 0;
13823 d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
13824 d = (d << 9 | d >>> 23) + a | 0;
13825 c += (d & b | a & ~b) + k[3] - 187363961 | 0;
13826 c = (c << 14 | c >>> 18) + d | 0;
13827 b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
13828 b = (b << 20 | b >>> 12) + c | 0;
13829 a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
13830 a = (a << 5 | a >>> 27) + b | 0;
13831 d += (a & c | b & ~c) + k[2] - 51403784 | 0;
13832 d = (d << 9 | d >>> 23) + a | 0;
13833 c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
13834 c = (c << 14 | c >>> 18) + d | 0;
13835 b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
13836 b = (b << 20 | b >>> 12) + c | 0;
13837
13838 a += (b ^ c ^ d) + k[5] - 378558 | 0;
13839 a = (a << 4 | a >>> 28) + b | 0;
13840 d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
13841 d = (d << 11 | d >>> 21) + a | 0;
13842 c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
13843 c = (c << 16 | c >>> 16) + d | 0;
13844 b += (c ^ d ^ a) + k[14] - 35309556 | 0;
13845 b = (b << 23 | b >>> 9) + c | 0;
13846 a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
13847 a = (a << 4 | a >>> 28) + b | 0;
13848 d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
13849 d = (d << 11 | d >>> 21) + a | 0;
13850 c += (d ^ a ^ b) + k[7] - 155497632 | 0;
13851 c = (c << 16 | c >>> 16) + d | 0;
13852 b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
13853 b = (b << 23 | b >>> 9) + c | 0;
13854 a += (b ^ c ^ d) + k[13] + 681279174 | 0;
13855 a = (a << 4 | a >>> 28) + b | 0;
13856 d += (a ^ b ^ c) + k[0] - 358537222 | 0;
13857 d = (d << 11 | d >>> 21) + a | 0;
13858 c += (d ^ a ^ b) + k[3] - 722521979 | 0;
13859 c = (c << 16 | c >>> 16) + d | 0;
13860 b += (c ^ d ^ a) + k[6] + 76029189 | 0;
13861 b = (b << 23 | b >>> 9) + c | 0;
13862 a += (b ^ c ^ d) + k[9] - 640364487 | 0;
13863 a = (a << 4 | a >>> 28) + b | 0;
13864 d += (a ^ b ^ c) + k[12] - 421815835 | 0;
13865 d = (d << 11 | d >>> 21) + a | 0;
13866 c += (d ^ a ^ b) + k[15] + 530742520 | 0;
13867 c = (c << 16 | c >>> 16) + d | 0;
13868 b += (c ^ d ^ a) + k[2] - 995338651 | 0;
13869 b = (b << 23 | b >>> 9) + c | 0;
13870
13871 a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
13872 a = (a << 6 | a >>> 26) + b | 0;
13873 d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
13874 d = (d << 10 | d >>> 22) + a | 0;
13875 c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
13876 c = (c << 15 | c >>> 17) + d | 0;
13877 b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
13878 b = (b << 21 |b >>> 11) + c | 0;
13879 a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
13880 a = (a << 6 | a >>> 26) + b | 0;
13881 d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
13882 d = (d << 10 | d >>> 22) + a | 0;
13883 c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
13884 c = (c << 15 | c >>> 17) + d | 0;
13885 b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
13886 b = (b << 21 |b >>> 11) + c | 0;
13887 a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
13888 a = (a << 6 | a >>> 26) + b | 0;
13889 d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
13890 d = (d << 10 | d >>> 22) + a | 0;
13891 c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
13892 c = (c << 15 | c >>> 17) + d | 0;
13893 b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
13894 b = (b << 21 |b >>> 11) + c | 0;
13895 a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
13896 a = (a << 6 | a >>> 26) + b | 0;
13897 d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
13898 d = (d << 10 | d >>> 22) + a | 0;
13899 c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
13900 c = (c << 15 | c >>> 17) + d | 0;
13901 b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
13902 b = (b << 21 | b >>> 11) + c | 0;
13903
13904 x[0] = a + x[0] | 0;
13905 x[1] = b + x[1] | 0;
13906 x[2] = c + x[2] | 0;
13907 x[3] = d + x[3] | 0;
13908 }
13909
13910 function md5blk(s) {
13911 var md5blks = [],
13912 i; /* Andy King said do it this way. */
13913
13914 for (i = 0; i < 64; i += 4) {
13915 md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
13916 }
13917 return md5blks;
13918 }
13919
13920 function md5blk_array(a) {
13921 var md5blks = [],
13922 i; /* Andy King said do it this way. */
13923
13924 for (i = 0; i < 64; i += 4) {
13925 md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
13926 }
13927 return md5blks;
13928 }
13929
13930 function md51(s) {
13931 var n = s.length,
13932 state = [1732584193, -271733879, -1732584194, 271733878],
13933 i,
13934 length,
13935 tail,
13936 tmp,
13937 lo,
13938 hi;
13939
13940 for (i = 64; i <= n; i += 64) {
13941 md5cycle(state, md5blk(s.substring(i - 64, i)));
13942 }
13943 s = s.substring(i - 64);
13944 length = s.length;
13945 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13946 for (i = 0; i < length; i += 1) {
13947 tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
13948 }
13949 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13950 if (i > 55) {
13951 md5cycle(state, tail);
13952 for (i = 0; i < 16; i += 1) {
13953 tail[i] = 0;
13954 }
13955 }
13956
13957 // Beware that the final length might not fit in 32 bits so we take care of that
13958 tmp = n * 8;
13959 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
13960 lo = parseInt(tmp[2], 16);
13961 hi = parseInt(tmp[1], 16) || 0;
13962
13963 tail[14] = lo;
13964 tail[15] = hi;
13965
13966 md5cycle(state, tail);
13967 return state;
13968 }
13969
13970 function md51_array(a) {
13971 var n = a.length,
13972 state = [1732584193, -271733879, -1732584194, 271733878],
13973 i,
13974 length,
13975 tail,
13976 tmp,
13977 lo,
13978 hi;
13979
13980 for (i = 64; i <= n; i += 64) {
13981 md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
13982 }
13983
13984 // Not sure if it is a bug, however IE10 will always produce a sub array of length 1
13985 // containing the last element of the parent array if the sub array specified starts
13986 // beyond the length of the parent array - weird.
13987 // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
13988 a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
13989
13990 length = a.length;
13991 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
13992 for (i = 0; i < length; i += 1) {
13993 tail[i >> 2] |= a[i] << ((i % 4) << 3);
13994 }
13995
13996 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
13997 if (i > 55) {
13998 md5cycle(state, tail);
13999 for (i = 0; i < 16; i += 1) {
14000 tail[i] = 0;
14001 }
14002 }
14003
14004 // Beware that the final length might not fit in 32 bits so we take care of that
14005 tmp = n * 8;
14006 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
14007 lo = parseInt(tmp[2], 16);
14008 hi = parseInt(tmp[1], 16) || 0;
14009
14010 tail[14] = lo;
14011 tail[15] = hi;
14012
14013 md5cycle(state, tail);
14014
14015 return state;
14016 }
14017
14018 function rhex(n) {
14019 var s = '',
14020 j;
14021 for (j = 0; j < 4; j += 1) {
14022 s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
14023 }
14024 return s;
14025 }
14026
14027 function hex(x) {
14028 var i;
14029 for (i = 0; i < x.length; i += 1) {
14030 x[i] = rhex(x[i]);
14031 }
14032 return x.join('');
14033 }
14034
14035 // In some cases the fast add32 function cannot be used..
14036 if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
14037 add32 = function (x, y) {
14038 var lsw = (x & 0xFFFF) + (y & 0xFFFF),
14039 msw = (x >> 16) + (y >> 16) + (lsw >> 16);
14040 return (msw << 16) | (lsw & 0xFFFF);
14041 };
14042 }
14043
14044 // ---------------------------------------------------
14045
14046 /**
14047 * ArrayBuffer slice polyfill.
14048 *
14049 * @see https://github.com/ttaubert/node-arraybuffer-slice
14050 */
14051
14052 if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
14053 (function () {
14054 function clamp(val, length) {
14055 val = (val | 0) || 0;
14056
14057 if (val < 0) {
14058 return Math.max(val + length, 0);
14059 }
14060
14061 return Math.min(val, length);
14062 }
14063
14064 ArrayBuffer.prototype.slice = function (from, to) {
14065 var length = this.byteLength,
14066 begin = clamp(from, length),
14067 end = length,
14068 num,
14069 target,
14070 targetArray,
14071 sourceArray;
14072
14073 if (to !== undefined) {
14074 end = clamp(to, length);
14075 }
14076
14077 if (begin > end) {
14078 return new ArrayBuffer(0);
14079 }
14080
14081 num = end - begin;
14082 target = new ArrayBuffer(num);
14083 targetArray = new Uint8Array(target);
14084
14085 sourceArray = new Uint8Array(this, begin, num);
14086 targetArray.set(sourceArray);
14087
14088 return target;
14089 };
14090 })();
14091 }
14092
14093 // ---------------------------------------------------
14094
14095 /**
14096 * Helpers.
14097 */
14098
14099 function toUtf8(str) {
14100 if (/[\u0080-\uFFFF]/.test(str)) {
14101 str = unescape(encodeURIComponent(str));
14102 }
14103
14104 return str;
14105 }
14106
14107 function utf8Str2ArrayBuffer(str, returnUInt8Array) {
14108 var length = str.length,
14109 buff = new ArrayBuffer(length),
14110 arr = new Uint8Array(buff),
14111 i;
14112
14113 for (i = 0; i < length; i += 1) {
14114 arr[i] = str.charCodeAt(i);
14115 }
14116
14117 return returnUInt8Array ? arr : buff;
14118 }
14119
14120 function arrayBuffer2Utf8Str(buff) {
14121 return String.fromCharCode.apply(null, new Uint8Array(buff));
14122 }
14123
14124 function concatenateArrayBuffers(first, second, returnUInt8Array) {
14125 var result = new Uint8Array(first.byteLength + second.byteLength);
14126
14127 result.set(new Uint8Array(first));
14128 result.set(new Uint8Array(second), first.byteLength);
14129
14130 return returnUInt8Array ? result : result.buffer;
14131 }
14132
14133 function hexToBinaryString(hex) {
14134 var bytes = [],
14135 length = hex.length,
14136 x;
14137
14138 for (x = 0; x < length - 1; x += 2) {
14139 bytes.push(parseInt(hex.substr(x, 2), 16));
14140 }
14141
14142 return String.fromCharCode.apply(String, bytes);
14143 }
14144
14145 // ---------------------------------------------------
14146
14147 /**
14148 * SparkMD5 OOP implementation.
14149 *
14150 * Use this class to perform an incremental md5, otherwise use the
14151 * static methods instead.
14152 */
14153
14154 function SparkMD5() {
14155 // call reset to init the instance
14156 this.reset();
14157 }
14158
14159 /**
14160 * Appends a string.
14161 * A conversion will be applied if an utf8 string is detected.
14162 *
14163 * @param {String} str The string to be appended
14164 *
14165 * @return {SparkMD5} The instance itself
14166 */
14167 SparkMD5.prototype.append = function (str) {
14168 // Converts the string to utf8 bytes if necessary
14169 // Then append as binary
14170 this.appendBinary(toUtf8(str));
14171
14172 return this;
14173 };
14174
14175 /**
14176 * Appends a binary string.
14177 *
14178 * @param {String} contents The binary string to be appended
14179 *
14180 * @return {SparkMD5} The instance itself
14181 */
14182 SparkMD5.prototype.appendBinary = function (contents) {
14183 this._buff += contents;
14184 this._length += contents.length;
14185
14186 var length = this._buff.length,
14187 i;
14188
14189 for (i = 64; i <= length; i += 64) {
14190 md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
14191 }
14192
14193 this._buff = this._buff.substring(i - 64);
14194
14195 return this;
14196 };
14197
14198 /**
14199 * Finishes the incremental computation, reseting the internal state and
14200 * returning the result.
14201 *
14202 * @param {Boolean} raw True to get the raw string, false to get the hex string
14203 *
14204 * @return {String} The result
14205 */
14206 SparkMD5.prototype.end = function (raw) {
14207 var buff = this._buff,
14208 length = buff.length,
14209 i,
14210 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
14211 ret;
14212
14213 for (i = 0; i < length; i += 1) {
14214 tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
14215 }
14216
14217 this._finish(tail, length);
14218 ret = hex(this._hash);
14219
14220 if (raw) {
14221 ret = hexToBinaryString(ret);
14222 }
14223
14224 this.reset();
14225
14226 return ret;
14227 };
14228
14229 /**
14230 * Resets the internal state of the computation.
14231 *
14232 * @return {SparkMD5} The instance itself
14233 */
14234 SparkMD5.prototype.reset = function () {
14235 this._buff = '';
14236 this._length = 0;
14237 this._hash = [1732584193, -271733879, -1732584194, 271733878];
14238
14239 return this;
14240 };
14241
14242 /**
14243 * Gets the internal state of the computation.
14244 *
14245 * @return {Object} The state
14246 */
14247 SparkMD5.prototype.getState = function () {
14248 return {
14249 buff: this._buff,
14250 length: this._length,
14251 hash: this._hash.slice()
14252 };
14253 };
14254
14255 /**
14256 * Gets the internal state of the computation.
14257 *
14258 * @param {Object} state The state
14259 *
14260 * @return {SparkMD5} The instance itself
14261 */
14262 SparkMD5.prototype.setState = function (state) {
14263 this._buff = state.buff;
14264 this._length = state.length;
14265 this._hash = state.hash;
14266
14267 return this;
14268 };
14269
14270 /**
14271 * Releases memory used by the incremental buffer and other additional
14272 * resources. If you plan to use the instance again, use reset instead.
14273 */
14274 SparkMD5.prototype.destroy = function () {
14275 delete this._hash;
14276 delete this._buff;
14277 delete this._length;
14278 };
14279
14280 /**
14281 * Finish the final calculation based on the tail.
14282 *
14283 * @param {Array} tail The tail (will be modified)
14284 * @param {Number} length The length of the remaining buffer
14285 */
14286 SparkMD5.prototype._finish = function (tail, length) {
14287 var i = length,
14288 tmp,
14289 lo,
14290 hi;
14291
14292 tail[i >> 2] |= 0x80 << ((i % 4) << 3);
14293 if (i > 55) {
14294 md5cycle(this._hash, tail);
14295 for (i = 0; i < 16; i += 1) {
14296 tail[i] = 0;
14297 }
14298 }
14299
14300 // Do the final computation based on the tail and length
14301 // Beware that the final length may not fit in 32 bits so we take care of that
14302 tmp = this._length * 8;
14303 tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
14304 lo = parseInt(tmp[2], 16);
14305 hi = parseInt(tmp[1], 16) || 0;
14306
14307 tail[14] = lo;
14308 tail[15] = hi;
14309 md5cycle(this._hash, tail);
14310 };
14311
14312 /**
14313 * Performs the md5 hash on a string.
14314 * A conversion will be applied if utf8 string is detected.
14315 *
14316 * @param {String} str The string
14317 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
14318 *
14319 * @return {String} The result
14320 */
14321 SparkMD5.hash = function (str, raw) {
14322 // Converts the string to utf8 bytes if necessary
14323 // Then compute it using the binary function
14324 return SparkMD5.hashBinary(toUtf8(str), raw);
14325 };
14326
14327 /**
14328 * Performs the md5 hash on a binary string.
14329 *
14330 * @param {String} content The binary string
14331 * @param {Boolean} [raw] True to get the raw string, false to get the hex string
14332 *
14333 * @return {String} The result
14334 */
14335 SparkMD5.hashBinary = function (content, raw) {
14336 var hash = md51(content),
14337 ret = hex(hash);
14338
14339 return raw ? hexToBinaryString(ret) : ret;
14340 };
14341
14342 // ---------------------------------------------------
14343
14344 /**
14345 * SparkMD5 OOP implementation for array buffers.
14346 *
14347 * Use this class to perform an incremental md5 ONLY for array buffers.
14348 */
14349 SparkMD5.ArrayBuffer = function () {
14350 // call reset to init the instance
14351 this.reset();
14352 };
14353
14354 /**
14355 * Appends an array buffer.
14356 *
14357 * @param {ArrayBuffer} arr The array to be appended
14358 *
14359 * @return {SparkMD5.ArrayBuffer} The instance itself
14360 */
14361 SparkMD5.ArrayBuffer.prototype.append = function (arr) {
14362 var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
14363 length = buff.length,
14364 i;
14365
14366 this._length += arr.byteLength;
14367
14368 for (i = 64; i <= length; i += 64) {
14369 md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
14370 }
14371
14372 this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
14373
14374 return this;
14375 };
14376
14377 /**
14378 * Finishes the incremental computation, reseting the internal state and
14379 * returning the result.
14380 *
14381 * @param {Boolean} raw True to get the raw string, false to get the hex string
14382 *
14383 * @return {String} The result
14384 */
14385 SparkMD5.ArrayBuffer.prototype.end = function (raw) {
14386 var buff = this._buff,
14387 length = buff.length,
14388 tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
14389 i,
14390 ret;
14391
14392 for (i = 0; i < length; i += 1) {
14393 tail[i >> 2] |= buff[i] << ((i % 4) << 3);
14394 }
14395
14396 this._finish(tail, length);
14397 ret = hex(this._hash);
14398
14399 if (raw) {
14400 ret = hexToBinaryString(ret);
14401 }
14402
14403 this.reset();
14404
14405 return ret;
14406 };
14407
14408 /**
14409 * Resets the internal state of the computation.
14410 *
14411 * @return {SparkMD5.ArrayBuffer} The instance itself
14412 */
14413 SparkMD5.ArrayBuffer.prototype.reset = function () {
14414 this._buff = new Uint8Array(0);
14415 this._length = 0;
14416 this._hash = [1732584193, -271733879, -1732584194, 271733878];
14417
14418 return this;
14419 };
14420
14421 /**
14422 * Gets the internal state of the computation.
14423 *
14424 * @return {Object} The state
14425 */
14426 SparkMD5.ArrayBuffer.prototype.getState = function () {
14427 var state = SparkMD5.prototype.getState.call(this);
14428
14429 // Convert buffer to a string
14430 state.buff = arrayBuffer2Utf8Str(state.buff);
14431
14432 return state;
14433 };
14434
14435 /**
14436 * Gets the internal state of the computation.
14437 *
14438 * @param {Object} state The state
14439 *
14440 * @return {SparkMD5.ArrayBuffer} The instance itself
14441 */
14442 SparkMD5.ArrayBuffer.prototype.setState = function (state) {
14443 // Convert string to buffer
14444 state.buff = utf8Str2ArrayBuffer(state.buff, true);
14445
14446 return SparkMD5.prototype.setState.call(this, state);
14447 };
14448
14449 SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
14450
14451 SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
14452
14453 /**
14454 * Performs the md5 hash on an array buffer.
14455 *
14456 * @param {ArrayBuffer} arr The array buffer
14457 * @param {Boolean} [raw] True to get the raw string, false to get the hex one
14458 *
14459 * @return {String} The result
14460 */
14461 SparkMD5.ArrayBuffer.hash = function (arr, raw) {
14462 var hash = md51_array(new Uint8Array(arr)),
14463 ret = hex(hash);
14464
14465 return raw ? hexToBinaryString(ret) : ret;
14466 };
14467
14468 return SparkMD5;
14469}));
14470
14471},{}],105:[function(_dereq_,module,exports){
14472// Copyright Joyent, Inc. and other Node contributors.
14473//
14474// Permission is hereby granted, free of charge, to any person obtaining a
14475// copy of this software and associated documentation files (the
14476// "Software"), to deal in the Software without restriction, including
14477// without limitation the rights to use, copy, modify, merge, publish,
14478// distribute, sublicense, and/or sell copies of the Software, and to permit
14479// persons to whom the Software is furnished to do so, subject to the
14480// following conditions:
14481//
14482// The above copyright notice and this permission notice shall be included
14483// in all copies or substantial portions of the Software.
14484//
14485// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14486// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14487// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14488// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14489// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14490// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14491// USE OR OTHER DEALINGS IN THE SOFTWARE.
14492
14493module.exports = Stream;
14494
14495var EE = _dereq_('events').EventEmitter;
14496var inherits = _dereq_('inherits');
14497
14498inherits(Stream, EE);
14499Stream.Readable = _dereq_('readable-stream/readable.js');
14500Stream.Writable = _dereq_('readable-stream/writable.js');
14501Stream.Duplex = _dereq_('readable-stream/duplex.js');
14502Stream.Transform = _dereq_('readable-stream/transform.js');
14503Stream.PassThrough = _dereq_('readable-stream/passthrough.js');
14504
14505// Backwards-compat with node 0.4.x
14506Stream.Stream = Stream;
14507
14508
14509
14510// old-style streams. Note that the pipe method (the only relevant
14511// part of this class) is overridden in the Readable class.
14512
14513function Stream() {
14514 EE.call(this);
14515}
14516
14517Stream.prototype.pipe = function(dest, options) {
14518 var source = this;
14519
14520 function ondata(chunk) {
14521 if (dest.writable) {
14522 if (false === dest.write(chunk) && source.pause) {
14523 source.pause();
14524 }
14525 }
14526 }
14527
14528 source.on('data', ondata);
14529
14530 function ondrain() {
14531 if (source.readable && source.resume) {
14532 source.resume();
14533 }
14534 }
14535
14536 dest.on('drain', ondrain);
14537
14538 // If the 'end' option is not supplied, dest.end() will be called when
14539 // source gets the 'end' or 'close' events. Only dest.end() once.
14540 if (!dest._isStdio && (!options || options.end !== false)) {
14541 source.on('end', onend);
14542 source.on('close', onclose);
14543 }
14544
14545 var didOnEnd = false;
14546 function onend() {
14547 if (didOnEnd) return;
14548 didOnEnd = true;
14549
14550 dest.end();
14551 }
14552
14553
14554 function onclose() {
14555 if (didOnEnd) return;
14556 didOnEnd = true;
14557
14558 if (typeof dest.destroy === 'function') dest.destroy();
14559 }
14560
14561 // don't leave dangling pipes when there are errors.
14562 function onerror(er) {
14563 cleanup();
14564 if (EE.listenerCount(this, 'error') === 0) {
14565 throw er; // Unhandled stream error in pipe.
14566 }
14567 }
14568
14569 source.on('error', onerror);
14570 dest.on('error', onerror);
14571
14572 // remove all the event listeners that were added.
14573 function cleanup() {
14574 source.removeListener('data', ondata);
14575 dest.removeListener('drain', ondrain);
14576
14577 source.removeListener('end', onend);
14578 source.removeListener('close', onclose);
14579
14580 source.removeListener('error', onerror);
14581 dest.removeListener('error', onerror);
14582
14583 source.removeListener('end', cleanup);
14584 source.removeListener('close', cleanup);
14585
14586 dest.removeListener('close', cleanup);
14587 }
14588
14589 source.on('end', cleanup);
14590 source.on('close', cleanup);
14591
14592 dest.on('close', cleanup);
14593
14594 dest.emit('pipe', source);
14595
14596 // Allow for unix-like usage: A.pipe(B).pipe(C)
14597 return dest;
14598};
14599
14600},{"events":33,"inherits":45,"readable-stream/duplex.js":107,"readable-stream/passthrough.js":116,"readable-stream/readable.js":117,"readable-stream/transform.js":118,"readable-stream/writable.js":119}],106:[function(_dereq_,module,exports){
14601var toString = {}.toString;
14602
14603module.exports = Array.isArray || function (arr) {
14604 return toString.call(arr) == '[object Array]';
14605};
14606
14607},{}],107:[function(_dereq_,module,exports){
14608module.exports = _dereq_('./lib/_stream_duplex.js');
14609
14610},{"./lib/_stream_duplex.js":108}],108:[function(_dereq_,module,exports){
14611// Copyright Joyent, Inc. and other Node contributors.
14612//
14613// Permission is hereby granted, free of charge, to any person obtaining a
14614// copy of this software and associated documentation files (the
14615// "Software"), to deal in the Software without restriction, including
14616// without limitation the rights to use, copy, modify, merge, publish,
14617// distribute, sublicense, and/or sell copies of the Software, and to permit
14618// persons to whom the Software is furnished to do so, subject to the
14619// following conditions:
14620//
14621// The above copyright notice and this permission notice shall be included
14622// in all copies or substantial portions of the Software.
14623//
14624// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14625// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14626// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14627// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14628// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14629// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14630// USE OR OTHER DEALINGS IN THE SOFTWARE.
14631
14632// a duplex stream is just a stream that is both readable and writable.
14633// Since JS doesn't have multiple prototypal inheritance, this class
14634// prototypally inherits from Readable, and then parasitically from
14635// Writable.
14636
14637'use strict';
14638
14639/*<replacement>*/
14640
14641var pna = _dereq_('process-nextick-args');
14642/*</replacement>*/
14643
14644/*<replacement>*/
14645var objectKeys = Object.keys || function (obj) {
14646 var keys = [];
14647 for (var key in obj) {
14648 keys.push(key);
14649 }return keys;
14650};
14651/*</replacement>*/
14652
14653module.exports = Duplex;
14654
14655/*<replacement>*/
14656var util = Object.create(_dereq_('core-util-is'));
14657util.inherits = _dereq_('inherits');
14658/*</replacement>*/
14659
14660var Readable = _dereq_('./_stream_readable');
14661var Writable = _dereq_('./_stream_writable');
14662
14663util.inherits(Duplex, Readable);
14664
14665{
14666 // avoid scope creep, the keys array can then be collected
14667 var keys = objectKeys(Writable.prototype);
14668 for (var v = 0; v < keys.length; v++) {
14669 var method = keys[v];
14670 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
14671 }
14672}
14673
14674function Duplex(options) {
14675 if (!(this instanceof Duplex)) return new Duplex(options);
14676
14677 Readable.call(this, options);
14678 Writable.call(this, options);
14679
14680 if (options && options.readable === false) this.readable = false;
14681
14682 if (options && options.writable === false) this.writable = false;
14683
14684 this.allowHalfOpen = true;
14685 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
14686
14687 this.once('end', onend);
14688}
14689
14690Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
14691 // making it explicit this property is not enumerable
14692 // because otherwise some prototype manipulation in
14693 // userland will fail
14694 enumerable: false,
14695 get: function () {
14696 return this._writableState.highWaterMark;
14697 }
14698});
14699
14700// the no-half-open enforcer
14701function onend() {
14702 // if we allow half-open state, or if the writable side ended,
14703 // then we're ok.
14704 if (this.allowHalfOpen || this._writableState.ended) return;
14705
14706 // no more data can be written.
14707 // But allow more writes to happen in this tick.
14708 pna.nextTick(onEndNT, this);
14709}
14710
14711function onEndNT(self) {
14712 self.end();
14713}
14714
14715Object.defineProperty(Duplex.prototype, 'destroyed', {
14716 get: function () {
14717 if (this._readableState === undefined || this._writableState === undefined) {
14718 return false;
14719 }
14720 return this._readableState.destroyed && this._writableState.destroyed;
14721 },
14722 set: function (value) {
14723 // we ignore the value if the stream
14724 // has not been initialized yet
14725 if (this._readableState === undefined || this._writableState === undefined) {
14726 return;
14727 }
14728
14729 // backward compatibility, the user is explicitly
14730 // managing destroyed
14731 this._readableState.destroyed = value;
14732 this._writableState.destroyed = value;
14733 }
14734});
14735
14736Duplex.prototype._destroy = function (err, cb) {
14737 this.push(null);
14738 this.end();
14739
14740 pna.nextTick(cb, err);
14741};
14742},{"./_stream_readable":110,"./_stream_writable":112,"core-util-is":7,"inherits":45,"process-nextick-args":92}],109:[function(_dereq_,module,exports){
14743// Copyright Joyent, Inc. and other Node contributors.
14744//
14745// Permission is hereby granted, free of charge, to any person obtaining a
14746// copy of this software and associated documentation files (the
14747// "Software"), to deal in the Software without restriction, including
14748// without limitation the rights to use, copy, modify, merge, publish,
14749// distribute, sublicense, and/or sell copies of the Software, and to permit
14750// persons to whom the Software is furnished to do so, subject to the
14751// following conditions:
14752//
14753// The above copyright notice and this permission notice shall be included
14754// in all copies or substantial portions of the Software.
14755//
14756// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14757// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14758// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14759// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14760// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14761// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14762// USE OR OTHER DEALINGS IN THE SOFTWARE.
14763
14764// a passthrough stream.
14765// basically just the most minimal sort of Transform stream.
14766// Every written chunk gets output as-is.
14767
14768'use strict';
14769
14770module.exports = PassThrough;
14771
14772var Transform = _dereq_('./_stream_transform');
14773
14774/*<replacement>*/
14775var util = Object.create(_dereq_('core-util-is'));
14776util.inherits = _dereq_('inherits');
14777/*</replacement>*/
14778
14779util.inherits(PassThrough, Transform);
14780
14781function PassThrough(options) {
14782 if (!(this instanceof PassThrough)) return new PassThrough(options);
14783
14784 Transform.call(this, options);
14785}
14786
14787PassThrough.prototype._transform = function (chunk, encoding, cb) {
14788 cb(null, chunk);
14789};
14790},{"./_stream_transform":111,"core-util-is":7,"inherits":45}],110:[function(_dereq_,module,exports){
14791(function (process,global){(function (){
14792// Copyright Joyent, Inc. and other Node contributors.
14793//
14794// Permission is hereby granted, free of charge, to any person obtaining a
14795// copy of this software and associated documentation files (the
14796// "Software"), to deal in the Software without restriction, including
14797// without limitation the rights to use, copy, modify, merge, publish,
14798// distribute, sublicense, and/or sell copies of the Software, and to permit
14799// persons to whom the Software is furnished to do so, subject to the
14800// following conditions:
14801//
14802// The above copyright notice and this permission notice shall be included
14803// in all copies or substantial portions of the Software.
14804//
14805// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14806// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14807// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14808// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14809// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14810// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14811// USE OR OTHER DEALINGS IN THE SOFTWARE.
14812
14813'use strict';
14814
14815/*<replacement>*/
14816
14817var pna = _dereq_('process-nextick-args');
14818/*</replacement>*/
14819
14820module.exports = Readable;
14821
14822/*<replacement>*/
14823var isArray = _dereq_('isarray');
14824/*</replacement>*/
14825
14826/*<replacement>*/
14827var Duplex;
14828/*</replacement>*/
14829
14830Readable.ReadableState = ReadableState;
14831
14832/*<replacement>*/
14833var EE = _dereq_('events').EventEmitter;
14834
14835var EElistenerCount = function (emitter, type) {
14836 return emitter.listeners(type).length;
14837};
14838/*</replacement>*/
14839
14840/*<replacement>*/
14841var Stream = _dereq_('./internal/streams/stream');
14842/*</replacement>*/
14843
14844/*<replacement>*/
14845
14846var Buffer = _dereq_('safe-buffer').Buffer;
14847var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
14848function _uint8ArrayToBuffer(chunk) {
14849 return Buffer.from(chunk);
14850}
14851function _isUint8Array(obj) {
14852 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
14853}
14854
14855/*</replacement>*/
14856
14857/*<replacement>*/
14858var util = Object.create(_dereq_('core-util-is'));
14859util.inherits = _dereq_('inherits');
14860/*</replacement>*/
14861
14862/*<replacement>*/
14863var debugUtil = _dereq_('util');
14864var debug = void 0;
14865if (debugUtil && debugUtil.debuglog) {
14866 debug = debugUtil.debuglog('stream');
14867} else {
14868 debug = function () {};
14869}
14870/*</replacement>*/
14871
14872var BufferList = _dereq_('./internal/streams/BufferList');
14873var destroyImpl = _dereq_('./internal/streams/destroy');
14874var StringDecoder;
14875
14876util.inherits(Readable, Stream);
14877
14878var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
14879
14880function prependListener(emitter, event, fn) {
14881 // Sadly this is not cacheable as some libraries bundle their own
14882 // event emitter implementation with them.
14883 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
14884
14885 // This is a hack to make sure that our error handler is attached before any
14886 // userland ones. NEVER DO THIS. This is here only because this code needs
14887 // to continue to work with older versions of Node.js that do not include
14888 // the prependListener() method. The goal is to eventually remove this hack.
14889 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
14890}
14891
14892function ReadableState(options, stream) {
14893 Duplex = Duplex || _dereq_('./_stream_duplex');
14894
14895 options = options || {};
14896
14897 // Duplex streams are both readable and writable, but share
14898 // the same options object.
14899 // However, some cases require setting options to different
14900 // values for the readable and the writable sides of the duplex stream.
14901 // These options can be provided separately as readableXXX and writableXXX.
14902 var isDuplex = stream instanceof Duplex;
14903
14904 // object stream flag. Used to make read(n) ignore n and to
14905 // make all the buffer merging and length checks go away
14906 this.objectMode = !!options.objectMode;
14907
14908 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
14909
14910 // the point at which it stops calling _read() to fill the buffer
14911 // Note: 0 is a valid value, means "don't call _read preemptively ever"
14912 var hwm = options.highWaterMark;
14913 var readableHwm = options.readableHighWaterMark;
14914 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
14915
14916 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
14917
14918 // cast to ints.
14919 this.highWaterMark = Math.floor(this.highWaterMark);
14920
14921 // A linked list is used to store data chunks instead of an array because the
14922 // linked list can remove elements from the beginning faster than
14923 // array.shift()
14924 this.buffer = new BufferList();
14925 this.length = 0;
14926 this.pipes = null;
14927 this.pipesCount = 0;
14928 this.flowing = null;
14929 this.ended = false;
14930 this.endEmitted = false;
14931 this.reading = false;
14932
14933 // a flag to be able to tell if the event 'readable'/'data' is emitted
14934 // immediately, or on a later tick. We set this to true at first, because
14935 // any actions that shouldn't happen until "later" should generally also
14936 // not happen before the first read call.
14937 this.sync = true;
14938
14939 // whenever we return null, then we set a flag to say
14940 // that we're awaiting a 'readable' event emission.
14941 this.needReadable = false;
14942 this.emittedReadable = false;
14943 this.readableListening = false;
14944 this.resumeScheduled = false;
14945
14946 // has it been destroyed
14947 this.destroyed = false;
14948
14949 // Crypto is kind of old and crusty. Historically, its default string
14950 // encoding is 'binary' so we have to make this configurable.
14951 // Everything else in the universe uses 'utf8', though.
14952 this.defaultEncoding = options.defaultEncoding || 'utf8';
14953
14954 // the number of writers that are awaiting a drain event in .pipe()s
14955 this.awaitDrain = 0;
14956
14957 // if true, a maybeReadMore has been scheduled
14958 this.readingMore = false;
14959
14960 this.decoder = null;
14961 this.encoding = null;
14962 if (options.encoding) {
14963 if (!StringDecoder) StringDecoder = _dereq_('string_decoder/').StringDecoder;
14964 this.decoder = new StringDecoder(options.encoding);
14965 this.encoding = options.encoding;
14966 }
14967}
14968
14969function Readable(options) {
14970 Duplex = Duplex || _dereq_('./_stream_duplex');
14971
14972 if (!(this instanceof Readable)) return new Readable(options);
14973
14974 this._readableState = new ReadableState(options, this);
14975
14976 // legacy
14977 this.readable = true;
14978
14979 if (options) {
14980 if (typeof options.read === 'function') this._read = options.read;
14981
14982 if (typeof options.destroy === 'function') this._destroy = options.destroy;
14983 }
14984
14985 Stream.call(this);
14986}
14987
14988Object.defineProperty(Readable.prototype, 'destroyed', {
14989 get: function () {
14990 if (this._readableState === undefined) {
14991 return false;
14992 }
14993 return this._readableState.destroyed;
14994 },
14995 set: function (value) {
14996 // we ignore the value if the stream
14997 // has not been initialized yet
14998 if (!this._readableState) {
14999 return;
15000 }
15001
15002 // backward compatibility, the user is explicitly
15003 // managing destroyed
15004 this._readableState.destroyed = value;
15005 }
15006});
15007
15008Readable.prototype.destroy = destroyImpl.destroy;
15009Readable.prototype._undestroy = destroyImpl.undestroy;
15010Readable.prototype._destroy = function (err, cb) {
15011 this.push(null);
15012 cb(err);
15013};
15014
15015// Manually shove something into the read() buffer.
15016// This returns true if the highWaterMark has not been hit yet,
15017// similar to how Writable.write() returns true if you should
15018// write() some more.
15019Readable.prototype.push = function (chunk, encoding) {
15020 var state = this._readableState;
15021 var skipChunkCheck;
15022
15023 if (!state.objectMode) {
15024 if (typeof chunk === 'string') {
15025 encoding = encoding || state.defaultEncoding;
15026 if (encoding !== state.encoding) {
15027 chunk = Buffer.from(chunk, encoding);
15028 encoding = '';
15029 }
15030 skipChunkCheck = true;
15031 }
15032 } else {
15033 skipChunkCheck = true;
15034 }
15035
15036 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
15037};
15038
15039// Unshift should *always* be something directly out of read()
15040Readable.prototype.unshift = function (chunk) {
15041 return readableAddChunk(this, chunk, null, true, false);
15042};
15043
15044function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
15045 var state = stream._readableState;
15046 if (chunk === null) {
15047 state.reading = false;
15048 onEofChunk(stream, state);
15049 } else {
15050 var er;
15051 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
15052 if (er) {
15053 stream.emit('error', er);
15054 } else if (state.objectMode || chunk && chunk.length > 0) {
15055 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
15056 chunk = _uint8ArrayToBuffer(chunk);
15057 }
15058
15059 if (addToFront) {
15060 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
15061 } else if (state.ended) {
15062 stream.emit('error', new Error('stream.push() after EOF'));
15063 } else {
15064 state.reading = false;
15065 if (state.decoder && !encoding) {
15066 chunk = state.decoder.write(chunk);
15067 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
15068 } else {
15069 addChunk(stream, state, chunk, false);
15070 }
15071 }
15072 } else if (!addToFront) {
15073 state.reading = false;
15074 }
15075 }
15076
15077 return needMoreData(state);
15078}
15079
15080function addChunk(stream, state, chunk, addToFront) {
15081 if (state.flowing && state.length === 0 && !state.sync) {
15082 stream.emit('data', chunk);
15083 stream.read(0);
15084 } else {
15085 // update the buffer info.
15086 state.length += state.objectMode ? 1 : chunk.length;
15087 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
15088
15089 if (state.needReadable) emitReadable(stream);
15090 }
15091 maybeReadMore(stream, state);
15092}
15093
15094function chunkInvalid(state, chunk) {
15095 var er;
15096 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
15097 er = new TypeError('Invalid non-string/buffer chunk');
15098 }
15099 return er;
15100}
15101
15102// if it's past the high water mark, we can push in some more.
15103// Also, if we have no data yet, we can stand some
15104// more bytes. This is to work around cases where hwm=0,
15105// such as the repl. Also, if the push() triggered a
15106// readable event, and the user called read(largeNumber) such that
15107// needReadable was set, then we ought to push more, so that another
15108// 'readable' event will be triggered.
15109function needMoreData(state) {
15110 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
15111}
15112
15113Readable.prototype.isPaused = function () {
15114 return this._readableState.flowing === false;
15115};
15116
15117// backwards compatibility.
15118Readable.prototype.setEncoding = function (enc) {
15119 if (!StringDecoder) StringDecoder = _dereq_('string_decoder/').StringDecoder;
15120 this._readableState.decoder = new StringDecoder(enc);
15121 this._readableState.encoding = enc;
15122 return this;
15123};
15124
15125// Don't raise the hwm > 8MB
15126var MAX_HWM = 0x800000;
15127function computeNewHighWaterMark(n) {
15128 if (n >= MAX_HWM) {
15129 n = MAX_HWM;
15130 } else {
15131 // Get the next highest power of 2 to prevent increasing hwm excessively in
15132 // tiny amounts
15133 n--;
15134 n |= n >>> 1;
15135 n |= n >>> 2;
15136 n |= n >>> 4;
15137 n |= n >>> 8;
15138 n |= n >>> 16;
15139 n++;
15140 }
15141 return n;
15142}
15143
15144// This function is designed to be inlinable, so please take care when making
15145// changes to the function body.
15146function howMuchToRead(n, state) {
15147 if (n <= 0 || state.length === 0 && state.ended) return 0;
15148 if (state.objectMode) return 1;
15149 if (n !== n) {
15150 // Only flow one buffer at a time
15151 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
15152 }
15153 // If we're asking for more than the current hwm, then raise the hwm.
15154 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
15155 if (n <= state.length) return n;
15156 // Don't have enough
15157 if (!state.ended) {
15158 state.needReadable = true;
15159 return 0;
15160 }
15161 return state.length;
15162}
15163
15164// you can override either this method, or the async _read(n) below.
15165Readable.prototype.read = function (n) {
15166 debug('read', n);
15167 n = parseInt(n, 10);
15168 var state = this._readableState;
15169 var nOrig = n;
15170
15171 if (n !== 0) state.emittedReadable = false;
15172
15173 // if we're doing read(0) to trigger a readable event, but we
15174 // already have a bunch of data in the buffer, then just trigger
15175 // the 'readable' event and move on.
15176 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
15177 debug('read: emitReadable', state.length, state.ended);
15178 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
15179 return null;
15180 }
15181
15182 n = howMuchToRead(n, state);
15183
15184 // if we've ended, and we're now clear, then finish it up.
15185 if (n === 0 && state.ended) {
15186 if (state.length === 0) endReadable(this);
15187 return null;
15188 }
15189
15190 // All the actual chunk generation logic needs to be
15191 // *below* the call to _read. The reason is that in certain
15192 // synthetic stream cases, such as passthrough streams, _read
15193 // may be a completely synchronous operation which may change
15194 // the state of the read buffer, providing enough data when
15195 // before there was *not* enough.
15196 //
15197 // So, the steps are:
15198 // 1. Figure out what the state of things will be after we do
15199 // a read from the buffer.
15200 //
15201 // 2. If that resulting state will trigger a _read, then call _read.
15202 // Note that this may be asynchronous, or synchronous. Yes, it is
15203 // deeply ugly to write APIs this way, but that still doesn't mean
15204 // that the Readable class should behave improperly, as streams are
15205 // designed to be sync/async agnostic.
15206 // Take note if the _read call is sync or async (ie, if the read call
15207 // has returned yet), so that we know whether or not it's safe to emit
15208 // 'readable' etc.
15209 //
15210 // 3. Actually pull the requested chunks out of the buffer and return.
15211
15212 // if we need a readable event, then we need to do some reading.
15213 var doRead = state.needReadable;
15214 debug('need readable', doRead);
15215
15216 // if we currently have less than the highWaterMark, then also read some
15217 if (state.length === 0 || state.length - n < state.highWaterMark) {
15218 doRead = true;
15219 debug('length less than watermark', doRead);
15220 }
15221
15222 // however, if we've ended, then there's no point, and if we're already
15223 // reading, then it's unnecessary.
15224 if (state.ended || state.reading) {
15225 doRead = false;
15226 debug('reading or ended', doRead);
15227 } else if (doRead) {
15228 debug('do read');
15229 state.reading = true;
15230 state.sync = true;
15231 // if the length is currently zero, then we *need* a readable event.
15232 if (state.length === 0) state.needReadable = true;
15233 // call internal read method
15234 this._read(state.highWaterMark);
15235 state.sync = false;
15236 // If _read pushed data synchronously, then `reading` will be false,
15237 // and we need to re-evaluate how much data we can return to the user.
15238 if (!state.reading) n = howMuchToRead(nOrig, state);
15239 }
15240
15241 var ret;
15242 if (n > 0) ret = fromList(n, state);else ret = null;
15243
15244 if (ret === null) {
15245 state.needReadable = true;
15246 n = 0;
15247 } else {
15248 state.length -= n;
15249 }
15250
15251 if (state.length === 0) {
15252 // If we have nothing in the buffer, then we want to know
15253 // as soon as we *do* get something into the buffer.
15254 if (!state.ended) state.needReadable = true;
15255
15256 // If we tried to read() past the EOF, then emit end on the next tick.
15257 if (nOrig !== n && state.ended) endReadable(this);
15258 }
15259
15260 if (ret !== null) this.emit('data', ret);
15261
15262 return ret;
15263};
15264
15265function onEofChunk(stream, state) {
15266 if (state.ended) return;
15267 if (state.decoder) {
15268 var chunk = state.decoder.end();
15269 if (chunk && chunk.length) {
15270 state.buffer.push(chunk);
15271 state.length += state.objectMode ? 1 : chunk.length;
15272 }
15273 }
15274 state.ended = true;
15275
15276 // emit 'readable' now to make sure it gets picked up.
15277 emitReadable(stream);
15278}
15279
15280// Don't emit readable right away in sync mode, because this can trigger
15281// another read() call => stack overflow. This way, it might trigger
15282// a nextTick recursion warning, but that's not so bad.
15283function emitReadable(stream) {
15284 var state = stream._readableState;
15285 state.needReadable = false;
15286 if (!state.emittedReadable) {
15287 debug('emitReadable', state.flowing);
15288 state.emittedReadable = true;
15289 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
15290 }
15291}
15292
15293function emitReadable_(stream) {
15294 debug('emit readable');
15295 stream.emit('readable');
15296 flow(stream);
15297}
15298
15299// at this point, the user has presumably seen the 'readable' event,
15300// and called read() to consume some data. that may have triggered
15301// in turn another _read(n) call, in which case reading = true if
15302// it's in progress.
15303// However, if we're not ended, or reading, and the length < hwm,
15304// then go ahead and try to read some more preemptively.
15305function maybeReadMore(stream, state) {
15306 if (!state.readingMore) {
15307 state.readingMore = true;
15308 pna.nextTick(maybeReadMore_, stream, state);
15309 }
15310}
15311
15312function maybeReadMore_(stream, state) {
15313 var len = state.length;
15314 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
15315 debug('maybeReadMore read 0');
15316 stream.read(0);
15317 if (len === state.length)
15318 // didn't get any data, stop spinning.
15319 break;else len = state.length;
15320 }
15321 state.readingMore = false;
15322}
15323
15324// abstract method. to be overridden in specific implementation classes.
15325// call cb(er, data) where data is <= n in length.
15326// for virtual (non-string, non-buffer) streams, "length" is somewhat
15327// arbitrary, and perhaps not very meaningful.
15328Readable.prototype._read = function (n) {
15329 this.emit('error', new Error('_read() is not implemented'));
15330};
15331
15332Readable.prototype.pipe = function (dest, pipeOpts) {
15333 var src = this;
15334 var state = this._readableState;
15335
15336 switch (state.pipesCount) {
15337 case 0:
15338 state.pipes = dest;
15339 break;
15340 case 1:
15341 state.pipes = [state.pipes, dest];
15342 break;
15343 default:
15344 state.pipes.push(dest);
15345 break;
15346 }
15347 state.pipesCount += 1;
15348 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
15349
15350 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
15351
15352 var endFn = doEnd ? onend : unpipe;
15353 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
15354
15355 dest.on('unpipe', onunpipe);
15356 function onunpipe(readable, unpipeInfo) {
15357 debug('onunpipe');
15358 if (readable === src) {
15359 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
15360 unpipeInfo.hasUnpiped = true;
15361 cleanup();
15362 }
15363 }
15364 }
15365
15366 function onend() {
15367 debug('onend');
15368 dest.end();
15369 }
15370
15371 // when the dest drains, it reduces the awaitDrain counter
15372 // on the source. This would be more elegant with a .once()
15373 // handler in flow(), but adding and removing repeatedly is
15374 // too slow.
15375 var ondrain = pipeOnDrain(src);
15376 dest.on('drain', ondrain);
15377
15378 var cleanedUp = false;
15379 function cleanup() {
15380 debug('cleanup');
15381 // cleanup event handlers once the pipe is broken
15382 dest.removeListener('close', onclose);
15383 dest.removeListener('finish', onfinish);
15384 dest.removeListener('drain', ondrain);
15385 dest.removeListener('error', onerror);
15386 dest.removeListener('unpipe', onunpipe);
15387 src.removeListener('end', onend);
15388 src.removeListener('end', unpipe);
15389 src.removeListener('data', ondata);
15390
15391 cleanedUp = true;
15392
15393 // if the reader is waiting for a drain event from this
15394 // specific writer, then it would cause it to never start
15395 // flowing again.
15396 // So, if this is awaiting a drain, then we just call it now.
15397 // If we don't know, then assume that we are waiting for one.
15398 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
15399 }
15400
15401 // If the user pushes more data while we're writing to dest then we'll end up
15402 // in ondata again. However, we only want to increase awaitDrain once because
15403 // dest will only emit one 'drain' event for the multiple writes.
15404 // => Introduce a guard on increasing awaitDrain.
15405 var increasedAwaitDrain = false;
15406 src.on('data', ondata);
15407 function ondata(chunk) {
15408 debug('ondata');
15409 increasedAwaitDrain = false;
15410 var ret = dest.write(chunk);
15411 if (false === ret && !increasedAwaitDrain) {
15412 // If the user unpiped during `dest.write()`, it is possible
15413 // to get stuck in a permanently paused state if that write
15414 // also returned false.
15415 // => Check whether `dest` is still a piping destination.
15416 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
15417 debug('false write response, pause', state.awaitDrain);
15418 state.awaitDrain++;
15419 increasedAwaitDrain = true;
15420 }
15421 src.pause();
15422 }
15423 }
15424
15425 // if the dest has an error, then stop piping into it.
15426 // however, don't suppress the throwing behavior for this.
15427 function onerror(er) {
15428 debug('onerror', er);
15429 unpipe();
15430 dest.removeListener('error', onerror);
15431 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
15432 }
15433
15434 // Make sure our error handler is attached before userland ones.
15435 prependListener(dest, 'error', onerror);
15436
15437 // Both close and finish should trigger unpipe, but only once.
15438 function onclose() {
15439 dest.removeListener('finish', onfinish);
15440 unpipe();
15441 }
15442 dest.once('close', onclose);
15443 function onfinish() {
15444 debug('onfinish');
15445 dest.removeListener('close', onclose);
15446 unpipe();
15447 }
15448 dest.once('finish', onfinish);
15449
15450 function unpipe() {
15451 debug('unpipe');
15452 src.unpipe(dest);
15453 }
15454
15455 // tell the dest that it's being piped to
15456 dest.emit('pipe', src);
15457
15458 // start the flow if it hasn't been started already.
15459 if (!state.flowing) {
15460 debug('pipe resume');
15461 src.resume();
15462 }
15463
15464 return dest;
15465};
15466
15467function pipeOnDrain(src) {
15468 return function () {
15469 var state = src._readableState;
15470 debug('pipeOnDrain', state.awaitDrain);
15471 if (state.awaitDrain) state.awaitDrain--;
15472 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
15473 state.flowing = true;
15474 flow(src);
15475 }
15476 };
15477}
15478
15479Readable.prototype.unpipe = function (dest) {
15480 var state = this._readableState;
15481 var unpipeInfo = { hasUnpiped: false };
15482
15483 // if we're not piping anywhere, then do nothing.
15484 if (state.pipesCount === 0) return this;
15485
15486 // just one destination. most common case.
15487 if (state.pipesCount === 1) {
15488 // passed in one, but it's not the right one.
15489 if (dest && dest !== state.pipes) return this;
15490
15491 if (!dest) dest = state.pipes;
15492
15493 // got a match.
15494 state.pipes = null;
15495 state.pipesCount = 0;
15496 state.flowing = false;
15497 if (dest) dest.emit('unpipe', this, unpipeInfo);
15498 return this;
15499 }
15500
15501 // slow case. multiple pipe destinations.
15502
15503 if (!dest) {
15504 // remove all.
15505 var dests = state.pipes;
15506 var len = state.pipesCount;
15507 state.pipes = null;
15508 state.pipesCount = 0;
15509 state.flowing = false;
15510
15511 for (var i = 0; i < len; i++) {
15512 dests[i].emit('unpipe', this, { hasUnpiped: false });
15513 }return this;
15514 }
15515
15516 // try to find the right one.
15517 var index = indexOf(state.pipes, dest);
15518 if (index === -1) return this;
15519
15520 state.pipes.splice(index, 1);
15521 state.pipesCount -= 1;
15522 if (state.pipesCount === 1) state.pipes = state.pipes[0];
15523
15524 dest.emit('unpipe', this, unpipeInfo);
15525
15526 return this;
15527};
15528
15529// set up data events if they are asked for
15530// Ensure readable listeners eventually get something
15531Readable.prototype.on = function (ev, fn) {
15532 var res = Stream.prototype.on.call(this, ev, fn);
15533
15534 if (ev === 'data') {
15535 // Start flowing on next tick if stream isn't explicitly paused
15536 if (this._readableState.flowing !== false) this.resume();
15537 } else if (ev === 'readable') {
15538 var state = this._readableState;
15539 if (!state.endEmitted && !state.readableListening) {
15540 state.readableListening = state.needReadable = true;
15541 state.emittedReadable = false;
15542 if (!state.reading) {
15543 pna.nextTick(nReadingNextTick, this);
15544 } else if (state.length) {
15545 emitReadable(this);
15546 }
15547 }
15548 }
15549
15550 return res;
15551};
15552Readable.prototype.addListener = Readable.prototype.on;
15553
15554function nReadingNextTick(self) {
15555 debug('readable nexttick read 0');
15556 self.read(0);
15557}
15558
15559// pause() and resume() are remnants of the legacy readable stream API
15560// If the user uses them, then switch into old mode.
15561Readable.prototype.resume = function () {
15562 var state = this._readableState;
15563 if (!state.flowing) {
15564 debug('resume');
15565 state.flowing = true;
15566 resume(this, state);
15567 }
15568 return this;
15569};
15570
15571function resume(stream, state) {
15572 if (!state.resumeScheduled) {
15573 state.resumeScheduled = true;
15574 pna.nextTick(resume_, stream, state);
15575 }
15576}
15577
15578function resume_(stream, state) {
15579 if (!state.reading) {
15580 debug('resume read 0');
15581 stream.read(0);
15582 }
15583
15584 state.resumeScheduled = false;
15585 state.awaitDrain = 0;
15586 stream.emit('resume');
15587 flow(stream);
15588 if (state.flowing && !state.reading) stream.read(0);
15589}
15590
15591Readable.prototype.pause = function () {
15592 debug('call pause flowing=%j', this._readableState.flowing);
15593 if (false !== this._readableState.flowing) {
15594 debug('pause');
15595 this._readableState.flowing = false;
15596 this.emit('pause');
15597 }
15598 return this;
15599};
15600
15601function flow(stream) {
15602 var state = stream._readableState;
15603 debug('flow', state.flowing);
15604 while (state.flowing && stream.read() !== null) {}
15605}
15606
15607// wrap an old-style stream as the async data source.
15608// This is *not* part of the readable stream interface.
15609// It is an ugly unfortunate mess of history.
15610Readable.prototype.wrap = function (stream) {
15611 var _this = this;
15612
15613 var state = this._readableState;
15614 var paused = false;
15615
15616 stream.on('end', function () {
15617 debug('wrapped end');
15618 if (state.decoder && !state.ended) {
15619 var chunk = state.decoder.end();
15620 if (chunk && chunk.length) _this.push(chunk);
15621 }
15622
15623 _this.push(null);
15624 });
15625
15626 stream.on('data', function (chunk) {
15627 debug('wrapped data');
15628 if (state.decoder) chunk = state.decoder.write(chunk);
15629
15630 // don't skip over falsy values in objectMode
15631 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
15632
15633 var ret = _this.push(chunk);
15634 if (!ret) {
15635 paused = true;
15636 stream.pause();
15637 }
15638 });
15639
15640 // proxy all the other methods.
15641 // important when wrapping filters and duplexes.
15642 for (var i in stream) {
15643 if (this[i] === undefined && typeof stream[i] === 'function') {
15644 this[i] = function (method) {
15645 return function () {
15646 return stream[method].apply(stream, arguments);
15647 };
15648 }(i);
15649 }
15650 }
15651
15652 // proxy certain important events.
15653 for (var n = 0; n < kProxyEvents.length; n++) {
15654 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
15655 }
15656
15657 // when we try to consume some more bytes, simply unpause the
15658 // underlying stream.
15659 this._read = function (n) {
15660 debug('wrapped _read', n);
15661 if (paused) {
15662 paused = false;
15663 stream.resume();
15664 }
15665 };
15666
15667 return this;
15668};
15669
15670Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
15671 // making it explicit this property is not enumerable
15672 // because otherwise some prototype manipulation in
15673 // userland will fail
15674 enumerable: false,
15675 get: function () {
15676 return this._readableState.highWaterMark;
15677 }
15678});
15679
15680// exposed for testing purposes only.
15681Readable._fromList = fromList;
15682
15683// Pluck off n bytes from an array of buffers.
15684// Length is the combined lengths of all the buffers in the list.
15685// This function is designed to be inlinable, so please take care when making
15686// changes to the function body.
15687function fromList(n, state) {
15688 // nothing buffered
15689 if (state.length === 0) return null;
15690
15691 var ret;
15692 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
15693 // read it all, truncate the list
15694 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
15695 state.buffer.clear();
15696 } else {
15697 // read part of list
15698 ret = fromListPartial(n, state.buffer, state.decoder);
15699 }
15700
15701 return ret;
15702}
15703
15704// Extracts only enough buffered data to satisfy the amount requested.
15705// This function is designed to be inlinable, so please take care when making
15706// changes to the function body.
15707function fromListPartial(n, list, hasStrings) {
15708 var ret;
15709 if (n < list.head.data.length) {
15710 // slice is the same for buffers and strings
15711 ret = list.head.data.slice(0, n);
15712 list.head.data = list.head.data.slice(n);
15713 } else if (n === list.head.data.length) {
15714 // first chunk is a perfect match
15715 ret = list.shift();
15716 } else {
15717 // result spans more than one buffer
15718 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
15719 }
15720 return ret;
15721}
15722
15723// Copies a specified amount of characters from the list of buffered data
15724// chunks.
15725// This function is designed to be inlinable, so please take care when making
15726// changes to the function body.
15727function copyFromBufferString(n, list) {
15728 var p = list.head;
15729 var c = 1;
15730 var ret = p.data;
15731 n -= ret.length;
15732 while (p = p.next) {
15733 var str = p.data;
15734 var nb = n > str.length ? str.length : n;
15735 if (nb === str.length) ret += str;else ret += str.slice(0, n);
15736 n -= nb;
15737 if (n === 0) {
15738 if (nb === str.length) {
15739 ++c;
15740 if (p.next) list.head = p.next;else list.head = list.tail = null;
15741 } else {
15742 list.head = p;
15743 p.data = str.slice(nb);
15744 }
15745 break;
15746 }
15747 ++c;
15748 }
15749 list.length -= c;
15750 return ret;
15751}
15752
15753// Copies a specified amount of bytes from the list of buffered data chunks.
15754// This function is designed to be inlinable, so please take care when making
15755// changes to the function body.
15756function copyFromBuffer(n, list) {
15757 var ret = Buffer.allocUnsafe(n);
15758 var p = list.head;
15759 var c = 1;
15760 p.data.copy(ret);
15761 n -= p.data.length;
15762 while (p = p.next) {
15763 var buf = p.data;
15764 var nb = n > buf.length ? buf.length : n;
15765 buf.copy(ret, ret.length - n, 0, nb);
15766 n -= nb;
15767 if (n === 0) {
15768 if (nb === buf.length) {
15769 ++c;
15770 if (p.next) list.head = p.next;else list.head = list.tail = null;
15771 } else {
15772 list.head = p;
15773 p.data = buf.slice(nb);
15774 }
15775 break;
15776 }
15777 ++c;
15778 }
15779 list.length -= c;
15780 return ret;
15781}
15782
15783function endReadable(stream) {
15784 var state = stream._readableState;
15785
15786 // If we get here before consuming all the bytes, then that is a
15787 // bug in node. Should never happen.
15788 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
15789
15790 if (!state.endEmitted) {
15791 state.ended = true;
15792 pna.nextTick(endReadableNT, state, stream);
15793 }
15794}
15795
15796function endReadableNT(state, stream) {
15797 // Check that we didn't get one last unshift.
15798 if (!state.endEmitted && state.length === 0) {
15799 state.endEmitted = true;
15800 stream.readable = false;
15801 stream.emit('end');
15802 }
15803}
15804
15805function indexOf(xs, x) {
15806 for (var i = 0, l = xs.length; i < l; i++) {
15807 if (xs[i] === x) return i;
15808 }
15809 return -1;
15810}
15811}).call(this)}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15812},{"./_stream_duplex":108,"./internal/streams/BufferList":113,"./internal/streams/destroy":114,"./internal/streams/stream":115,"_process":93,"core-util-is":7,"events":33,"inherits":45,"isarray":106,"process-nextick-args":92,"safe-buffer":120,"string_decoder/":121,"util":3}],111:[function(_dereq_,module,exports){
15813// Copyright Joyent, Inc. and other Node contributors.
15814//
15815// Permission is hereby granted, free of charge, to any person obtaining a
15816// copy of this software and associated documentation files (the
15817// "Software"), to deal in the Software without restriction, including
15818// without limitation the rights to use, copy, modify, merge, publish,
15819// distribute, sublicense, and/or sell copies of the Software, and to permit
15820// persons to whom the Software is furnished to do so, subject to the
15821// following conditions:
15822//
15823// The above copyright notice and this permission notice shall be included
15824// in all copies or substantial portions of the Software.
15825//
15826// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15827// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15828// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15829// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15830// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15831// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15832// USE OR OTHER DEALINGS IN THE SOFTWARE.
15833
15834// a transform stream is a readable/writable stream where you do
15835// something with the data. Sometimes it's called a "filter",
15836// but that's not a great name for it, since that implies a thing where
15837// some bits pass through, and others are simply ignored. (That would
15838// be a valid example of a transform, of course.)
15839//
15840// While the output is causally related to the input, it's not a
15841// necessarily symmetric or synchronous transformation. For example,
15842// a zlib stream might take multiple plain-text writes(), and then
15843// emit a single compressed chunk some time in the future.
15844//
15845// Here's how this works:
15846//
15847// The Transform stream has all the aspects of the readable and writable
15848// stream classes. When you write(chunk), that calls _write(chunk,cb)
15849// internally, and returns false if there's a lot of pending writes
15850// buffered up. When you call read(), that calls _read(n) until
15851// there's enough pending readable data buffered up.
15852//
15853// In a transform stream, the written data is placed in a buffer. When
15854// _read(n) is called, it transforms the queued up data, calling the
15855// buffered _write cb's as it consumes chunks. If consuming a single
15856// written chunk would result in multiple output chunks, then the first
15857// outputted bit calls the readcb, and subsequent chunks just go into
15858// the read buffer, and will cause it to emit 'readable' if necessary.
15859//
15860// This way, back-pressure is actually determined by the reading side,
15861// since _read has to be called to start processing a new chunk. However,
15862// a pathological inflate type of transform can cause excessive buffering
15863// here. For example, imagine a stream where every byte of input is
15864// interpreted as an integer from 0-255, and then results in that many
15865// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
15866// 1kb of data being output. In this case, you could write a very small
15867// amount of input, and end up with a very large amount of output. In
15868// such a pathological inflating mechanism, there'd be no way to tell
15869// the system to stop doing the transform. A single 4MB write could
15870// cause the system to run out of memory.
15871//
15872// However, even in such a pathological case, only a single written chunk
15873// would be consumed, and then the rest would wait (un-transformed) until
15874// the results of the previous transformed chunk were consumed.
15875
15876'use strict';
15877
15878module.exports = Transform;
15879
15880var Duplex = _dereq_('./_stream_duplex');
15881
15882/*<replacement>*/
15883var util = Object.create(_dereq_('core-util-is'));
15884util.inherits = _dereq_('inherits');
15885/*</replacement>*/
15886
15887util.inherits(Transform, Duplex);
15888
15889function afterTransform(er, data) {
15890 var ts = this._transformState;
15891 ts.transforming = false;
15892
15893 var cb = ts.writecb;
15894
15895 if (!cb) {
15896 return this.emit('error', new Error('write callback called multiple times'));
15897 }
15898
15899 ts.writechunk = null;
15900 ts.writecb = null;
15901
15902 if (data != null) // single equals check for both `null` and `undefined`
15903 this.push(data);
15904
15905 cb(er);
15906
15907 var rs = this._readableState;
15908 rs.reading = false;
15909 if (rs.needReadable || rs.length < rs.highWaterMark) {
15910 this._read(rs.highWaterMark);
15911 }
15912}
15913
15914function Transform(options) {
15915 if (!(this instanceof Transform)) return new Transform(options);
15916
15917 Duplex.call(this, options);
15918
15919 this._transformState = {
15920 afterTransform: afterTransform.bind(this),
15921 needTransform: false,
15922 transforming: false,
15923 writecb: null,
15924 writechunk: null,
15925 writeencoding: null
15926 };
15927
15928 // start out asking for a readable event once data is transformed.
15929 this._readableState.needReadable = true;
15930
15931 // we have implemented the _read method, and done the other things
15932 // that Readable wants before the first _read call, so unset the
15933 // sync guard flag.
15934 this._readableState.sync = false;
15935
15936 if (options) {
15937 if (typeof options.transform === 'function') this._transform = options.transform;
15938
15939 if (typeof options.flush === 'function') this._flush = options.flush;
15940 }
15941
15942 // When the writable side finishes, then flush out anything remaining.
15943 this.on('prefinish', prefinish);
15944}
15945
15946function prefinish() {
15947 var _this = this;
15948
15949 if (typeof this._flush === 'function') {
15950 this._flush(function (er, data) {
15951 done(_this, er, data);
15952 });
15953 } else {
15954 done(this, null, null);
15955 }
15956}
15957
15958Transform.prototype.push = function (chunk, encoding) {
15959 this._transformState.needTransform = false;
15960 return Duplex.prototype.push.call(this, chunk, encoding);
15961};
15962
15963// This is the part where you do stuff!
15964// override this function in implementation classes.
15965// 'chunk' is an input chunk.
15966//
15967// Call `push(newChunk)` to pass along transformed output
15968// to the readable side. You may call 'push' zero or more times.
15969//
15970// Call `cb(err)` when you are done with this chunk. If you pass
15971// an error, then that'll put the hurt on the whole operation. If you
15972// never call cb(), then you'll never get another chunk.
15973Transform.prototype._transform = function (chunk, encoding, cb) {
15974 throw new Error('_transform() is not implemented');
15975};
15976
15977Transform.prototype._write = function (chunk, encoding, cb) {
15978 var ts = this._transformState;
15979 ts.writecb = cb;
15980 ts.writechunk = chunk;
15981 ts.writeencoding = encoding;
15982 if (!ts.transforming) {
15983 var rs = this._readableState;
15984 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
15985 }
15986};
15987
15988// Doesn't matter what the args are here.
15989// _transform does all the work.
15990// That we got here means that the readable side wants more data.
15991Transform.prototype._read = function (n) {
15992 var ts = this._transformState;
15993
15994 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
15995 ts.transforming = true;
15996 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
15997 } else {
15998 // mark that we need a transform, so that any data that comes in
15999 // will get processed, now that we've asked for it.
16000 ts.needTransform = true;
16001 }
16002};
16003
16004Transform.prototype._destroy = function (err, cb) {
16005 var _this2 = this;
16006
16007 Duplex.prototype._destroy.call(this, err, function (err2) {
16008 cb(err2);
16009 _this2.emit('close');
16010 });
16011};
16012
16013function done(stream, er, data) {
16014 if (er) return stream.emit('error', er);
16015
16016 if (data != null) // single equals check for both `null` and `undefined`
16017 stream.push(data);
16018
16019 // if there's nothing in the write buffer, then that means
16020 // that nothing more will ever be provided
16021 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
16022
16023 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
16024
16025 return stream.push(null);
16026}
16027},{"./_stream_duplex":108,"core-util-is":7,"inherits":45}],112:[function(_dereq_,module,exports){
16028(function (process,global,setImmediate){(function (){
16029// Copyright Joyent, Inc. and other Node contributors.
16030//
16031// Permission is hereby granted, free of charge, to any person obtaining a
16032// copy of this software and associated documentation files (the
16033// "Software"), to deal in the Software without restriction, including
16034// without limitation the rights to use, copy, modify, merge, publish,
16035// distribute, sublicense, and/or sell copies of the Software, and to permit
16036// persons to whom the Software is furnished to do so, subject to the
16037// following conditions:
16038//
16039// The above copyright notice and this permission notice shall be included
16040// in all copies or substantial portions of the Software.
16041//
16042// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16043// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16044// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16045// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16046// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16047// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16048// USE OR OTHER DEALINGS IN THE SOFTWARE.
16049
16050// A bit simpler than readable streams.
16051// Implement an async ._write(chunk, encoding, cb), and it'll handle all
16052// the drain event emission and buffering.
16053
16054'use strict';
16055
16056/*<replacement>*/
16057
16058var pna = _dereq_('process-nextick-args');
16059/*</replacement>*/
16060
16061module.exports = Writable;
16062
16063/* <replacement> */
16064function WriteReq(chunk, encoding, cb) {
16065 this.chunk = chunk;
16066 this.encoding = encoding;
16067 this.callback = cb;
16068 this.next = null;
16069}
16070
16071// It seems a linked list but it is not
16072// there will be only 2 of these for each stream
16073function CorkedRequest(state) {
16074 var _this = this;
16075
16076 this.next = null;
16077 this.entry = null;
16078 this.finish = function () {
16079 onCorkedFinish(_this, state);
16080 };
16081}
16082/* </replacement> */
16083
16084/*<replacement>*/
16085var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
16086/*</replacement>*/
16087
16088/*<replacement>*/
16089var Duplex;
16090/*</replacement>*/
16091
16092Writable.WritableState = WritableState;
16093
16094/*<replacement>*/
16095var util = Object.create(_dereq_('core-util-is'));
16096util.inherits = _dereq_('inherits');
16097/*</replacement>*/
16098
16099/*<replacement>*/
16100var internalUtil = {
16101 deprecate: _dereq_('util-deprecate')
16102};
16103/*</replacement>*/
16104
16105/*<replacement>*/
16106var Stream = _dereq_('./internal/streams/stream');
16107/*</replacement>*/
16108
16109/*<replacement>*/
16110
16111var Buffer = _dereq_('safe-buffer').Buffer;
16112var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
16113function _uint8ArrayToBuffer(chunk) {
16114 return Buffer.from(chunk);
16115}
16116function _isUint8Array(obj) {
16117 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
16118}
16119
16120/*</replacement>*/
16121
16122var destroyImpl = _dereq_('./internal/streams/destroy');
16123
16124util.inherits(Writable, Stream);
16125
16126function nop() {}
16127
16128function WritableState(options, stream) {
16129 Duplex = Duplex || _dereq_('./_stream_duplex');
16130
16131 options = options || {};
16132
16133 // Duplex streams are both readable and writable, but share
16134 // the same options object.
16135 // However, some cases require setting options to different
16136 // values for the readable and the writable sides of the duplex stream.
16137 // These options can be provided separately as readableXXX and writableXXX.
16138 var isDuplex = stream instanceof Duplex;
16139
16140 // object stream flag to indicate whether or not this stream
16141 // contains buffers or objects.
16142 this.objectMode = !!options.objectMode;
16143
16144 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
16145
16146 // the point at which write() starts returning false
16147 // Note: 0 is a valid value, means that we always return false if
16148 // the entire buffer is not flushed immediately on write()
16149 var hwm = options.highWaterMark;
16150 var writableHwm = options.writableHighWaterMark;
16151 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
16152
16153 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
16154
16155 // cast to ints.
16156 this.highWaterMark = Math.floor(this.highWaterMark);
16157
16158 // if _final has been called
16159 this.finalCalled = false;
16160
16161 // drain event flag.
16162 this.needDrain = false;
16163 // at the start of calling end()
16164 this.ending = false;
16165 // when end() has been called, and returned
16166 this.ended = false;
16167 // when 'finish' is emitted
16168 this.finished = false;
16169
16170 // has it been destroyed
16171 this.destroyed = false;
16172
16173 // should we decode strings into buffers before passing to _write?
16174 // this is here so that some node-core streams can optimize string
16175 // handling at a lower level.
16176 var noDecode = options.decodeStrings === false;
16177 this.decodeStrings = !noDecode;
16178
16179 // Crypto is kind of old and crusty. Historically, its default string
16180 // encoding is 'binary' so we have to make this configurable.
16181 // Everything else in the universe uses 'utf8', though.
16182 this.defaultEncoding = options.defaultEncoding || 'utf8';
16183
16184 // not an actual buffer we keep track of, but a measurement
16185 // of how much we're waiting to get pushed to some underlying
16186 // socket or file.
16187 this.length = 0;
16188
16189 // a flag to see when we're in the middle of a write.
16190 this.writing = false;
16191
16192 // when true all writes will be buffered until .uncork() call
16193 this.corked = 0;
16194
16195 // a flag to be able to tell if the onwrite cb is called immediately,
16196 // or on a later tick. We set this to true at first, because any
16197 // actions that shouldn't happen until "later" should generally also
16198 // not happen before the first write call.
16199 this.sync = true;
16200
16201 // a flag to know if we're processing previously buffered items, which
16202 // may call the _write() callback in the same tick, so that we don't
16203 // end up in an overlapped onwrite situation.
16204 this.bufferProcessing = false;
16205
16206 // the callback that's passed to _write(chunk,cb)
16207 this.onwrite = function (er) {
16208 onwrite(stream, er);
16209 };
16210
16211 // the callback that the user supplies to write(chunk,encoding,cb)
16212 this.writecb = null;
16213
16214 // the amount that is being written when _write is called.
16215 this.writelen = 0;
16216
16217 this.bufferedRequest = null;
16218 this.lastBufferedRequest = null;
16219
16220 // number of pending user-supplied write callbacks
16221 // this must be 0 before 'finish' can be emitted
16222 this.pendingcb = 0;
16223
16224 // emit prefinish if the only thing we're waiting for is _write cbs
16225 // This is relevant for synchronous Transform streams
16226 this.prefinished = false;
16227
16228 // True if the error was already emitted and should not be thrown again
16229 this.errorEmitted = false;
16230
16231 // count buffered requests
16232 this.bufferedRequestCount = 0;
16233
16234 // allocate the first CorkedRequest, there is always
16235 // one allocated and free to use, and we maintain at most two
16236 this.corkedRequestsFree = new CorkedRequest(this);
16237}
16238
16239WritableState.prototype.getBuffer = function getBuffer() {
16240 var current = this.bufferedRequest;
16241 var out = [];
16242 while (current) {
16243 out.push(current);
16244 current = current.next;
16245 }
16246 return out;
16247};
16248
16249(function () {
16250 try {
16251 Object.defineProperty(WritableState.prototype, 'buffer', {
16252 get: internalUtil.deprecate(function () {
16253 return this.getBuffer();
16254 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
16255 });
16256 } catch (_) {}
16257})();
16258
16259// Test _writableState for inheritance to account for Duplex streams,
16260// whose prototype chain only points to Readable.
16261var realHasInstance;
16262if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
16263 realHasInstance = Function.prototype[Symbol.hasInstance];
16264 Object.defineProperty(Writable, Symbol.hasInstance, {
16265 value: function (object) {
16266 if (realHasInstance.call(this, object)) return true;
16267 if (this !== Writable) return false;
16268
16269 return object && object._writableState instanceof WritableState;
16270 }
16271 });
16272} else {
16273 realHasInstance = function (object) {
16274 return object instanceof this;
16275 };
16276}
16277
16278function Writable(options) {
16279 Duplex = Duplex || _dereq_('./_stream_duplex');
16280
16281 // Writable ctor is applied to Duplexes, too.
16282 // `realHasInstance` is necessary because using plain `instanceof`
16283 // would return false, as no `_writableState` property is attached.
16284
16285 // Trying to use the custom `instanceof` for Writable here will also break the
16286 // Node.js LazyTransform implementation, which has a non-trivial getter for
16287 // `_writableState` that would lead to infinite recursion.
16288 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
16289 return new Writable(options);
16290 }
16291
16292 this._writableState = new WritableState(options, this);
16293
16294 // legacy.
16295 this.writable = true;
16296
16297 if (options) {
16298 if (typeof options.write === 'function') this._write = options.write;
16299
16300 if (typeof options.writev === 'function') this._writev = options.writev;
16301
16302 if (typeof options.destroy === 'function') this._destroy = options.destroy;
16303
16304 if (typeof options.final === 'function') this._final = options.final;
16305 }
16306
16307 Stream.call(this);
16308}
16309
16310// Otherwise people can pipe Writable streams, which is just wrong.
16311Writable.prototype.pipe = function () {
16312 this.emit('error', new Error('Cannot pipe, not readable'));
16313};
16314
16315function writeAfterEnd(stream, cb) {
16316 var er = new Error('write after end');
16317 // TODO: defer error events consistently everywhere, not just the cb
16318 stream.emit('error', er);
16319 pna.nextTick(cb, er);
16320}
16321
16322// Checks that a user-supplied chunk is valid, especially for the particular
16323// mode the stream is in. Currently this means that `null` is never accepted
16324// and undefined/non-string values are only allowed in object mode.
16325function validChunk(stream, state, chunk, cb) {
16326 var valid = true;
16327 var er = false;
16328
16329 if (chunk === null) {
16330 er = new TypeError('May not write null values to stream');
16331 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
16332 er = new TypeError('Invalid non-string/buffer chunk');
16333 }
16334 if (er) {
16335 stream.emit('error', er);
16336 pna.nextTick(cb, er);
16337 valid = false;
16338 }
16339 return valid;
16340}
16341
16342Writable.prototype.write = function (chunk, encoding, cb) {
16343 var state = this._writableState;
16344 var ret = false;
16345 var isBuf = !state.objectMode && _isUint8Array(chunk);
16346
16347 if (isBuf && !Buffer.isBuffer(chunk)) {
16348 chunk = _uint8ArrayToBuffer(chunk);
16349 }
16350
16351 if (typeof encoding === 'function') {
16352 cb = encoding;
16353 encoding = null;
16354 }
16355
16356 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
16357
16358 if (typeof cb !== 'function') cb = nop;
16359
16360 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
16361 state.pendingcb++;
16362 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
16363 }
16364
16365 return ret;
16366};
16367
16368Writable.prototype.cork = function () {
16369 var state = this._writableState;
16370
16371 state.corked++;
16372};
16373
16374Writable.prototype.uncork = function () {
16375 var state = this._writableState;
16376
16377 if (state.corked) {
16378 state.corked--;
16379
16380 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
16381 }
16382};
16383
16384Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
16385 // node::ParseEncoding() requires lower case.
16386 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
16387 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
16388 this._writableState.defaultEncoding = encoding;
16389 return this;
16390};
16391
16392function decodeChunk(state, chunk, encoding) {
16393 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
16394 chunk = Buffer.from(chunk, encoding);
16395 }
16396 return chunk;
16397}
16398
16399Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
16400 // making it explicit this property is not enumerable
16401 // because otherwise some prototype manipulation in
16402 // userland will fail
16403 enumerable: false,
16404 get: function () {
16405 return this._writableState.highWaterMark;
16406 }
16407});
16408
16409// if we're already writing something, then just put this
16410// in the queue, and wait our turn. Otherwise, call _write
16411// If we return false, then we need a drain event, so set that flag.
16412function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
16413 if (!isBuf) {
16414 var newChunk = decodeChunk(state, chunk, encoding);
16415 if (chunk !== newChunk) {
16416 isBuf = true;
16417 encoding = 'buffer';
16418 chunk = newChunk;
16419 }
16420 }
16421 var len = state.objectMode ? 1 : chunk.length;
16422
16423 state.length += len;
16424
16425 var ret = state.length < state.highWaterMark;
16426 // we must ensure that previous needDrain will not be reset to false.
16427 if (!ret) state.needDrain = true;
16428
16429 if (state.writing || state.corked) {
16430 var last = state.lastBufferedRequest;
16431 state.lastBufferedRequest = {
16432 chunk: chunk,
16433 encoding: encoding,
16434 isBuf: isBuf,
16435 callback: cb,
16436 next: null
16437 };
16438 if (last) {
16439 last.next = state.lastBufferedRequest;
16440 } else {
16441 state.bufferedRequest = state.lastBufferedRequest;
16442 }
16443 state.bufferedRequestCount += 1;
16444 } else {
16445 doWrite(stream, state, false, len, chunk, encoding, cb);
16446 }
16447
16448 return ret;
16449}
16450
16451function doWrite(stream, state, writev, len, chunk, encoding, cb) {
16452 state.writelen = len;
16453 state.writecb = cb;
16454 state.writing = true;
16455 state.sync = true;
16456 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
16457 state.sync = false;
16458}
16459
16460function onwriteError(stream, state, sync, er, cb) {
16461 --state.pendingcb;
16462
16463 if (sync) {
16464 // defer the callback if we are being called synchronously
16465 // to avoid piling up things on the stack
16466 pna.nextTick(cb, er);
16467 // this can emit finish, and it will always happen
16468 // after error
16469 pna.nextTick(finishMaybe, stream, state);
16470 stream._writableState.errorEmitted = true;
16471 stream.emit('error', er);
16472 } else {
16473 // the caller expect this to happen before if
16474 // it is async
16475 cb(er);
16476 stream._writableState.errorEmitted = true;
16477 stream.emit('error', er);
16478 // this can emit finish, but finish must
16479 // always follow error
16480 finishMaybe(stream, state);
16481 }
16482}
16483
16484function onwriteStateUpdate(state) {
16485 state.writing = false;
16486 state.writecb = null;
16487 state.length -= state.writelen;
16488 state.writelen = 0;
16489}
16490
16491function onwrite(stream, er) {
16492 var state = stream._writableState;
16493 var sync = state.sync;
16494 var cb = state.writecb;
16495
16496 onwriteStateUpdate(state);
16497
16498 if (er) onwriteError(stream, state, sync, er, cb);else {
16499 // Check if we're actually ready to finish, but don't emit yet
16500 var finished = needFinish(state);
16501
16502 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
16503 clearBuffer(stream, state);
16504 }
16505
16506 if (sync) {
16507 /*<replacement>*/
16508 asyncWrite(afterWrite, stream, state, finished, cb);
16509 /*</replacement>*/
16510 } else {
16511 afterWrite(stream, state, finished, cb);
16512 }
16513 }
16514}
16515
16516function afterWrite(stream, state, finished, cb) {
16517 if (!finished) onwriteDrain(stream, state);
16518 state.pendingcb--;
16519 cb();
16520 finishMaybe(stream, state);
16521}
16522
16523// Must force callback to be called on nextTick, so that we don't
16524// emit 'drain' before the write() consumer gets the 'false' return
16525// value, and has a chance to attach a 'drain' listener.
16526function onwriteDrain(stream, state) {
16527 if (state.length === 0 && state.needDrain) {
16528 state.needDrain = false;
16529 stream.emit('drain');
16530 }
16531}
16532
16533// if there's something in the buffer waiting, then process it
16534function clearBuffer(stream, state) {
16535 state.bufferProcessing = true;
16536 var entry = state.bufferedRequest;
16537
16538 if (stream._writev && entry && entry.next) {
16539 // Fast case, write everything using _writev()
16540 var l = state.bufferedRequestCount;
16541 var buffer = new Array(l);
16542 var holder = state.corkedRequestsFree;
16543 holder.entry = entry;
16544
16545 var count = 0;
16546 var allBuffers = true;
16547 while (entry) {
16548 buffer[count] = entry;
16549 if (!entry.isBuf) allBuffers = false;
16550 entry = entry.next;
16551 count += 1;
16552 }
16553 buffer.allBuffers = allBuffers;
16554
16555 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
16556
16557 // doWrite is almost always async, defer these to save a bit of time
16558 // as the hot path ends with doWrite
16559 state.pendingcb++;
16560 state.lastBufferedRequest = null;
16561 if (holder.next) {
16562 state.corkedRequestsFree = holder.next;
16563 holder.next = null;
16564 } else {
16565 state.corkedRequestsFree = new CorkedRequest(state);
16566 }
16567 state.bufferedRequestCount = 0;
16568 } else {
16569 // Slow case, write chunks one-by-one
16570 while (entry) {
16571 var chunk = entry.chunk;
16572 var encoding = entry.encoding;
16573 var cb = entry.callback;
16574 var len = state.objectMode ? 1 : chunk.length;
16575
16576 doWrite(stream, state, false, len, chunk, encoding, cb);
16577 entry = entry.next;
16578 state.bufferedRequestCount--;
16579 // if we didn't call the onwrite immediately, then
16580 // it means that we need to wait until it does.
16581 // also, that means that the chunk and cb are currently
16582 // being processed, so move the buffer counter past them.
16583 if (state.writing) {
16584 break;
16585 }
16586 }
16587
16588 if (entry === null) state.lastBufferedRequest = null;
16589 }
16590
16591 state.bufferedRequest = entry;
16592 state.bufferProcessing = false;
16593}
16594
16595Writable.prototype._write = function (chunk, encoding, cb) {
16596 cb(new Error('_write() is not implemented'));
16597};
16598
16599Writable.prototype._writev = null;
16600
16601Writable.prototype.end = function (chunk, encoding, cb) {
16602 var state = this._writableState;
16603
16604 if (typeof chunk === 'function') {
16605 cb = chunk;
16606 chunk = null;
16607 encoding = null;
16608 } else if (typeof encoding === 'function') {
16609 cb = encoding;
16610 encoding = null;
16611 }
16612
16613 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
16614
16615 // .end() fully uncorks
16616 if (state.corked) {
16617 state.corked = 1;
16618 this.uncork();
16619 }
16620
16621 // ignore unnecessary end() calls.
16622 if (!state.ending) endWritable(this, state, cb);
16623};
16624
16625function needFinish(state) {
16626 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
16627}
16628function callFinal(stream, state) {
16629 stream._final(function (err) {
16630 state.pendingcb--;
16631 if (err) {
16632 stream.emit('error', err);
16633 }
16634 state.prefinished = true;
16635 stream.emit('prefinish');
16636 finishMaybe(stream, state);
16637 });
16638}
16639function prefinish(stream, state) {
16640 if (!state.prefinished && !state.finalCalled) {
16641 if (typeof stream._final === 'function') {
16642 state.pendingcb++;
16643 state.finalCalled = true;
16644 pna.nextTick(callFinal, stream, state);
16645 } else {
16646 state.prefinished = true;
16647 stream.emit('prefinish');
16648 }
16649 }
16650}
16651
16652function finishMaybe(stream, state) {
16653 var need = needFinish(state);
16654 if (need) {
16655 prefinish(stream, state);
16656 if (state.pendingcb === 0) {
16657 state.finished = true;
16658 stream.emit('finish');
16659 }
16660 }
16661 return need;
16662}
16663
16664function endWritable(stream, state, cb) {
16665 state.ending = true;
16666 finishMaybe(stream, state);
16667 if (cb) {
16668 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
16669 }
16670 state.ended = true;
16671 stream.writable = false;
16672}
16673
16674function onCorkedFinish(corkReq, state, err) {
16675 var entry = corkReq.entry;
16676 corkReq.entry = null;
16677 while (entry) {
16678 var cb = entry.callback;
16679 state.pendingcb--;
16680 cb(err);
16681 entry = entry.next;
16682 }
16683
16684 // reuse the free corkReq.
16685 state.corkedRequestsFree.next = corkReq;
16686}
16687
16688Object.defineProperty(Writable.prototype, 'destroyed', {
16689 get: function () {
16690 if (this._writableState === undefined) {
16691 return false;
16692 }
16693 return this._writableState.destroyed;
16694 },
16695 set: function (value) {
16696 // we ignore the value if the stream
16697 // has not been initialized yet
16698 if (!this._writableState) {
16699 return;
16700 }
16701
16702 // backward compatibility, the user is explicitly
16703 // managing destroyed
16704 this._writableState.destroyed = value;
16705 }
16706});
16707
16708Writable.prototype.destroy = destroyImpl.destroy;
16709Writable.prototype._undestroy = destroyImpl.undestroy;
16710Writable.prototype._destroy = function (err, cb) {
16711 this.end();
16712 cb(err);
16713};
16714}).call(this)}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_dereq_("timers").setImmediate)
16715},{"./_stream_duplex":108,"./internal/streams/destroy":114,"./internal/streams/stream":115,"_process":93,"core-util-is":7,"inherits":45,"process-nextick-args":92,"safe-buffer":120,"timers":139,"util-deprecate":140}],113:[function(_dereq_,module,exports){
16716'use strict';
16717
16718function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
16719
16720var Buffer = _dereq_('safe-buffer').Buffer;
16721var util = _dereq_('util');
16722
16723function copyBuffer(src, target, offset) {
16724 src.copy(target, offset);
16725}
16726
16727module.exports = function () {
16728 function BufferList() {
16729 _classCallCheck(this, BufferList);
16730
16731 this.head = null;
16732 this.tail = null;
16733 this.length = 0;
16734 }
16735
16736 BufferList.prototype.push = function push(v) {
16737 var entry = { data: v, next: null };
16738 if (this.length > 0) this.tail.next = entry;else this.head = entry;
16739 this.tail = entry;
16740 ++this.length;
16741 };
16742
16743 BufferList.prototype.unshift = function unshift(v) {
16744 var entry = { data: v, next: this.head };
16745 if (this.length === 0) this.tail = entry;
16746 this.head = entry;
16747 ++this.length;
16748 };
16749
16750 BufferList.prototype.shift = function shift() {
16751 if (this.length === 0) return;
16752 var ret = this.head.data;
16753 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
16754 --this.length;
16755 return ret;
16756 };
16757
16758 BufferList.prototype.clear = function clear() {
16759 this.head = this.tail = null;
16760 this.length = 0;
16761 };
16762
16763 BufferList.prototype.join = function join(s) {
16764 if (this.length === 0) return '';
16765 var p = this.head;
16766 var ret = '' + p.data;
16767 while (p = p.next) {
16768 ret += s + p.data;
16769 }return ret;
16770 };
16771
16772 BufferList.prototype.concat = function concat(n) {
16773 if (this.length === 0) return Buffer.alloc(0);
16774 var ret = Buffer.allocUnsafe(n >>> 0);
16775 var p = this.head;
16776 var i = 0;
16777 while (p) {
16778 copyBuffer(p.data, ret, i);
16779 i += p.data.length;
16780 p = p.next;
16781 }
16782 return ret;
16783 };
16784
16785 return BufferList;
16786}();
16787
16788if (util && util.inspect && util.inspect.custom) {
16789 module.exports.prototype[util.inspect.custom] = function () {
16790 var obj = util.inspect({ length: this.length });
16791 return this.constructor.name + ' ' + obj;
16792 };
16793}
16794},{"safe-buffer":120,"util":3}],114:[function(_dereq_,module,exports){
16795'use strict';
16796
16797/*<replacement>*/
16798
16799var pna = _dereq_('process-nextick-args');
16800/*</replacement>*/
16801
16802// undocumented cb() API, needed for core, not for public API
16803function destroy(err, cb) {
16804 var _this = this;
16805
16806 var readableDestroyed = this._readableState && this._readableState.destroyed;
16807 var writableDestroyed = this._writableState && this._writableState.destroyed;
16808
16809 if (readableDestroyed || writableDestroyed) {
16810 if (cb) {
16811 cb(err);
16812 } else if (err) {
16813 if (!this._writableState) {
16814 pna.nextTick(emitErrorNT, this, err);
16815 } else if (!this._writableState.errorEmitted) {
16816 this._writableState.errorEmitted = true;
16817 pna.nextTick(emitErrorNT, this, err);
16818 }
16819 }
16820
16821 return this;
16822 }
16823
16824 // we set destroyed to true before firing error callbacks in order
16825 // to make it re-entrance safe in case destroy() is called within callbacks
16826
16827 if (this._readableState) {
16828 this._readableState.destroyed = true;
16829 }
16830
16831 // if this is a duplex stream mark the writable part as destroyed as well
16832 if (this._writableState) {
16833 this._writableState.destroyed = true;
16834 }
16835
16836 this._destroy(err || null, function (err) {
16837 if (!cb && err) {
16838 if (!_this._writableState) {
16839 pna.nextTick(emitErrorNT, _this, err);
16840 } else if (!_this._writableState.errorEmitted) {
16841 _this._writableState.errorEmitted = true;
16842 pna.nextTick(emitErrorNT, _this, err);
16843 }
16844 } else if (cb) {
16845 cb(err);
16846 }
16847 });
16848
16849 return this;
16850}
16851
16852function undestroy() {
16853 if (this._readableState) {
16854 this._readableState.destroyed = false;
16855 this._readableState.reading = false;
16856 this._readableState.ended = false;
16857 this._readableState.endEmitted = false;
16858 }
16859
16860 if (this._writableState) {
16861 this._writableState.destroyed = false;
16862 this._writableState.ended = false;
16863 this._writableState.ending = false;
16864 this._writableState.finalCalled = false;
16865 this._writableState.prefinished = false;
16866 this._writableState.finished = false;
16867 this._writableState.errorEmitted = false;
16868 }
16869}
16870
16871function emitErrorNT(self, err) {
16872 self.emit('error', err);
16873}
16874
16875module.exports = {
16876 destroy: destroy,
16877 undestroy: undestroy
16878};
16879},{"process-nextick-args":92}],115:[function(_dereq_,module,exports){
16880arguments[4][65][0].apply(exports,arguments)
16881},{"dup":65,"events":33}],116:[function(_dereq_,module,exports){
16882module.exports = _dereq_('./readable').PassThrough
16883
16884},{"./readable":117}],117:[function(_dereq_,module,exports){
16885exports = module.exports = _dereq_('./lib/_stream_readable.js');
16886exports.Stream = exports;
16887exports.Readable = exports;
16888exports.Writable = _dereq_('./lib/_stream_writable.js');
16889exports.Duplex = _dereq_('./lib/_stream_duplex.js');
16890exports.Transform = _dereq_('./lib/_stream_transform.js');
16891exports.PassThrough = _dereq_('./lib/_stream_passthrough.js');
16892
16893},{"./lib/_stream_duplex.js":108,"./lib/_stream_passthrough.js":109,"./lib/_stream_readable.js":110,"./lib/_stream_transform.js":111,"./lib/_stream_writable.js":112}],118:[function(_dereq_,module,exports){
16894module.exports = _dereq_('./readable').Transform
16895
16896},{"./readable":117}],119:[function(_dereq_,module,exports){
16897module.exports = _dereq_('./lib/_stream_writable.js');
16898
16899},{"./lib/_stream_writable.js":112}],120:[function(_dereq_,module,exports){
16900arguments[4][86][0].apply(exports,arguments)
16901},{"buffer":4,"dup":86}],121:[function(_dereq_,module,exports){
16902// Copyright Joyent, Inc. and other Node contributors.
16903//
16904// Permission is hereby granted, free of charge, to any person obtaining a
16905// copy of this software and associated documentation files (the
16906// "Software"), to deal in the Software without restriction, including
16907// without limitation the rights to use, copy, modify, merge, publish,
16908// distribute, sublicense, and/or sell copies of the Software, and to permit
16909// persons to whom the Software is furnished to do so, subject to the
16910// following conditions:
16911//
16912// The above copyright notice and this permission notice shall be included
16913// in all copies or substantial portions of the Software.
16914//
16915// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16916// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16917// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16918// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16919// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16920// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16921// USE OR OTHER DEALINGS IN THE SOFTWARE.
16922
16923'use strict';
16924
16925/*<replacement>*/
16926
16927var Buffer = _dereq_('safe-buffer').Buffer;
16928/*</replacement>*/
16929
16930var isEncoding = Buffer.isEncoding || function (encoding) {
16931 encoding = '' + encoding;
16932 switch (encoding && encoding.toLowerCase()) {
16933 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':
16934 return true;
16935 default:
16936 return false;
16937 }
16938};
16939
16940function _normalizeEncoding(enc) {
16941 if (!enc) return 'utf8';
16942 var retried;
16943 while (true) {
16944 switch (enc) {
16945 case 'utf8':
16946 case 'utf-8':
16947 return 'utf8';
16948 case 'ucs2':
16949 case 'ucs-2':
16950 case 'utf16le':
16951 case 'utf-16le':
16952 return 'utf16le';
16953 case 'latin1':
16954 case 'binary':
16955 return 'latin1';
16956 case 'base64':
16957 case 'ascii':
16958 case 'hex':
16959 return enc;
16960 default:
16961 if (retried) return; // undefined
16962 enc = ('' + enc).toLowerCase();
16963 retried = true;
16964 }
16965 }
16966};
16967
16968// Do not cache `Buffer.isEncoding` when checking encoding names as some
16969// modules monkey-patch it to support additional encodings
16970function normalizeEncoding(enc) {
16971 var nenc = _normalizeEncoding(enc);
16972 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
16973 return nenc || enc;
16974}
16975
16976// StringDecoder provides an interface for efficiently splitting a series of
16977// buffers into a series of JS strings without breaking apart multi-byte
16978// characters.
16979exports.StringDecoder = StringDecoder;
16980function StringDecoder(encoding) {
16981 this.encoding = normalizeEncoding(encoding);
16982 var nb;
16983 switch (this.encoding) {
16984 case 'utf16le':
16985 this.text = utf16Text;
16986 this.end = utf16End;
16987 nb = 4;
16988 break;
16989 case 'utf8':
16990 this.fillLast = utf8FillLast;
16991 nb = 4;
16992 break;
16993 case 'base64':
16994 this.text = base64Text;
16995 this.end = base64End;
16996 nb = 3;
16997 break;
16998 default:
16999 this.write = simpleWrite;
17000 this.end = simpleEnd;
17001 return;
17002 }
17003 this.lastNeed = 0;
17004 this.lastTotal = 0;
17005 this.lastChar = Buffer.allocUnsafe(nb);
17006}
17007
17008StringDecoder.prototype.write = function (buf) {
17009 if (buf.length === 0) return '';
17010 var r;
17011 var i;
17012 if (this.lastNeed) {
17013 r = this.fillLast(buf);
17014 if (r === undefined) return '';
17015 i = this.lastNeed;
17016 this.lastNeed = 0;
17017 } else {
17018 i = 0;
17019 }
17020 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
17021 return r || '';
17022};
17023
17024StringDecoder.prototype.end = utf8End;
17025
17026// Returns only complete characters in a Buffer
17027StringDecoder.prototype.text = utf8Text;
17028
17029// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
17030StringDecoder.prototype.fillLast = function (buf) {
17031 if (this.lastNeed <= buf.length) {
17032 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
17033 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
17034 }
17035 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
17036 this.lastNeed -= buf.length;
17037};
17038
17039// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
17040// continuation byte. If an invalid byte is detected, -2 is returned.
17041function utf8CheckByte(byte) {
17042 if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
17043 return byte >> 6 === 0x02 ? -1 : -2;
17044}
17045
17046// Checks at most 3 bytes at the end of a Buffer in order to detect an
17047// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
17048// needed to complete the UTF-8 character (if applicable) are returned.
17049function utf8CheckIncomplete(self, buf, i) {
17050 var j = buf.length - 1;
17051 if (j < i) return 0;
17052 var nb = utf8CheckByte(buf[j]);
17053 if (nb >= 0) {
17054 if (nb > 0) self.lastNeed = nb - 1;
17055 return nb;
17056 }
17057 if (--j < i || nb === -2) return 0;
17058 nb = utf8CheckByte(buf[j]);
17059 if (nb >= 0) {
17060 if (nb > 0) self.lastNeed = nb - 2;
17061 return nb;
17062 }
17063 if (--j < i || nb === -2) return 0;
17064 nb = utf8CheckByte(buf[j]);
17065 if (nb >= 0) {
17066 if (nb > 0) {
17067 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
17068 }
17069 return nb;
17070 }
17071 return 0;
17072}
17073
17074// Validates as many continuation bytes for a multi-byte UTF-8 character as
17075// needed or are available. If we see a non-continuation byte where we expect
17076// one, we "replace" the validated continuation bytes we've seen so far with
17077// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
17078// behavior. The continuation byte check is included three times in the case
17079// where all of the continuation bytes for a character exist in the same buffer.
17080// It is also done this way as a slight performance increase instead of using a
17081// loop.
17082function utf8CheckExtraBytes(self, buf, p) {
17083 if ((buf[0] & 0xC0) !== 0x80) {
17084 self.lastNeed = 0;
17085 return '\ufffd';
17086 }
17087 if (self.lastNeed > 1 && buf.length > 1) {
17088 if ((buf[1] & 0xC0) !== 0x80) {
17089 self.lastNeed = 1;
17090 return '\ufffd';
17091 }
17092 if (self.lastNeed > 2 && buf.length > 2) {
17093 if ((buf[2] & 0xC0) !== 0x80) {
17094 self.lastNeed = 2;
17095 return '\ufffd';
17096 }
17097 }
17098 }
17099}
17100
17101// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
17102function utf8FillLast(buf) {
17103 var p = this.lastTotal - this.lastNeed;
17104 var r = utf8CheckExtraBytes(this, buf, p);
17105 if (r !== undefined) return r;
17106 if (this.lastNeed <= buf.length) {
17107 buf.copy(this.lastChar, p, 0, this.lastNeed);
17108 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
17109 }
17110 buf.copy(this.lastChar, p, 0, buf.length);
17111 this.lastNeed -= buf.length;
17112}
17113
17114// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
17115// partial character, the character's bytes are buffered until the required
17116// number of bytes are available.
17117function utf8Text(buf, i) {
17118 var total = utf8CheckIncomplete(this, buf, i);
17119 if (!this.lastNeed) return buf.toString('utf8', i);
17120 this.lastTotal = total;
17121 var end = buf.length - (total - this.lastNeed);
17122 buf.copy(this.lastChar, 0, end);
17123 return buf.toString('utf8', i, end);
17124}
17125
17126// For UTF-8, a replacement character is added when ending on a partial
17127// character.
17128function utf8End(buf) {
17129 var r = buf && buf.length ? this.write(buf) : '';
17130 if (this.lastNeed) return r + '\ufffd';
17131 return r;
17132}
17133
17134// UTF-16LE typically needs two bytes per character, but even if we have an even
17135// number of bytes available, we need to check if we end on a leading/high
17136// surrogate. In that case, we need to wait for the next two bytes in order to
17137// decode the last character properly.
17138function utf16Text(buf, i) {
17139 if ((buf.length - i) % 2 === 0) {
17140 var r = buf.toString('utf16le', i);
17141 if (r) {
17142 var c = r.charCodeAt(r.length - 1);
17143 if (c >= 0xD800 && c <= 0xDBFF) {
17144 this.lastNeed = 2;
17145 this.lastTotal = 4;
17146 this.lastChar[0] = buf[buf.length - 2];
17147 this.lastChar[1] = buf[buf.length - 1];
17148 return r.slice(0, -1);
17149 }
17150 }
17151 return r;
17152 }
17153 this.lastNeed = 1;
17154 this.lastTotal = 2;
17155 this.lastChar[0] = buf[buf.length - 1];
17156 return buf.toString('utf16le', i, buf.length - 1);
17157}
17158
17159// For UTF-16LE we do not explicitly append special replacement characters if we
17160// end on a partial character, we simply let v8 handle that.
17161function utf16End(buf) {
17162 var r = buf && buf.length ? this.write(buf) : '';
17163 if (this.lastNeed) {
17164 var end = this.lastTotal - this.lastNeed;
17165 return r + this.lastChar.toString('utf16le', 0, end);
17166 }
17167 return r;
17168}
17169
17170function base64Text(buf, i) {
17171 var n = (buf.length - i) % 3;
17172 if (n === 0) return buf.toString('base64', i);
17173 this.lastNeed = 3 - n;
17174 this.lastTotal = 3;
17175 if (n === 1) {
17176 this.lastChar[0] = buf[buf.length - 1];
17177 } else {
17178 this.lastChar[0] = buf[buf.length - 2];
17179 this.lastChar[1] = buf[buf.length - 1];
17180 }
17181 return buf.toString('base64', i, buf.length - n);
17182}
17183
17184function base64End(buf) {
17185 var r = buf && buf.length ? this.write(buf) : '';
17186 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
17187 return r;
17188}
17189
17190// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
17191function simpleWrite(buf) {
17192 return buf.toString(this.encoding);
17193}
17194
17195function simpleEnd(buf) {
17196 return buf && buf.length ? this.write(buf) : '';
17197}
17198},{"safe-buffer":120}],122:[function(_dereq_,module,exports){
17199arguments[4][121][0].apply(exports,arguments)
17200},{"dup":121,"safe-buffer":102}],123:[function(_dereq_,module,exports){
17201arguments[4][52][0].apply(exports,arguments)
17202},{"dup":52}],124:[function(_dereq_,module,exports){
17203arguments[4][53][0].apply(exports,arguments)
17204},{"./_stream_readable":126,"./_stream_writable":128,"_process":93,"dup":53,"inherits":45}],125:[function(_dereq_,module,exports){
17205arguments[4][54][0].apply(exports,arguments)
17206},{"./_stream_transform":127,"dup":54,"inherits":45}],126:[function(_dereq_,module,exports){
17207arguments[4][55][0].apply(exports,arguments)
17208},{"../errors":123,"./_stream_duplex":124,"./internal/streams/async_iterator":129,"./internal/streams/buffer_list":130,"./internal/streams/destroy":131,"./internal/streams/from":133,"./internal/streams/state":135,"./internal/streams/stream":136,"_process":93,"buffer":4,"dup":55,"events":33,"inherits":45,"string_decoder/":122,"util":3}],127:[function(_dereq_,module,exports){
17209arguments[4][56][0].apply(exports,arguments)
17210},{"../errors":123,"./_stream_duplex":124,"dup":56,"inherits":45}],128:[function(_dereq_,module,exports){
17211arguments[4][57][0].apply(exports,arguments)
17212},{"../errors":123,"./_stream_duplex":124,"./internal/streams/destroy":131,"./internal/streams/state":135,"./internal/streams/stream":136,"_process":93,"buffer":4,"dup":57,"inherits":45,"util-deprecate":140}],129:[function(_dereq_,module,exports){
17213arguments[4][58][0].apply(exports,arguments)
17214},{"./end-of-stream":132,"_process":93,"dup":58}],130:[function(_dereq_,module,exports){
17215arguments[4][59][0].apply(exports,arguments)
17216},{"buffer":4,"dup":59,"util":3}],131:[function(_dereq_,module,exports){
17217arguments[4][60][0].apply(exports,arguments)
17218},{"_process":93,"dup":60}],132:[function(_dereq_,module,exports){
17219arguments[4][61][0].apply(exports,arguments)
17220},{"../../../errors":123,"dup":61}],133:[function(_dereq_,module,exports){
17221arguments[4][62][0].apply(exports,arguments)
17222},{"dup":62}],134:[function(_dereq_,module,exports){
17223arguments[4][63][0].apply(exports,arguments)
17224},{"../../../errors":123,"./end-of-stream":132,"dup":63}],135:[function(_dereq_,module,exports){
17225arguments[4][64][0].apply(exports,arguments)
17226},{"../../../errors":123,"dup":64}],136:[function(_dereq_,module,exports){
17227arguments[4][65][0].apply(exports,arguments)
17228},{"dup":65,"events":33}],137:[function(_dereq_,module,exports){
17229arguments[4][66][0].apply(exports,arguments)
17230},{"./lib/_stream_duplex.js":124,"./lib/_stream_passthrough.js":125,"./lib/_stream_readable.js":126,"./lib/_stream_transform.js":127,"./lib/_stream_writable.js":128,"./lib/internal/streams/end-of-stream.js":132,"./lib/internal/streams/pipeline.js":134,"dup":66}],138:[function(_dereq_,module,exports){
17231(function (process){(function (){
17232var Transform = _dereq_('readable-stream').Transform
17233 , inherits = _dereq_('inherits')
17234
17235function DestroyableTransform(opts) {
17236 Transform.call(this, opts)
17237 this._destroyed = false
17238}
17239
17240inherits(DestroyableTransform, Transform)
17241
17242DestroyableTransform.prototype.destroy = function(err) {
17243 if (this._destroyed) return
17244 this._destroyed = true
17245
17246 var self = this
17247 process.nextTick(function() {
17248 if (err)
17249 self.emit('error', err)
17250 self.emit('close')
17251 })
17252}
17253
17254// a noop _transform function
17255function noop (chunk, enc, callback) {
17256 callback(null, chunk)
17257}
17258
17259
17260// create a new export function, used by both the main export and
17261// the .ctor export, contains common logic for dealing with arguments
17262function through2 (construct) {
17263 return function (options, transform, flush) {
17264 if (typeof options == 'function') {
17265 flush = transform
17266 transform = options
17267 options = {}
17268 }
17269
17270 if (typeof transform != 'function')
17271 transform = noop
17272
17273 if (typeof flush != 'function')
17274 flush = null
17275
17276 return construct(options, transform, flush)
17277 }
17278}
17279
17280
17281// main export, just make me a transform stream!
17282module.exports = through2(function (options, transform, flush) {
17283 var t2 = new DestroyableTransform(options)
17284
17285 t2._transform = transform
17286
17287 if (flush)
17288 t2._flush = flush
17289
17290 return t2
17291})
17292
17293
17294// make me a reusable prototype that I can `new`, or implicitly `new`
17295// with a constructor call
17296module.exports.ctor = through2(function (options, transform, flush) {
17297 function Through2 (override) {
17298 if (!(this instanceof Through2))
17299 return new Through2(override)
17300
17301 this.options = Object.assign({}, options, override)
17302
17303 DestroyableTransform.call(this, this.options)
17304 }
17305
17306 inherits(Through2, DestroyableTransform)
17307
17308 Through2.prototype._transform = transform
17309
17310 if (flush)
17311 Through2.prototype._flush = flush
17312
17313 return Through2
17314})
17315
17316
17317module.exports.obj = through2(function (options, transform, flush) {
17318 var t2 = new DestroyableTransform(Object.assign({ objectMode: true, highWaterMark: 16 }, options))
17319
17320 t2._transform = transform
17321
17322 if (flush)
17323 t2._flush = flush
17324
17325 return t2
17326})
17327
17328}).call(this)}).call(this,_dereq_('_process'))
17329},{"_process":93,"inherits":45,"readable-stream":137}],139:[function(_dereq_,module,exports){
17330(function (setImmediate,clearImmediate){(function (){
17331var nextTick = _dereq_('process/browser.js').nextTick;
17332var apply = Function.prototype.apply;
17333var slice = Array.prototype.slice;
17334var immediateIds = {};
17335var nextImmediateId = 0;
17336
17337// DOM APIs, for completeness
17338
17339exports.setTimeout = function() {
17340 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
17341};
17342exports.setInterval = function() {
17343 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
17344};
17345exports.clearTimeout =
17346exports.clearInterval = function(timeout) { timeout.close(); };
17347
17348function Timeout(id, clearFn) {
17349 this._id = id;
17350 this._clearFn = clearFn;
17351}
17352Timeout.prototype.unref = Timeout.prototype.ref = function() {};
17353Timeout.prototype.close = function() {
17354 this._clearFn.call(window, this._id);
17355};
17356
17357// Does not start the time, just sets up the members needed.
17358exports.enroll = function(item, msecs) {
17359 clearTimeout(item._idleTimeoutId);
17360 item._idleTimeout = msecs;
17361};
17362
17363exports.unenroll = function(item) {
17364 clearTimeout(item._idleTimeoutId);
17365 item._idleTimeout = -1;
17366};
17367
17368exports._unrefActive = exports.active = function(item) {
17369 clearTimeout(item._idleTimeoutId);
17370
17371 var msecs = item._idleTimeout;
17372 if (msecs >= 0) {
17373 item._idleTimeoutId = setTimeout(function onTimeout() {
17374 if (item._onTimeout)
17375 item._onTimeout();
17376 }, msecs);
17377 }
17378};
17379
17380// That's not how node.js implements it but the exposed api is the same.
17381exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
17382 var id = nextImmediateId++;
17383 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
17384
17385 immediateIds[id] = true;
17386
17387 nextTick(function onNextTick() {
17388 if (immediateIds[id]) {
17389 // fn.call() is faster so we optimize for the common use-case
17390 // @see http://jsperf.com/call-apply-segu
17391 if (args) {
17392 fn.apply(null, args);
17393 } else {
17394 fn.call(null);
17395 }
17396 // Prevent ids from leaking
17397 exports.clearImmediate(id);
17398 }
17399 });
17400
17401 return id;
17402};
17403
17404exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
17405 delete immediateIds[id];
17406};
17407}).call(this)}).call(this,_dereq_("timers").setImmediate,_dereq_("timers").clearImmediate)
17408},{"process/browser.js":93,"timers":139}],140:[function(_dereq_,module,exports){
17409(function (global){(function (){
17410
17411/**
17412 * Module exports.
17413 */
17414
17415module.exports = deprecate;
17416
17417/**
17418 * Mark that a method should not be used.
17419 * Returns a modified function which warns once by default.
17420 *
17421 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
17422 *
17423 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
17424 * will throw an Error when invoked.
17425 *
17426 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
17427 * will invoke `console.trace()` instead of `console.error()`.
17428 *
17429 * @param {Function} fn - the function to deprecate
17430 * @param {String} msg - the string to print to the console when `fn` is invoked
17431 * @returns {Function} a new "deprecated" version of `fn`
17432 * @api public
17433 */
17434
17435function deprecate (fn, msg) {
17436 if (config('noDeprecation')) {
17437 return fn;
17438 }
17439
17440 var warned = false;
17441 function deprecated() {
17442 if (!warned) {
17443 if (config('throwDeprecation')) {
17444 throw new Error(msg);
17445 } else if (config('traceDeprecation')) {
17446 console.trace(msg);
17447 } else {
17448 console.warn(msg);
17449 }
17450 warned = true;
17451 }
17452 return fn.apply(this, arguments);
17453 }
17454
17455 return deprecated;
17456}
17457
17458/**
17459 * Checks `localStorage` for boolean values for the given `name`.
17460 *
17461 * @param {String} name
17462 * @returns {Boolean}
17463 * @api private
17464 */
17465
17466function config (name) {
17467 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
17468 try {
17469 if (!global.localStorage) return false;
17470 } catch (_) {
17471 return false;
17472 }
17473 var val = global.localStorage[name];
17474 if (null == val) return false;
17475 return String(val).toLowerCase() === 'true';
17476}
17477
17478}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
17479},{}],141:[function(_dereq_,module,exports){
17480if (typeof Object.create === 'function') {
17481 // implementation from standard node.js 'util' module
17482 module.exports = function inherits(ctor, superCtor) {
17483 ctor.super_ = superCtor
17484 ctor.prototype = Object.create(superCtor.prototype, {
17485 constructor: {
17486 value: ctor,
17487 enumerable: false,
17488 writable: true,
17489 configurable: true
17490 }
17491 });
17492 };
17493} else {
17494 // old school shim for old browsers
17495 module.exports = function inherits(ctor, superCtor) {
17496 ctor.super_ = superCtor
17497 var TempCtor = function () {}
17498 TempCtor.prototype = superCtor.prototype
17499 ctor.prototype = new TempCtor()
17500 ctor.prototype.constructor = ctor
17501 }
17502}
17503
17504},{}],142:[function(_dereq_,module,exports){
17505module.exports = function isBuffer(arg) {
17506 return arg && typeof arg === 'object'
17507 && typeof arg.copy === 'function'
17508 && typeof arg.fill === 'function'
17509 && typeof arg.readUInt8 === 'function';
17510}
17511},{}],143:[function(_dereq_,module,exports){
17512(function (process,global){(function (){
17513// Copyright Joyent, Inc. and other Node contributors.
17514//
17515// Permission is hereby granted, free of charge, to any person obtaining a
17516// copy of this software and associated documentation files (the
17517// "Software"), to deal in the Software without restriction, including
17518// without limitation the rights to use, copy, modify, merge, publish,
17519// distribute, sublicense, and/or sell copies of the Software, and to permit
17520// persons to whom the Software is furnished to do so, subject to the
17521// following conditions:
17522//
17523// The above copyright notice and this permission notice shall be included
17524// in all copies or substantial portions of the Software.
17525//
17526// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17527// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17528// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17529// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
17530// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17531// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
17532// USE OR OTHER DEALINGS IN THE SOFTWARE.
17533
17534var formatRegExp = /%[sdj%]/g;
17535exports.format = function(f) {
17536 if (!isString(f)) {
17537 var objects = [];
17538 for (var i = 0; i < arguments.length; i++) {
17539 objects.push(inspect(arguments[i]));
17540 }
17541 return objects.join(' ');
17542 }
17543
17544 var i = 1;
17545 var args = arguments;
17546 var len = args.length;
17547 var str = String(f).replace(formatRegExp, function(x) {
17548 if (x === '%%') return '%';
17549 if (i >= len) return x;
17550 switch (x) {
17551 case '%s': return String(args[i++]);
17552 case '%d': return Number(args[i++]);
17553 case '%j':
17554 try {
17555 return JSON.stringify(args[i++]);
17556 } catch (_) {
17557 return '[Circular]';
17558 }
17559 default:
17560 return x;
17561 }
17562 });
17563 for (var x = args[i]; i < len; x = args[++i]) {
17564 if (isNull(x) || !isObject(x)) {
17565 str += ' ' + x;
17566 } else {
17567 str += ' ' + inspect(x);
17568 }
17569 }
17570 return str;
17571};
17572
17573
17574// Mark that a method should not be used.
17575// Returns a modified function which warns once by default.
17576// If --no-deprecation is set, then it is a no-op.
17577exports.deprecate = function(fn, msg) {
17578 // Allow for deprecating things in the process of starting up.
17579 if (isUndefined(global.process)) {
17580 return function() {
17581 return exports.deprecate(fn, msg).apply(this, arguments);
17582 };
17583 }
17584
17585 if (process.noDeprecation === true) {
17586 return fn;
17587 }
17588
17589 var warned = false;
17590 function deprecated() {
17591 if (!warned) {
17592 if (process.throwDeprecation) {
17593 throw new Error(msg);
17594 } else if (process.traceDeprecation) {
17595 console.trace(msg);
17596 } else {
17597 console.error(msg);
17598 }
17599 warned = true;
17600 }
17601 return fn.apply(this, arguments);
17602 }
17603
17604 return deprecated;
17605};
17606
17607
17608var debugs = {};
17609var debugEnviron;
17610exports.debuglog = function(set) {
17611 if (isUndefined(debugEnviron))
17612 debugEnviron = process.env.NODE_DEBUG || '';
17613 set = set.toUpperCase();
17614 if (!debugs[set]) {
17615 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
17616 var pid = process.pid;
17617 debugs[set] = function() {
17618 var msg = exports.format.apply(exports, arguments);
17619 console.error('%s %d: %s', set, pid, msg);
17620 };
17621 } else {
17622 debugs[set] = function() {};
17623 }
17624 }
17625 return debugs[set];
17626};
17627
17628
17629/**
17630 * Echos the value of a value. Trys to print the value out
17631 * in the best way possible given the different types.
17632 *
17633 * @param {Object} obj The object to print out.
17634 * @param {Object} opts Optional options object that alters the output.
17635 */
17636/* legacy: obj, showHidden, depth, colors*/
17637function inspect(obj, opts) {
17638 // default options
17639 var ctx = {
17640 seen: [],
17641 stylize: stylizeNoColor
17642 };
17643 // legacy...
17644 if (arguments.length >= 3) ctx.depth = arguments[2];
17645 if (arguments.length >= 4) ctx.colors = arguments[3];
17646 if (isBoolean(opts)) {
17647 // legacy...
17648 ctx.showHidden = opts;
17649 } else if (opts) {
17650 // got an "options" object
17651 exports._extend(ctx, opts);
17652 }
17653 // set default options
17654 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
17655 if (isUndefined(ctx.depth)) ctx.depth = 2;
17656 if (isUndefined(ctx.colors)) ctx.colors = false;
17657 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
17658 if (ctx.colors) ctx.stylize = stylizeWithColor;
17659 return formatValue(ctx, obj, ctx.depth);
17660}
17661exports.inspect = inspect;
17662
17663
17664// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
17665inspect.colors = {
17666 'bold' : [1, 22],
17667 'italic' : [3, 23],
17668 'underline' : [4, 24],
17669 'inverse' : [7, 27],
17670 'white' : [37, 39],
17671 'grey' : [90, 39],
17672 'black' : [30, 39],
17673 'blue' : [34, 39],
17674 'cyan' : [36, 39],
17675 'green' : [32, 39],
17676 'magenta' : [35, 39],
17677 'red' : [31, 39],
17678 'yellow' : [33, 39]
17679};
17680
17681// Don't use 'blue' not visible on cmd.exe
17682inspect.styles = {
17683 'special': 'cyan',
17684 'number': 'yellow',
17685 'boolean': 'yellow',
17686 'undefined': 'grey',
17687 'null': 'bold',
17688 'string': 'green',
17689 'date': 'magenta',
17690 // "name": intentionally not styling
17691 'regexp': 'red'
17692};
17693
17694
17695function stylizeWithColor(str, styleType) {
17696 var style = inspect.styles[styleType];
17697
17698 if (style) {
17699 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
17700 '\u001b[' + inspect.colors[style][1] + 'm';
17701 } else {
17702 return str;
17703 }
17704}
17705
17706
17707function stylizeNoColor(str, styleType) {
17708 return str;
17709}
17710
17711
17712function arrayToHash(array) {
17713 var hash = {};
17714
17715 array.forEach(function(val, idx) {
17716 hash[val] = true;
17717 });
17718
17719 return hash;
17720}
17721
17722
17723function formatValue(ctx, value, recurseTimes) {
17724 // Provide a hook for user-specified inspect functions.
17725 // Check that value is an object with an inspect function on it
17726 if (ctx.customInspect &&
17727 value &&
17728 isFunction(value.inspect) &&
17729 // Filter out the util module, it's inspect function is special
17730 value.inspect !== exports.inspect &&
17731 // Also filter out any prototype objects using the circular check.
17732 !(value.constructor && value.constructor.prototype === value)) {
17733 var ret = value.inspect(recurseTimes, ctx);
17734 if (!isString(ret)) {
17735 ret = formatValue(ctx, ret, recurseTimes);
17736 }
17737 return ret;
17738 }
17739
17740 // Primitive types cannot have properties
17741 var primitive = formatPrimitive(ctx, value);
17742 if (primitive) {
17743 return primitive;
17744 }
17745
17746 // Look up the keys of the object.
17747 var keys = Object.keys(value);
17748 var visibleKeys = arrayToHash(keys);
17749
17750 if (ctx.showHidden) {
17751 keys = Object.getOwnPropertyNames(value);
17752 }
17753
17754 // IE doesn't make error fields non-enumerable
17755 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
17756 if (isError(value)
17757 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
17758 return formatError(value);
17759 }
17760
17761 // Some type of object without properties can be shortcutted.
17762 if (keys.length === 0) {
17763 if (isFunction(value)) {
17764 var name = value.name ? ': ' + value.name : '';
17765 return ctx.stylize('[Function' + name + ']', 'special');
17766 }
17767 if (isRegExp(value)) {
17768 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
17769 }
17770 if (isDate(value)) {
17771 return ctx.stylize(Date.prototype.toString.call(value), 'date');
17772 }
17773 if (isError(value)) {
17774 return formatError(value);
17775 }
17776 }
17777
17778 var base = '', array = false, braces = ['{', '}'];
17779
17780 // Make Array say that they are Array
17781 if (isArray(value)) {
17782 array = true;
17783 braces = ['[', ']'];
17784 }
17785
17786 // Make functions say that they are functions
17787 if (isFunction(value)) {
17788 var n = value.name ? ': ' + value.name : '';
17789 base = ' [Function' + n + ']';
17790 }
17791
17792 // Make RegExps say that they are RegExps
17793 if (isRegExp(value)) {
17794 base = ' ' + RegExp.prototype.toString.call(value);
17795 }
17796
17797 // Make dates with properties first say the date
17798 if (isDate(value)) {
17799 base = ' ' + Date.prototype.toUTCString.call(value);
17800 }
17801
17802 // Make error with message first say the error
17803 if (isError(value)) {
17804 base = ' ' + formatError(value);
17805 }
17806
17807 if (keys.length === 0 && (!array || value.length == 0)) {
17808 return braces[0] + base + braces[1];
17809 }
17810
17811 if (recurseTimes < 0) {
17812 if (isRegExp(value)) {
17813 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
17814 } else {
17815 return ctx.stylize('[Object]', 'special');
17816 }
17817 }
17818
17819 ctx.seen.push(value);
17820
17821 var output;
17822 if (array) {
17823 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
17824 } else {
17825 output = keys.map(function(key) {
17826 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
17827 });
17828 }
17829
17830 ctx.seen.pop();
17831
17832 return reduceToSingleString(output, base, braces);
17833}
17834
17835
17836function formatPrimitive(ctx, value) {
17837 if (isUndefined(value))
17838 return ctx.stylize('undefined', 'undefined');
17839 if (isString(value)) {
17840 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
17841 .replace(/'/g, "\\'")
17842 .replace(/\\"/g, '"') + '\'';
17843 return ctx.stylize(simple, 'string');
17844 }
17845 if (isNumber(value))
17846 return ctx.stylize('' + value, 'number');
17847 if (isBoolean(value))
17848 return ctx.stylize('' + value, 'boolean');
17849 // For some reason typeof null is "object", so special case here.
17850 if (isNull(value))
17851 return ctx.stylize('null', 'null');
17852}
17853
17854
17855function formatError(value) {
17856 return '[' + Error.prototype.toString.call(value) + ']';
17857}
17858
17859
17860function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
17861 var output = [];
17862 for (var i = 0, l = value.length; i < l; ++i) {
17863 if (hasOwnProperty(value, String(i))) {
17864 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
17865 String(i), true));
17866 } else {
17867 output.push('');
17868 }
17869 }
17870 keys.forEach(function(key) {
17871 if (!key.match(/^\d+$/)) {
17872 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
17873 key, true));
17874 }
17875 });
17876 return output;
17877}
17878
17879
17880function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
17881 var name, str, desc;
17882 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
17883 if (desc.get) {
17884 if (desc.set) {
17885 str = ctx.stylize('[Getter/Setter]', 'special');
17886 } else {
17887 str = ctx.stylize('[Getter]', 'special');
17888 }
17889 } else {
17890 if (desc.set) {
17891 str = ctx.stylize('[Setter]', 'special');
17892 }
17893 }
17894 if (!hasOwnProperty(visibleKeys, key)) {
17895 name = '[' + key + ']';
17896 }
17897 if (!str) {
17898 if (ctx.seen.indexOf(desc.value) < 0) {
17899 if (isNull(recurseTimes)) {
17900 str = formatValue(ctx, desc.value, null);
17901 } else {
17902 str = formatValue(ctx, desc.value, recurseTimes - 1);
17903 }
17904 if (str.indexOf('\n') > -1) {
17905 if (array) {
17906 str = str.split('\n').map(function(line) {
17907 return ' ' + line;
17908 }).join('\n').substr(2);
17909 } else {
17910 str = '\n' + str.split('\n').map(function(line) {
17911 return ' ' + line;
17912 }).join('\n');
17913 }
17914 }
17915 } else {
17916 str = ctx.stylize('[Circular]', 'special');
17917 }
17918 }
17919 if (isUndefined(name)) {
17920 if (array && key.match(/^\d+$/)) {
17921 return str;
17922 }
17923 name = JSON.stringify('' + key);
17924 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
17925 name = name.substr(1, name.length - 2);
17926 name = ctx.stylize(name, 'name');
17927 } else {
17928 name = name.replace(/'/g, "\\'")
17929 .replace(/\\"/g, '"')
17930 .replace(/(^"|"$)/g, "'");
17931 name = ctx.stylize(name, 'string');
17932 }
17933 }
17934
17935 return name + ': ' + str;
17936}
17937
17938
17939function reduceToSingleString(output, base, braces) {
17940 var numLinesEst = 0;
17941 var length = output.reduce(function(prev, cur) {
17942 numLinesEst++;
17943 if (cur.indexOf('\n') >= 0) numLinesEst++;
17944 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
17945 }, 0);
17946
17947 if (length > 60) {
17948 return braces[0] +
17949 (base === '' ? '' : base + '\n ') +
17950 ' ' +
17951 output.join(',\n ') +
17952 ' ' +
17953 braces[1];
17954 }
17955
17956 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
17957}
17958
17959
17960// NOTE: These type checking functions intentionally don't use `instanceof`
17961// because it is fragile and can be easily faked with `Object.create()`.
17962function isArray(ar) {
17963 return Array.isArray(ar);
17964}
17965exports.isArray = isArray;
17966
17967function isBoolean(arg) {
17968 return typeof arg === 'boolean';
17969}
17970exports.isBoolean = isBoolean;
17971
17972function isNull(arg) {
17973 return arg === null;
17974}
17975exports.isNull = isNull;
17976
17977function isNullOrUndefined(arg) {
17978 return arg == null;
17979}
17980exports.isNullOrUndefined = isNullOrUndefined;
17981
17982function isNumber(arg) {
17983 return typeof arg === 'number';
17984}
17985exports.isNumber = isNumber;
17986
17987function isString(arg) {
17988 return typeof arg === 'string';
17989}
17990exports.isString = isString;
17991
17992function isSymbol(arg) {
17993 return typeof arg === 'symbol';
17994}
17995exports.isSymbol = isSymbol;
17996
17997function isUndefined(arg) {
17998 return arg === void 0;
17999}
18000exports.isUndefined = isUndefined;
18001
18002function isRegExp(re) {
18003 return isObject(re) && objectToString(re) === '[object RegExp]';
18004}
18005exports.isRegExp = isRegExp;
18006
18007function isObject(arg) {
18008 return typeof arg === 'object' && arg !== null;
18009}
18010exports.isObject = isObject;
18011
18012function isDate(d) {
18013 return isObject(d) && objectToString(d) === '[object Date]';
18014}
18015exports.isDate = isDate;
18016
18017function isError(e) {
18018 return isObject(e) &&
18019 (objectToString(e) === '[object Error]' || e instanceof Error);
18020}
18021exports.isError = isError;
18022
18023function isFunction(arg) {
18024 return typeof arg === 'function';
18025}
18026exports.isFunction = isFunction;
18027
18028function isPrimitive(arg) {
18029 return arg === null ||
18030 typeof arg === 'boolean' ||
18031 typeof arg === 'number' ||
18032 typeof arg === 'string' ||
18033 typeof arg === 'symbol' || // ES6 symbol
18034 typeof arg === 'undefined';
18035}
18036exports.isPrimitive = isPrimitive;
18037
18038exports.isBuffer = _dereq_('./support/isBuffer');
18039
18040function objectToString(o) {
18041 return Object.prototype.toString.call(o);
18042}
18043
18044
18045function pad(n) {
18046 return n < 10 ? '0' + n.toString(10) : n.toString(10);
18047}
18048
18049
18050var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
18051 'Oct', 'Nov', 'Dec'];
18052
18053// 26 Feb 16:19:34
18054function timestamp() {
18055 var d = new Date();
18056 var time = [pad(d.getHours()),
18057 pad(d.getMinutes()),
18058 pad(d.getSeconds())].join(':');
18059 return [d.getDate(), months[d.getMonth()], time].join(' ');
18060}
18061
18062
18063// log is just a thin wrapper to console.log that prepends a timestamp
18064exports.log = function() {
18065 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
18066};
18067
18068
18069/**
18070 * Inherit the prototype methods from one constructor into another.
18071 *
18072 * The Function.prototype.inherits from lang.js rewritten as a standalone
18073 * function (not on Function.prototype). NOTE: If this file is to be loaded
18074 * during bootstrapping this function needs to be rewritten using some native
18075 * functions as prototype setup using normal JavaScript does not work as
18076 * expected during bootstrapping (see mirror.js in r114903).
18077 *
18078 * @param {function} ctor Constructor function which needs to inherit the
18079 * prototype.
18080 * @param {function} superCtor Constructor function to inherit prototype from.
18081 */
18082exports.inherits = _dereq_('inherits');
18083
18084exports._extend = function(origin, add) {
18085 // Don't do anything if add isn't an object
18086 if (!add || !isObject(add)) return origin;
18087
18088 var keys = Object.keys(add);
18089 var i = keys.length;
18090 while (i--) {
18091 origin[keys[i]] = add[keys[i]];
18092 }
18093 return origin;
18094};
18095
18096function hasOwnProperty(obj, prop) {
18097 return Object.prototype.hasOwnProperty.call(obj, prop);
18098}
18099
18100}).call(this)}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
18101},{"./support/isBuffer":142,"_process":93,"inherits":141}],144:[function(_dereq_,module,exports){
18102"use strict";
18103
18104Object.defineProperty(exports, "__esModule", {
18105 value: true
18106});
18107Object.defineProperty(exports, "v1", {
18108 enumerable: true,
18109 get: function () {
18110 return _v.default;
18111 }
18112});
18113Object.defineProperty(exports, "v3", {
18114 enumerable: true,
18115 get: function () {
18116 return _v2.default;
18117 }
18118});
18119Object.defineProperty(exports, "v4", {
18120 enumerable: true,
18121 get: function () {
18122 return _v3.default;
18123 }
18124});
18125Object.defineProperty(exports, "v5", {
18126 enumerable: true,
18127 get: function () {
18128 return _v4.default;
18129 }
18130});
18131Object.defineProperty(exports, "NIL", {
18132 enumerable: true,
18133 get: function () {
18134 return _nil.default;
18135 }
18136});
18137Object.defineProperty(exports, "version", {
18138 enumerable: true,
18139 get: function () {
18140 return _version.default;
18141 }
18142});
18143Object.defineProperty(exports, "validate", {
18144 enumerable: true,
18145 get: function () {
18146 return _validate.default;
18147 }
18148});
18149Object.defineProperty(exports, "stringify", {
18150 enumerable: true,
18151 get: function () {
18152 return _stringify.default;
18153 }
18154});
18155Object.defineProperty(exports, "parse", {
18156 enumerable: true,
18157 get: function () {
18158 return _parse.default;
18159 }
18160});
18161
18162var _v = _interopRequireDefault(_dereq_("./v1.js"));
18163
18164var _v2 = _interopRequireDefault(_dereq_("./v3.js"));
18165
18166var _v3 = _interopRequireDefault(_dereq_("./v4.js"));
18167
18168var _v4 = _interopRequireDefault(_dereq_("./v5.js"));
18169
18170var _nil = _interopRequireDefault(_dereq_("./nil.js"));
18171
18172var _version = _interopRequireDefault(_dereq_("./version.js"));
18173
18174var _validate = _interopRequireDefault(_dereq_("./validate.js"));
18175
18176var _stringify = _interopRequireDefault(_dereq_("./stringify.js"));
18177
18178var _parse = _interopRequireDefault(_dereq_("./parse.js"));
18179
18180function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18181},{"./nil.js":146,"./parse.js":147,"./stringify.js":151,"./v1.js":152,"./v3.js":153,"./v4.js":155,"./v5.js":156,"./validate.js":157,"./version.js":158}],145:[function(_dereq_,module,exports){
18182"use strict";
18183
18184Object.defineProperty(exports, "__esModule", {
18185 value: true
18186});
18187exports.default = void 0;
18188
18189/*
18190 * Browser-compatible JavaScript MD5
18191 *
18192 * Modification of JavaScript MD5
18193 * https://github.com/blueimp/JavaScript-MD5
18194 *
18195 * Copyright 2011, Sebastian Tschan
18196 * https://blueimp.net
18197 *
18198 * Licensed under the MIT license:
18199 * https://opensource.org/licenses/MIT
18200 *
18201 * Based on
18202 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
18203 * Digest Algorithm, as defined in RFC 1321.
18204 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
18205 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
18206 * Distributed under the BSD License
18207 * See http://pajhome.org.uk/crypt/md5 for more info.
18208 */
18209function md5(bytes) {
18210 if (typeof bytes === 'string') {
18211 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
18212
18213 bytes = new Uint8Array(msg.length);
18214
18215 for (let i = 0; i < msg.length; ++i) {
18216 bytes[i] = msg.charCodeAt(i);
18217 }
18218 }
18219
18220 return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
18221}
18222/*
18223 * Convert an array of little-endian words to an array of bytes
18224 */
18225
18226
18227function md5ToHexEncodedArray(input) {
18228 const output = [];
18229 const length32 = input.length * 32;
18230 const hexTab = '0123456789abcdef';
18231
18232 for (let i = 0; i < length32; i += 8) {
18233 const x = input[i >> 5] >>> i % 32 & 0xff;
18234 const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
18235 output.push(hex);
18236 }
18237
18238 return output;
18239}
18240/**
18241 * Calculate output length with padding and bit length
18242 */
18243
18244
18245function getOutputLength(inputLength8) {
18246 return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
18247}
18248/*
18249 * Calculate the MD5 of an array of little-endian words, and a bit length.
18250 */
18251
18252
18253function wordsToMd5(x, len) {
18254 /* append padding */
18255 x[len >> 5] |= 0x80 << len % 32;
18256 x[getOutputLength(len) - 1] = len;
18257 let a = 1732584193;
18258 let b = -271733879;
18259 let c = -1732584194;
18260 let d = 271733878;
18261
18262 for (let i = 0; i < x.length; i += 16) {
18263 const olda = a;
18264 const oldb = b;
18265 const oldc = c;
18266 const oldd = d;
18267 a = md5ff(a, b, c, d, x[i], 7, -680876936);
18268 d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
18269 c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
18270 b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
18271 a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
18272 d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
18273 c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
18274 b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
18275 a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
18276 d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
18277 c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
18278 b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
18279 a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
18280 d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
18281 c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
18282 b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
18283 a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
18284 d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
18285 c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
18286 b = md5gg(b, c, d, a, x[i], 20, -373897302);
18287 a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
18288 d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
18289 c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
18290 b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
18291 a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
18292 d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
18293 c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
18294 b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
18295 a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
18296 d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
18297 c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
18298 b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
18299 a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
18300 d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
18301 c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
18302 b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
18303 a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
18304 d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
18305 c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
18306 b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
18307 a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
18308 d = md5hh(d, a, b, c, x[i], 11, -358537222);
18309 c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
18310 b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
18311 a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
18312 d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
18313 c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
18314 b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
18315 a = md5ii(a, b, c, d, x[i], 6, -198630844);
18316 d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
18317 c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
18318 b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
18319 a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
18320 d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
18321 c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
18322 b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
18323 a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
18324 d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
18325 c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
18326 b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
18327 a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
18328 d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
18329 c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
18330 b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
18331 a = safeAdd(a, olda);
18332 b = safeAdd(b, oldb);
18333 c = safeAdd(c, oldc);
18334 d = safeAdd(d, oldd);
18335 }
18336
18337 return [a, b, c, d];
18338}
18339/*
18340 * Convert an array bytes to an array of little-endian words
18341 * Characters >255 have their high-byte silently ignored.
18342 */
18343
18344
18345function bytesToWords(input) {
18346 if (input.length === 0) {
18347 return [];
18348 }
18349
18350 const length8 = input.length * 8;
18351 const output = new Uint32Array(getOutputLength(length8));
18352
18353 for (let i = 0; i < length8; i += 8) {
18354 output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
18355 }
18356
18357 return output;
18358}
18359/*
18360 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
18361 * to work around bugs in some JS interpreters.
18362 */
18363
18364
18365function safeAdd(x, y) {
18366 const lsw = (x & 0xffff) + (y & 0xffff);
18367 const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
18368 return msw << 16 | lsw & 0xffff;
18369}
18370/*
18371 * Bitwise rotate a 32-bit number to the left.
18372 */
18373
18374
18375function bitRotateLeft(num, cnt) {
18376 return num << cnt | num >>> 32 - cnt;
18377}
18378/*
18379 * These functions implement the four basic operations the algorithm uses.
18380 */
18381
18382
18383function md5cmn(q, a, b, x, s, t) {
18384 return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
18385}
18386
18387function md5ff(a, b, c, d, x, s, t) {
18388 return md5cmn(b & c | ~b & d, a, b, x, s, t);
18389}
18390
18391function md5gg(a, b, c, d, x, s, t) {
18392 return md5cmn(b & d | c & ~d, a, b, x, s, t);
18393}
18394
18395function md5hh(a, b, c, d, x, s, t) {
18396 return md5cmn(b ^ c ^ d, a, b, x, s, t);
18397}
18398
18399function md5ii(a, b, c, d, x, s, t) {
18400 return md5cmn(c ^ (b | ~d), a, b, x, s, t);
18401}
18402
18403var _default = md5;
18404exports.default = _default;
18405},{}],146:[function(_dereq_,module,exports){
18406"use strict";
18407
18408Object.defineProperty(exports, "__esModule", {
18409 value: true
18410});
18411exports.default = void 0;
18412var _default = '00000000-0000-0000-0000-000000000000';
18413exports.default = _default;
18414},{}],147:[function(_dereq_,module,exports){
18415"use strict";
18416
18417Object.defineProperty(exports, "__esModule", {
18418 value: true
18419});
18420exports.default = void 0;
18421
18422var _validate = _interopRequireDefault(_dereq_("./validate.js"));
18423
18424function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18425
18426function parse(uuid) {
18427 if (!(0, _validate.default)(uuid)) {
18428 throw TypeError('Invalid UUID');
18429 }
18430
18431 let v;
18432 const arr = new Uint8Array(16); // Parse ########-....-....-....-............
18433
18434 arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
18435 arr[1] = v >>> 16 & 0xff;
18436 arr[2] = v >>> 8 & 0xff;
18437 arr[3] = v & 0xff; // Parse ........-####-....-....-............
18438
18439 arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
18440 arr[5] = v & 0xff; // Parse ........-....-####-....-............
18441
18442 arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
18443 arr[7] = v & 0xff; // Parse ........-....-....-####-............
18444
18445 arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
18446 arr[9] = v & 0xff; // Parse ........-....-....-....-############
18447 // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
18448
18449 arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
18450 arr[11] = v / 0x100000000 & 0xff;
18451 arr[12] = v >>> 24 & 0xff;
18452 arr[13] = v >>> 16 & 0xff;
18453 arr[14] = v >>> 8 & 0xff;
18454 arr[15] = v & 0xff;
18455 return arr;
18456}
18457
18458var _default = parse;
18459exports.default = _default;
18460},{"./validate.js":157}],148:[function(_dereq_,module,exports){
18461"use strict";
18462
18463Object.defineProperty(exports, "__esModule", {
18464 value: true
18465});
18466exports.default = void 0;
18467var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
18468exports.default = _default;
18469},{}],149:[function(_dereq_,module,exports){
18470"use strict";
18471
18472Object.defineProperty(exports, "__esModule", {
18473 value: true
18474});
18475exports.default = rng;
18476// Unique ID creation requires a high quality random # generator. In the browser we therefore
18477// require the crypto API and do not support built-in fallback to lower quality random number
18478// generators (like Math.random()).
18479let getRandomValues;
18480const rnds8 = new Uint8Array(16);
18481
18482function rng() {
18483 // lazy load so that environments that need to polyfill have a chance to do so
18484 if (!getRandomValues) {
18485 // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
18486 // find the complete implementation of crypto (msCrypto) on IE11.
18487 getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
18488
18489 if (!getRandomValues) {
18490 throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
18491 }
18492 }
18493
18494 return getRandomValues(rnds8);
18495}
18496},{}],150:[function(_dereq_,module,exports){
18497"use strict";
18498
18499Object.defineProperty(exports, "__esModule", {
18500 value: true
18501});
18502exports.default = void 0;
18503
18504// Adapted from Chris Veness' SHA1 code at
18505// http://www.movable-type.co.uk/scripts/sha1.html
18506function f(s, x, y, z) {
18507 switch (s) {
18508 case 0:
18509 return x & y ^ ~x & z;
18510
18511 case 1:
18512 return x ^ y ^ z;
18513
18514 case 2:
18515 return x & y ^ x & z ^ y & z;
18516
18517 case 3:
18518 return x ^ y ^ z;
18519 }
18520}
18521
18522function ROTL(x, n) {
18523 return x << n | x >>> 32 - n;
18524}
18525
18526function sha1(bytes) {
18527 const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
18528 const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
18529
18530 if (typeof bytes === 'string') {
18531 const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
18532
18533 bytes = [];
18534
18535 for (let i = 0; i < msg.length; ++i) {
18536 bytes.push(msg.charCodeAt(i));
18537 }
18538 } else if (!Array.isArray(bytes)) {
18539 // Convert Array-like to Array
18540 bytes = Array.prototype.slice.call(bytes);
18541 }
18542
18543 bytes.push(0x80);
18544 const l = bytes.length / 4 + 2;
18545 const N = Math.ceil(l / 16);
18546 const M = new Array(N);
18547
18548 for (let i = 0; i < N; ++i) {
18549 const arr = new Uint32Array(16);
18550
18551 for (let j = 0; j < 16; ++j) {
18552 arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3];
18553 }
18554
18555 M[i] = arr;
18556 }
18557
18558 M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
18559 M[N - 1][14] = Math.floor(M[N - 1][14]);
18560 M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
18561
18562 for (let i = 0; i < N; ++i) {
18563 const W = new Uint32Array(80);
18564
18565 for (let t = 0; t < 16; ++t) {
18566 W[t] = M[i][t];
18567 }
18568
18569 for (let t = 16; t < 80; ++t) {
18570 W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
18571 }
18572
18573 let a = H[0];
18574 let b = H[1];
18575 let c = H[2];
18576 let d = H[3];
18577 let e = H[4];
18578
18579 for (let t = 0; t < 80; ++t) {
18580 const s = Math.floor(t / 20);
18581 const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
18582 e = d;
18583 d = c;
18584 c = ROTL(b, 30) >>> 0;
18585 b = a;
18586 a = T;
18587 }
18588
18589 H[0] = H[0] + a >>> 0;
18590 H[1] = H[1] + b >>> 0;
18591 H[2] = H[2] + c >>> 0;
18592 H[3] = H[3] + d >>> 0;
18593 H[4] = H[4] + e >>> 0;
18594 }
18595
18596 return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
18597}
18598
18599var _default = sha1;
18600exports.default = _default;
18601},{}],151:[function(_dereq_,module,exports){
18602"use strict";
18603
18604Object.defineProperty(exports, "__esModule", {
18605 value: true
18606});
18607exports.default = void 0;
18608
18609var _validate = _interopRequireDefault(_dereq_("./validate.js"));
18610
18611function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18612
18613/**
18614 * Convert array of 16 byte values to UUID string format of the form:
18615 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
18616 */
18617const byteToHex = [];
18618
18619for (let i = 0; i < 256; ++i) {
18620 byteToHex.push((i + 0x100).toString(16).substr(1));
18621}
18622
18623function stringify(arr, offset = 0) {
18624 // Note: Be careful editing this code! It's been tuned for performance
18625 // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
18626 const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
18627 // of the following:
18628 // - One or more input array values don't map to a hex octet (leading to
18629 // "undefined" in the uuid)
18630 // - Invalid input values for the RFC `version` or `variant` fields
18631
18632 if (!(0, _validate.default)(uuid)) {
18633 throw TypeError('Stringified UUID is invalid');
18634 }
18635
18636 return uuid;
18637}
18638
18639var _default = stringify;
18640exports.default = _default;
18641},{"./validate.js":157}],152:[function(_dereq_,module,exports){
18642"use strict";
18643
18644Object.defineProperty(exports, "__esModule", {
18645 value: true
18646});
18647exports.default = void 0;
18648
18649var _rng = _interopRequireDefault(_dereq_("./rng.js"));
18650
18651var _stringify = _interopRequireDefault(_dereq_("./stringify.js"));
18652
18653function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18654
18655// **`v1()` - Generate time-based UUID**
18656//
18657// Inspired by https://github.com/LiosK/UUID.js
18658// and http://docs.python.org/library/uuid.html
18659let _nodeId;
18660
18661let _clockseq; // Previous uuid creation time
18662
18663
18664let _lastMSecs = 0;
18665let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
18666
18667function v1(options, buf, offset) {
18668 let i = buf && offset || 0;
18669 const b = buf || new Array(16);
18670 options = options || {};
18671 let node = options.node || _nodeId;
18672 let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
18673 // specified. We do this lazily to minimize issues related to insufficient
18674 // system entropy. See #189
18675
18676 if (node == null || clockseq == null) {
18677 const seedBytes = options.random || (options.rng || _rng.default)();
18678
18679 if (node == null) {
18680 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
18681 node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
18682 }
18683
18684 if (clockseq == null) {
18685 // Per 4.2.2, randomize (14 bit) clockseq
18686 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
18687 }
18688 } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
18689 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
18690 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
18691 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
18692
18693
18694 let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
18695 // cycle to simulate higher resolution clock
18696
18697 let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
18698
18699 const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
18700
18701 if (dt < 0 && options.clockseq === undefined) {
18702 clockseq = clockseq + 1 & 0x3fff;
18703 } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
18704 // time interval
18705
18706
18707 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
18708 nsecs = 0;
18709 } // Per 4.2.1.2 Throw error if too many uuids are requested
18710
18711
18712 if (nsecs >= 10000) {
18713 throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
18714 }
18715
18716 _lastMSecs = msecs;
18717 _lastNSecs = nsecs;
18718 _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
18719
18720 msecs += 12219292800000; // `time_low`
18721
18722 const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
18723 b[i++] = tl >>> 24 & 0xff;
18724 b[i++] = tl >>> 16 & 0xff;
18725 b[i++] = tl >>> 8 & 0xff;
18726 b[i++] = tl & 0xff; // `time_mid`
18727
18728 const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
18729 b[i++] = tmh >>> 8 & 0xff;
18730 b[i++] = tmh & 0xff; // `time_high_and_version`
18731
18732 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
18733
18734 b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
18735
18736 b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
18737
18738 b[i++] = clockseq & 0xff; // `node`
18739
18740 for (let n = 0; n < 6; ++n) {
18741 b[i + n] = node[n];
18742 }
18743
18744 return buf || (0, _stringify.default)(b);
18745}
18746
18747var _default = v1;
18748exports.default = _default;
18749},{"./rng.js":149,"./stringify.js":151}],153:[function(_dereq_,module,exports){
18750"use strict";
18751
18752Object.defineProperty(exports, "__esModule", {
18753 value: true
18754});
18755exports.default = void 0;
18756
18757var _v = _interopRequireDefault(_dereq_("./v35.js"));
18758
18759var _md = _interopRequireDefault(_dereq_("./md5.js"));
18760
18761function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18762
18763const v3 = (0, _v.default)('v3', 0x30, _md.default);
18764var _default = v3;
18765exports.default = _default;
18766},{"./md5.js":145,"./v35.js":154}],154:[function(_dereq_,module,exports){
18767"use strict";
18768
18769Object.defineProperty(exports, "__esModule", {
18770 value: true
18771});
18772exports.default = _default;
18773exports.URL = exports.DNS = void 0;
18774
18775var _stringify = _interopRequireDefault(_dereq_("./stringify.js"));
18776
18777var _parse = _interopRequireDefault(_dereq_("./parse.js"));
18778
18779function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18780
18781function stringToBytes(str) {
18782 str = unescape(encodeURIComponent(str)); // UTF8 escape
18783
18784 const bytes = [];
18785
18786 for (let i = 0; i < str.length; ++i) {
18787 bytes.push(str.charCodeAt(i));
18788 }
18789
18790 return bytes;
18791}
18792
18793const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
18794exports.DNS = DNS;
18795const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
18796exports.URL = URL;
18797
18798function _default(name, version, hashfunc) {
18799 function generateUUID(value, namespace, buf, offset) {
18800 if (typeof value === 'string') {
18801 value = stringToBytes(value);
18802 }
18803
18804 if (typeof namespace === 'string') {
18805 namespace = (0, _parse.default)(namespace);
18806 }
18807
18808 if (namespace.length !== 16) {
18809 throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
18810 } // Compute hash of namespace and value, Per 4.3
18811 // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
18812 // hashfunc([...namespace, ... value])`
18813
18814
18815 let bytes = new Uint8Array(16 + value.length);
18816 bytes.set(namespace);
18817 bytes.set(value, namespace.length);
18818 bytes = hashfunc(bytes);
18819 bytes[6] = bytes[6] & 0x0f | version;
18820 bytes[8] = bytes[8] & 0x3f | 0x80;
18821
18822 if (buf) {
18823 offset = offset || 0;
18824
18825 for (let i = 0; i < 16; ++i) {
18826 buf[offset + i] = bytes[i];
18827 }
18828
18829 return buf;
18830 }
18831
18832 return (0, _stringify.default)(bytes);
18833 } // Function#name is not settable on some platforms (#270)
18834
18835
18836 try {
18837 generateUUID.name = name; // eslint-disable-next-line no-empty
18838 } catch (err) {} // For CommonJS default export support
18839
18840
18841 generateUUID.DNS = DNS;
18842 generateUUID.URL = URL;
18843 return generateUUID;
18844}
18845},{"./parse.js":147,"./stringify.js":151}],155:[function(_dereq_,module,exports){
18846"use strict";
18847
18848Object.defineProperty(exports, "__esModule", {
18849 value: true
18850});
18851exports.default = void 0;
18852
18853var _rng = _interopRequireDefault(_dereq_("./rng.js"));
18854
18855var _stringify = _interopRequireDefault(_dereq_("./stringify.js"));
18856
18857function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18858
18859function v4(options, buf, offset) {
18860 options = options || {};
18861
18862 const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
18863
18864
18865 rnds[6] = rnds[6] & 0x0f | 0x40;
18866 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
18867
18868 if (buf) {
18869 offset = offset || 0;
18870
18871 for (let i = 0; i < 16; ++i) {
18872 buf[offset + i] = rnds[i];
18873 }
18874
18875 return buf;
18876 }
18877
18878 return (0, _stringify.default)(rnds);
18879}
18880
18881var _default = v4;
18882exports.default = _default;
18883},{"./rng.js":149,"./stringify.js":151}],156:[function(_dereq_,module,exports){
18884"use strict";
18885
18886Object.defineProperty(exports, "__esModule", {
18887 value: true
18888});
18889exports.default = void 0;
18890
18891var _v = _interopRequireDefault(_dereq_("./v35.js"));
18892
18893var _sha = _interopRequireDefault(_dereq_("./sha1.js"));
18894
18895function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18896
18897const v5 = (0, _v.default)('v5', 0x50, _sha.default);
18898var _default = v5;
18899exports.default = _default;
18900},{"./sha1.js":150,"./v35.js":154}],157:[function(_dereq_,module,exports){
18901"use strict";
18902
18903Object.defineProperty(exports, "__esModule", {
18904 value: true
18905});
18906exports.default = void 0;
18907
18908var _regex = _interopRequireDefault(_dereq_("./regex.js"));
18909
18910function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18911
18912function validate(uuid) {
18913 return typeof uuid === 'string' && _regex.default.test(uuid);
18914}
18915
18916var _default = validate;
18917exports.default = _default;
18918},{"./regex.js":148}],158:[function(_dereq_,module,exports){
18919"use strict";
18920
18921Object.defineProperty(exports, "__esModule", {
18922 value: true
18923});
18924exports.default = void 0;
18925
18926var _validate = _interopRequireDefault(_dereq_("./validate.js"));
18927
18928function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18929
18930function version(uuid) {
18931 if (!(0, _validate.default)(uuid)) {
18932 throw TypeError('Invalid UUID');
18933 }
18934
18935 return parseInt(uuid.substr(14, 1), 16);
18936}
18937
18938var _default = version;
18939exports.default = _default;
18940},{"./validate.js":157}],159:[function(_dereq_,module,exports){
18941'use strict';
18942
18943/**
18944 * Stringify/parse functions that don't operate
18945 * recursively, so they avoid call stack exceeded
18946 * errors.
18947 */
18948exports.stringify = function stringify(input) {
18949 var queue = [];
18950 queue.push({obj: input});
18951
18952 var res = '';
18953 var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;
18954 while ((next = queue.pop())) {
18955 obj = next.obj;
18956 prefix = next.prefix || '';
18957 val = next.val || '';
18958 res += prefix;
18959 if (val) {
18960 res += val;
18961 } else if (typeof obj !== 'object') {
18962 res += typeof obj === 'undefined' ? null : JSON.stringify(obj);
18963 } else if (obj === null) {
18964 res += 'null';
18965 } else if (Array.isArray(obj)) {
18966 queue.push({val: ']'});
18967 for (i = obj.length - 1; i >= 0; i--) {
18968 arrayPrefix = i === 0 ? '' : ',';
18969 queue.push({obj: obj[i], prefix: arrayPrefix});
18970 }
18971 queue.push({val: '['});
18972 } else { // object
18973 keys = [];
18974 for (k in obj) {
18975 if (obj.hasOwnProperty(k)) {
18976 keys.push(k);
18977 }
18978 }
18979 queue.push({val: '}'});
18980 for (i = keys.length - 1; i >= 0; i--) {
18981 key = keys[i];
18982 value = obj[key];
18983 objPrefix = (i > 0 ? ',' : '');
18984 objPrefix += JSON.stringify(key) + ':';
18985 queue.push({obj: value, prefix: objPrefix});
18986 }
18987 queue.push({val: '{'});
18988 }
18989 }
18990 return res;
18991};
18992
18993// Convenience function for the parse function.
18994// This pop function is basically copied from
18995// pouchCollate.parseIndexableString
18996function pop(obj, stack, metaStack) {
18997 var lastMetaElement = metaStack[metaStack.length - 1];
18998 if (obj === lastMetaElement.element) {
18999 // popping a meta-element, e.g. an object whose value is another object
19000 metaStack.pop();
19001 lastMetaElement = metaStack[metaStack.length - 1];
19002 }
19003 var element = lastMetaElement.element;
19004 var lastElementIndex = lastMetaElement.index;
19005 if (Array.isArray(element)) {
19006 element.push(obj);
19007 } else if (lastElementIndex === stack.length - 2) { // obj with key+value
19008 var key = stack.pop();
19009 element[key] = obj;
19010 } else {
19011 stack.push(obj); // obj with key only
19012 }
19013}
19014
19015exports.parse = function (str) {
19016 var stack = [];
19017 var metaStack = []; // stack for arrays and objects
19018 var i = 0;
19019 var collationIndex,parsedNum,numChar;
19020 var parsedString,lastCh,numConsecutiveSlashes,ch;
19021 var arrayElement, objElement;
19022 while (true) {
19023 collationIndex = str[i++];
19024 if (collationIndex === '}' ||
19025 collationIndex === ']' ||
19026 typeof collationIndex === 'undefined') {
19027 if (stack.length === 1) {
19028 return stack.pop();
19029 } else {
19030 pop(stack.pop(), stack, metaStack);
19031 continue;
19032 }
19033 }
19034 switch (collationIndex) {
19035 case ' ':
19036 case '\t':
19037 case '\n':
19038 case ':':
19039 case ',':
19040 break;
19041 case 'n':
19042 i += 3; // 'ull'
19043 pop(null, stack, metaStack);
19044 break;
19045 case 't':
19046 i += 3; // 'rue'
19047 pop(true, stack, metaStack);
19048 break;
19049 case 'f':
19050 i += 4; // 'alse'
19051 pop(false, stack, metaStack);
19052 break;
19053 case '0':
19054 case '1':
19055 case '2':
19056 case '3':
19057 case '4':
19058 case '5':
19059 case '6':
19060 case '7':
19061 case '8':
19062 case '9':
19063 case '-':
19064 parsedNum = '';
19065 i--;
19066 while (true) {
19067 numChar = str[i++];
19068 if (/[\d\.\-e\+]/.test(numChar)) {
19069 parsedNum += numChar;
19070 } else {
19071 i--;
19072 break;
19073 }
19074 }
19075 pop(parseFloat(parsedNum), stack, metaStack);
19076 break;
19077 case '"':
19078 parsedString = '';
19079 lastCh = void 0;
19080 numConsecutiveSlashes = 0;
19081 while (true) {
19082 ch = str[i++];
19083 if (ch !== '"' || (lastCh === '\\' &&
19084 numConsecutiveSlashes % 2 === 1)) {
19085 parsedString += ch;
19086 lastCh = ch;
19087 if (lastCh === '\\') {
19088 numConsecutiveSlashes++;
19089 } else {
19090 numConsecutiveSlashes = 0;
19091 }
19092 } else {
19093 break;
19094 }
19095 }
19096 pop(JSON.parse('"' + parsedString + '"'), stack, metaStack);
19097 break;
19098 case '[':
19099 arrayElement = { element: [], index: stack.length };
19100 stack.push(arrayElement.element);
19101 metaStack.push(arrayElement);
19102 break;
19103 case '{':
19104 objElement = { element: {}, index: stack.length };
19105 stack.push(objElement.element);
19106 metaStack.push(objElement);
19107 break;
19108 default:
19109 throw new Error(
19110 'unexpectedly reached end of input: ' + collationIndex);
19111 }
19112 }
19113};
19114
19115},{}],160:[function(_dereq_,module,exports){
19116module.exports = extend
19117
19118var hasOwnProperty = Object.prototype.hasOwnProperty;
19119
19120function extend() {
19121 var target = {}
19122
19123 for (var i = 0; i < arguments.length; i++) {
19124 var source = arguments[i]
19125
19126 for (var key in source) {
19127 if (hasOwnProperty.call(source, key)) {
19128 target[key] = source[key]
19129 }
19130 }
19131 }
19132
19133 return target
19134}
19135
19136},{}],161:[function(_dereq_,module,exports){
19137module.exports = extend
19138
19139var hasOwnProperty = Object.prototype.hasOwnProperty;
19140
19141function extend(target) {
19142 for (var i = 1; i < arguments.length; i++) {
19143 var source = arguments[i]
19144
19145 for (var key in source) {
19146 if (hasOwnProperty.call(source, key)) {
19147 target[key] = source[key]
19148 }
19149 }
19150 }
19151
19152 return target
19153}
19154
19155},{}],162:[function(_dereq_,module,exports){
19156(function (Buffer){(function (){
19157'use strict';
19158
19159function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
19160
19161var levelup = _interopDefault(_dereq_('levelup'));
19162var ltgt = _interopDefault(_dereq_('ltgt'));
19163var Codec = _interopDefault(_dereq_('level-codec'));
19164var ReadableStreamCore = _interopDefault(_dereq_('readable-stream'));
19165var through2 = _dereq_('through2');
19166var Deque = _interopDefault(_dereq_('double-ended-queue'));
19167var Md5 = _interopDefault(_dereq_('spark-md5'));
19168var EE = _interopDefault(_dereq_('events'));
19169var uuid = _dereq_('uuid');
19170var vuvuzela = _interopDefault(_dereq_('vuvuzela'));
19171var memdown = _interopDefault(_dereq_('memdown'));
19172
19173function isFunction(f) {
19174 return 'function' === typeof f;
19175}
19176
19177function getPrefix(db) {
19178 if (isFunction(db.prefix)) {
19179 return db.prefix();
19180 }
19181 return db;
19182}
19183
19184function clone(_obj) {
19185 var obj = {};
19186 for (var k in _obj) {
19187 obj[k] = _obj[k];
19188 }
19189 return obj;
19190}
19191
19192function nut(db, precodec, codec) {
19193 function encodePrefix(prefix, key, opts1, opts2) {
19194 return precodec.encode([ prefix, codec.encodeKey(key, opts1, opts2 ) ]);
19195 }
19196
19197 function addEncodings(op, prefix) {
19198 if (prefix && prefix.options) {
19199 op.keyEncoding =
19200 op.keyEncoding || prefix.options.keyEncoding;
19201 op.valueEncoding =
19202 op.valueEncoding || prefix.options.valueEncoding;
19203 }
19204 return op;
19205 }
19206
19207 db.open(function () { /* no-op */});
19208
19209 return {
19210 apply: function (ops, opts, cb) {
19211 opts = opts || {};
19212
19213 var batch = [];
19214 var i = -1;
19215 var len = ops.length;
19216
19217 while (++i < len) {
19218 var op = ops[i];
19219 addEncodings(op, op.prefix);
19220 op.prefix = getPrefix(op.prefix);
19221 batch.push({
19222 key: encodePrefix(op.prefix, op.key, opts, op),
19223 value: op.type !== 'del' && codec.encodeValue(op.value, opts, op),
19224 type: op.type
19225 });
19226 }
19227 db.db.batch(batch, opts, cb);
19228 },
19229 get: function (key, prefix, opts, cb) {
19230 opts.asBuffer = codec.valueAsBuffer(opts);
19231 return db.db.get(
19232 encodePrefix(prefix, key, opts),
19233 opts,
19234 function (err, value) {
19235 if (err) {
19236 cb(err);
19237 } else {
19238 cb(null, codec.decodeValue(value, opts));
19239 }
19240 }
19241 );
19242 },
19243 createDecoder: function (opts) {
19244 return function (key, value) {
19245 return {
19246 key: codec.decodeKey(precodec.decode(key)[1], opts),
19247 value: codec.decodeValue(value, opts)
19248 };
19249 };
19250 },
19251 isClosed: function isClosed() {
19252 return db.isClosed();
19253 },
19254 close: function close(cb) {
19255 return db.close(cb);
19256 },
19257 iterator: function (_opts) {
19258 var opts = clone(_opts || {});
19259 var prefix = _opts.prefix || [];
19260
19261 function encodeKey(key) {
19262 return encodePrefix(prefix, key, opts, {});
19263 }
19264
19265 ltgt.toLtgt(_opts, opts, encodeKey, precodec.lowerBound, precodec.upperBound);
19266
19267 // if these legacy values are in the options, remove them
19268
19269 opts.prefix = null;
19270
19271 //************************************************
19272 //hard coded defaults, for now...
19273 //TODO: pull defaults and encoding out of levelup.
19274 opts.keyAsBuffer = opts.valueAsBuffer = false;
19275 //************************************************
19276
19277
19278 //this is vital, otherwise limit: undefined will
19279 //create an empty stream.
19280 /* istanbul ignore next */
19281 if ('number' !== typeof opts.limit) {
19282 opts.limit = -1;
19283 }
19284
19285 opts.keyAsBuffer = precodec.buffer;
19286 opts.valueAsBuffer = codec.valueAsBuffer(opts);
19287
19288 function wrapIterator(iterator) {
19289 return {
19290 next: function (cb) {
19291 return iterator.next(cb);
19292 },
19293 end: function (cb) {
19294 iterator.end(cb);
19295 }
19296 };
19297 }
19298
19299 return wrapIterator(db.db.iterator(opts));
19300 }
19301 };
19302}
19303
19304class NotFoundError extends Error {
19305 constructor() {
19306 super();
19307 this.name = 'NotFoundError';
19308 }
19309}
19310
19311var EventEmitter = EE.EventEmitter;
19312var version = "6.5.4";
19313
19314var NOT_FOUND_ERROR = new NotFoundError();
19315
19316var sublevel = function (nut, prefix, createStream, options) {
19317 var emitter = new EventEmitter();
19318 emitter.sublevels = {};
19319 emitter.options = options;
19320
19321 emitter.version = version;
19322
19323 emitter.methods = {};
19324 prefix = prefix || [];
19325
19326 function mergeOpts(opts) {
19327 var o = {};
19328 var k;
19329 if (options) {
19330 for (k in options) {
19331 if (typeof options[k] !== 'undefined') {
19332 o[k] = options[k];
19333 }
19334 }
19335 }
19336 if (opts) {
19337 for (k in opts) {
19338 if (typeof opts[k] !== 'undefined') {
19339 o[k] = opts[k];
19340 }
19341 }
19342 }
19343 return o;
19344 }
19345
19346 emitter.put = function (key, value, opts, cb) {
19347 if ('function' === typeof opts) {
19348 cb = opts;
19349 opts = {};
19350 }
19351
19352 nut.apply([{
19353 key, value,
19354 prefix: prefix.slice(), type: 'put'
19355 }], mergeOpts(opts), function (err) {
19356 /* istanbul ignore next */
19357 if (err) {
19358 return cb(err);
19359 }
19360 emitter.emit('put', key, value);
19361 cb(null);
19362 });
19363 };
19364
19365 emitter.prefix = function () {
19366 return prefix.slice();
19367 };
19368
19369 emitter.batch = function (ops, opts, cb) {
19370 if ('function' === typeof opts) {
19371 cb = opts;
19372 opts = {};
19373 }
19374
19375 ops = ops.map(function (op) {
19376 return {
19377 key: op.key,
19378 value: op.value,
19379 prefix: op.prefix || prefix,
19380 keyEncoding: op.keyEncoding, // *
19381 valueEncoding: op.valueEncoding, // * (TODO: encodings on sublevel)
19382 type: op.type
19383 };
19384 });
19385
19386 nut.apply(ops, mergeOpts(opts), function (err) {
19387 /* istanbul ignore next */
19388 if (err) {
19389 return cb(err);
19390 }
19391 emitter.emit('batch', ops);
19392 cb(null);
19393 });
19394 };
19395
19396 emitter.get = function (key, opts, cb) {
19397 /* istanbul ignore else */
19398 if ('function' === typeof opts) {
19399 cb = opts;
19400 opts = {};
19401 }
19402 nut.get(key, prefix, mergeOpts(opts), function (err, value) {
19403 if (err) {
19404 cb(NOT_FOUND_ERROR);
19405 } else {
19406 cb(null, value);
19407 }
19408 });
19409 };
19410
19411 emitter.sublevel = function (name, opts) {
19412 return emitter.sublevels[name] =
19413 emitter.sublevels[name] || sublevel(nut, prefix.concat(name), createStream, mergeOpts(opts));
19414 };
19415
19416 emitter.readStream = emitter.createReadStream = function (opts) {
19417 opts = mergeOpts(opts);
19418 opts.prefix = prefix;
19419 var stream;
19420 var it = nut.iterator(opts);
19421
19422 stream = createStream(opts, nut.createDecoder(opts));
19423 stream.setIterator(it);
19424
19425 return stream;
19426 };
19427
19428 emitter.close = function (cb) {
19429 nut.close(cb);
19430 };
19431
19432 emitter.isOpen = nut.isOpen;
19433 emitter.isClosed = nut.isClosed;
19434
19435 return emitter;
19436};
19437
19438/* Copyright (c) 2012-2014 LevelUP contributors
19439 * See list at <https://github.com/rvagg/node-levelup#contributing>
19440 * MIT License <https://github.com/rvagg/node-levelup/blob/master/LICENSE.md>
19441 */
19442
19443var Readable = ReadableStreamCore.Readable;
19444
19445function createClass(parent, init) {
19446 let klass = function (...args) {
19447 if (!(this instanceof klass)) {
19448 return new klass(...args);
19449 }
19450 init.apply(this, args);
19451 };
19452 klass.prototype = Object.create(parent.prototype, {
19453 constructor: { value: klass }
19454 });
19455 return klass;
19456}
19457
19458class ReadStreamInternal extends Readable {
19459 constructor(options, makeData) {
19460 super({ objectMode: true, highWaterMark: options.highWaterMark });
19461 this._setup(options, makeData);
19462 }
19463
19464 _setup(options, makeData) {
19465 super.constructor({ objectMode: true, highWaterMark: options.highWaterMark });
19466
19467 // purely to keep `db` around until we're done so it's not GCed if the user doesn't keep a ref
19468 this._waiting = false;
19469 this._options = options;
19470 this._makeData = makeData;
19471 }
19472
19473 setIterator(it) {
19474 this._iterator = it;
19475 /* istanbul ignore if */
19476 if (this._destroyed) {
19477 return it.end(function () {});
19478 }
19479 /* istanbul ignore if */
19480 if (this._waiting) {
19481 this._waiting = false;
19482 return this._read();
19483 }
19484 return this;
19485 }
19486
19487 _cleanup(err) {
19488 if (this._destroyed) {
19489 return;
19490 }
19491
19492 this._destroyed = true;
19493
19494 var self = this;
19495 /* istanbul ignore if */
19496 if (err && err.message !== 'iterator has ended') {
19497 self.emit('error', err);
19498 }
19499
19500 /* istanbul ignore else */
19501 if (self._iterator) {
19502 self._iterator.end(function () {
19503 self._iterator = null;
19504 self.emit('close');
19505 });
19506 } else {
19507 self.emit('close');
19508 }
19509 }
19510
19511 destroy() {
19512 this._cleanup();
19513 }
19514
19515 _read() {
19516 var self = this;
19517 /* istanbul ignore if */
19518 if (self._destroyed) {
19519 return;
19520 }
19521 /* istanbul ignore if */
19522 if (!self._iterator) {
19523 return this._waiting = true;
19524 }
19525
19526 self._iterator.next(function (err, key, value) {
19527 if (err || (key === undefined && value === undefined)) {
19528 if (!err && !self._destroyed) {
19529 self.push(null);
19530 }
19531 return self._cleanup(err);
19532 }
19533
19534
19535 value = self._makeData(key, value);
19536 if (!self._destroyed) {
19537 self.push(value);
19538 }
19539 });
19540 }
19541}
19542
19543const ReadStream = createClass(ReadStreamInternal, function (options, makeData) {
19544 ReadStreamInternal.prototype._setup.call(this, options, makeData);
19545});
19546
19547var precodec = {
19548 encode: function (decodedKey) {
19549 return '\xff' + decodedKey[0] + '\xff' + decodedKey[1];
19550 },
19551 decode: function (encodedKeyAsBuffer) {
19552 var str = encodedKeyAsBuffer.toString();
19553 var idx = str.indexOf('\xff', 1);
19554 return [str.substring(1, idx), str.substring(idx + 1)];
19555 },
19556 lowerBound: '\x00',
19557 upperBound: '\xff'
19558};
19559
19560var codec = new Codec();
19561
19562function sublevelPouch(db) {
19563 return sublevel(nut(db, precodec, codec), [], ReadStream, db.options);
19564}
19565
19566function isBinaryObject(object) {
19567 return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
19568 (typeof Blob !== 'undefined' && object instanceof Blob);
19569}
19570
19571/**
19572 * @template {ArrayBuffer | Blob} T
19573 * @param {T} object
19574 * @returns {T}
19575 */
19576function cloneBinaryObject(object) {
19577 return object instanceof ArrayBuffer
19578 ? object.slice(0)
19579 : object.slice(0, object.size, object.type);
19580}
19581
19582// most of this is borrowed from lodash.isPlainObject:
19583// https://github.com/fis-components/lodash.isplainobject/
19584// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
19585
19586var funcToString = Function.prototype.toString;
19587var objectCtorString = funcToString.call(Object);
19588
19589function isPlainObject(value) {
19590 var proto = Object.getPrototypeOf(value);
19591 /* istanbul ignore if */
19592 if (proto === null) { // not sure when this happens, but I guess it can
19593 return true;
19594 }
19595 var Ctor = proto.constructor;
19596 return (typeof Ctor == 'function' &&
19597 Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
19598}
19599
19600function clone$1(object) {
19601 var newObject;
19602 var i;
19603 var len;
19604
19605 if (!object || typeof object !== 'object') {
19606 return object;
19607 }
19608
19609 if (Array.isArray(object)) {
19610 newObject = [];
19611 for (i = 0, len = object.length; i < len; i++) {
19612 newObject[i] = clone$1(object[i]);
19613 }
19614 return newObject;
19615 }
19616
19617 // special case: to avoid inconsistencies between IndexedDB
19618 // and other backends, we automatically stringify Dates
19619 if (object instanceof Date && isFinite(object)) {
19620 return object.toISOString();
19621 }
19622
19623 if (isBinaryObject(object)) {
19624 return cloneBinaryObject(object);
19625 }
19626
19627 if (!isPlainObject(object)) {
19628 return object; // don't clone objects like Workers
19629 }
19630
19631 newObject = {};
19632 for (i in object) {
19633 /* istanbul ignore else */
19634 if (Object.prototype.hasOwnProperty.call(object, i)) {
19635 var value = clone$1(object[i]);
19636 if (typeof value !== 'undefined') {
19637 newObject[i] = value;
19638 }
19639 }
19640 }
19641 return newObject;
19642}
19643
19644function once(fun) {
19645 var called = false;
19646 return function (...args) {
19647 /* istanbul ignore if */
19648 if (called) {
19649 // this is a smoke test and should never actually happen
19650 throw new Error('once called more than once');
19651 } else {
19652 called = true;
19653 fun.apply(this, args);
19654 }
19655 };
19656}
19657
19658function toPromise(func) {
19659 //create the function we will be returning
19660 return function (...args) {
19661 // Clone arguments
19662 args = clone$1(args);
19663 var self = this;
19664 // if the last argument is a function, assume its a callback
19665 var usedCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;
19666 var promise = new Promise(function (fulfill, reject) {
19667 var resp;
19668 try {
19669 var callback = once(function (err, mesg) {
19670 if (err) {
19671 reject(err);
19672 } else {
19673 fulfill(mesg);
19674 }
19675 });
19676 // create a callback for this invocation
19677 // apply the function in the orig context
19678 args.push(callback);
19679 resp = func.apply(self, args);
19680 if (resp && typeof resp.then === 'function') {
19681 fulfill(resp);
19682 }
19683 } catch (e) {
19684 reject(e);
19685 }
19686 });
19687 // if there is a callback, call it back
19688 if (usedCB) {
19689 promise.then(function (result) {
19690 usedCB(null, result);
19691 }, usedCB);
19692 }
19693 return promise;
19694 };
19695}
19696
19697function logApiCall(self, name, args) {
19698 /* istanbul ignore if */
19699 if (self.constructor.listeners('debug').length) {
19700 var logArgs = ['api', self.name, name];
19701 for (var i = 0; i < args.length - 1; i++) {
19702 logArgs.push(args[i]);
19703 }
19704 self.constructor.emit('debug', logArgs);
19705
19706 // override the callback itself to log the response
19707 var origCallback = args[args.length - 1];
19708 args[args.length - 1] = function (err, res) {
19709 var responseArgs = ['api', self.name, name];
19710 responseArgs = responseArgs.concat(
19711 err ? ['error', err] : ['success', res]
19712 );
19713 self.constructor.emit('debug', responseArgs);
19714 origCallback(err, res);
19715 };
19716 }
19717}
19718
19719function adapterFun(name, callback) {
19720 return toPromise(function (...args) {
19721 if (this._closed) {
19722 return Promise.reject(new Error('database is closed'));
19723 }
19724 if (this._destroyed) {
19725 return Promise.reject(new Error('database is destroyed'));
19726 }
19727 var self = this;
19728 logApiCall(self, name, args);
19729 if (!this.taskqueue.isReady) {
19730 return new Promise(function (fulfill, reject) {
19731 self.taskqueue.addTask(function (failed) {
19732 if (failed) {
19733 reject(failed);
19734 } else {
19735 fulfill(self[name].apply(self, args));
19736 }
19737 });
19738 });
19739 }
19740 return callback.apply(this, args);
19741 });
19742}
19743
19744// like underscore/lodash _.pick()
19745function pick(obj, arr) {
19746 var res = {};
19747 for (var i = 0, len = arr.length; i < len; i++) {
19748 var prop = arr[i];
19749 if (prop in obj) {
19750 res[prop] = obj[prop];
19751 }
19752 }
19753 return res;
19754}
19755
19756// Most browsers throttle concurrent requests at 6, so it's silly
19757// to shim _bulk_get by trying to launch potentially hundreds of requests
19758// and then letting the majority time out. We can handle this ourselves.
19759var MAX_NUM_CONCURRENT_REQUESTS = 6;
19760
19761function identityFunction(x) {
19762 return x;
19763}
19764
19765function formatResultForOpenRevsGet(result) {
19766 return [{
19767 ok: result
19768 }];
19769}
19770
19771// shim for P/CouchDB adapters that don't directly implement _bulk_get
19772function bulkGet(db, opts, callback) {
19773 var requests = opts.docs;
19774
19775 // consolidate into one request per doc if possible
19776 var requestsById = new Map();
19777 requests.forEach(function (request) {
19778 if (requestsById.has(request.id)) {
19779 requestsById.get(request.id).push(request);
19780 } else {
19781 requestsById.set(request.id, [request]);
19782 }
19783 });
19784
19785 var numDocs = requestsById.size;
19786 var numDone = 0;
19787 var perDocResults = new Array(numDocs);
19788
19789 function collapseResultsAndFinish() {
19790 var results = [];
19791 perDocResults.forEach(function (res) {
19792 res.docs.forEach(function (info) {
19793 results.push({
19794 id: res.id,
19795 docs: [info]
19796 });
19797 });
19798 });
19799 callback(null, {results});
19800 }
19801
19802 function checkDone() {
19803 if (++numDone === numDocs) {
19804 collapseResultsAndFinish();
19805 }
19806 }
19807
19808 function gotResult(docIndex, id, docs) {
19809 perDocResults[docIndex] = {id, docs};
19810 checkDone();
19811 }
19812
19813 var allRequests = [];
19814 requestsById.forEach(function (value, key) {
19815 allRequests.push(key);
19816 });
19817
19818 var i = 0;
19819
19820 function nextBatch() {
19821
19822 if (i >= allRequests.length) {
19823 return;
19824 }
19825
19826 var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);
19827 var batch = allRequests.slice(i, upTo);
19828 processBatch(batch, i);
19829 i += batch.length;
19830 }
19831
19832 function processBatch(batch, offset) {
19833 batch.forEach(function (docId, j) {
19834 var docIdx = offset + j;
19835 var docRequests = requestsById.get(docId);
19836
19837 // just use the first request as the "template"
19838 // TODO: The _bulk_get API allows for more subtle use cases than this,
19839 // but for now it is unlikely that there will be a mix of different
19840 // "atts_since" or "attachments" in the same request, since it's just
19841 // replicate.js that is using this for the moment.
19842 // Also, atts_since is aspirational, since we don't support it yet.
19843 var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);
19844 docOpts.open_revs = docRequests.map(function (request) {
19845 // rev is optional, open_revs disallowed
19846 return request.rev;
19847 });
19848
19849 // remove falsey / undefined revisions
19850 docOpts.open_revs = docOpts.open_revs.filter(identityFunction);
19851
19852 var formatResult = identityFunction;
19853
19854 if (docOpts.open_revs.length === 0) {
19855 delete docOpts.open_revs;
19856
19857 // when fetching only the "winning" leaf,
19858 // transform the result so it looks like an open_revs
19859 // request
19860 formatResult = formatResultForOpenRevsGet;
19861 }
19862
19863 // globally-supplied options
19864 ['revs', 'attachments', 'binary', 'ajax', 'latest'].forEach(function (param) {
19865 if (param in opts) {
19866 docOpts[param] = opts[param];
19867 }
19868 });
19869 db.get(docId, docOpts, function (err, res) {
19870 var result;
19871 /* istanbul ignore if */
19872 if (err) {
19873 result = [{error: err}];
19874 } else {
19875 result = formatResult(res);
19876 }
19877 gotResult(docIdx, docId, result);
19878 nextBatch();
19879 });
19880 });
19881 }
19882
19883 nextBatch();
19884
19885}
19886
19887var hasLocal;
19888
19889try {
19890 localStorage.setItem('_pouch_check_localstorage', 1);
19891 hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
19892} catch (e) {
19893 hasLocal = false;
19894}
19895
19896function hasLocalStorage() {
19897 return hasLocal;
19898}
19899
19900const nextTick = typeof queueMicrotask === "function"
19901 ? queueMicrotask
19902 : function nextTick(fn) {
19903 Promise.resolve().then(fn);
19904 };
19905
19906class Changes extends EE {
19907 constructor() {
19908 super();
19909
19910 this._listeners = {};
19911
19912 if (hasLocalStorage()) {
19913 addEventListener("storage", (e) => {
19914 this.emit(e.key);
19915 });
19916 }
19917 }
19918
19919 addListener(dbName, id, db, opts) {
19920 if (this._listeners[id]) {
19921 return;
19922 }
19923 var inprogress = false;
19924 var self = this;
19925 function eventFunction() {
19926 if (!self._listeners[id]) {
19927 return;
19928 }
19929 if (inprogress) {
19930 inprogress = 'waiting';
19931 return;
19932 }
19933 inprogress = true;
19934 var changesOpts = pick(opts, [
19935 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
19936 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'
19937 ]);
19938
19939 function onError() {
19940 inprogress = false;
19941 }
19942
19943 db.changes(changesOpts).on('change', function (c) {
19944 if (c.seq > opts.since && !opts.cancelled) {
19945 opts.since = c.seq;
19946 opts.onChange(c);
19947 }
19948 }).on('complete', function () {
19949 if (inprogress === 'waiting') {
19950 nextTick(eventFunction);
19951 }
19952 inprogress = false;
19953 }).on('error', onError);
19954 }
19955 this._listeners[id] = eventFunction;
19956 this.on(dbName, eventFunction);
19957 }
19958
19959 removeListener(dbName, id) {
19960 if (!(id in this._listeners)) {
19961 return;
19962 }
19963 super.removeListener(dbName, this._listeners[id]);
19964 delete this._listeners[id];
19965 }
19966
19967 notifyLocalWindows(dbName) {
19968 //do a useless change on a storage thing
19969 //in order to get other windows's listeners to activate
19970 if (hasLocalStorage()) {
19971 localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
19972 }
19973 }
19974
19975 notify(dbName) {
19976 this.emit(dbName);
19977 this.notifyLocalWindows(dbName);
19978 }
19979}
19980
19981function guardedConsole(method) {
19982 /* istanbul ignore else */
19983 if (typeof console !== 'undefined' && typeof console[method] === 'function') {
19984 var args = Array.prototype.slice.call(arguments, 1);
19985 console[method].apply(console, args);
19986 }
19987}
19988
19989class PouchError extends Error {
19990 constructor(status, error, reason) {
19991 super();
19992 this.status = status;
19993 this.name = error;
19994 this.message = reason;
19995 this.error = true;
19996 }
19997
19998 toString() {
19999 return JSON.stringify({
20000 status: this.status,
20001 name: this.name,
20002 message: this.message,
20003 reason: this.reason
20004 });
20005 }
20006}
20007
20008var UNAUTHORIZED = new PouchError(401, 'unauthorized', "Name or password is incorrect.");
20009var MISSING_BULK_DOCS = new PouchError(400, 'bad_request', "Missing JSON list of 'docs'");
20010var MISSING_DOC = new PouchError(404, 'not_found', 'missing');
20011var REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');
20012var INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');
20013var MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');
20014var RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');
20015var NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');
20016var UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');
20017var BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');
20018var INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');
20019var QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');
20020var DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');
20021var BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');
20022var NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');
20023var DB_MISSING = new PouchError(404, 'not_found', 'Database not found');
20024var IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');
20025var WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');
20026var LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');
20027var FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');
20028var INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');
20029var FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');
20030var MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\'t found');
20031var INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');
20032
20033function createError(error, reason) {
20034 function CustomPouchError(reason) {
20035 // inherit error properties from our parent error manually
20036 // so as to allow proper JSON parsing.
20037 var names = Object.getOwnPropertyNames(error);
20038 for (var i = 0, len = names.length; i < len; i++) {
20039 if (typeof error[names[i]] !== 'function') {
20040 this[names[i]] = error[names[i]];
20041 }
20042 }
20043
20044 if (this.stack === undefined) {
20045 this.stack = (new Error()).stack;
20046 }
20047
20048 if (reason !== undefined) {
20049 this.reason = reason;
20050 }
20051 }
20052 CustomPouchError.prototype = PouchError.prototype;
20053 return new CustomPouchError(reason);
20054}
20055
20056function generateErrorFromResponse(err) {
20057
20058 if (typeof err !== 'object') {
20059 var data = err;
20060 err = UNKNOWN_ERROR;
20061 err.data = data;
20062 }
20063
20064 if ('error' in err && err.error === 'conflict') {
20065 err.name = 'conflict';
20066 err.status = 409;
20067 }
20068
20069 if (!('name' in err)) {
20070 err.name = err.error || 'unknown';
20071 }
20072
20073 if (!('status' in err)) {
20074 err.status = 500;
20075 }
20076
20077 if (!('message' in err)) {
20078 err.message = err.message || err.reason;
20079 }
20080
20081 if (!('stack' in err)) {
20082 err.stack = (new Error()).stack;
20083 }
20084
20085 return err;
20086}
20087
20088function tryFilter(filter, doc, req) {
20089 try {
20090 return !filter(doc, req);
20091 } catch (err) {
20092 var msg = 'Filter function threw: ' + err.toString();
20093 return createError(BAD_REQUEST, msg);
20094 }
20095}
20096
20097function filterChange(opts) {
20098 var req = {};
20099 var hasFilter = opts.filter && typeof opts.filter === 'function';
20100 req.query = opts.query_params;
20101
20102 return function filter(change) {
20103 if (!change.doc) {
20104 // CSG sends events on the changes feed that don't have documents,
20105 // this hack makes a whole lot of existing code robust.
20106 change.doc = {};
20107 }
20108
20109 var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
20110
20111 if (typeof filterReturn === 'object') {
20112 return filterReturn;
20113 }
20114
20115 if (filterReturn) {
20116 return false;
20117 }
20118
20119 if (!opts.include_docs) {
20120 delete change.doc;
20121 } else if (!opts.attachments) {
20122 for (var att in change.doc._attachments) {
20123 /* istanbul ignore else */
20124 if (Object.prototype.hasOwnProperty.call(change.doc._attachments, att)) {
20125 change.doc._attachments[att].stub = true;
20126 }
20127 }
20128 }
20129 return true;
20130 };
20131}
20132
20133// shim for Function.prototype.name,
20134// for browsers that don't support it like IE
20135
20136/* istanbul ignore next */
20137function f() {}
20138
20139var hasName = f.name;
20140var res;
20141
20142// We don't run coverage in IE
20143/* istanbul ignore else */
20144if (hasName) {
20145 res = function (fun) {
20146 return fun.name;
20147 };
20148} else {
20149 res = function (fun) {
20150 var match = fun.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
20151 if (match && match[1]) {
20152 return match[1];
20153 }
20154 else {
20155 return '';
20156 }
20157 };
20158}
20159
20160var functionName = res;
20161
20162// Determine id an ID is valid
20163// - invalid IDs begin with an underescore that does not begin '_design' or
20164// '_local'
20165// - any other string value is a valid id
20166// Returns the specific error object for each case
20167function invalidIdError(id) {
20168 var err;
20169 if (!id) {
20170 err = createError(MISSING_ID);
20171 } else if (typeof id !== 'string') {
20172 err = createError(INVALID_ID);
20173 } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
20174 err = createError(RESERVED_ID);
20175 }
20176 if (err) {
20177 throw err;
20178 }
20179}
20180
20181// Checks if a PouchDB object is "remote" or not. This is
20182
20183function isRemote(db) {
20184 if (typeof db._remote === 'boolean') {
20185 return db._remote;
20186 }
20187 /* istanbul ignore next */
20188 if (typeof db.type === 'function') {
20189 guardedConsole('warn',
20190 'db.type() is deprecated and will be removed in ' +
20191 'a future version of PouchDB');
20192 return db.type() === 'http';
20193 }
20194 /* istanbul ignore next */
20195 return false;
20196}
20197
20198function listenerCount(ee, type) {
20199 return 'listenerCount' in ee ? ee.listenerCount(type) :
20200 EE.listenerCount(ee, type);
20201}
20202
20203function parseDesignDocFunctionName(s) {
20204 if (!s) {
20205 return null;
20206 }
20207 var parts = s.split('/');
20208 if (parts.length === 2) {
20209 return parts;
20210 }
20211 if (parts.length === 1) {
20212 return [s, s];
20213 }
20214 return null;
20215}
20216
20217function normalizeDesignDocFunctionName(s) {
20218 var normalized = parseDesignDocFunctionName(s);
20219 return normalized ? normalized.join('/') : null;
20220}
20221
20222// originally parseUri 1.2.2, now patched by us
20223
20224// Based on https://github.com/alexdavid/scope-eval v0.0.3
20225// (source: https://unpkg.com/scope-eval@0.0.3/scope_eval.js)
20226// This is basically just a wrapper around new Function()
20227
20228function scopeEval(source, scope) {
20229 var keys = [];
20230 var values = [];
20231 for (var key in scope) {
20232 if (Object.prototype.hasOwnProperty.call(scope, key)) {
20233 keys.push(key);
20234 values.push(scope[key]);
20235 }
20236 }
20237 keys.push(source);
20238 return Function.apply(null, keys).apply(null, values);
20239}
20240
20241// this is essentially the "update sugar" function from daleharvey/pouchdb#1388
20242// the diffFun tells us what delta to apply to the doc. it either returns
20243// the doc, or false if it doesn't need to do an update after all
20244function upsert(db, docId, diffFun) {
20245 return db.get(docId)
20246 .catch(function (err) {
20247 /* istanbul ignore next */
20248 if (err.status !== 404) {
20249 throw err;
20250 }
20251 return {};
20252 })
20253 .then(function (doc) {
20254 // the user might change the _rev, so save it for posterity
20255 var docRev = doc._rev;
20256 var newDoc = diffFun(doc);
20257
20258 if (!newDoc) {
20259 // if the diffFun returns falsy, we short-circuit as
20260 // an optimization
20261 return {updated: false, rev: docRev};
20262 }
20263
20264 // users aren't allowed to modify these values,
20265 // so reset them here
20266 newDoc._id = docId;
20267 newDoc._rev = docRev;
20268 return tryAndPut(db, newDoc, diffFun);
20269 });
20270}
20271
20272function tryAndPut(db, doc, diffFun) {
20273 return db.put(doc).then(function (res) {
20274 return {
20275 updated: true,
20276 rev: res.rev
20277 };
20278 }, function (err) {
20279 /* istanbul ignore next */
20280 if (err.status !== 409) {
20281 throw err;
20282 }
20283 return upsert(db, doc._id, diffFun);
20284 });
20285}
20286
20287var thisAtob = function (str) {
20288 return atob(str);
20289};
20290
20291var thisBtoa = function (str) {
20292 return btoa(str);
20293};
20294
20295// Abstracts constructing a Blob object, so it also works in older
20296// browsers that don't support the native Blob constructor (e.g.
20297// old QtWebKit versions, Android < 4.4).
20298function createBlob(parts, properties) {
20299 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
20300 parts = parts || [];
20301 properties = properties || {};
20302 try {
20303 return new Blob(parts, properties);
20304 } catch (e) {
20305 if (e.name !== "TypeError") {
20306 throw e;
20307 }
20308 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
20309 typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
20310 typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
20311 WebKitBlobBuilder;
20312 var builder = new Builder();
20313 for (var i = 0; i < parts.length; i += 1) {
20314 builder.append(parts[i]);
20315 }
20316 return builder.getBlob(properties.type);
20317 }
20318}
20319
20320// From http://stackoverflow.com/questions/14967647/ (continues on next line)
20321// encode-decode-image-with-base64-breaks-image (2013-04-21)
20322function binaryStringToArrayBuffer(bin) {
20323 var length = bin.length;
20324 var buf = new ArrayBuffer(length);
20325 var arr = new Uint8Array(buf);
20326 for (var i = 0; i < length; i++) {
20327 arr[i] = bin.charCodeAt(i);
20328 }
20329 return buf;
20330}
20331
20332function binStringToBluffer(binString, type) {
20333 return createBlob([binaryStringToArrayBuffer(binString)], {type});
20334}
20335
20336//Can't find original post, but this is close
20337//http://stackoverflow.com/questions/6965107/ (continues on next line)
20338//converting-between-strings-and-arraybuffers
20339function arrayBufferToBinaryString(buffer) {
20340 var binary = '';
20341 var bytes = new Uint8Array(buffer);
20342 var length = bytes.byteLength;
20343 for (var i = 0; i < length; i++) {
20344 binary += String.fromCharCode(bytes[i]);
20345 }
20346 return binary;
20347}
20348
20349// shim for browsers that don't support it
20350function readAsBinaryString(blob, callback) {
20351 var reader = new FileReader();
20352 var hasBinaryString = typeof reader.readAsBinaryString === 'function';
20353 reader.onloadend = function (e) {
20354 var result = e.target.result || '';
20355 if (hasBinaryString) {
20356 return callback(result);
20357 }
20358 callback(arrayBufferToBinaryString(result));
20359 };
20360 if (hasBinaryString) {
20361 reader.readAsBinaryString(blob);
20362 } else {
20363 reader.readAsArrayBuffer(blob);
20364 }
20365}
20366
20367// simplified API. universal browser support is assumed
20368function readAsArrayBuffer(blob, callback) {
20369 var reader = new FileReader();
20370 reader.onloadend = function (e) {
20371 var result = e.target.result || new ArrayBuffer(0);
20372 callback(result);
20373 };
20374 reader.readAsArrayBuffer(blob);
20375}
20376
20377// this is not used in the browser
20378
20379var setImmediateShim = self.setImmediate || self.setTimeout;
20380var MD5_CHUNK_SIZE = 32768;
20381
20382function rawToBase64(raw) {
20383 return thisBtoa(raw);
20384}
20385
20386function appendBlob(buffer, blob, start, end, callback) {
20387 if (start > 0 || end < blob.size) {
20388 // only slice blob if we really need to
20389 blob = blob.slice(start, end);
20390 }
20391 readAsArrayBuffer(blob, function (arrayBuffer) {
20392 buffer.append(arrayBuffer);
20393 callback();
20394 });
20395}
20396
20397function appendString(buffer, string, start, end, callback) {
20398 if (start > 0 || end < string.length) {
20399 // only create a substring if we really need to
20400 string = string.substring(start, end);
20401 }
20402 buffer.appendBinary(string);
20403 callback();
20404}
20405
20406function binaryMd5(data, callback) {
20407 var inputIsString = typeof data === 'string';
20408 var len = inputIsString ? data.length : data.size;
20409 var chunkSize = Math.min(MD5_CHUNK_SIZE, len);
20410 var chunks = Math.ceil(len / chunkSize);
20411 var currentChunk = 0;
20412 var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();
20413
20414 var append = inputIsString ? appendString : appendBlob;
20415
20416 function next() {
20417 setImmediateShim(loadNextChunk);
20418 }
20419
20420 function done() {
20421 var raw = buffer.end(true);
20422 var base64 = rawToBase64(raw);
20423 callback(base64);
20424 buffer.destroy();
20425 }
20426
20427 function loadNextChunk() {
20428 var start = currentChunk * chunkSize;
20429 var end = start + chunkSize;
20430 currentChunk++;
20431 if (currentChunk < chunks) {
20432 append(buffer, data, start, end, next);
20433 } else {
20434 append(buffer, data, start, end, done);
20435 }
20436 }
20437 loadNextChunk();
20438}
20439
20440function stringMd5(string) {
20441 return Md5.hash(string);
20442}
20443
20444/**
20445 * Creates a new revision string that does NOT include the revision height
20446 * For example '56649f1b0506c6ca9fda0746eb0cacdf'
20447 */
20448function rev(doc, deterministic_revs) {
20449 if (!deterministic_revs) {
20450 return uuid.v4().replace(/-/g, '').toLowerCase();
20451 }
20452
20453 var mutateableDoc = Object.assign({}, doc);
20454 delete mutateableDoc._rev_tree;
20455 return stringMd5(JSON.stringify(mutateableDoc));
20456}
20457
20458var uuid$1 = uuid.v4; // mimic old import, only v4 is ever used elsewhere
20459
20460// We fetch all leafs of the revision tree, and sort them based on tree length
20461// and whether they were deleted, undeleted documents with the longest revision
20462// tree (most edits) win
20463// The final sort algorithm is slightly documented in a sidebar here:
20464// http://guide.couchdb.org/draft/conflicts.html
20465function winningRev(metadata) {
20466 var winningId;
20467 var winningPos;
20468 var winningDeleted;
20469 var toVisit = metadata.rev_tree.slice();
20470 var node;
20471 while ((node = toVisit.pop())) {
20472 var tree = node.ids;
20473 var branches = tree[2];
20474 var pos = node.pos;
20475 if (branches.length) { // non-leaf
20476 for (var i = 0, len = branches.length; i < len; i++) {
20477 toVisit.push({pos: pos + 1, ids: branches[i]});
20478 }
20479 continue;
20480 }
20481 var deleted = !!tree[1].deleted;
20482 var id = tree[0];
20483 // sort by deleted, then pos, then id
20484 if (!winningId || (winningDeleted !== deleted ? winningDeleted :
20485 winningPos !== pos ? winningPos < pos : winningId < id)) {
20486 winningId = id;
20487 winningPos = pos;
20488 winningDeleted = deleted;
20489 }
20490 }
20491
20492 return winningPos + '-' + winningId;
20493}
20494
20495// Pretty much all below can be combined into a higher order function to
20496// traverse revisions
20497// The return value from the callback will be passed as context to all
20498// children of that node
20499function traverseRevTree(revs, callback) {
20500 var toVisit = revs.slice();
20501
20502 var node;
20503 while ((node = toVisit.pop())) {
20504 var pos = node.pos;
20505 var tree = node.ids;
20506 var branches = tree[2];
20507 var newCtx =
20508 callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);
20509 for (var i = 0, len = branches.length; i < len; i++) {
20510 toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});
20511 }
20512 }
20513}
20514
20515function sortByPos(a, b) {
20516 return a.pos - b.pos;
20517}
20518
20519function collectLeaves(revs) {
20520 var leaves = [];
20521 traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {
20522 if (isLeaf) {
20523 leaves.push({rev: pos + "-" + id, pos, opts});
20524 }
20525 });
20526 leaves.sort(sortByPos).reverse();
20527 for (var i = 0, len = leaves.length; i < len; i++) {
20528 delete leaves[i].pos;
20529 }
20530 return leaves;
20531}
20532
20533// returns revs of all conflicts that is leaves such that
20534// 1. are not deleted and
20535// 2. are different than winning revision
20536function collectConflicts(metadata) {
20537 var win = winningRev(metadata);
20538 var leaves = collectLeaves(metadata.rev_tree);
20539 var conflicts = [];
20540 for (var i = 0, len = leaves.length; i < len; i++) {
20541 var leaf = leaves[i];
20542 if (leaf.rev !== win && !leaf.opts.deleted) {
20543 conflicts.push(leaf.rev);
20544 }
20545 }
20546 return conflicts;
20547}
20548
20549// compact a tree by marking its non-leafs as missing,
20550// and return a list of revs to delete
20551function compactTree(metadata) {
20552 var revs = [];
20553 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
20554 revHash, ctx, opts) {
20555 if (opts.status === 'available' && !isLeaf) {
20556 revs.push(pos + '-' + revHash);
20557 opts.status = 'missing';
20558 }
20559 });
20560 return revs;
20561}
20562
20563// `findPathToLeaf()` returns an array of revs that goes from the specified
20564// leaf rev to the root of that leaf’s branch.
20565//
20566// eg. for this rev tree:
20567// 1-9692 ▶ 2-37aa ▶ 3-df22 ▶ 4-6e94 ▶ 5-df4a ▶ 6-6a3a ▶ 7-57e5
20568// ┃ ┗━━━━━━▶ 5-8d8c ▶ 6-65e0
20569// ┗━━━━━━▶ 3-43f6 ▶ 4-a3b4
20570//
20571// For a `targetRev` of '7-57e5', `findPathToLeaf()` would return ['7-57e5', '6-6a3a', '5-df4a']
20572// The `revs` argument has the same structure as what `revs_tree` has on e.g.
20573// the IndexedDB representation of the rev tree datastructure. Please refer to
20574// tests/unit/test.purge.js for examples of what these look like.
20575//
20576// This function will throw an error if:
20577// - The requested revision does not exist
20578// - The requested revision is not a leaf
20579function findPathToLeaf(revs, targetRev) {
20580 let path = [];
20581 const toVisit = revs.slice();
20582
20583 let node;
20584 while ((node = toVisit.pop())) {
20585 const { pos, ids: tree } = node;
20586 const rev = `${pos}-${tree[0]}`;
20587 const branches = tree[2];
20588
20589 // just assuming we're already working on the path up towards our desired leaf.
20590 path.push(rev);
20591
20592 // we've reached the leaf of our dreams, so return the computed path.
20593 if (rev === targetRev) {
20594 //…unleeeeess
20595 if (branches.length !== 0) {
20596 throw new Error('The requested revision is not a leaf');
20597 }
20598 return path.reverse();
20599 }
20600
20601 // this is based on the assumption that after we have a leaf (`branches.length == 0`), we handle the next
20602 // branch. this is true for all branches other than the path leading to the winning rev (which is 7-57e5 in
20603 // the example above. i've added a reset condition for branching nodes (`branches.length > 1`) as well.
20604 if (branches.length === 0 || branches.length > 1) {
20605 path = [];
20606 }
20607
20608 // as a next step, we push the branches of this node to `toVisit` for visiting it during the next iteration
20609 for (let i = 0, len = branches.length; i < len; i++) {
20610 toVisit.push({ pos: pos + 1, ids: branches[i] });
20611 }
20612 }
20613 if (path.length === 0) {
20614 throw new Error('The requested revision does not exist');
20615 }
20616 return path.reverse();
20617}
20618
20619// build up a list of all the paths to the leafs in this revision tree
20620function rootToLeaf(revs) {
20621 var paths = [];
20622 var toVisit = revs.slice();
20623 var node;
20624 while ((node = toVisit.pop())) {
20625 var pos = node.pos;
20626 var tree = node.ids;
20627 var id = tree[0];
20628 var opts = tree[1];
20629 var branches = tree[2];
20630 var isLeaf = branches.length === 0;
20631
20632 var history = node.history ? node.history.slice() : [];
20633 history.push({id, opts});
20634 if (isLeaf) {
20635 paths.push({pos: (pos + 1 - history.length), ids: history});
20636 }
20637 for (var i = 0, len = branches.length; i < len; i++) {
20638 toVisit.push({pos: pos + 1, ids: branches[i], history});
20639 }
20640 }
20641 return paths.reverse();
20642}
20643
20644// for a better overview of what this is doing, read:
20645
20646function sortByPos$1(a, b) {
20647 return a.pos - b.pos;
20648}
20649
20650// classic binary search
20651function binarySearch(arr, item, comparator) {
20652 var low = 0;
20653 var high = arr.length;
20654 var mid;
20655 while (low < high) {
20656 mid = (low + high) >>> 1;
20657 if (comparator(arr[mid], item) < 0) {
20658 low = mid + 1;
20659 } else {
20660 high = mid;
20661 }
20662 }
20663 return low;
20664}
20665
20666// assuming the arr is sorted, insert the item in the proper place
20667function insertSorted(arr, item, comparator) {
20668 var idx = binarySearch(arr, item, comparator);
20669 arr.splice(idx, 0, item);
20670}
20671
20672// Turn a path as a flat array into a tree with a single branch.
20673// If any should be stemmed from the beginning of the array, that's passed
20674// in as the second argument
20675function pathToTree(path, numStemmed) {
20676 var root;
20677 var leaf;
20678 for (var i = numStemmed, len = path.length; i < len; i++) {
20679 var node = path[i];
20680 var currentLeaf = [node.id, node.opts, []];
20681 if (leaf) {
20682 leaf[2].push(currentLeaf);
20683 leaf = currentLeaf;
20684 } else {
20685 root = leaf = currentLeaf;
20686 }
20687 }
20688 return root;
20689}
20690
20691// compare the IDs of two trees
20692function compareTree(a, b) {
20693 return a[0] < b[0] ? -1 : 1;
20694}
20695
20696// Merge two trees together
20697// The roots of tree1 and tree2 must be the same revision
20698function mergeTree(in_tree1, in_tree2) {
20699 var queue = [{tree1: in_tree1, tree2: in_tree2}];
20700 var conflicts = false;
20701 while (queue.length > 0) {
20702 var item = queue.pop();
20703 var tree1 = item.tree1;
20704 var tree2 = item.tree2;
20705
20706 if (tree1[1].status || tree2[1].status) {
20707 tree1[1].status =
20708 (tree1[1].status === 'available' ||
20709 tree2[1].status === 'available') ? 'available' : 'missing';
20710 }
20711
20712 for (var i = 0; i < tree2[2].length; i++) {
20713 if (!tree1[2][0]) {
20714 conflicts = 'new_leaf';
20715 tree1[2][0] = tree2[2][i];
20716 continue;
20717 }
20718
20719 var merged = false;
20720 for (var j = 0; j < tree1[2].length; j++) {
20721 if (tree1[2][j][0] === tree2[2][i][0]) {
20722 queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
20723 merged = true;
20724 }
20725 }
20726 if (!merged) {
20727 conflicts = 'new_branch';
20728 insertSorted(tree1[2], tree2[2][i], compareTree);
20729 }
20730 }
20731 }
20732 return {conflicts, tree: in_tree1};
20733}
20734
20735function doMerge(tree, path, dontExpand) {
20736 var restree = [];
20737 var conflicts = false;
20738 var merged = false;
20739 var res;
20740
20741 if (!tree.length) {
20742 return {tree: [path], conflicts: 'new_leaf'};
20743 }
20744
20745 for (var i = 0, len = tree.length; i < len; i++) {
20746 var branch = tree[i];
20747 if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {
20748 // Paths start at the same position and have the same root, so they need
20749 // merged
20750 res = mergeTree(branch.ids, path.ids);
20751 restree.push({pos: branch.pos, ids: res.tree});
20752 conflicts = conflicts || res.conflicts;
20753 merged = true;
20754 } else if (dontExpand !== true) {
20755 // The paths start at a different position, take the earliest path and
20756 // traverse up until it as at the same point from root as the path we
20757 // want to merge. If the keys match we return the longer path with the
20758 // other merged After stemming we don't want to expand the trees
20759
20760 var t1 = branch.pos < path.pos ? branch : path;
20761 var t2 = branch.pos < path.pos ? path : branch;
20762 var diff = t2.pos - t1.pos;
20763
20764 var candidateParents = [];
20765
20766 var trees = [];
20767 trees.push({ids: t1.ids, diff, parent: null, parentIdx: null});
20768 while (trees.length > 0) {
20769 var item = trees.pop();
20770 if (item.diff === 0) {
20771 if (item.ids[0] === t2.ids[0]) {
20772 candidateParents.push(item);
20773 }
20774 continue;
20775 }
20776 var elements = item.ids[2];
20777 for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {
20778 trees.push({
20779 ids: elements[j],
20780 diff: item.diff - 1,
20781 parent: item.ids,
20782 parentIdx: j
20783 });
20784 }
20785 }
20786
20787 var el = candidateParents[0];
20788
20789 if (!el) {
20790 restree.push(branch);
20791 } else {
20792 res = mergeTree(el.ids, t2.ids);
20793 el.parent[2][el.parentIdx] = res.tree;
20794 restree.push({pos: t1.pos, ids: t1.ids});
20795 conflicts = conflicts || res.conflicts;
20796 merged = true;
20797 }
20798 } else {
20799 restree.push(branch);
20800 }
20801 }
20802
20803 // We didnt find
20804 if (!merged) {
20805 restree.push(path);
20806 }
20807
20808 restree.sort(sortByPos$1);
20809
20810 return {
20811 tree: restree,
20812 conflicts: conflicts || 'internal_node'
20813 };
20814}
20815
20816// To ensure we don't grow the revision tree infinitely, we stem old revisions
20817function stem(tree, depth) {
20818 // First we break out the tree into a complete list of root to leaf paths
20819 var paths = rootToLeaf(tree);
20820 var stemmedRevs;
20821
20822 var result;
20823 for (var i = 0, len = paths.length; i < len; i++) {
20824 // Then for each path, we cut off the start of the path based on the
20825 // `depth` to stem to, and generate a new set of flat trees
20826 var path = paths[i];
20827 var stemmed = path.ids;
20828 var node;
20829 if (stemmed.length > depth) {
20830 // only do the stemming work if we actually need to stem
20831 if (!stemmedRevs) {
20832 stemmedRevs = {}; // avoid allocating this object unnecessarily
20833 }
20834 var numStemmed = stemmed.length - depth;
20835 node = {
20836 pos: path.pos + numStemmed,
20837 ids: pathToTree(stemmed, numStemmed)
20838 };
20839
20840 for (var s = 0; s < numStemmed; s++) {
20841 var rev = (path.pos + s) + '-' + stemmed[s].id;
20842 stemmedRevs[rev] = true;
20843 }
20844 } else { // no need to actually stem
20845 node = {
20846 pos: path.pos,
20847 ids: pathToTree(stemmed, 0)
20848 };
20849 }
20850
20851 // Then we remerge all those flat trees together, ensuring that we don't
20852 // connect trees that would go beyond the depth limit
20853 if (result) {
20854 result = doMerge(result, node, true).tree;
20855 } else {
20856 result = [node];
20857 }
20858 }
20859
20860 // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
20861 if (stemmedRevs) {
20862 traverseRevTree(result, function (isLeaf, pos, revHash) {
20863 // some revisions may have been removed in a branch but not in another
20864 delete stemmedRevs[pos + '-' + revHash];
20865 });
20866 }
20867
20868 return {
20869 tree: result,
20870 revs: stemmedRevs ? Object.keys(stemmedRevs) : []
20871 };
20872}
20873
20874function merge(tree, path, depth) {
20875 var newTree = doMerge(tree, path);
20876 var stemmed = stem(newTree.tree, depth);
20877 return {
20878 tree: stemmed.tree,
20879 stemmedRevs: stemmed.revs,
20880 conflicts: newTree.conflicts
20881 };
20882}
20883
20884// return true if a rev exists in the rev tree, false otherwise
20885function revExists(revs, rev) {
20886 var toVisit = revs.slice();
20887 var splitRev = rev.split('-');
20888 var targetPos = parseInt(splitRev[0], 10);
20889 var targetId = splitRev[1];
20890
20891 var node;
20892 while ((node = toVisit.pop())) {
20893 if (node.pos === targetPos && node.ids[0] === targetId) {
20894 return true;
20895 }
20896 var branches = node.ids[2];
20897 for (var i = 0, len = branches.length; i < len; i++) {
20898 toVisit.push({pos: node.pos + 1, ids: branches[i]});
20899 }
20900 }
20901 return false;
20902}
20903
20904function getTrees(node) {
20905 return node.ids;
20906}
20907
20908// check if a specific revision of a doc has been deleted
20909// - metadata: the metadata object from the doc store
20910// - rev: (optional) the revision to check. defaults to winning revision
20911function isDeleted(metadata, rev) {
20912 if (!rev) {
20913 rev = winningRev(metadata);
20914 }
20915 var id = rev.substring(rev.indexOf('-') + 1);
20916 var toVisit = metadata.rev_tree.map(getTrees);
20917
20918 var tree;
20919 while ((tree = toVisit.pop())) {
20920 if (tree[0] === id) {
20921 return !!tree[1].deleted;
20922 }
20923 toVisit = toVisit.concat(tree[2]);
20924 }
20925}
20926
20927function isLocalId(id) {
20928 return typeof id === 'string' && id.startsWith('_local/');
20929}
20930
20931// returns the current leaf node for a given revision
20932function latest(rev, metadata) {
20933 var toVisit = metadata.rev_tree.slice();
20934 var node;
20935 while ((node = toVisit.pop())) {
20936 var pos = node.pos;
20937 var tree = node.ids;
20938 var id = tree[0];
20939 var opts = tree[1];
20940 var branches = tree[2];
20941 var isLeaf = branches.length === 0;
20942
20943 var history = node.history ? node.history.slice() : [];
20944 history.push({id, pos, opts});
20945
20946 if (isLeaf) {
20947 for (var i = 0, len = history.length; i < len; i++) {
20948 var historyNode = history[i];
20949 var historyRev = historyNode.pos + '-' + historyNode.id;
20950
20951 if (historyRev === rev) {
20952 // return the rev of this leaf
20953 return pos + '-' + id;
20954 }
20955 }
20956 }
20957
20958 for (var j = 0, l = branches.length; j < l; j++) {
20959 toVisit.push({pos: pos + 1, ids: branches[j], history});
20960 }
20961 }
20962
20963 /* istanbul ignore next */
20964 throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);
20965}
20966
20967function tryCatchInChangeListener(self, change, pending, lastSeq) {
20968 // isolate try/catches to avoid V8 deoptimizations
20969 try {
20970 self.emit('change', change, pending, lastSeq);
20971 } catch (e) {
20972 guardedConsole('error', 'Error in .on("change", function):', e);
20973 }
20974}
20975
20976function processChange(doc, metadata, opts) {
20977 var changeList = [{rev: doc._rev}];
20978 if (opts.style === 'all_docs') {
20979 changeList = collectLeaves(metadata.rev_tree)
20980 .map(function (x) { return {rev: x.rev}; });
20981 }
20982 var change = {
20983 id: metadata.id,
20984 changes: changeList,
20985 doc
20986 };
20987
20988 if (isDeleted(metadata, doc._rev)) {
20989 change.deleted = true;
20990 }
20991 if (opts.conflicts) {
20992 change.doc._conflicts = collectConflicts(metadata);
20993 if (!change.doc._conflicts.length) {
20994 delete change.doc._conflicts;
20995 }
20996 }
20997 return change;
20998}
20999
21000class Changes$1 extends EE {
21001 constructor(db, opts, callback) {
21002 super();
21003 this.db = db;
21004 opts = opts ? clone$1(opts) : {};
21005 var complete = opts.complete = once((err, resp) => {
21006 if (err) {
21007 if (listenerCount(this, 'error') > 0) {
21008 this.emit('error', err);
21009 }
21010 } else {
21011 this.emit('complete', resp);
21012 }
21013 this.removeAllListeners();
21014 db.removeListener('destroyed', onDestroy);
21015 });
21016 if (callback) {
21017 this.on('complete', function (resp) {
21018 callback(null, resp);
21019 });
21020 this.on('error', callback);
21021 }
21022 const onDestroy = () => {
21023 this.cancel();
21024 };
21025 db.once('destroyed', onDestroy);
21026
21027 opts.onChange = (change, pending, lastSeq) => {
21028 /* istanbul ignore if */
21029 if (this.isCancelled) {
21030 return;
21031 }
21032 tryCatchInChangeListener(this, change, pending, lastSeq);
21033 };
21034
21035 var promise = new Promise(function (fulfill, reject) {
21036 opts.complete = function (err, res) {
21037 if (err) {
21038 reject(err);
21039 } else {
21040 fulfill(res);
21041 }
21042 };
21043 });
21044 this.once('cancel', function () {
21045 db.removeListener('destroyed', onDestroy);
21046 opts.complete(null, {status: 'cancelled'});
21047 });
21048 this.then = promise.then.bind(promise);
21049 this['catch'] = promise['catch'].bind(promise);
21050 this.then(function (result) {
21051 complete(null, result);
21052 }, complete);
21053
21054
21055
21056 if (!db.taskqueue.isReady) {
21057 db.taskqueue.addTask((failed) => {
21058 if (failed) {
21059 opts.complete(failed);
21060 } else if (this.isCancelled) {
21061 this.emit('cancel');
21062 } else {
21063 this.validateChanges(opts);
21064 }
21065 });
21066 } else {
21067 this.validateChanges(opts);
21068 }
21069 }
21070
21071 cancel() {
21072 this.isCancelled = true;
21073 if (this.db.taskqueue.isReady) {
21074 this.emit('cancel');
21075 }
21076 }
21077
21078 validateChanges(opts) {
21079 var callback = opts.complete;
21080
21081 /* istanbul ignore else */
21082 if (PouchDB$1._changesFilterPlugin) {
21083 PouchDB$1._changesFilterPlugin.validate(opts, (err) => {
21084 if (err) {
21085 return callback(err);
21086 }
21087 this.doChanges(opts);
21088 });
21089 } else {
21090 this.doChanges(opts);
21091 }
21092 }
21093
21094 doChanges(opts) {
21095 var callback = opts.complete;
21096
21097 opts = clone$1(opts);
21098 if ('live' in opts && !('continuous' in opts)) {
21099 opts.continuous = opts.live;
21100 }
21101 opts.processChange = processChange;
21102
21103 if (opts.since === 'latest') {
21104 opts.since = 'now';
21105 }
21106 if (!opts.since) {
21107 opts.since = 0;
21108 }
21109 if (opts.since === 'now') {
21110 this.db.info().then((info) => {
21111 /* istanbul ignore if */
21112 if (this.isCancelled) {
21113 callback(null, {status: 'cancelled'});
21114 return;
21115 }
21116 opts.since = info.update_seq;
21117 this.doChanges(opts);
21118 }, callback);
21119 return;
21120 }
21121
21122 /* istanbul ignore else */
21123 if (PouchDB$1._changesFilterPlugin) {
21124 PouchDB$1._changesFilterPlugin.normalize(opts);
21125 if (PouchDB$1._changesFilterPlugin.shouldFilter(this, opts)) {
21126 return PouchDB$1._changesFilterPlugin.filter(this, opts);
21127 }
21128 } else {
21129 ['doc_ids', 'filter', 'selector', 'view'].forEach(function (key) {
21130 if (key in opts) {
21131 guardedConsole('warn',
21132 'The "' + key + '" option was passed in to changes/replicate, ' +
21133 'but pouchdb-changes-filter plugin is not installed, so it ' +
21134 'was ignored. Please install the plugin to enable filtering.'
21135 );
21136 }
21137 });
21138 }
21139
21140 if (!('descending' in opts)) {
21141 opts.descending = false;
21142 }
21143
21144 // 0 and 1 should return 1 document
21145 opts.limit = opts.limit === 0 ? 1 : opts.limit;
21146 opts.complete = callback;
21147 var newPromise = this.db._changes(opts);
21148 /* istanbul ignore else */
21149 if (newPromise && typeof newPromise.cancel === 'function') {
21150 const cancel = this.cancel;
21151 this.cancel = (...args) => {
21152 newPromise.cancel();
21153 cancel.apply(this, args);
21154 };
21155 }
21156 }
21157}
21158
21159/*
21160 * A generic pouch adapter
21161 */
21162
21163// Wrapper for functions that call the bulkdocs api with a single doc,
21164// if the first result is an error, return an error
21165function yankError(callback, docId) {
21166 return function (err, results) {
21167 if (err || (results[0] && results[0].error)) {
21168 err = err || results[0];
21169 err.docId = docId;
21170 callback(err);
21171 } else {
21172 callback(null, results.length ? results[0] : results);
21173 }
21174 };
21175}
21176
21177// clean docs given to us by the user
21178function cleanDocs(docs) {
21179 for (var i = 0; i < docs.length; i++) {
21180 var doc = docs[i];
21181 if (doc._deleted) {
21182 delete doc._attachments; // ignore atts for deleted docs
21183 } else if (doc._attachments) {
21184 // filter out extraneous keys from _attachments
21185 var atts = Object.keys(doc._attachments);
21186 for (var j = 0; j < atts.length; j++) {
21187 var att = atts[j];
21188 doc._attachments[att] = pick(doc._attachments[att],
21189 ['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);
21190 }
21191 }
21192 }
21193}
21194
21195// compare two docs, first by _id then by _rev
21196function compareByIdThenRev(a, b) {
21197 if (a._id === b._id) {
21198 const aStart = a._revisions ? a._revisions.start : 0;
21199 const bStart = b._revisions ? b._revisions.start : 0;
21200 return aStart - bStart;
21201 }
21202 return a._id < b._id ? -1 : 1;
21203}
21204
21205// for every node in a revision tree computes its distance from the closest
21206// leaf
21207function computeHeight(revs) {
21208 var height = {};
21209 var edges = [];
21210 traverseRevTree(revs, function (isLeaf, pos, id, prnt) {
21211 var rev$$1 = pos + "-" + id;
21212 if (isLeaf) {
21213 height[rev$$1] = 0;
21214 }
21215 if (prnt !== undefined) {
21216 edges.push({from: prnt, to: rev$$1});
21217 }
21218 return rev$$1;
21219 });
21220
21221 edges.reverse();
21222 edges.forEach(function (edge) {
21223 if (height[edge.from] === undefined) {
21224 height[edge.from] = 1 + height[edge.to];
21225 } else {
21226 height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);
21227 }
21228 });
21229 return height;
21230}
21231
21232function allDocsKeysParse(opts) {
21233 var keys = ('limit' in opts) ?
21234 opts.keys.slice(opts.skip, opts.limit + opts.skip) :
21235 (opts.skip > 0) ? opts.keys.slice(opts.skip) : opts.keys;
21236 opts.keys = keys;
21237 opts.skip = 0;
21238 delete opts.limit;
21239 if (opts.descending) {
21240 keys.reverse();
21241 opts.descending = false;
21242 }
21243}
21244
21245// all compaction is done in a queue, to avoid attaching
21246// too many listeners at once
21247function doNextCompaction(self) {
21248 var task = self._compactionQueue[0];
21249 var opts = task.opts;
21250 var callback = task.callback;
21251 self.get('_local/compaction').catch(function () {
21252 return false;
21253 }).then(function (doc) {
21254 if (doc && doc.last_seq) {
21255 opts.last_seq = doc.last_seq;
21256 }
21257 self._compact(opts, function (err, res) {
21258 /* istanbul ignore if */
21259 if (err) {
21260 callback(err);
21261 } else {
21262 callback(null, res);
21263 }
21264 nextTick(function () {
21265 self._compactionQueue.shift();
21266 if (self._compactionQueue.length) {
21267 doNextCompaction(self);
21268 }
21269 });
21270 });
21271 });
21272}
21273
21274function appendPurgeSeq(db, docId, rev$$1) {
21275 return db.get('_local/purges').then(function (doc) {
21276 const purgeSeq = doc.purgeSeq + 1;
21277 doc.purges.push({
21278 docId,
21279 rev: rev$$1,
21280 purgeSeq,
21281 });
21282 if (doc.purges.length > self.purged_infos_limit) {
21283 doc.purges.splice(0, doc.purges.length - self.purged_infos_limit);
21284 }
21285 doc.purgeSeq = purgeSeq;
21286 return doc;
21287 }).catch(function (err) {
21288 if (err.status !== 404) {
21289 throw err;
21290 }
21291 return {
21292 _id: '_local/purges',
21293 purges: [{
21294 docId,
21295 rev: rev$$1,
21296 purgeSeq: 0,
21297 }],
21298 purgeSeq: 0,
21299 };
21300 }).then(function (doc) {
21301 return db.put(doc);
21302 });
21303}
21304
21305function attachmentNameError(name) {
21306 if (name.charAt(0) === '_') {
21307 return name + ' is not a valid attachment name, attachment ' +
21308 'names cannot start with \'_\'';
21309 }
21310 return false;
21311}
21312
21313function isNotSingleDoc(doc) {
21314 return doc === null || typeof doc !== 'object' || Array.isArray(doc);
21315}
21316
21317const validRevRegex = /^\d+-[^-]*$/;
21318function isValidRev(rev$$1) {
21319 return typeof rev$$1 === 'string' && validRevRegex.test(rev$$1);
21320}
21321
21322class AbstractPouchDB extends EE {
21323 _setup() {
21324 this.post = adapterFun('post', function (doc, opts, callback) {
21325 if (typeof opts === 'function') {
21326 callback = opts;
21327 opts = {};
21328 }
21329 if (isNotSingleDoc(doc)) {
21330 return callback(createError(NOT_AN_OBJECT));
21331 }
21332 this.bulkDocs({docs: [doc]}, opts, yankError(callback, doc._id));
21333 }).bind(this);
21334
21335 this.put = adapterFun('put', function (doc, opts, cb) {
21336 if (typeof opts === 'function') {
21337 cb = opts;
21338 opts = {};
21339 }
21340 if (isNotSingleDoc(doc)) {
21341 return cb(createError(NOT_AN_OBJECT));
21342 }
21343 invalidIdError(doc._id);
21344 if ('_rev' in doc && !isValidRev(doc._rev)) {
21345 return cb(createError(INVALID_REV));
21346 }
21347 if (isLocalId(doc._id) && typeof this._putLocal === 'function') {
21348 if (doc._deleted) {
21349 return this._removeLocal(doc, cb);
21350 } else {
21351 return this._putLocal(doc, cb);
21352 }
21353 }
21354
21355 const putDoc = (next) => {
21356 if (typeof this._put === 'function' && opts.new_edits !== false) {
21357 this._put(doc, opts, next);
21358 } else {
21359 this.bulkDocs({docs: [doc]}, opts, yankError(next, doc._id));
21360 }
21361 };
21362
21363 if (opts.force && doc._rev) {
21364 transformForceOptionToNewEditsOption();
21365 putDoc(function (err) {
21366 var result = err ? null : {ok: true, id: doc._id, rev: doc._rev};
21367 cb(err, result);
21368 });
21369 } else {
21370 putDoc(cb);
21371 }
21372
21373 function transformForceOptionToNewEditsOption() {
21374 var parts = doc._rev.split('-');
21375 var oldRevId = parts[1];
21376 var oldRevNum = parseInt(parts[0], 10);
21377
21378 var newRevNum = oldRevNum + 1;
21379 var newRevId = rev();
21380
21381 doc._revisions = {
21382 start: newRevNum,
21383 ids: [newRevId, oldRevId]
21384 };
21385 doc._rev = newRevNum + '-' + newRevId;
21386 opts.new_edits = false;
21387 }
21388 }).bind(this);
21389
21390 this.putAttachment = adapterFun('putAttachment', function (docId, attachmentId, rev$$1, blob, type) {
21391 var api = this;
21392 if (typeof type === 'function') {
21393 type = blob;
21394 blob = rev$$1;
21395 rev$$1 = null;
21396 }
21397 // Lets fix in https://github.com/pouchdb/pouchdb/issues/3267
21398 /* istanbul ignore if */
21399 if (typeof type === 'undefined') {
21400 type = blob;
21401 blob = rev$$1;
21402 rev$$1 = null;
21403 }
21404 if (!type) {
21405 guardedConsole('warn', 'Attachment', attachmentId, 'on document', docId, 'is missing content_type');
21406 }
21407
21408 function createAttachment(doc) {
21409 var prevrevpos = '_rev' in doc ? parseInt(doc._rev, 10) : 0;
21410 doc._attachments = doc._attachments || {};
21411 doc._attachments[attachmentId] = {
21412 content_type: type,
21413 data: blob,
21414 revpos: ++prevrevpos
21415 };
21416 return api.put(doc);
21417 }
21418
21419 return api.get(docId).then(function (doc) {
21420 if (doc._rev !== rev$$1) {
21421 throw createError(REV_CONFLICT);
21422 }
21423
21424 return createAttachment(doc);
21425 }, function (err) {
21426 // create new doc
21427 /* istanbul ignore else */
21428 if (err.reason === MISSING_DOC.message) {
21429 return createAttachment({_id: docId});
21430 } else {
21431 throw err;
21432 }
21433 });
21434 }).bind(this);
21435
21436 this.removeAttachment = adapterFun('removeAttachment', function (docId, attachmentId, rev$$1, callback) {
21437 this.get(docId, (err, obj) => {
21438 /* istanbul ignore if */
21439 if (err) {
21440 callback(err);
21441 return;
21442 }
21443 if (obj._rev !== rev$$1) {
21444 callback(createError(REV_CONFLICT));
21445 return;
21446 }
21447 /* istanbul ignore if */
21448 if (!obj._attachments) {
21449 return callback();
21450 }
21451 delete obj._attachments[attachmentId];
21452 if (Object.keys(obj._attachments).length === 0) {
21453 delete obj._attachments;
21454 }
21455 this.put(obj, callback);
21456 });
21457 }).bind(this);
21458
21459 this.remove = adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {
21460 var doc;
21461 if (typeof optsOrRev === 'string') {
21462 // id, rev, opts, callback style
21463 doc = {
21464 _id: docOrId,
21465 _rev: optsOrRev
21466 };
21467 if (typeof opts === 'function') {
21468 callback = opts;
21469 opts = {};
21470 }
21471 } else {
21472 // doc, opts, callback style
21473 doc = docOrId;
21474 if (typeof optsOrRev === 'function') {
21475 callback = optsOrRev;
21476 opts = {};
21477 } else {
21478 callback = opts;
21479 opts = optsOrRev;
21480 }
21481 }
21482 opts = opts || {};
21483 opts.was_delete = true;
21484 var newDoc = {_id: doc._id, _rev: (doc._rev || opts.rev)};
21485 newDoc._deleted = true;
21486 if (isLocalId(newDoc._id) && typeof this._removeLocal === 'function') {
21487 return this._removeLocal(doc, callback);
21488 }
21489 this.bulkDocs({docs: [newDoc]}, opts, yankError(callback, newDoc._id));
21490 }).bind(this);
21491
21492 this.revsDiff = adapterFun('revsDiff', function (req, opts, callback) {
21493 if (typeof opts === 'function') {
21494 callback = opts;
21495 opts = {};
21496 }
21497 var ids = Object.keys(req);
21498
21499 if (!ids.length) {
21500 return callback(null, {});
21501 }
21502
21503 var count = 0;
21504 var missing = new Map();
21505
21506 function addToMissing(id, revId) {
21507 if (!missing.has(id)) {
21508 missing.set(id, {missing: []});
21509 }
21510 missing.get(id).missing.push(revId);
21511 }
21512
21513 function processDoc(id, rev_tree) {
21514 // Is this fast enough? Maybe we should switch to a set simulated by a map
21515 var missingForId = req[id].slice(0);
21516 traverseRevTree(rev_tree, function (isLeaf, pos, revHash, ctx,
21517 opts) {
21518 var rev$$1 = pos + '-' + revHash;
21519 var idx = missingForId.indexOf(rev$$1);
21520 if (idx === -1) {
21521 return;
21522 }
21523
21524 missingForId.splice(idx, 1);
21525 /* istanbul ignore if */
21526 if (opts.status !== 'available') {
21527 addToMissing(id, rev$$1);
21528 }
21529 });
21530
21531 // Traversing the tree is synchronous, so now `missingForId` contains
21532 // revisions that were not found in the tree
21533 missingForId.forEach(function (rev$$1) {
21534 addToMissing(id, rev$$1);
21535 });
21536 }
21537
21538 ids.forEach(function (id) {
21539 this._getRevisionTree(id, function (err, rev_tree) {
21540 if (err && err.status === 404 && err.message === 'missing') {
21541 missing.set(id, {missing: req[id]});
21542 } else if (err) {
21543 /* istanbul ignore next */
21544 return callback(err);
21545 } else {
21546 processDoc(id, rev_tree);
21547 }
21548
21549 if (++count === ids.length) {
21550 // convert LazyMap to object
21551 var missingObj = {};
21552 missing.forEach(function (value, key) {
21553 missingObj[key] = value;
21554 });
21555 return callback(null, missingObj);
21556 }
21557 });
21558 }, this);
21559 }).bind(this);
21560
21561 // _bulk_get API for faster replication, as described in
21562 // https://github.com/apache/couchdb-chttpd/pull/33
21563 // At the "abstract" level, it will just run multiple get()s in
21564 // parallel, because this isn't much of a performance cost
21565 // for local databases (except the cost of multiple transactions, which is
21566 // small). The http adapter overrides this in order
21567 // to do a more efficient single HTTP request.
21568 this.bulkGet = adapterFun('bulkGet', function (opts, callback) {
21569 bulkGet(this, opts, callback);
21570 }).bind(this);
21571
21572 // compact one document and fire callback
21573 // by compacting we mean removing all revisions which
21574 // are further from the leaf in revision tree than max_height
21575 this.compactDocument = adapterFun('compactDocument', function (docId, maxHeight, callback) {
21576 this._getRevisionTree(docId, (err, revTree) => {
21577 /* istanbul ignore if */
21578 if (err) {
21579 return callback(err);
21580 }
21581 var height = computeHeight(revTree);
21582 var candidates = [];
21583 var revs = [];
21584 Object.keys(height).forEach(function (rev$$1) {
21585 if (height[rev$$1] > maxHeight) {
21586 candidates.push(rev$$1);
21587 }
21588 });
21589
21590 traverseRevTree(revTree, function (isLeaf, pos, revHash, ctx, opts) {
21591 var rev$$1 = pos + '-' + revHash;
21592 if (opts.status === 'available' && candidates.indexOf(rev$$1) !== -1) {
21593 revs.push(rev$$1);
21594 }
21595 });
21596 this._doCompaction(docId, revs, callback);
21597 });
21598 }).bind(this);
21599
21600 // compact the whole database using single document
21601 // compaction
21602 this.compact = adapterFun('compact', function (opts, callback) {
21603 if (typeof opts === 'function') {
21604 callback = opts;
21605 opts = {};
21606 }
21607
21608 opts = opts || {};
21609
21610 this._compactionQueue = this._compactionQueue || [];
21611 this._compactionQueue.push({opts, callback});
21612 if (this._compactionQueue.length === 1) {
21613 doNextCompaction(this);
21614 }
21615 }).bind(this);
21616
21617 /* Begin api wrappers. Specific functionality to storage belongs in the _[method] */
21618 this.get = adapterFun('get', function (id, opts, cb) {
21619 if (typeof opts === 'function') {
21620 cb = opts;
21621 opts = {};
21622 }
21623 opts = opts || {};
21624 if (typeof id !== 'string') {
21625 return cb(createError(INVALID_ID));
21626 }
21627 if (isLocalId(id) && typeof this._getLocal === 'function') {
21628 return this._getLocal(id, cb);
21629 }
21630 var leaves = [];
21631
21632 const finishOpenRevs = () => {
21633 var result = [];
21634 var count = leaves.length;
21635 /* istanbul ignore if */
21636 if (!count) {
21637 return cb(null, result);
21638 }
21639
21640 // order with open_revs is unspecified
21641 leaves.forEach((leaf) => {
21642 this.get(id, {
21643 rev: leaf,
21644 revs: opts.revs,
21645 latest: opts.latest,
21646 attachments: opts.attachments,
21647 binary: opts.binary
21648 }, function (err, doc) {
21649 if (!err) {
21650 // using latest=true can produce duplicates
21651 var existing;
21652 for (var i = 0, l = result.length; i < l; i++) {
21653 if (result[i].ok && result[i].ok._rev === doc._rev) {
21654 existing = true;
21655 break;
21656 }
21657 }
21658 if (!existing) {
21659 result.push({ok: doc});
21660 }
21661 } else {
21662 result.push({missing: leaf});
21663 }
21664 count--;
21665 if (!count) {
21666 cb(null, result);
21667 }
21668 });
21669 });
21670 };
21671
21672 if (opts.open_revs) {
21673 if (opts.open_revs === "all") {
21674 this._getRevisionTree(id, function (err, rev_tree) {
21675 /* istanbul ignore if */
21676 if (err) {
21677 return cb(err);
21678 }
21679 leaves = collectLeaves(rev_tree).map(function (leaf) {
21680 return leaf.rev;
21681 });
21682 finishOpenRevs();
21683 });
21684 } else {
21685 if (Array.isArray(opts.open_revs)) {
21686 leaves = opts.open_revs;
21687 for (var i = 0; i < leaves.length; i++) {
21688 var l = leaves[i];
21689 // looks like it's the only thing couchdb checks
21690 if (!isValidRev(l)) {
21691 return cb(createError(INVALID_REV));
21692 }
21693 }
21694 finishOpenRevs();
21695 } else {
21696 return cb(createError(UNKNOWN_ERROR, 'function_clause'));
21697 }
21698 }
21699 return; // open_revs does not like other options
21700 }
21701
21702 return this._get(id, opts, (err, result) => {
21703 if (err) {
21704 err.docId = id;
21705 return cb(err);
21706 }
21707
21708 var doc = result.doc;
21709 var metadata = result.metadata;
21710 var ctx = result.ctx;
21711
21712 if (opts.conflicts) {
21713 var conflicts = collectConflicts(metadata);
21714 if (conflicts.length) {
21715 doc._conflicts = conflicts;
21716 }
21717 }
21718
21719 if (isDeleted(metadata, doc._rev)) {
21720 doc._deleted = true;
21721 }
21722
21723 if (opts.revs || opts.revs_info) {
21724 var splittedRev = doc._rev.split('-');
21725 var revNo = parseInt(splittedRev[0], 10);
21726 var revHash = splittedRev[1];
21727
21728 var paths = rootToLeaf(metadata.rev_tree);
21729 var path = null;
21730
21731 for (var i = 0; i < paths.length; i++) {
21732 var currentPath = paths[i];
21733 const hashIndex = currentPath.ids.findIndex(x => x.id === revHash);
21734 var hashFoundAtRevPos = hashIndex === (revNo - 1);
21735
21736 if (hashFoundAtRevPos || (!path && hashIndex !== -1)) {
21737 path = currentPath;
21738 }
21739 }
21740
21741 /* istanbul ignore if */
21742 if (!path) {
21743 err = new Error('invalid rev tree');
21744 err.docId = id;
21745 return cb(err);
21746 }
21747
21748 const pathId = doc._rev.split('-')[1];
21749 const indexOfRev = path.ids.findIndex(x => x.id === pathId) + 1;
21750 var howMany = path.ids.length - indexOfRev;
21751 path.ids.splice(indexOfRev, howMany);
21752 path.ids.reverse();
21753
21754 if (opts.revs) {
21755 doc._revisions = {
21756 start: (path.pos + path.ids.length) - 1,
21757 ids: path.ids.map(function (rev$$1) {
21758 return rev$$1.id;
21759 })
21760 };
21761 }
21762 if (opts.revs_info) {
21763 var pos = path.pos + path.ids.length;
21764 doc._revs_info = path.ids.map(function (rev$$1) {
21765 pos--;
21766 return {
21767 rev: pos + '-' + rev$$1.id,
21768 status: rev$$1.opts.status
21769 };
21770 });
21771 }
21772 }
21773
21774 if (opts.attachments && doc._attachments) {
21775 var attachments = doc._attachments;
21776 var count = Object.keys(attachments).length;
21777 if (count === 0) {
21778 return cb(null, doc);
21779 }
21780 Object.keys(attachments).forEach((key) => {
21781 this._getAttachment(doc._id, key, attachments[key], {
21782 binary: opts.binary,
21783 metadata,
21784 ctx
21785 }, function (err, data) {
21786 var att = doc._attachments[key];
21787 att.data = data;
21788 delete att.stub;
21789 delete att.length;
21790 if (!--count) {
21791 cb(null, doc);
21792 }
21793 });
21794 });
21795 } else {
21796 if (doc._attachments) {
21797 for (var key in doc._attachments) {
21798 /* istanbul ignore else */
21799 if (Object.prototype.hasOwnProperty.call(doc._attachments, key)) {
21800 doc._attachments[key].stub = true;
21801 }
21802 }
21803 }
21804 cb(null, doc);
21805 }
21806 });
21807 }).bind(this);
21808
21809 // TODO: I don't like this, it forces an extra read for every
21810 // attachment read and enforces a confusing api between
21811 // adapter.js and the adapter implementation
21812 this.getAttachment = adapterFun('getAttachment', function (docId, attachmentId, opts, callback) {
21813 if (opts instanceof Function) {
21814 callback = opts;
21815 opts = {};
21816 }
21817 this._get(docId, opts, (err, res) => {
21818 if (err) {
21819 return callback(err);
21820 }
21821 if (res.doc._attachments && res.doc._attachments[attachmentId]) {
21822 opts.ctx = res.ctx;
21823 opts.binary = true;
21824 opts.metadata = res.metadata;
21825 this._getAttachment(docId, attachmentId,
21826 res.doc._attachments[attachmentId], opts, callback);
21827 } else {
21828 return callback(createError(MISSING_DOC));
21829 }
21830 });
21831 }).bind(this);
21832
21833 this.allDocs = adapterFun('allDocs', function (opts, callback) {
21834 if (typeof opts === 'function') {
21835 callback = opts;
21836 opts = {};
21837 }
21838 opts.skip = typeof opts.skip !== 'undefined' ? opts.skip : 0;
21839 if (opts.start_key) {
21840 opts.startkey = opts.start_key;
21841 }
21842 if (opts.end_key) {
21843 opts.endkey = opts.end_key;
21844 }
21845 if ('keys' in opts) {
21846 if (!Array.isArray(opts.keys)) {
21847 return callback(new TypeError('options.keys must be an array'));
21848 }
21849 var incompatibleOpt =
21850 ['startkey', 'endkey', 'key'].filter(function (incompatibleOpt) {
21851 return incompatibleOpt in opts;
21852 })[0];
21853 if (incompatibleOpt) {
21854 callback(createError(QUERY_PARSE_ERROR,
21855 'Query parameter `' + incompatibleOpt +
21856 '` is not compatible with multi-get'
21857 ));
21858 return;
21859 }
21860 if (!isRemote(this)) {
21861 allDocsKeysParse(opts);
21862 if (opts.keys.length === 0) {
21863 return this._allDocs({limit: 0}, callback);
21864 }
21865 }
21866 }
21867
21868 return this._allDocs(opts, callback);
21869 }).bind(this);
21870
21871 this.close = adapterFun('close', function (callback) {
21872 this._closed = true;
21873 this.emit('closed');
21874 return this._close(callback);
21875 }).bind(this);
21876
21877 this.info = adapterFun('info', function (callback) {
21878 this._info((err, info) => {
21879 if (err) {
21880 return callback(err);
21881 }
21882 // assume we know better than the adapter, unless it informs us
21883 info.db_name = info.db_name || this.name;
21884 info.auto_compaction = !!(this.auto_compaction && !isRemote(this));
21885 info.adapter = this.adapter;
21886 callback(null, info);
21887 });
21888 }).bind(this);
21889
21890 this.id = adapterFun('id', function (callback) {
21891 return this._id(callback);
21892 }).bind(this);
21893
21894 this.bulkDocs = adapterFun('bulkDocs', function (req, opts, callback) {
21895 if (typeof opts === 'function') {
21896 callback = opts;
21897 opts = {};
21898 }
21899
21900 opts = opts || {};
21901
21902 if (Array.isArray(req)) {
21903 req = {
21904 docs: req
21905 };
21906 }
21907
21908 if (!req || !req.docs || !Array.isArray(req.docs)) {
21909 return callback(createError(MISSING_BULK_DOCS));
21910 }
21911
21912 for (var i = 0; i < req.docs.length; ++i) {
21913 const doc = req.docs[i];
21914 if (isNotSingleDoc(doc)) {
21915 return callback(createError(NOT_AN_OBJECT));
21916 }
21917 if ('_rev' in doc && !isValidRev(doc._rev)) {
21918 return callback(createError(INVALID_REV));
21919 }
21920 }
21921
21922 var attachmentError;
21923 req.docs.forEach(function (doc) {
21924 if (doc._attachments) {
21925 Object.keys(doc._attachments).forEach(function (name) {
21926 attachmentError = attachmentError || attachmentNameError(name);
21927 if (!doc._attachments[name].content_type) {
21928 guardedConsole('warn', 'Attachment', name, 'on document', doc._id, 'is missing content_type');
21929 }
21930 });
21931 }
21932 });
21933
21934 if (attachmentError) {
21935 return callback(createError(BAD_REQUEST, attachmentError));
21936 }
21937
21938 if (!('new_edits' in opts)) {
21939 if ('new_edits' in req) {
21940 opts.new_edits = req.new_edits;
21941 } else {
21942 opts.new_edits = true;
21943 }
21944 }
21945
21946 var adapter = this;
21947 if (!opts.new_edits && !isRemote(adapter)) {
21948 // ensure revisions of the same doc are sorted, so that
21949 // the local adapter processes them correctly (#2935)
21950 req.docs.sort(compareByIdThenRev);
21951 }
21952
21953 cleanDocs(req.docs);
21954
21955 // in the case of conflicts, we want to return the _ids to the user
21956 // however, the underlying adapter may destroy the docs array, so
21957 // create a copy here
21958 var ids = req.docs.map(function (doc) {
21959 return doc._id;
21960 });
21961
21962 this._bulkDocs(req, opts, function (err, res) {
21963 if (err) {
21964 return callback(err);
21965 }
21966 if (!opts.new_edits) {
21967 // this is what couch does when new_edits is false
21968 res = res.filter(function (x) {
21969 return x.error;
21970 });
21971 }
21972 // add ids for error/conflict responses (not required for CouchDB)
21973 if (!isRemote(adapter)) {
21974 for (var i = 0, l = res.length; i < l; i++) {
21975 res[i].id = res[i].id || ids[i];
21976 }
21977 }
21978
21979 callback(null, res);
21980 });
21981 }).bind(this);
21982
21983 this.registerDependentDatabase = adapterFun('registerDependentDatabase', function (dependentDb, callback) {
21984 var dbOptions = clone$1(this.__opts);
21985 if (this.__opts.view_adapter) {
21986 dbOptions.adapter = this.__opts.view_adapter;
21987 }
21988
21989 var depDB = new this.constructor(dependentDb, dbOptions);
21990
21991 function diffFun(doc) {
21992 doc.dependentDbs = doc.dependentDbs || {};
21993 if (doc.dependentDbs[dependentDb]) {
21994 return false; // no update required
21995 }
21996 doc.dependentDbs[dependentDb] = true;
21997 return doc;
21998 }
21999 upsert(this, '_local/_pouch_dependentDbs', diffFun).then(function () {
22000 callback(null, {db: depDB});
22001 }).catch(callback);
22002 }).bind(this);
22003
22004 this.destroy = adapterFun('destroy', function (opts, callback) {
22005
22006 if (typeof opts === 'function') {
22007 callback = opts;
22008 opts = {};
22009 }
22010
22011 var usePrefix = 'use_prefix' in this ? this.use_prefix : true;
22012
22013 const destroyDb = () => {
22014 // call destroy method of the particular adaptor
22015 this._destroy(opts, (err, resp) => {
22016 if (err) {
22017 return callback(err);
22018 }
22019 this._destroyed = true;
22020 this.emit('destroyed');
22021 callback(null, resp || { 'ok': true });
22022 });
22023 };
22024
22025 if (isRemote(this)) {
22026 // no need to check for dependent DBs if it's a remote DB
22027 return destroyDb();
22028 }
22029
22030 this.get('_local/_pouch_dependentDbs', (err, localDoc) => {
22031 if (err) {
22032 /* istanbul ignore if */
22033 if (err.status !== 404) {
22034 return callback(err);
22035 } else { // no dependencies
22036 return destroyDb();
22037 }
22038 }
22039 var dependentDbs = localDoc.dependentDbs;
22040 var PouchDB = this.constructor;
22041 var deletedMap = Object.keys(dependentDbs).map((name) => {
22042 // use_prefix is only false in the browser
22043 /* istanbul ignore next */
22044 var trueName = usePrefix ?
22045 name.replace(new RegExp('^' + PouchDB.prefix), '') : name;
22046 return new PouchDB(trueName, this.__opts).destroy();
22047 });
22048 Promise.all(deletedMap).then(destroyDb, callback);
22049 });
22050 }).bind(this);
22051 }
22052
22053 _compact(opts, callback) {
22054 var changesOpts = {
22055 return_docs: false,
22056 last_seq: opts.last_seq || 0,
22057 since: opts.last_seq || 0
22058 };
22059 var promises = [];
22060
22061 var taskId;
22062 var compactedDocs = 0;
22063
22064 const onChange = (row) => {
22065 this.activeTasks.update(taskId, {
22066 completed_items: ++compactedDocs
22067 });
22068 promises.push(this.compactDocument(row.id, 0));
22069 };
22070 const onError = (err) => {
22071 this.activeTasks.remove(taskId, err);
22072 callback(err);
22073 };
22074 const onComplete = (resp) => {
22075 var lastSeq = resp.last_seq;
22076 Promise.all(promises).then(() => {
22077 return upsert(this, '_local/compaction', (doc) => {
22078 if (!doc.last_seq || doc.last_seq < lastSeq) {
22079 doc.last_seq = lastSeq;
22080 return doc;
22081 }
22082 return false; // somebody else got here first, don't update
22083 });
22084 }).then(() => {
22085 this.activeTasks.remove(taskId);
22086 callback(null, {ok: true});
22087 }).catch(onError);
22088 };
22089
22090 this.info().then((info) => {
22091 taskId = this.activeTasks.add({
22092 name: 'database_compaction',
22093 total_items: info.update_seq - changesOpts.last_seq,
22094 });
22095
22096 this.changes(changesOpts)
22097 .on('change', onChange)
22098 .on('complete', onComplete)
22099 .on('error', onError);
22100 });
22101 }
22102
22103 changes(opts, callback) {
22104 if (typeof opts === 'function') {
22105 callback = opts;
22106 opts = {};
22107 }
22108
22109 opts = opts || {};
22110
22111 // By default set return_docs to false if the caller has opts.live = true,
22112 // this will prevent us from collecting the set of changes indefinitely
22113 // resulting in growing memory
22114 opts.return_docs = ('return_docs' in opts) ? opts.return_docs : !opts.live;
22115
22116 return new Changes$1(this, opts, callback);
22117 }
22118
22119 type() {
22120 return (typeof this._type === 'function') ? this._type() : this.adapter;
22121 }
22122}
22123
22124// The abstract purge implementation expects a doc id and the rev of a leaf node in that doc.
22125// It will return errors if the rev doesn’t exist or isn’t a leaf.
22126AbstractPouchDB.prototype.purge = adapterFun('_purge', function (docId, rev$$1, callback) {
22127 if (typeof this._purge === 'undefined') {
22128 return callback(createError(UNKNOWN_ERROR, 'Purge is not implemented in the ' + this.adapter + ' adapter.'));
22129 }
22130 var self = this;
22131
22132 self._getRevisionTree(docId, (error, revs) => {
22133 if (error) {
22134 return callback(error);
22135 }
22136 if (!revs) {
22137 return callback(createError(MISSING_DOC));
22138 }
22139 let path;
22140 try {
22141 path = findPathToLeaf(revs, rev$$1);
22142 } catch (error) {
22143 return callback(error.message || error);
22144 }
22145 self._purge(docId, path, (error, result) => {
22146 if (error) {
22147 return callback(error);
22148 } else {
22149 appendPurgeSeq(self, docId, rev$$1).then(function () {
22150 return callback(null, result);
22151 });
22152 }
22153 });
22154 });
22155});
22156
22157class TaskQueue {
22158 constructor() {
22159 this.isReady = false;
22160 this.failed = false;
22161 this.queue = [];
22162 }
22163
22164 execute() {
22165 var fun;
22166 if (this.failed) {
22167 while ((fun = this.queue.shift())) {
22168 fun(this.failed);
22169 }
22170 } else {
22171 while ((fun = this.queue.shift())) {
22172 fun();
22173 }
22174 }
22175 }
22176
22177 fail(err) {
22178 this.failed = err;
22179 this.execute();
22180 }
22181
22182 ready(db) {
22183 this.isReady = true;
22184 this.db = db;
22185 this.execute();
22186 }
22187
22188 addTask(fun) {
22189 this.queue.push(fun);
22190 if (this.failed) {
22191 this.execute();
22192 }
22193 }
22194}
22195
22196function parseAdapter(name, opts) {
22197 var match = name.match(/([a-z-]*):\/\/(.*)/);
22198 if (match) {
22199 // the http adapter expects the fully qualified name
22200 return {
22201 name: /https?/.test(match[1]) ? match[1] + '://' + match[2] : match[2],
22202 adapter: match[1]
22203 };
22204 }
22205
22206 var adapters = PouchDB$1.adapters;
22207 var preferredAdapters = PouchDB$1.preferredAdapters;
22208 var prefix = PouchDB$1.prefix;
22209 var adapterName = opts.adapter;
22210
22211 if (!adapterName) { // automatically determine adapter
22212 for (var i = 0; i < preferredAdapters.length; ++i) {
22213 adapterName = preferredAdapters[i];
22214 // check for browsers that have been upgraded from websql-only to websql+idb
22215 /* istanbul ignore if */
22216 if (adapterName === 'idb' && 'websql' in adapters &&
22217 hasLocalStorage() && localStorage['_pouch__websqldb_' + prefix + name]) {
22218 // log it, because this can be confusing during development
22219 guardedConsole('log', 'PouchDB is downgrading "' + name + '" to WebSQL to' +
22220 ' avoid data loss, because it was already opened with WebSQL.');
22221 continue; // keep using websql to avoid user data loss
22222 }
22223 break;
22224 }
22225 }
22226
22227 var adapter = adapters[adapterName];
22228
22229 // if adapter is invalid, then an error will be thrown later
22230 var usePrefix = (adapter && 'use_prefix' in adapter) ?
22231 adapter.use_prefix : true;
22232
22233 return {
22234 name: usePrefix ? (prefix + name) : name,
22235 adapter: adapterName
22236 };
22237}
22238
22239function inherits(A, B) {
22240 A.prototype = Object.create(B.prototype, {
22241 constructor: { value: A }
22242 });
22243}
22244
22245function createClass$1(parent, init) {
22246 let klass = function (...args) {
22247 if (!(this instanceof klass)) {
22248 return new klass(...args);
22249 }
22250 init.apply(this, args);
22251 };
22252 inherits(klass, parent);
22253 return klass;
22254}
22255
22256// OK, so here's the deal. Consider this code:
22257// var db1 = new PouchDB('foo');
22258// var db2 = new PouchDB('foo');
22259// db1.destroy();
22260// ^ these two both need to emit 'destroyed' events,
22261// as well as the PouchDB constructor itself.
22262// So we have one db object (whichever one got destroy() called on it)
22263// responsible for emitting the initial event, which then gets emitted
22264// by the constructor, which then broadcasts it to any other dbs
22265// that may have been created with the same name.
22266function prepareForDestruction(self) {
22267
22268 function onDestroyed(from_constructor) {
22269 self.removeListener('closed', onClosed);
22270 if (!from_constructor) {
22271 self.constructor.emit('destroyed', self.name);
22272 }
22273 }
22274
22275 function onClosed() {
22276 self.removeListener('destroyed', onDestroyed);
22277 self.constructor.emit('unref', self);
22278 }
22279
22280 self.once('destroyed', onDestroyed);
22281 self.once('closed', onClosed);
22282 self.constructor.emit('ref', self);
22283}
22284
22285class PouchInternal extends AbstractPouchDB {
22286 constructor(name, opts) {
22287 super();
22288 this._setup(name, opts);
22289 }
22290
22291 _setup(name, opts) {
22292 super._setup();
22293 opts = opts || {};
22294
22295 if (name && typeof name === 'object') {
22296 opts = name;
22297 name = opts.name;
22298 delete opts.name;
22299 }
22300
22301 if (opts.deterministic_revs === undefined) {
22302 opts.deterministic_revs = true;
22303 }
22304
22305 this.__opts = opts = clone$1(opts);
22306
22307 this.auto_compaction = opts.auto_compaction;
22308 this.purged_infos_limit = opts.purged_infos_limit || 1000;
22309 this.prefix = PouchDB$1.prefix;
22310
22311 if (typeof name !== 'string') {
22312 throw new Error('Missing/invalid DB name');
22313 }
22314
22315 var prefixedName = (opts.prefix || '') + name;
22316 var backend = parseAdapter(prefixedName, opts);
22317
22318 opts.name = backend.name;
22319 opts.adapter = opts.adapter || backend.adapter;
22320
22321 this.name = name;
22322 this._adapter = opts.adapter;
22323 PouchDB$1.emit('debug', ['adapter', 'Picked adapter: ', opts.adapter]);
22324
22325 if (!PouchDB$1.adapters[opts.adapter] ||
22326 !PouchDB$1.adapters[opts.adapter].valid()) {
22327 throw new Error('Invalid Adapter: ' + opts.adapter);
22328 }
22329
22330 if (opts.view_adapter) {
22331 if (!PouchDB$1.adapters[opts.view_adapter] ||
22332 !PouchDB$1.adapters[opts.view_adapter].valid()) {
22333 throw new Error('Invalid View Adapter: ' + opts.view_adapter);
22334 }
22335 }
22336
22337 this.taskqueue = new TaskQueue();
22338
22339 this.adapter = opts.adapter;
22340
22341 PouchDB$1.adapters[opts.adapter].call(this, opts, (err) => {
22342 if (err) {
22343 return this.taskqueue.fail(err);
22344 }
22345 prepareForDestruction(this);
22346
22347 this.emit('created', this);
22348 PouchDB$1.emit('created', this.name);
22349 this.taskqueue.ready(this);
22350 });
22351 }
22352}
22353
22354const PouchDB$1 = createClass$1(PouchInternal, function (name, opts) {
22355 PouchInternal.prototype._setup.call(this, name, opts);
22356});
22357
22358var f$1 = fetch;
22359
22360class ActiveTasks {
22361 constructor() {
22362 this.tasks = {};
22363 }
22364
22365 list() {
22366 return Object.values(this.tasks);
22367 }
22368
22369 add(task) {
22370 const id = uuid.v4();
22371 this.tasks[id] = {
22372 id,
22373 name: task.name,
22374 total_items: task.total_items,
22375 created_at: new Date().toJSON()
22376 };
22377 return id;
22378 }
22379
22380 get(id) {
22381 return this.tasks[id];
22382 }
22383
22384 /* eslint-disable no-unused-vars */
22385 remove(id, reason) {
22386 delete this.tasks[id];
22387 return this.tasks;
22388 }
22389
22390 update(id, updatedTask) {
22391 const task = this.tasks[id];
22392 if (typeof task !== 'undefined') {
22393 const mergedTask = {
22394 id: task.id,
22395 name: task.name,
22396 created_at: task.created_at,
22397 total_items: updatedTask.total_items || task.total_items,
22398 completed_items: updatedTask.completed_items || task.completed_items,
22399 updated_at: new Date().toJSON()
22400 };
22401 this.tasks[id] = mergedTask;
22402 }
22403 return this.tasks;
22404 }
22405}
22406
22407PouchDB$1.adapters = {};
22408PouchDB$1.preferredAdapters = [];
22409
22410PouchDB$1.prefix = '_pouch_';
22411
22412var eventEmitter = new EE();
22413
22414function setUpEventEmitter(Pouch) {
22415 Object.keys(EE.prototype).forEach(function (key) {
22416 if (typeof EE.prototype[key] === 'function') {
22417 Pouch[key] = eventEmitter[key].bind(eventEmitter);
22418 }
22419 });
22420
22421 // these are created in constructor.js, and allow us to notify each DB with
22422 // the same name that it was destroyed, via the constructor object
22423 var destructListeners = Pouch._destructionListeners = new Map();
22424
22425 Pouch.on('ref', function onConstructorRef(db) {
22426 if (!destructListeners.has(db.name)) {
22427 destructListeners.set(db.name, []);
22428 }
22429 destructListeners.get(db.name).push(db);
22430 });
22431
22432 Pouch.on('unref', function onConstructorUnref(db) {
22433 if (!destructListeners.has(db.name)) {
22434 return;
22435 }
22436 var dbList = destructListeners.get(db.name);
22437 var pos = dbList.indexOf(db);
22438 if (pos < 0) {
22439 /* istanbul ignore next */
22440 return;
22441 }
22442 dbList.splice(pos, 1);
22443 if (dbList.length > 1) {
22444 /* istanbul ignore next */
22445 destructListeners.set(db.name, dbList);
22446 } else {
22447 destructListeners.delete(db.name);
22448 }
22449 });
22450
22451 Pouch.on('destroyed', function onConstructorDestroyed(name) {
22452 if (!destructListeners.has(name)) {
22453 return;
22454 }
22455 var dbList = destructListeners.get(name);
22456 destructListeners.delete(name);
22457 dbList.forEach(function (db) {
22458 db.emit('destroyed',true);
22459 });
22460 });
22461}
22462
22463setUpEventEmitter(PouchDB$1);
22464
22465PouchDB$1.adapter = function (id, obj, addToPreferredAdapters) {
22466 /* istanbul ignore else */
22467 if (obj.valid()) {
22468 PouchDB$1.adapters[id] = obj;
22469 if (addToPreferredAdapters) {
22470 PouchDB$1.preferredAdapters.push(id);
22471 }
22472 }
22473};
22474
22475PouchDB$1.plugin = function (obj) {
22476 if (typeof obj === 'function') { // function style for plugins
22477 obj(PouchDB$1);
22478 } else if (typeof obj !== 'object' || Object.keys(obj).length === 0) {
22479 throw new Error('Invalid plugin: got "' + obj + '", expected an object or a function');
22480 } else {
22481 Object.keys(obj).forEach(function (id) { // object style for plugins
22482 PouchDB$1.prototype[id] = obj[id];
22483 });
22484 }
22485 if (this.__defaults) {
22486 PouchDB$1.__defaults = Object.assign({}, this.__defaults);
22487 }
22488 return PouchDB$1;
22489};
22490
22491PouchDB$1.defaults = function (defaultOpts) {
22492 let PouchWithDefaults = createClass$1(PouchDB$1, function (name, opts) {
22493 opts = opts || {};
22494
22495 if (name && typeof name === 'object') {
22496 opts = name;
22497 name = opts.name;
22498 delete opts.name;
22499 }
22500
22501 opts = Object.assign({}, PouchWithDefaults.__defaults, opts);
22502 PouchDB$1.call(this, name, opts);
22503 });
22504
22505 PouchWithDefaults.preferredAdapters = PouchDB$1.preferredAdapters.slice();
22506 Object.keys(PouchDB$1).forEach(function (key) {
22507 if (!(key in PouchWithDefaults)) {
22508 PouchWithDefaults[key] = PouchDB$1[key];
22509 }
22510 });
22511
22512 // make default options transitive
22513 // https://github.com/pouchdb/pouchdb/issues/5922
22514 PouchWithDefaults.__defaults = Object.assign({}, this.__defaults, defaultOpts);
22515
22516 return PouchWithDefaults;
22517};
22518
22519PouchDB$1.fetch = function (url, opts) {
22520 return f$1(url, opts);
22521};
22522
22523PouchDB$1.prototype.activeTasks = PouchDB$1.activeTasks = new ActiveTasks();
22524
22525// managed automatically by set-version.js
22526var version$1 = "9.0.0";
22527
22528// this would just be "return doc[field]", but fields
22529// can be "deep" due to dot notation
22530function getFieldFromDoc(doc, parsedField) {
22531 var value = doc;
22532 for (var i = 0, len = parsedField.length; i < len; i++) {
22533 var key = parsedField[i];
22534 value = value[key];
22535 if (!value) {
22536 break;
22537 }
22538 }
22539 return value;
22540}
22541
22542function compare(left, right) {
22543 return left < right ? -1 : left > right ? 1 : 0;
22544}
22545
22546// Converts a string in dot notation to an array of its components, with backslash escaping
22547function parseField(fieldName) {
22548 // fields may be deep (e.g. "foo.bar.baz"), so parse
22549 var fields = [];
22550 var current = '';
22551 for (var i = 0, len = fieldName.length; i < len; i++) {
22552 var ch = fieldName[i];
22553 if (i > 0 && fieldName[i - 1] === '\\' && (ch === '$' || ch === '.')) {
22554 // escaped delimiter
22555 current = current.substring(0, current.length - 1) + ch;
22556 } else if (ch === '.') {
22557 // When `.` is not escaped (above), it is a field delimiter
22558 fields.push(current);
22559 current = '';
22560 } else { // normal character
22561 current += ch;
22562 }
22563 }
22564 fields.push(current);
22565 return fields;
22566}
22567
22568var combinationFields = ['$or', '$nor', '$not'];
22569function isCombinationalField(field) {
22570 return combinationFields.indexOf(field) > -1;
22571}
22572
22573function getKey(obj) {
22574 return Object.keys(obj)[0];
22575}
22576
22577function getValue(obj) {
22578 return obj[getKey(obj)];
22579}
22580
22581
22582// flatten an array of selectors joined by an $and operator
22583function mergeAndedSelectors(selectors) {
22584
22585 // sort to ensure that e.g. if the user specified
22586 // $and: [{$gt: 'a'}, {$gt: 'b'}], then it's collapsed into
22587 // just {$gt: 'b'}
22588 var res = {};
22589 var first = {$or: true, $nor: true};
22590
22591 selectors.forEach(function (selector) {
22592 Object.keys(selector).forEach(function (field) {
22593 var matcher = selector[field];
22594 if (typeof matcher !== 'object') {
22595 matcher = {$eq: matcher};
22596 }
22597
22598 if (isCombinationalField(field)) {
22599 // or, nor
22600 if (matcher instanceof Array) {
22601 if (first[field]) {
22602 first[field] = false;
22603 res[field] = matcher;
22604 return;
22605 }
22606
22607 var entries = [];
22608 res[field].forEach(function (existing) {
22609 Object.keys(matcher).forEach(function (key) {
22610 var m = matcher[key];
22611 var longest = Math.max(Object.keys(existing).length, Object.keys(m).length);
22612 var merged = mergeAndedSelectors([existing, m]);
22613 if (Object.keys(merged).length <= longest) {
22614 // we have a situation like: (a :{$eq :1} || ...) && (a {$eq: 2} || ...)
22615 // merging would produce a $eq 2 when actually we shouldn't ever match against these merged conditions
22616 // merged should always contain more values to be valid
22617 return;
22618 }
22619 entries.push(merged);
22620 });
22621 });
22622 res[field] = entries;
22623 } else {
22624 // not
22625 res[field] = mergeAndedSelectors([matcher]);
22626 }
22627 } else {
22628 var fieldMatchers = res[field] = res[field] || {};
22629 Object.keys(matcher).forEach(function (operator) {
22630 var value = matcher[operator];
22631
22632 if (operator === '$gt' || operator === '$gte') {
22633 return mergeGtGte(operator, value, fieldMatchers);
22634 } else if (operator === '$lt' || operator === '$lte') {
22635 return mergeLtLte(operator, value, fieldMatchers);
22636 } else if (operator === '$ne') {
22637 return mergeNe(value, fieldMatchers);
22638 } else if (operator === '$eq') {
22639 return mergeEq(value, fieldMatchers);
22640 } else if (operator === "$regex") {
22641 return mergeRegex(value, fieldMatchers);
22642 }
22643 fieldMatchers[operator] = value;
22644 });
22645 }
22646 });
22647 });
22648
22649 return res;
22650}
22651
22652
22653
22654// collapse logically equivalent gt/gte values
22655function mergeGtGte(operator, value, fieldMatchers) {
22656 if (typeof fieldMatchers.$eq !== 'undefined') {
22657 return; // do nothing
22658 }
22659 if (typeof fieldMatchers.$gte !== 'undefined') {
22660 if (operator === '$gte') {
22661 if (value > fieldMatchers.$gte) { // more specificity
22662 fieldMatchers.$gte = value;
22663 }
22664 } else { // operator === '$gt'
22665 if (value >= fieldMatchers.$gte) { // more specificity
22666 delete fieldMatchers.$gte;
22667 fieldMatchers.$gt = value;
22668 }
22669 }
22670 } else if (typeof fieldMatchers.$gt !== 'undefined') {
22671 if (operator === '$gte') {
22672 if (value > fieldMatchers.$gt) { // more specificity
22673 delete fieldMatchers.$gt;
22674 fieldMatchers.$gte = value;
22675 }
22676 } else { // operator === '$gt'
22677 if (value > fieldMatchers.$gt) { // more specificity
22678 fieldMatchers.$gt = value;
22679 }
22680 }
22681 } else {
22682 fieldMatchers[operator] = value;
22683 }
22684}
22685
22686// collapse logically equivalent lt/lte values
22687function mergeLtLte(operator, value, fieldMatchers) {
22688 if (typeof fieldMatchers.$eq !== 'undefined') {
22689 return; // do nothing
22690 }
22691 if (typeof fieldMatchers.$lte !== 'undefined') {
22692 if (operator === '$lte') {
22693 if (value < fieldMatchers.$lte) { // more specificity
22694 fieldMatchers.$lte = value;
22695 }
22696 } else { // operator === '$gt'
22697 if (value <= fieldMatchers.$lte) { // more specificity
22698 delete fieldMatchers.$lte;
22699 fieldMatchers.$lt = value;
22700 }
22701 }
22702 } else if (typeof fieldMatchers.$lt !== 'undefined') {
22703 if (operator === '$lte') {
22704 if (value < fieldMatchers.$lt) { // more specificity
22705 delete fieldMatchers.$lt;
22706 fieldMatchers.$lte = value;
22707 }
22708 } else { // operator === '$gt'
22709 if (value < fieldMatchers.$lt) { // more specificity
22710 fieldMatchers.$lt = value;
22711 }
22712 }
22713 } else {
22714 fieldMatchers[operator] = value;
22715 }
22716}
22717
22718// combine $ne values into one array
22719function mergeNe(value, fieldMatchers) {
22720 if ('$ne' in fieldMatchers) {
22721 // there are many things this could "not" be
22722 fieldMatchers.$ne.push(value);
22723 } else { // doesn't exist yet
22724 fieldMatchers.$ne = [value];
22725 }
22726}
22727
22728// add $eq into the mix
22729function mergeEq(value, fieldMatchers) {
22730 // these all have less specificity than the $eq
22731 // TODO: check for user errors here
22732 delete fieldMatchers.$gt;
22733 delete fieldMatchers.$gte;
22734 delete fieldMatchers.$lt;
22735 delete fieldMatchers.$lte;
22736 delete fieldMatchers.$ne;
22737 fieldMatchers.$eq = value;
22738}
22739
22740// combine $regex values into one array
22741function mergeRegex(value, fieldMatchers) {
22742 if ('$regex' in fieldMatchers) {
22743 // a value could match multiple regexes
22744 fieldMatchers.$regex.push(value);
22745 } else { // doesn't exist yet
22746 fieldMatchers.$regex = [value];
22747 }
22748}
22749
22750//#7458: execute function mergeAndedSelectors on nested $and
22751function mergeAndedSelectorsNested(obj) {
22752 for (var prop in obj) {
22753 if (Array.isArray(obj)) {
22754 for (var i in obj) {
22755 if (obj[i]['$and']) {
22756 obj[i] = mergeAndedSelectors(obj[i]['$and']);
22757 }
22758 }
22759 }
22760 var value = obj[prop];
22761 if (typeof value === 'object') {
22762 mergeAndedSelectorsNested(value); // <- recursive call
22763 }
22764 }
22765 return obj;
22766}
22767
22768//#7458: determine id $and is present in selector (at any level)
22769function isAndInSelector(obj, isAnd) {
22770 for (var prop in obj) {
22771 if (prop === '$and') {
22772 isAnd = true;
22773 }
22774 var value = obj[prop];
22775 if (typeof value === 'object') {
22776 isAnd = isAndInSelector(value, isAnd); // <- recursive call
22777 }
22778 }
22779 return isAnd;
22780}
22781
22782//
22783// normalize the selector
22784//
22785function massageSelector(input) {
22786 var result = clone$1(input);
22787
22788 //#7458: if $and is present in selector (at any level) merge nested $and
22789 if (isAndInSelector(result, false)) {
22790 result = mergeAndedSelectorsNested(result);
22791 if ('$and' in result) {
22792 result = mergeAndedSelectors(result['$and']);
22793 }
22794 }
22795
22796 ['$or', '$nor'].forEach(function (orOrNor) {
22797 if (orOrNor in result) {
22798 // message each individual selector
22799 // e.g. {foo: 'bar'} becomes {foo: {$eq: 'bar'}}
22800 result[orOrNor].forEach(function (subSelector) {
22801 var fields = Object.keys(subSelector);
22802 for (var i = 0; i < fields.length; i++) {
22803 var field = fields[i];
22804 var matcher = subSelector[field];
22805 if (typeof matcher !== 'object' || matcher === null) {
22806 subSelector[field] = {$eq: matcher};
22807 }
22808 }
22809 });
22810 }
22811 });
22812
22813 if ('$not' in result) {
22814 //This feels a little like forcing, but it will work for now,
22815 //I would like to come back to this and make the merging of selectors a little more generic
22816 result['$not'] = mergeAndedSelectors([result['$not']]);
22817 }
22818
22819 var fields = Object.keys(result);
22820
22821 for (var i = 0; i < fields.length; i++) {
22822 var field = fields[i];
22823 var matcher = result[field];
22824
22825 if (typeof matcher !== 'object' || matcher === null) {
22826 matcher = {$eq: matcher};
22827 }
22828 result[field] = matcher;
22829 }
22830
22831 normalizeArrayOperators(result);
22832
22833 return result;
22834}
22835
22836//
22837// The $ne and $regex values must be placed in an array because these operators can be used multiple times on the same field.
22838// When $and is used, mergeAndedSelectors takes care of putting some of them into arrays, otherwise it's done here.
22839//
22840function normalizeArrayOperators(selector) {
22841 Object.keys(selector).forEach(function (field) {
22842 var matcher = selector[field];
22843
22844 if (Array.isArray(matcher)) {
22845 matcher.forEach(function (matcherItem) {
22846 if (matcherItem && typeof matcherItem === 'object') {
22847 normalizeArrayOperators(matcherItem);
22848 }
22849 });
22850 } else if (field === '$ne') {
22851 selector.$ne = [matcher];
22852 } else if (field === '$regex') {
22853 selector.$regex = [matcher];
22854 } else if (matcher && typeof matcher === 'object') {
22855 normalizeArrayOperators(matcher);
22856 }
22857 });
22858}
22859
22860function collate(a, b) {
22861
22862 if (a === b) {
22863 return 0;
22864 }
22865
22866 a = normalizeKey(a);
22867 b = normalizeKey(b);
22868
22869 var ai = collationIndex(a);
22870 var bi = collationIndex(b);
22871 if ((ai - bi) !== 0) {
22872 return ai - bi;
22873 }
22874 switch (typeof a) {
22875 case 'number':
22876 return a - b;
22877 case 'boolean':
22878 return a < b ? -1 : 1;
22879 case 'string':
22880 return stringCollate(a, b);
22881 }
22882 return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b);
22883}
22884
22885// couch considers null/NaN/Infinity/-Infinity === undefined,
22886// for the purposes of mapreduce indexes. also, dates get stringified.
22887function normalizeKey(key) {
22888 switch (typeof key) {
22889 case 'undefined':
22890 return null;
22891 case 'number':
22892 if (key === Infinity || key === -Infinity || isNaN(key)) {
22893 return null;
22894 }
22895 return key;
22896 case 'object':
22897 var origKey = key;
22898 if (Array.isArray(key)) {
22899 var len = key.length;
22900 key = new Array(len);
22901 for (var i = 0; i < len; i++) {
22902 key[i] = normalizeKey(origKey[i]);
22903 }
22904 /* istanbul ignore next */
22905 } else if (key instanceof Date) {
22906 return key.toJSON();
22907 } else if (key !== null) { // generic object
22908 key = {};
22909 for (var k in origKey) {
22910 if (Object.prototype.hasOwnProperty.call(origKey, k)) {
22911 var val = origKey[k];
22912 if (typeof val !== 'undefined') {
22913 key[k] = normalizeKey(val);
22914 }
22915 }
22916 }
22917 }
22918 }
22919 return key;
22920}
22921
22922function arrayCollate(a, b) {
22923 var len = Math.min(a.length, b.length);
22924 for (var i = 0; i < len; i++) {
22925 var sort = collate(a[i], b[i]);
22926 if (sort !== 0) {
22927 return sort;
22928 }
22929 }
22930 return (a.length === b.length) ? 0 :
22931 (a.length > b.length) ? 1 : -1;
22932}
22933function stringCollate(a, b) {
22934 // See: https://github.com/daleharvey/pouchdb/issues/40
22935 // This is incompatible with the CouchDB implementation, but its the
22936 // best we can do for now
22937 return (a === b) ? 0 : ((a > b) ? 1 : -1);
22938}
22939function objectCollate(a, b) {
22940 var ak = Object.keys(a), bk = Object.keys(b);
22941 var len = Math.min(ak.length, bk.length);
22942 for (var i = 0; i < len; i++) {
22943 // First sort the keys
22944 var sort = collate(ak[i], bk[i]);
22945 if (sort !== 0) {
22946 return sort;
22947 }
22948 // if the keys are equal sort the values
22949 sort = collate(a[ak[i]], b[bk[i]]);
22950 if (sort !== 0) {
22951 return sort;
22952 }
22953
22954 }
22955 return (ak.length === bk.length) ? 0 :
22956 (ak.length > bk.length) ? 1 : -1;
22957}
22958// The collation is defined by erlangs ordered terms
22959// the atoms null, true, false come first, then numbers, strings,
22960// arrays, then objects
22961// null/undefined/NaN/Infinity/-Infinity are all considered null
22962function collationIndex(x) {
22963 var id = ['boolean', 'number', 'string', 'object'];
22964 var idx = id.indexOf(typeof x);
22965 //false if -1 otherwise true, but fast!!!!1
22966 if (~idx) {
22967 if (x === null) {
22968 return 1;
22969 }
22970 if (Array.isArray(x)) {
22971 return 5;
22972 }
22973 return idx < 3 ? (idx + 2) : (idx + 3);
22974 }
22975 /* istanbul ignore next */
22976 if (Array.isArray(x)) {
22977 return 5;
22978 }
22979}
22980
22981// create a comparator based on the sort object
22982function createFieldSorter(sort) {
22983
22984 function getFieldValuesAsArray(doc) {
22985 return sort.map(function (sorting) {
22986 var fieldName = getKey(sorting);
22987 var parsedField = parseField(fieldName);
22988 var docFieldValue = getFieldFromDoc(doc, parsedField);
22989 return docFieldValue;
22990 });
22991 }
22992
22993 return function (aRow, bRow) {
22994 var aFieldValues = getFieldValuesAsArray(aRow.doc);
22995 var bFieldValues = getFieldValuesAsArray(bRow.doc);
22996 var collation = collate(aFieldValues, bFieldValues);
22997 if (collation !== 0) {
22998 return collation;
22999 }
23000 // this is what mango seems to do
23001 return compare(aRow.doc._id, bRow.doc._id);
23002 };
23003}
23004
23005function filterInMemoryFields(rows, requestDef, inMemoryFields) {
23006 rows = rows.filter(function (row) {
23007 return rowFilter(row.doc, requestDef.selector, inMemoryFields);
23008 });
23009
23010 if (requestDef.sort) {
23011 // in-memory sort
23012 var fieldSorter = createFieldSorter(requestDef.sort);
23013 rows = rows.sort(fieldSorter);
23014 if (typeof requestDef.sort[0] !== 'string' &&
23015 getValue(requestDef.sort[0]) === 'desc') {
23016 rows = rows.reverse();
23017 }
23018 }
23019
23020 if ('limit' in requestDef || 'skip' in requestDef) {
23021 // have to do the limit in-memory
23022 var skip = requestDef.skip || 0;
23023 var limit = ('limit' in requestDef ? requestDef.limit : rows.length) + skip;
23024 rows = rows.slice(skip, limit);
23025 }
23026 return rows;
23027}
23028
23029function rowFilter(doc, selector, inMemoryFields) {
23030 return inMemoryFields.every(function (field) {
23031 var matcher = selector[field];
23032 var parsedField = parseField(field);
23033 var docFieldValue = getFieldFromDoc(doc, parsedField);
23034 if (isCombinationalField(field)) {
23035 return matchCominationalSelector(field, matcher, doc);
23036 }
23037
23038 return matchSelector(matcher, doc, parsedField, docFieldValue);
23039 });
23040}
23041
23042function matchSelector(matcher, doc, parsedField, docFieldValue) {
23043 if (!matcher) {
23044 // no filtering necessary; this field is just needed for sorting
23045 return true;
23046 }
23047
23048 // is matcher an object, if so continue recursion
23049 if (typeof matcher === 'object') {
23050 return Object.keys(matcher).every(function (maybeUserOperator) {
23051 var userValue = matcher[ maybeUserOperator ];
23052 // explicit operator
23053 if (maybeUserOperator.indexOf("$") === 0) {
23054 return match(maybeUserOperator, doc, userValue, parsedField, docFieldValue);
23055 } else {
23056 var subParsedField = parseField(maybeUserOperator);
23057
23058 if (
23059 docFieldValue === undefined &&
23060 typeof userValue !== "object" &&
23061 subParsedField.length > 0
23062 ) {
23063 // the field does not exist, return or getFieldFromDoc will throw
23064 return false;
23065 }
23066
23067 var subDocFieldValue = getFieldFromDoc(docFieldValue, subParsedField);
23068
23069 if (typeof userValue === "object") {
23070 // field value is an object that might contain more operators
23071 return matchSelector(userValue, doc, parsedField, subDocFieldValue);
23072 }
23073
23074 // implicit operator
23075 return match("$eq", doc, userValue, subParsedField, subDocFieldValue);
23076 }
23077 });
23078 }
23079
23080 // no more depth, No need to recurse further
23081 return matcher === docFieldValue;
23082}
23083
23084function matchCominationalSelector(field, matcher, doc) {
23085
23086 if (field === '$or') {
23087 return matcher.some(function (orMatchers) {
23088 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
23089 });
23090 }
23091
23092 if (field === '$not') {
23093 return !rowFilter(doc, matcher, Object.keys(matcher));
23094 }
23095
23096 //`$nor`
23097 return !matcher.find(function (orMatchers) {
23098 return rowFilter(doc, orMatchers, Object.keys(orMatchers));
23099 });
23100
23101}
23102
23103function match(userOperator, doc, userValue, parsedField, docFieldValue) {
23104 if (!matchers[userOperator]) {
23105 /* istanbul ignore next */
23106 throw new Error('unknown operator "' + userOperator +
23107 '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, ' +
23108 '$nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');
23109 }
23110 return matchers[userOperator](doc, userValue, parsedField, docFieldValue);
23111}
23112
23113function fieldExists(docFieldValue) {
23114 return typeof docFieldValue !== 'undefined' && docFieldValue !== null;
23115}
23116
23117function fieldIsNotUndefined(docFieldValue) {
23118 return typeof docFieldValue !== 'undefined';
23119}
23120
23121function modField(docFieldValue, userValue) {
23122 if (typeof docFieldValue !== "number" ||
23123 parseInt(docFieldValue, 10) !== docFieldValue) {
23124 return false;
23125 }
23126
23127 var divisor = userValue[0];
23128 var mod = userValue[1];
23129
23130 return docFieldValue % divisor === mod;
23131}
23132
23133function arrayContainsValue(docFieldValue, userValue) {
23134 return userValue.some(function (val) {
23135 if (docFieldValue instanceof Array) {
23136 return docFieldValue.some(function (docFieldValueItem) {
23137 return collate(val, docFieldValueItem) === 0;
23138 });
23139 }
23140
23141 return collate(val, docFieldValue) === 0;
23142 });
23143}
23144
23145function arrayContainsAllValues(docFieldValue, userValue) {
23146 return userValue.every(function (val) {
23147 return docFieldValue.some(function (docFieldValueItem) {
23148 return collate(val, docFieldValueItem) === 0;
23149 });
23150 });
23151}
23152
23153function arraySize(docFieldValue, userValue) {
23154 return docFieldValue.length === userValue;
23155}
23156
23157function regexMatch(docFieldValue, userValue) {
23158 var re = new RegExp(userValue);
23159
23160 return re.test(docFieldValue);
23161}
23162
23163function typeMatch(docFieldValue, userValue) {
23164
23165 switch (userValue) {
23166 case 'null':
23167 return docFieldValue === null;
23168 case 'boolean':
23169 return typeof (docFieldValue) === 'boolean';
23170 case 'number':
23171 return typeof (docFieldValue) === 'number';
23172 case 'string':
23173 return typeof (docFieldValue) === 'string';
23174 case 'array':
23175 return docFieldValue instanceof Array;
23176 case 'object':
23177 return ({}).toString.call(docFieldValue) === '[object Object]';
23178 }
23179}
23180
23181var matchers = {
23182
23183 '$elemMatch': function (doc, userValue, parsedField, docFieldValue) {
23184 if (!Array.isArray(docFieldValue)) {
23185 return false;
23186 }
23187
23188 if (docFieldValue.length === 0) {
23189 return false;
23190 }
23191
23192 if (typeof docFieldValue[0] === 'object' && docFieldValue[0] !== null) {
23193 return docFieldValue.some(function (val) {
23194 return rowFilter(val, userValue, Object.keys(userValue));
23195 });
23196 }
23197
23198 return docFieldValue.some(function (val) {
23199 return matchSelector(userValue, doc, parsedField, val);
23200 });
23201 },
23202
23203 '$allMatch': function (doc, userValue, parsedField, docFieldValue) {
23204 if (!Array.isArray(docFieldValue)) {
23205 return false;
23206 }
23207
23208 /* istanbul ignore next */
23209 if (docFieldValue.length === 0) {
23210 return false;
23211 }
23212
23213 if (typeof docFieldValue[0] === 'object' && docFieldValue[0] !== null) {
23214 return docFieldValue.every(function (val) {
23215 return rowFilter(val, userValue, Object.keys(userValue));
23216 });
23217 }
23218
23219 return docFieldValue.every(function (val) {
23220 return matchSelector(userValue, doc, parsedField, val);
23221 });
23222 },
23223
23224 '$eq': function (doc, userValue, parsedField, docFieldValue) {
23225 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) === 0;
23226 },
23227
23228 '$gte': function (doc, userValue, parsedField, docFieldValue) {
23229 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) >= 0;
23230 },
23231
23232 '$gt': function (doc, userValue, parsedField, docFieldValue) {
23233 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) > 0;
23234 },
23235
23236 '$lte': function (doc, userValue, parsedField, docFieldValue) {
23237 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) <= 0;
23238 },
23239
23240 '$lt': function (doc, userValue, parsedField, docFieldValue) {
23241 return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) < 0;
23242 },
23243
23244 '$exists': function (doc, userValue, parsedField, docFieldValue) {
23245 //a field that is null is still considered to exist
23246 if (userValue) {
23247 return fieldIsNotUndefined(docFieldValue);
23248 }
23249
23250 return !fieldIsNotUndefined(docFieldValue);
23251 },
23252
23253 '$mod': function (doc, userValue, parsedField, docFieldValue) {
23254 return fieldExists(docFieldValue) && modField(docFieldValue, userValue);
23255 },
23256
23257 '$ne': function (doc, userValue, parsedField, docFieldValue) {
23258 return userValue.every(function (neValue) {
23259 return collate(docFieldValue, neValue) !== 0;
23260 });
23261 },
23262 '$in': function (doc, userValue, parsedField, docFieldValue) {
23263 return fieldExists(docFieldValue) && arrayContainsValue(docFieldValue, userValue);
23264 },
23265
23266 '$nin': function (doc, userValue, parsedField, docFieldValue) {
23267 return fieldExists(docFieldValue) && !arrayContainsValue(docFieldValue, userValue);
23268 },
23269
23270 '$size': function (doc, userValue, parsedField, docFieldValue) {
23271 return fieldExists(docFieldValue) &&
23272 Array.isArray(docFieldValue) &&
23273 arraySize(docFieldValue, userValue);
23274 },
23275
23276 '$all': function (doc, userValue, parsedField, docFieldValue) {
23277 return Array.isArray(docFieldValue) && arrayContainsAllValues(docFieldValue, userValue);
23278 },
23279
23280 '$regex': function (doc, userValue, parsedField, docFieldValue) {
23281 return fieldExists(docFieldValue) &&
23282 typeof docFieldValue == "string" &&
23283 userValue.every(function (regexValue) {
23284 return regexMatch(docFieldValue, regexValue);
23285 });
23286 },
23287
23288 '$type': function (doc, userValue, parsedField, docFieldValue) {
23289 return typeMatch(docFieldValue, userValue);
23290 }
23291};
23292
23293// return true if the given doc matches the supplied selector
23294function matchesSelector(doc, selector) {
23295 /* istanbul ignore if */
23296 if (typeof selector !== 'object') {
23297 // match the CouchDB error message
23298 throw new Error('Selector error: expected a JSON object');
23299 }
23300
23301 selector = massageSelector(selector);
23302 var row = {
23303 doc
23304 };
23305
23306 var rowsMatched = filterInMemoryFields([row], { selector }, Object.keys(selector));
23307 return rowsMatched && rowsMatched.length === 1;
23308}
23309
23310function evalFilter(input) {
23311 return scopeEval('"use strict";\nreturn ' + input + ';', {});
23312}
23313
23314function evalView(input) {
23315 var code = [
23316 'return function(doc) {',
23317 ' "use strict";',
23318 ' var emitted = false;',
23319 ' var emit = function (a, b) {',
23320 ' emitted = true;',
23321 ' };',
23322 ' var view = ' + input + ';',
23323 ' view(doc);',
23324 ' if (emitted) {',
23325 ' return true;',
23326 ' }',
23327 '};'
23328 ].join('\n');
23329
23330 return scopeEval(code, {});
23331}
23332
23333function validate(opts, callback) {
23334 if (opts.selector) {
23335 if (opts.filter && opts.filter !== '_selector') {
23336 var filterName = typeof opts.filter === 'string' ?
23337 opts.filter : 'function';
23338 return callback(new Error('selector invalid for filter "' + filterName + '"'));
23339 }
23340 }
23341 callback();
23342}
23343
23344function normalize(opts) {
23345 if (opts.view && !opts.filter) {
23346 opts.filter = '_view';
23347 }
23348
23349 if (opts.selector && !opts.filter) {
23350 opts.filter = '_selector';
23351 }
23352
23353 if (opts.filter && typeof opts.filter === 'string') {
23354 if (opts.filter === '_view') {
23355 opts.view = normalizeDesignDocFunctionName(opts.view);
23356 } else {
23357 opts.filter = normalizeDesignDocFunctionName(opts.filter);
23358 }
23359 }
23360}
23361
23362function shouldFilter(changesHandler, opts) {
23363 return opts.filter && typeof opts.filter === 'string' &&
23364 !opts.doc_ids && !isRemote(changesHandler.db);
23365}
23366
23367function filter(changesHandler, opts) {
23368 var callback = opts.complete;
23369 if (opts.filter === '_view') {
23370 if (!opts.view || typeof opts.view !== 'string') {
23371 var err = createError(BAD_REQUEST,
23372 '`view` filter parameter not found or invalid.');
23373 return callback(err);
23374 }
23375 // fetch a view from a design doc, make it behave like a filter
23376 var viewName = parseDesignDocFunctionName(opts.view);
23377 changesHandler.db.get('_design/' + viewName[0], function (err, ddoc) {
23378 /* istanbul ignore if */
23379 if (changesHandler.isCancelled) {
23380 return callback(null, {status: 'cancelled'});
23381 }
23382 /* istanbul ignore next */
23383 if (err) {
23384 return callback(generateErrorFromResponse(err));
23385 }
23386 var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] &&
23387 ddoc.views[viewName[1]].map;
23388 if (!mapFun) {
23389 return callback(createError(MISSING_DOC,
23390 (ddoc.views ? 'missing json key: ' + viewName[1] :
23391 'missing json key: views')));
23392 }
23393 opts.filter = evalView(mapFun);
23394 changesHandler.doChanges(opts);
23395 });
23396 } else if (opts.selector) {
23397 opts.filter = function (doc) {
23398 return matchesSelector(doc, opts.selector);
23399 };
23400 changesHandler.doChanges(opts);
23401 } else {
23402 // fetch a filter from a design doc
23403 var filterName = parseDesignDocFunctionName(opts.filter);
23404 changesHandler.db.get('_design/' + filterName[0], function (err, ddoc) {
23405 /* istanbul ignore if */
23406 if (changesHandler.isCancelled) {
23407 return callback(null, {status: 'cancelled'});
23408 }
23409 /* istanbul ignore next */
23410 if (err) {
23411 return callback(generateErrorFromResponse(err));
23412 }
23413 var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]];
23414 if (!filterFun) {
23415 return callback(createError(MISSING_DOC,
23416 ((ddoc && ddoc.filters) ? 'missing json key: ' + filterName[1]
23417 : 'missing json key: filters')));
23418 }
23419 opts.filter = evalFilter(filterFun);
23420 changesHandler.doChanges(opts);
23421 });
23422 }
23423}
23424
23425function applyChangesFilterPlugin(PouchDB) {
23426 PouchDB._changesFilterPlugin = {
23427 validate,
23428 normalize,
23429 shouldFilter,
23430 filter
23431 };
23432}
23433
23434// TODO: remove from pouchdb-core (breaking)
23435PouchDB$1.plugin(applyChangesFilterPlugin);
23436
23437PouchDB$1.version = version$1;
23438
23439function allDocsKeysQuery(api, opts) {
23440 var keys = opts.keys;
23441 var finalResults = {
23442 offset: opts.skip
23443 };
23444 return Promise.all(keys.map(function (key) {
23445 var subOpts = Object.assign({key, deleted: 'ok'}, opts);
23446 ['limit', 'skip', 'keys'].forEach(function (optKey) {
23447 delete subOpts[optKey];
23448 });
23449 return new Promise(function (resolve, reject) {
23450 api._allDocs(subOpts, function (err, res) {
23451 /* istanbul ignore if */
23452 if (err) {
23453 return reject(err);
23454 }
23455 /* istanbul ignore if */
23456 if (opts.update_seq && res.update_seq !== undefined) {
23457 finalResults.update_seq = res.update_seq;
23458 }
23459 finalResults.total_rows = res.total_rows;
23460 resolve(res.rows[0] || {key, error: 'not_found'});
23461 });
23462 });
23463 })).then(function (results) {
23464 finalResults.rows = results;
23465 return finalResults;
23466 });
23467}
23468
23469function toObject(array) {
23470 return array.reduce(function (obj, item) {
23471 obj[item] = true;
23472 return obj;
23473 }, {});
23474}
23475// List of top level reserved words for doc
23476var reservedWords = toObject([
23477 '_id',
23478 '_rev',
23479 '_access',
23480 '_attachments',
23481 '_deleted',
23482 '_revisions',
23483 '_revs_info',
23484 '_conflicts',
23485 '_deleted_conflicts',
23486 '_local_seq',
23487 '_rev_tree',
23488 // replication documents
23489 '_replication_id',
23490 '_replication_state',
23491 '_replication_state_time',
23492 '_replication_state_reason',
23493 '_replication_stats',
23494 // Specific to Couchbase Sync Gateway
23495 '_removed'
23496]);
23497
23498// List of reserved words that should end up in the document
23499var dataWords = toObject([
23500 '_access',
23501 '_attachments',
23502 // replication documents
23503 '_replication_id',
23504 '_replication_state',
23505 '_replication_state_time',
23506 '_replication_state_reason',
23507 '_replication_stats'
23508]);
23509
23510function parseRevisionInfo(rev$$1) {
23511 if (!/^\d+-/.test(rev$$1)) {
23512 return createError(INVALID_REV);
23513 }
23514 var idx = rev$$1.indexOf('-');
23515 var left = rev$$1.substring(0, idx);
23516 var right = rev$$1.substring(idx + 1);
23517 return {
23518 prefix: parseInt(left, 10),
23519 id: right
23520 };
23521}
23522
23523function makeRevTreeFromRevisions(revisions, opts) {
23524 var pos = revisions.start - revisions.ids.length + 1;
23525
23526 var revisionIds = revisions.ids;
23527 var ids = [revisionIds[0], opts, []];
23528
23529 for (var i = 1, len = revisionIds.length; i < len; i++) {
23530 ids = [revisionIds[i], {status: 'missing'}, [ids]];
23531 }
23532
23533 return [{
23534 pos,
23535 ids
23536 }];
23537}
23538
23539// Preprocess documents, parse their revisions, assign an id and a
23540// revision for new writes that are missing them, etc
23541function parseDoc(doc, newEdits, dbOpts) {
23542 if (!dbOpts) {
23543 dbOpts = {
23544 deterministic_revs: true
23545 };
23546 }
23547
23548 var nRevNum;
23549 var newRevId;
23550 var revInfo;
23551 var opts = {status: 'available'};
23552 if (doc._deleted) {
23553 opts.deleted = true;
23554 }
23555
23556 if (newEdits) {
23557 if (!doc._id) {
23558 doc._id = uuid$1();
23559 }
23560 newRevId = rev(doc, dbOpts.deterministic_revs);
23561 if (doc._rev) {
23562 revInfo = parseRevisionInfo(doc._rev);
23563 if (revInfo.error) {
23564 return revInfo;
23565 }
23566 doc._rev_tree = [{
23567 pos: revInfo.prefix,
23568 ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]
23569 }];
23570 nRevNum = revInfo.prefix + 1;
23571 } else {
23572 doc._rev_tree = [{
23573 pos: 1,
23574 ids : [newRevId, opts, []]
23575 }];
23576 nRevNum = 1;
23577 }
23578 } else {
23579 if (doc._revisions) {
23580 doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);
23581 nRevNum = doc._revisions.start;
23582 newRevId = doc._revisions.ids[0];
23583 }
23584 if (!doc._rev_tree) {
23585 revInfo = parseRevisionInfo(doc._rev);
23586 if (revInfo.error) {
23587 return revInfo;
23588 }
23589 nRevNum = revInfo.prefix;
23590 newRevId = revInfo.id;
23591 doc._rev_tree = [{
23592 pos: nRevNum,
23593 ids: [newRevId, opts, []]
23594 }];
23595 }
23596 }
23597
23598 invalidIdError(doc._id);
23599
23600 doc._rev = nRevNum + '-' + newRevId;
23601
23602 var result = {metadata : {}, data : {}};
23603 for (var key in doc) {
23604 /* istanbul ignore else */
23605 if (Object.prototype.hasOwnProperty.call(doc, key)) {
23606 var specialKey = key[0] === '_';
23607 if (specialKey && !reservedWords[key]) {
23608 var error = createError(DOC_VALIDATION, key);
23609 error.message = DOC_VALIDATION.message + ': ' + key;
23610 throw error;
23611 } else if (specialKey && !dataWords[key]) {
23612 result.metadata[key.slice(1)] = doc[key];
23613 } else {
23614 result.data[key] = doc[key];
23615 }
23616 }
23617 }
23618 return result;
23619}
23620
23621function updateDoc(revLimit, prev, docInfo, results,
23622 i, cb, writeDoc, newEdits) {
23623
23624 if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {
23625 results[i] = docInfo;
23626 return cb();
23627 }
23628
23629 // sometimes this is pre-calculated. historically not always
23630 var previousWinningRev = prev.winningRev || winningRev(prev);
23631 var previouslyDeleted = 'deleted' in prev ? prev.deleted :
23632 isDeleted(prev, previousWinningRev);
23633 var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
23634 isDeleted(docInfo.metadata);
23635 var isRoot = /^1-/.test(docInfo.metadata.rev);
23636
23637 if (previouslyDeleted && !deleted && newEdits && isRoot) {
23638 var newDoc = docInfo.data;
23639 newDoc._rev = previousWinningRev;
23640 newDoc._id = docInfo.metadata.id;
23641 docInfo = parseDoc(newDoc, newEdits);
23642 }
23643
23644 var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
23645
23646 var inConflict = newEdits && ((
23647 (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||
23648 (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
23649 (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
23650
23651 if (inConflict) {
23652 var err = createError(REV_CONFLICT);
23653 results[i] = err;
23654 return cb();
23655 }
23656
23657 var newRev = docInfo.metadata.rev;
23658 docInfo.metadata.rev_tree = merged.tree;
23659 docInfo.stemmedRevs = merged.stemmedRevs || [];
23660 /* istanbul ignore else */
23661 if (prev.rev_map) {
23662 docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
23663 }
23664
23665 // recalculate
23666 var winningRev$$1 = winningRev(docInfo.metadata);
23667 var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);
23668
23669 // calculate the total number of documents that were added/removed,
23670 // from the perspective of total_rows/doc_count
23671 var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
23672 previouslyDeleted < winningRevIsDeleted ? -1 : 1;
23673
23674 var newRevIsDeleted;
23675 if (newRev === winningRev$$1) {
23676 // if the new rev is the same as the winning rev, we can reuse that value
23677 newRevIsDeleted = winningRevIsDeleted;
23678 } else {
23679 // if they're not the same, then we need to recalculate
23680 newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
23681 }
23682
23683 writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
23684 true, delta, i, cb);
23685}
23686
23687function rootIsMissing(docInfo) {
23688 return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';
23689}
23690
23691function processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,
23692 writeDoc, opts, overallCallback) {
23693
23694 // Default to 1000 locally
23695 revLimit = revLimit || 1000;
23696
23697 function insertDoc(docInfo, resultsIdx, callback) {
23698 // Cant insert new deleted documents
23699 var winningRev$$1 = winningRev(docInfo.metadata);
23700 var deleted = isDeleted(docInfo.metadata, winningRev$$1);
23701 if ('was_delete' in opts && deleted) {
23702 results[resultsIdx] = createError(MISSING_DOC, 'deleted');
23703 return callback();
23704 }
23705
23706 // 4712 - detect whether a new document was inserted with a _rev
23707 var inConflict = newEdits && rootIsMissing(docInfo);
23708
23709 if (inConflict) {
23710 var err = createError(REV_CONFLICT);
23711 results[resultsIdx] = err;
23712 return callback();
23713 }
23714
23715 var delta = deleted ? 0 : 1;
23716
23717 writeDoc(docInfo, winningRev$$1, deleted, deleted, false,
23718 delta, resultsIdx, callback);
23719 }
23720
23721 var newEdits = opts.new_edits;
23722 var idsToDocs = new Map();
23723
23724 var docsDone = 0;
23725 var docsToDo = docInfos.length;
23726
23727 function checkAllDocsDone() {
23728 if (++docsDone === docsToDo && overallCallback) {
23729 overallCallback();
23730 }
23731 }
23732
23733 docInfos.forEach(function (currentDoc, resultsIdx) {
23734
23735 if (currentDoc._id && isLocalId(currentDoc._id)) {
23736 var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';
23737 api[fun](currentDoc, {ctx: tx}, function (err, res) {
23738 results[resultsIdx] = err || res;
23739 checkAllDocsDone();
23740 });
23741 return;
23742 }
23743
23744 var id = currentDoc.metadata.id;
23745 if (idsToDocs.has(id)) {
23746 docsToDo--; // duplicate
23747 idsToDocs.get(id).push([currentDoc, resultsIdx]);
23748 } else {
23749 idsToDocs.set(id, [[currentDoc, resultsIdx]]);
23750 }
23751 });
23752
23753 // in the case of new_edits, the user can provide multiple docs
23754 // with the same id. these need to be processed sequentially
23755 idsToDocs.forEach(function (docs, id) {
23756 var numDone = 0;
23757
23758 function docWritten() {
23759 if (++numDone < docs.length) {
23760 nextDoc();
23761 } else {
23762 checkAllDocsDone();
23763 }
23764 }
23765 function nextDoc() {
23766 var value = docs[numDone];
23767 var currentDoc = value[0];
23768 var resultsIdx = value[1];
23769
23770 if (fetchedDocs.has(id)) {
23771 updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,
23772 resultsIdx, docWritten, writeDoc, newEdits);
23773 } else {
23774 // Ensure stemming applies to new writes as well
23775 var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);
23776 currentDoc.metadata.rev_tree = merged.tree;
23777 currentDoc.stemmedRevs = merged.stemmedRevs || [];
23778 insertDoc(currentDoc, resultsIdx, docWritten);
23779 }
23780 }
23781 nextDoc();
23782 });
23783}
23784
23785function safeJsonParse(str) {
23786 // This try/catch guards against stack overflow errors.
23787 // JSON.parse() is faster than vuvuzela.parse() but vuvuzela
23788 // cannot overflow.
23789 try {
23790 return JSON.parse(str);
23791 } catch (e) {
23792 /* istanbul ignore next */
23793 return vuvuzela.parse(str);
23794 }
23795}
23796
23797function safeJsonStringify(json) {
23798 try {
23799 return JSON.stringify(json);
23800 } catch (e) {
23801 /* istanbul ignore next */
23802 return vuvuzela.stringify(json);
23803 }
23804}
23805
23806function readAsBlobOrBuffer(storedObject, type) {
23807 // In the browser, we've stored a binary string. This now comes back as a
23808 // browserified Node-style Buffer (implemented as a typed array),
23809 // but we want a Blob instead.
23810 var byteArray = new Uint8Array(storedObject);
23811 return createBlob([byteArray], {type});
23812}
23813
23814// In the browser, we store a binary string
23815function prepareAttachmentForStorage(attData, cb) {
23816 readAsBinaryString(attData, cb);
23817}
23818
23819function createEmptyBlobOrBuffer(type) {
23820 return createBlob([''], {type});
23821}
23822
23823// similar to an idb or websql transaction object
23824
23825function getCacheFor(transaction, store) {
23826 var prefix = store.prefix()[0];
23827 var cache = transaction._cache;
23828 var subCache = cache.get(prefix);
23829 if (!subCache) {
23830 subCache = new Map();
23831 cache.set(prefix, subCache);
23832 }
23833 return subCache;
23834}
23835
23836class LevelTransaction {
23837 constructor() {
23838 this._batch = [];
23839 this._cache = new Map();
23840 }
23841
23842 get(store, key, callback) {
23843 var cache = getCacheFor(this, store);
23844 var exists = cache.get(key);
23845 if (exists) {
23846 return nextTick(function () {
23847 callback(null, exists);
23848 });
23849 } else if (exists === null) { // deleted marker
23850 /* istanbul ignore next */
23851 return nextTick(function () {
23852 callback({name: 'NotFoundError'});
23853 });
23854 }
23855 store.get(key, function (err, res) {
23856 if (err) {
23857 /* istanbul ignore else */
23858 if (err.name === 'NotFoundError') {
23859 cache.set(key, null);
23860 }
23861 return callback(err);
23862 }
23863 cache.set(key, res);
23864 callback(null, res);
23865 });
23866 }
23867
23868 batch(batch) {
23869 for (var i = 0, len = batch.length; i < len; i++) {
23870 var operation = batch[i];
23871
23872 var cache = getCacheFor(this, operation.prefix);
23873
23874 if (operation.type === 'put') {
23875 cache.set(operation.key, operation.value);
23876 } else {
23877 cache.set(operation.key, null);
23878 }
23879 }
23880 this._batch = this._batch.concat(batch);
23881 }
23882
23883 execute(db, callback) {
23884 var keys = new Set();
23885 var uniqBatches = [];
23886
23887 // remove duplicates; last one wins
23888 for (var i = this._batch.length - 1; i >= 0; i--) {
23889 var operation = this._batch[i];
23890 var lookupKey = operation.prefix.prefix()[0] + '\xff' + operation.key;
23891 if (keys.has(lookupKey)) {
23892 continue;
23893 }
23894 keys.add(lookupKey);
23895 uniqBatches.push(operation);
23896 }
23897
23898 db.batch(uniqBatches, callback);
23899 }
23900}
23901
23902var DOC_STORE = 'document-store';
23903var BY_SEQ_STORE = 'by-sequence';
23904var ATTACHMENT_STORE = 'attach-store';
23905var BINARY_STORE = 'attach-binary-store';
23906var LOCAL_STORE = 'local-store';
23907var META_STORE = 'meta-store';
23908
23909// leveldb barks if we try to open a db multiple times
23910// so we cache opened connections here for initstore()
23911var dbStores = new Map();
23912
23913// store the value of update_seq in the by-sequence store the key name will
23914// never conflict, since the keys in the by-sequence store are integers
23915var UPDATE_SEQ_KEY = '_local_last_update_seq';
23916var DOC_COUNT_KEY = '_local_doc_count';
23917var UUID_KEY = '_local_uuid';
23918
23919var MD5_PREFIX = 'md5-';
23920
23921var safeJsonEncoding = {
23922 encode: safeJsonStringify,
23923 decode: safeJsonParse,
23924 buffer: false,
23925 type: 'cheap-json'
23926};
23927
23928var levelChanges = new Changes();
23929
23930// winningRev and deleted are performance-killers, but
23931// in newer versions of PouchDB, they are cached on the metadata
23932function getWinningRev(metadata) {
23933 return 'winningRev' in metadata ?
23934 metadata.winningRev : winningRev(metadata);
23935}
23936
23937function getIsDeleted(metadata, winningRev$$1) {
23938 return 'deleted' in metadata ?
23939 metadata.deleted : isDeleted(metadata, winningRev$$1);
23940}
23941
23942function fetchAttachment(att, stores, opts) {
23943 var type = att.content_type;
23944 return new Promise(function (resolve, reject) {
23945 stores.binaryStore.get(att.digest, function (err, buffer) {
23946 var data;
23947 if (err) {
23948 /* istanbul ignore if */
23949 if (err.name !== 'NotFoundError') {
23950 return reject(err);
23951 } else {
23952 // empty
23953 if (!opts.binary) {
23954 data = '';
23955 } else {
23956 data = binStringToBluffer('', type);
23957 }
23958 }
23959 } else { // non-empty
23960 if (opts.binary) {
23961 data = readAsBlobOrBuffer(buffer, type);
23962 } else {
23963 data = buffer.toString('base64');
23964 }
23965 }
23966 delete att.stub;
23967 delete att.length;
23968 att.data = data;
23969 resolve();
23970 });
23971 });
23972}
23973
23974function fetchAttachments(results, stores, opts) {
23975 var atts = [];
23976 results.forEach(function (row) {
23977 if (!(row.doc && row.doc._attachments)) {
23978 return;
23979 }
23980 var attNames = Object.keys(row.doc._attachments);
23981 attNames.forEach(function (attName) {
23982 var att = row.doc._attachments[attName];
23983 if (!('data' in att)) {
23984 atts.push(att);
23985 }
23986 });
23987 });
23988
23989 return Promise.all(atts.map(function (att) {
23990 return fetchAttachment(att, stores, opts);
23991 }));
23992}
23993
23994function LevelPouch(opts, callback) {
23995 opts = clone$1(opts);
23996 var api = this;
23997 var instanceId;
23998 var stores = {};
23999 var revLimit = opts.revs_limit;
24000 var db;
24001 var name = opts.name;
24002 // TODO: this is undocumented and unused probably
24003 /* istanbul ignore else */
24004 if (typeof opts.createIfMissing === 'undefined') {
24005 opts.createIfMissing = true;
24006 }
24007
24008 var leveldown = opts.db;
24009
24010 var dbStore;
24011 var leveldownName = functionName(leveldown);
24012 if (dbStores.has(leveldownName)) {
24013 dbStore = dbStores.get(leveldownName);
24014 } else {
24015 dbStore = new Map();
24016 dbStores.set(leveldownName, dbStore);
24017 }
24018 if (dbStore.has(name)) {
24019 db = dbStore.get(name);
24020 afterDBCreated();
24021 } else {
24022 dbStore.set(name, sublevelPouch(levelup(leveldown(name), opts, function (err) {
24023 /* istanbul ignore if */
24024 if (err) {
24025 dbStore.delete(name);
24026 return callback(err);
24027 }
24028 db = dbStore.get(name);
24029 db._docCount = -1;
24030 db._queue = new Deque();
24031 /* istanbul ignore else */
24032 if (typeof opts.migrate === 'object') { // migration for leveldown
24033 opts.migrate.doMigrationOne(name, db, afterDBCreated);
24034 } else {
24035 afterDBCreated();
24036 }
24037 })));
24038 }
24039
24040 function afterDBCreated() {
24041 stores.docStore = db.sublevel(DOC_STORE, {valueEncoding: safeJsonEncoding});
24042 stores.bySeqStore = db.sublevel(BY_SEQ_STORE, {valueEncoding: 'json'});
24043 stores.attachmentStore =
24044 db.sublevel(ATTACHMENT_STORE, {valueEncoding: 'json'});
24045 stores.binaryStore = db.sublevel(BINARY_STORE, {valueEncoding: 'binary'});
24046 stores.localStore = db.sublevel(LOCAL_STORE, {valueEncoding: 'json'});
24047 stores.metaStore = db.sublevel(META_STORE, {valueEncoding: 'json'});
24048 /* istanbul ignore else */
24049 if (typeof opts.migrate === 'object') { // migration for leveldown
24050 opts.migrate.doMigrationTwo(db, stores, afterLastMigration);
24051 } else {
24052 afterLastMigration();
24053 }
24054 }
24055
24056 function afterLastMigration() {
24057 stores.metaStore.get(UPDATE_SEQ_KEY, function (err, value) {
24058 if (typeof db._updateSeq === 'undefined') {
24059 db._updateSeq = value || 0;
24060 }
24061 stores.metaStore.get(DOC_COUNT_KEY, function (err, value) {
24062 db._docCount = !err ? value : 0;
24063 stores.metaStore.get(UUID_KEY, function (err, value) {
24064 instanceId = !err ? value : uuid$1();
24065 stores.metaStore.put(UUID_KEY, instanceId, function () {
24066 nextTick(function () {
24067 callback(null, api);
24068 });
24069 });
24070 });
24071 });
24072 });
24073 }
24074
24075 function countDocs(callback) {
24076 /* istanbul ignore if */
24077 if (db.isClosed()) {
24078 return callback(new Error('database is closed'));
24079 }
24080 return callback(null, db._docCount); // use cached value
24081 }
24082
24083 api._remote = false;
24084 /* istanbul ignore next */
24085 api.type = function () {
24086 return 'leveldb';
24087 };
24088
24089 api._id = function (callback) {
24090 callback(null, instanceId);
24091 };
24092
24093 api._info = function (callback) {
24094 var res = {
24095 doc_count: db._docCount,
24096 update_seq: db._updateSeq,
24097 backend_adapter: functionName(leveldown)
24098 };
24099 return nextTick(function () {
24100 callback(null, res);
24101 });
24102 };
24103
24104 function tryCode(fun, args) {
24105 try {
24106 fun.apply(null, args);
24107 } catch (err) {
24108 args[args.length - 1](err);
24109 }
24110 }
24111
24112 function executeNext() {
24113 var firstTask = db._queue.peekFront();
24114
24115 if (firstTask.type === 'read') {
24116 runReadOperation(firstTask);
24117 } else { // write, only do one at a time
24118 runWriteOperation(firstTask);
24119 }
24120 }
24121
24122 function runReadOperation(firstTask) {
24123 // do multiple reads at once simultaneously, because it's safe
24124
24125 var readTasks = [firstTask];
24126 var i = 1;
24127 var nextTask = db._queue.get(i);
24128 while (typeof nextTask !== 'undefined' && nextTask.type === 'read') {
24129 readTasks.push(nextTask);
24130 i++;
24131 nextTask = db._queue.get(i);
24132 }
24133
24134 var numDone = 0;
24135
24136 readTasks.forEach(function (readTask) {
24137 var args = readTask.args;
24138 var callback = args[args.length - 1];
24139 args[args.length - 1] = function (...cbArgs) {
24140 callback.apply(null, cbArgs);
24141 if (++numDone === readTasks.length) {
24142 nextTick(function () {
24143 // all read tasks have finished
24144 readTasks.forEach(function () {
24145 db._queue.shift();
24146 });
24147 if (db._queue.length) {
24148 executeNext();
24149 }
24150 });
24151 }
24152 };
24153 tryCode(readTask.fun, args);
24154 });
24155 }
24156
24157 function runWriteOperation(firstTask) {
24158 var args = firstTask.args;
24159 var callback = args[args.length - 1];
24160 args[args.length - 1] = function (...cbArgs) {
24161 callback.apply(null, cbArgs);
24162 nextTick(function () {
24163 db._queue.shift();
24164 if (db._queue.length) {
24165 executeNext();
24166 }
24167 });
24168 };
24169 tryCode(firstTask.fun, args);
24170 }
24171
24172 // all read/write operations to the database are done in a queue,
24173 // similar to how websql/idb works. this avoids problems such
24174 // as e.g. compaction needing to have a lock on the database while
24175 // it updates stuff. in the future we can revisit this.
24176 function writeLock(fun) {
24177 return function (...args) {
24178 db._queue.push({
24179 fun,
24180 args,
24181 type: 'write'
24182 });
24183
24184 if (db._queue.length === 1) {
24185 nextTick(executeNext);
24186 }
24187 };
24188 }
24189
24190 // same as the writelock, but multiple can run at once
24191 function readLock(fun) {
24192 return function (...args) {
24193 db._queue.push({
24194 fun,
24195 args,
24196 type: 'read'
24197 });
24198
24199 if (db._queue.length === 1) {
24200 nextTick(executeNext);
24201 }
24202 };
24203 }
24204
24205 function formatSeq(n) {
24206 return ('0000000000000000' + n).slice(-16);
24207 }
24208
24209 function parseSeq(s) {
24210 return parseInt(s, 10);
24211 }
24212
24213 api._get = readLock(function (id, opts, callback) {
24214 opts = clone$1(opts);
24215
24216 stores.docStore.get(id, function (err, metadata) {
24217
24218 if (err || !metadata) {
24219 return callback(createError(MISSING_DOC, 'missing'));
24220 }
24221
24222 var rev$$1;
24223 if (!opts.rev) {
24224 rev$$1 = getWinningRev(metadata);
24225 var deleted = getIsDeleted(metadata, rev$$1);
24226 if (deleted) {
24227 return callback(createError(MISSING_DOC, "deleted"));
24228 }
24229 } else {
24230 rev$$1 = opts.latest ? latest(opts.rev, metadata) : opts.rev;
24231 }
24232
24233 var seq = metadata.rev_map[rev$$1];
24234
24235 stores.bySeqStore.get(formatSeq(seq), function (err, doc) {
24236 if (!doc) {
24237 return callback(createError(MISSING_DOC));
24238 }
24239 /* istanbul ignore if */
24240 if ('_id' in doc && doc._id !== metadata.id) {
24241 // this failing implies something very wrong
24242 return callback(new Error('wrong doc returned'));
24243 }
24244 doc._id = metadata.id;
24245 if ('_rev' in doc) {
24246 /* istanbul ignore if */
24247 if (doc._rev !== rev$$1) {
24248 // this failing implies something very wrong
24249 return callback(new Error('wrong doc returned'));
24250 }
24251 } else {
24252 // we didn't always store this
24253 doc._rev = rev$$1;
24254 }
24255 return callback(null, {doc, metadata});
24256 });
24257 });
24258 });
24259
24260 // not technically part of the spec, but if putAttachment has its own
24261 // method...
24262 api._getAttachment = function (docId, attachId, attachment, opts, callback) {
24263 var digest = attachment.digest;
24264 var type = attachment.content_type;
24265
24266 stores.binaryStore.get(digest, function (err, attach) {
24267 if (err) {
24268 /* istanbul ignore if */
24269 if (err.name !== 'NotFoundError') {
24270 return callback(err);
24271 }
24272 // Empty attachment
24273 return callback(null, opts.binary ? createEmptyBlobOrBuffer(type) : '');
24274 }
24275
24276 if (opts.binary) {
24277 callback(null, readAsBlobOrBuffer(attach, type));
24278 } else {
24279 callback(null, attach.toString('base64'));
24280 }
24281 });
24282 };
24283
24284 api._bulkDocs = writeLock(function (req, opts, callback) {
24285 var newEdits = opts.new_edits;
24286 var results = new Array(req.docs.length);
24287 var fetchedDocs = new Map();
24288 var stemmedRevs = new Map();
24289
24290 var txn = new LevelTransaction();
24291 var docCountDelta = 0;
24292 var newUpdateSeq = db._updateSeq;
24293
24294 // parse the docs and give each a sequence number
24295 var userDocs = req.docs;
24296 var docInfos = userDocs.map(function (doc) {
24297 if (doc._id && isLocalId(doc._id)) {
24298 return doc;
24299 }
24300 var newDoc = parseDoc(doc, newEdits, api.__opts);
24301
24302 if (newDoc.metadata && !newDoc.metadata.rev_map) {
24303 newDoc.metadata.rev_map = {};
24304 }
24305
24306 return newDoc;
24307 });
24308 var infoErrors = docInfos.filter(function (doc) {
24309 return doc.error;
24310 });
24311
24312 if (infoErrors.length) {
24313 return callback(infoErrors[0]);
24314 }
24315
24316 // verify any stub attachments as a precondition test
24317
24318 function verifyAttachment(digest, callback) {
24319 txn.get(stores.attachmentStore, digest, function (levelErr) {
24320 if (levelErr) {
24321 var err = createError(MISSING_STUB,
24322 'unknown stub attachment with digest ' +
24323 digest);
24324 callback(err);
24325 } else {
24326 callback();
24327 }
24328 });
24329 }
24330
24331 function verifyAttachments(finish) {
24332 var digests = [];
24333 userDocs.forEach(function (doc) {
24334 if (doc && doc._attachments) {
24335 Object.keys(doc._attachments).forEach(function (filename) {
24336 var att = doc._attachments[filename];
24337 if (att.stub) {
24338 digests.push(att.digest);
24339 }
24340 });
24341 }
24342 });
24343 if (!digests.length) {
24344 return finish();
24345 }
24346 var numDone = 0;
24347 var err;
24348
24349 digests.forEach(function (digest) {
24350 verifyAttachment(digest, function (attErr) {
24351 if (attErr && !err) {
24352 err = attErr;
24353 }
24354
24355 if (++numDone === digests.length) {
24356 finish(err);
24357 }
24358 });
24359 });
24360 }
24361
24362 function fetchExistingDocs(finish) {
24363 var numDone = 0;
24364 var overallErr;
24365 function checkDone() {
24366 if (++numDone === userDocs.length) {
24367 return finish(overallErr);
24368 }
24369 }
24370
24371 userDocs.forEach(function (doc) {
24372 if (doc._id && isLocalId(doc._id)) {
24373 // skip local docs
24374 return checkDone();
24375 }
24376 txn.get(stores.docStore, doc._id, function (err, info) {
24377 if (err) {
24378 /* istanbul ignore if */
24379 if (err.name !== 'NotFoundError') {
24380 overallErr = err;
24381 }
24382 } else {
24383 fetchedDocs.set(doc._id, info);
24384 }
24385 checkDone();
24386 });
24387 });
24388 }
24389
24390 function compact(revsMap, callback) {
24391 var promise = Promise.resolve();
24392 revsMap.forEach(function (revs, docId) {
24393 // TODO: parallelize, for now need to be sequential to
24394 // pass orphaned attachment tests
24395 promise = promise.then(function () {
24396 return new Promise(function (resolve, reject) {
24397 api._doCompactionNoLock(docId, revs, {ctx: txn}, function (err) {
24398 /* istanbul ignore if */
24399 if (err) {
24400 return reject(err);
24401 }
24402 resolve();
24403 });
24404 });
24405 });
24406 });
24407
24408 promise.then(function () {
24409 callback();
24410 }, callback);
24411 }
24412
24413 function autoCompact(callback) {
24414 var revsMap = new Map();
24415 fetchedDocs.forEach(function (metadata, docId) {
24416 revsMap.set(docId, compactTree(metadata));
24417 });
24418 compact(revsMap, callback);
24419 }
24420
24421 function finish() {
24422 compact(stemmedRevs, function (error) {
24423 /* istanbul ignore if */
24424 if (error) {
24425 complete(error);
24426 }
24427 if (api.auto_compaction) {
24428 return autoCompact(complete);
24429 }
24430 complete();
24431 });
24432 }
24433
24434 function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,
24435 isUpdate, delta, resultsIdx, callback2) {
24436 docCountDelta += delta;
24437
24438 var err = null;
24439 var recv = 0;
24440
24441 docInfo.metadata.winningRev = winningRev$$1;
24442 docInfo.metadata.deleted = winningRevIsDeleted;
24443
24444 docInfo.data._id = docInfo.metadata.id;
24445 docInfo.data._rev = docInfo.metadata.rev;
24446
24447 if (newRevIsDeleted) {
24448 docInfo.data._deleted = true;
24449 }
24450
24451 if (docInfo.stemmedRevs.length) {
24452 stemmedRevs.set(docInfo.metadata.id, docInfo.stemmedRevs);
24453 }
24454
24455 var attachments = docInfo.data._attachments ?
24456 Object.keys(docInfo.data._attachments) :
24457 [];
24458
24459 function attachmentSaved(attachmentErr) {
24460 recv++;
24461 if (!err) {
24462 /* istanbul ignore if */
24463 if (attachmentErr) {
24464 err = attachmentErr;
24465 callback2(err);
24466 } else if (recv === attachments.length) {
24467 finish();
24468 }
24469 }
24470 }
24471
24472 function onMD5Load(doc, key, data, attachmentSaved) {
24473 return function (result) {
24474 saveAttachment(doc, MD5_PREFIX + result, key, data, attachmentSaved);
24475 };
24476 }
24477
24478 function doMD5(doc, key, attachmentSaved) {
24479 return function (data) {
24480 binaryMd5(data, onMD5Load(doc, key, data, attachmentSaved));
24481 };
24482 }
24483
24484 for (var i = 0; i < attachments.length; i++) {
24485 var key = attachments[i];
24486 var att = docInfo.data._attachments[key];
24487
24488 if (att.stub) {
24489 // still need to update the refs mapping
24490 var id = docInfo.data._id;
24491 var rev$$1 = docInfo.data._rev;
24492 saveAttachmentRefs(id, rev$$1, att.digest, attachmentSaved);
24493 continue;
24494 }
24495 var data;
24496 if (typeof att.data === 'string') {
24497 // input is assumed to be a base64 string
24498 try {
24499 data = thisAtob(att.data);
24500 } catch (e) {
24501 callback(createError(BAD_ARG,
24502 'Attachment is not a valid base64 string'));
24503 return;
24504 }
24505 doMD5(docInfo, key, attachmentSaved)(data);
24506 } else {
24507 prepareAttachmentForStorage(att.data,
24508 doMD5(docInfo, key, attachmentSaved));
24509 }
24510 }
24511
24512 function finish() {
24513 var seq = docInfo.metadata.rev_map[docInfo.metadata.rev];
24514 /* istanbul ignore if */
24515 if (seq) {
24516 // check that there aren't any existing revisions with the same
24517 // revision id, else we shouldn't do anything
24518 return callback2();
24519 }
24520 seq = ++newUpdateSeq;
24521 docInfo.metadata.rev_map[docInfo.metadata.rev] =
24522 docInfo.metadata.seq = seq;
24523 var seqKey = formatSeq(seq);
24524 var batch = [{
24525 key: seqKey,
24526 value: docInfo.data,
24527 prefix: stores.bySeqStore,
24528 type: 'put'
24529 }, {
24530 key: docInfo.metadata.id,
24531 value: docInfo.metadata,
24532 prefix: stores.docStore,
24533 type: 'put'
24534 }];
24535 txn.batch(batch);
24536 results[resultsIdx] = {
24537 ok: true,
24538 id: docInfo.metadata.id,
24539 rev: docInfo.metadata.rev
24540 };
24541 fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);
24542 callback2();
24543 }
24544
24545 if (!attachments.length) {
24546 finish();
24547 }
24548 }
24549
24550 // attachments are queued per-digest, otherwise the refs could be
24551 // overwritten by concurrent writes in the same bulkDocs session
24552 var attachmentQueues = {};
24553
24554 function saveAttachmentRefs(id, rev$$1, digest, callback) {
24555
24556 function fetchAtt() {
24557 return new Promise(function (resolve, reject) {
24558 txn.get(stores.attachmentStore, digest, function (err, oldAtt) {
24559 /* istanbul ignore if */
24560 if (err && err.name !== 'NotFoundError') {
24561 return reject(err);
24562 }
24563 resolve(oldAtt);
24564 });
24565 });
24566 }
24567
24568 function saveAtt(oldAtt) {
24569 var ref = [id, rev$$1].join('@');
24570 var newAtt = {};
24571
24572 if (oldAtt) {
24573 if (oldAtt.refs) {
24574 // only update references if this attachment already has them
24575 // since we cannot migrate old style attachments here without
24576 // doing a full db scan for references
24577 newAtt.refs = oldAtt.refs;
24578 newAtt.refs[ref] = true;
24579 }
24580 } else {
24581 newAtt.refs = {};
24582 newAtt.refs[ref] = true;
24583 }
24584
24585 return new Promise(function (resolve) {
24586 txn.batch([{
24587 type: 'put',
24588 prefix: stores.attachmentStore,
24589 key: digest,
24590 value: newAtt
24591 }]);
24592 resolve(!oldAtt);
24593 });
24594 }
24595
24596 // put attachments in a per-digest queue, to avoid two docs with the same
24597 // attachment overwriting each other
24598 var queue = attachmentQueues[digest] || Promise.resolve();
24599 attachmentQueues[digest] = queue.then(function () {
24600 return fetchAtt().then(saveAtt).then(function (isNewAttachment) {
24601 callback(null, isNewAttachment);
24602 }, callback);
24603 });
24604 }
24605
24606 function saveAttachment(docInfo, digest, key, data, callback) {
24607 var att = docInfo.data._attachments[key];
24608 delete att.data;
24609 att.digest = digest;
24610 att.length = data.length;
24611 var id = docInfo.metadata.id;
24612 var rev$$1 = docInfo.metadata.rev;
24613 att.revpos = parseInt(rev$$1, 10);
24614
24615 saveAttachmentRefs(id, rev$$1, digest, function (err, isNewAttachment) {
24616 /* istanbul ignore if */
24617 if (err) {
24618 return callback(err);
24619 }
24620 // do not try to store empty attachments
24621 if (data.length === 0) {
24622 return callback(err);
24623 }
24624 if (!isNewAttachment) {
24625 // small optimization - don't bother writing it again
24626 return callback(err);
24627 }
24628 txn.batch([{
24629 type: 'put',
24630 prefix: stores.binaryStore,
24631 key: digest,
24632 value: Buffer.from(data, 'binary')
24633 }]);
24634 callback();
24635 });
24636 }
24637
24638 function complete(err) {
24639 /* istanbul ignore if */
24640 if (err) {
24641 return nextTick(function () {
24642 callback(err);
24643 });
24644 }
24645 txn.batch([
24646 {
24647 prefix: stores.metaStore,
24648 type: 'put',
24649 key: UPDATE_SEQ_KEY,
24650 value: newUpdateSeq
24651 },
24652 {
24653 prefix: stores.metaStore,
24654 type: 'put',
24655 key: DOC_COUNT_KEY,
24656 value: db._docCount + docCountDelta
24657 }
24658 ]);
24659 txn.execute(db, function (err) {
24660 /* istanbul ignore if */
24661 if (err) {
24662 return callback(err);
24663 }
24664 db._docCount += docCountDelta;
24665 db._updateSeq = newUpdateSeq;
24666 levelChanges.notify(name);
24667 nextTick(function () {
24668 callback(null, results);
24669 });
24670 });
24671 }
24672
24673 if (!docInfos.length) {
24674 return callback(null, []);
24675 }
24676
24677 verifyAttachments(function (err) {
24678 if (err) {
24679 return callback(err);
24680 }
24681 fetchExistingDocs(function (err) {
24682 /* istanbul ignore if */
24683 if (err) {
24684 return callback(err);
24685 }
24686 processDocs(revLimit, docInfos, api, fetchedDocs, txn, results,
24687 writeDoc, opts, finish);
24688 });
24689 });
24690 });
24691 api._allDocs = function (opts, callback) {
24692 if ('keys' in opts) {
24693 return allDocsKeysQuery(this, opts);
24694 }
24695 return readLock(function (opts, callback) {
24696 opts = clone$1(opts);
24697 countDocs(function (err, docCount) {
24698 /* istanbul ignore if */
24699 if (err) {
24700 return callback(err);
24701 }
24702 var readstreamOpts = {};
24703 var skip = opts.skip || 0;
24704 if (opts.startkey) {
24705 readstreamOpts.gte = opts.startkey;
24706 }
24707 if (opts.endkey) {
24708 readstreamOpts.lte = opts.endkey;
24709 }
24710 if (opts.key) {
24711 readstreamOpts.gte = readstreamOpts.lte = opts.key;
24712 }
24713 if (opts.descending) {
24714 readstreamOpts.reverse = true;
24715 // switch start and ends
24716 var tmp = readstreamOpts.lte;
24717 readstreamOpts.lte = readstreamOpts.gte;
24718 readstreamOpts.gte = tmp;
24719 }
24720 var limit;
24721 if (typeof opts.limit === 'number') {
24722 limit = opts.limit;
24723 }
24724 if (limit === 0 ||
24725 ('gte' in readstreamOpts && 'lte' in readstreamOpts &&
24726 readstreamOpts.gte > readstreamOpts.lte)) {
24727 // should return 0 results when start is greater than end.
24728 // normally level would "fix" this for us by reversing the order,
24729 // so short-circuit instead
24730 var returnVal = {
24731 total_rows: docCount,
24732 offset: opts.skip,
24733 rows: []
24734 };
24735 /* istanbul ignore if */
24736 if (opts.update_seq) {
24737 returnVal.update_seq = db._updateSeq;
24738 }
24739 return callback(null, returnVal);
24740 }
24741 var results = [];
24742 var docstream = stores.docStore.readStream(readstreamOpts);
24743
24744 var throughStream = through2.obj(function (entry, _, next) {
24745 var metadata = entry.value;
24746 // winningRev and deleted are performance-killers, but
24747 // in newer versions of PouchDB, they are cached on the metadata
24748 var winningRev$$1 = getWinningRev(metadata);
24749 var deleted = getIsDeleted(metadata, winningRev$$1);
24750 if (!deleted) {
24751 if (skip-- > 0) {
24752 next();
24753 return;
24754 } else if (typeof limit === 'number' && limit-- <= 0) {
24755 docstream.unpipe();
24756 docstream.destroy();
24757 next();
24758 return;
24759 }
24760 } else if (opts.deleted !== 'ok') {
24761 next();
24762 return;
24763 }
24764 function allDocsInner(data) {
24765 var doc = {
24766 id: metadata.id,
24767 key: metadata.id,
24768 value: {
24769 rev: winningRev$$1
24770 }
24771 };
24772 if (opts.include_docs) {
24773 doc.doc = data;
24774 doc.doc._rev = doc.value.rev;
24775 if (opts.conflicts) {
24776 var conflicts = collectConflicts(metadata);
24777 if (conflicts.length) {
24778 doc.doc._conflicts = conflicts;
24779 }
24780 }
24781 for (var att in doc.doc._attachments) {
24782 if (Object.prototype.hasOwnProperty.call(doc.doc._attachments, att)) {
24783 doc.doc._attachments[att].stub = true;
24784 }
24785 }
24786 }
24787 if (opts.inclusive_end === false && metadata.id === opts.endkey) {
24788 return next();
24789 } else if (deleted) {
24790 if (opts.deleted === 'ok') {
24791 doc.value.deleted = true;
24792 doc.doc = null;
24793 } else {
24794 /* istanbul ignore next */
24795 return next();
24796 }
24797 }
24798 results.push(doc);
24799 next();
24800 }
24801 if (opts.include_docs) {
24802 var seq = metadata.rev_map[winningRev$$1];
24803 stores.bySeqStore.get(formatSeq(seq), function (err, data) {
24804 allDocsInner(data);
24805 });
24806 }
24807 else {
24808 allDocsInner();
24809 }
24810 }, function (next) {
24811 Promise.resolve().then(function () {
24812 if (opts.include_docs && opts.attachments) {
24813 return fetchAttachments(results, stores, opts);
24814 }
24815 }).then(function () {
24816 var returnVal = {
24817 total_rows: docCount,
24818 offset: opts.skip,
24819 rows: results
24820 };
24821
24822 /* istanbul ignore if */
24823 if (opts.update_seq) {
24824 returnVal.update_seq = db._updateSeq;
24825 }
24826 callback(null, returnVal);
24827 }, callback);
24828 next();
24829 }).on('unpipe', function () {
24830 throughStream.end();
24831 });
24832
24833 docstream.on('error', callback);
24834
24835 docstream.pipe(throughStream);
24836 });
24837 })(opts, callback);
24838 };
24839
24840 api._changes = function (opts) {
24841 opts = clone$1(opts);
24842
24843 if (opts.continuous) {
24844 var id = name + ':' + uuid$1();
24845 levelChanges.addListener(name, id, api, opts);
24846 levelChanges.notify(name);
24847 return {
24848 cancel: function () {
24849 levelChanges.removeListener(name, id);
24850 }
24851 };
24852 }
24853
24854 var descending = opts.descending;
24855 var results = [];
24856 var lastSeq = opts.since || 0;
24857 var called = 0;
24858 var streamOpts = {
24859 reverse: descending
24860 };
24861 var limit;
24862 if ('limit' in opts && opts.limit > 0) {
24863 limit = opts.limit;
24864 }
24865 if (!streamOpts.reverse) {
24866 streamOpts.start = formatSeq(opts.since || 0);
24867 }
24868
24869 var docIds = opts.doc_ids && new Set(opts.doc_ids);
24870 var filter = filterChange(opts);
24871 var docIdsToMetadata = new Map();
24872
24873 function complete() {
24874 opts.done = true;
24875 if (opts.return_docs && opts.limit) {
24876 /* istanbul ignore if */
24877 if (opts.limit < results.length) {
24878 results.length = opts.limit;
24879 }
24880 }
24881 changeStream.unpipe(throughStream);
24882 changeStream.destroy();
24883 if (!opts.continuous && !opts.cancelled) {
24884 if (opts.include_docs && opts.attachments && opts.return_docs) {
24885 fetchAttachments(results, stores, opts).then(function () {
24886 opts.complete(null, {results, last_seq: lastSeq});
24887 });
24888 } else {
24889 opts.complete(null, {results, last_seq: lastSeq});
24890 }
24891 }
24892 }
24893 var changeStream = stores.bySeqStore.readStream(streamOpts);
24894 var throughStream = through2.obj(function (data, _, next) {
24895 if (limit && called >= limit) {
24896 complete();
24897 return next();
24898 }
24899 if (opts.cancelled || opts.done) {
24900 return next();
24901 }
24902
24903 var seq = parseSeq(data.key);
24904 var doc = data.value;
24905
24906 if (seq === opts.since && !descending) {
24907 // couchdb ignores `since` if descending=true
24908 return next();
24909 }
24910
24911 if (docIds && !docIds.has(doc._id)) {
24912 return next();
24913 }
24914
24915 var metadata;
24916
24917 function onGetMetadata(metadata) {
24918 var winningRev$$1 = getWinningRev(metadata);
24919
24920 function onGetWinningDoc(winningDoc) {
24921
24922 var change = opts.processChange(winningDoc, metadata, opts);
24923 change.seq = metadata.seq;
24924
24925 var filtered = filter(change);
24926 if (typeof filtered === 'object') {
24927 return opts.complete(filtered);
24928 }
24929
24930 if (filtered) {
24931 called++;
24932
24933 if (opts.attachments && opts.include_docs) {
24934 // fetch attachment immediately for the benefit
24935 // of live listeners
24936 fetchAttachments([change], stores, opts).then(function () {
24937 opts.onChange(change);
24938 });
24939 } else {
24940 opts.onChange(change);
24941 }
24942
24943 if (opts.return_docs) {
24944 results.push(change);
24945 }
24946 }
24947 next();
24948 }
24949
24950 if (metadata.seq !== seq) {
24951 // some other seq is later
24952 return next();
24953 }
24954
24955 lastSeq = seq;
24956
24957 if (winningRev$$1 === doc._rev) {
24958 return onGetWinningDoc(doc);
24959 }
24960
24961 // fetch the winner
24962
24963 var winningSeq = metadata.rev_map[winningRev$$1];
24964
24965 stores.bySeqStore.get(formatSeq(winningSeq), function (err, doc) {
24966 onGetWinningDoc(doc);
24967 });
24968 }
24969
24970 metadata = docIdsToMetadata.get(doc._id);
24971 if (metadata) { // cached
24972 return onGetMetadata(metadata);
24973 }
24974 // metadata not cached, have to go fetch it
24975 stores.docStore.get(doc._id, function (err, metadata) {
24976 /* istanbul ignore if */
24977 if (opts.cancelled || opts.done || db.isClosed() ||
24978 isLocalId(metadata.id)) {
24979 return next();
24980 }
24981 docIdsToMetadata.set(doc._id, metadata);
24982 onGetMetadata(metadata);
24983 });
24984 }, function (next) {
24985 if (opts.cancelled) {
24986 return next();
24987 }
24988 if (opts.return_docs && opts.limit) {
24989 /* istanbul ignore if */
24990 if (opts.limit < results.length) {
24991 results.length = opts.limit;
24992 }
24993 }
24994
24995 next();
24996 }).on('unpipe', function () {
24997 throughStream.end();
24998 complete();
24999 });
25000 changeStream.pipe(throughStream);
25001 return {
25002 cancel: function () {
25003 opts.cancelled = true;
25004 complete();
25005 }
25006 };
25007 };
25008
25009 api._close = function (callback) {
25010 /* istanbul ignore if */
25011 if (db.isClosed()) {
25012 return callback(createError(NOT_OPEN));
25013 }
25014 db.close(function (err) {
25015 /* istanbul ignore if */
25016 if (err) {
25017 callback(err);
25018 } else {
25019 dbStore.delete(name);
25020
25021 var adapterName = functionName(leveldown);
25022 var adapterStore = dbStores.get(adapterName);
25023 var viewNamePrefix = PouchDB$1.prefix + name + "-mrview-";
25024 var keys = [...adapterStore.keys()].filter(k => k.includes(viewNamePrefix));
25025 keys.forEach(key => {
25026 var eventEmitter = adapterStore.get(key);
25027 eventEmitter.removeAllListeners();
25028 eventEmitter.close();
25029 adapterStore.delete(key);
25030 });
25031
25032 callback();
25033 }
25034 });
25035 };
25036
25037 api._getRevisionTree = function (docId, callback) {
25038 stores.docStore.get(docId, function (err, metadata) {
25039 if (err) {
25040 callback(createError(MISSING_DOC));
25041 } else {
25042 callback(null, metadata.rev_tree);
25043 }
25044 });
25045 };
25046
25047 api._doCompaction = writeLock(function (docId, revs, opts, callback) {
25048 api._doCompactionNoLock(docId, revs, opts, callback);
25049 });
25050
25051 // the NoLock version is for use by bulkDocs
25052 api._doCompactionNoLock = function (docId, revs, opts, callback) {
25053 if (typeof opts === 'function') {
25054 callback = opts;
25055 opts = {};
25056 }
25057
25058 if (!revs.length) {
25059 return callback();
25060 }
25061 var txn = opts.ctx || new LevelTransaction();
25062
25063 txn.get(stores.docStore, docId, function (err, metadata) {
25064 /* istanbul ignore if */
25065 if (err) {
25066 return callback(err);
25067 }
25068 var seqs = revs.map(function (rev$$1) {
25069 var seq = metadata.rev_map[rev$$1];
25070 delete metadata.rev_map[rev$$1];
25071 return seq;
25072 });
25073 traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
25074 revHash, ctx, opts) {
25075 var rev$$1 = pos + '-' + revHash;
25076 if (revs.indexOf(rev$$1) !== -1) {
25077 opts.status = 'missing';
25078 }
25079 });
25080
25081 var batch = [];
25082 batch.push({
25083 key: metadata.id,
25084 value: metadata,
25085 type: 'put',
25086 prefix: stores.docStore
25087 });
25088
25089 var digestMap = {};
25090 var numDone = 0;
25091 var overallErr;
25092 function checkDone(err) {
25093 /* istanbul ignore if */
25094 if (err) {
25095 overallErr = err;
25096 }
25097 if (++numDone === revs.length) { // done
25098 /* istanbul ignore if */
25099 if (overallErr) {
25100 return callback(overallErr);
25101 }
25102 deleteOrphanedAttachments();
25103 }
25104 }
25105
25106 function finish(err) {
25107 /* istanbul ignore if */
25108 if (err) {
25109 return callback(err);
25110 }
25111 txn.batch(batch);
25112 if (opts.ctx) {
25113 // don't execute immediately
25114 return callback();
25115 }
25116 txn.execute(db, callback);
25117 }
25118
25119 function deleteOrphanedAttachments() {
25120 var possiblyOrphanedAttachments = Object.keys(digestMap);
25121 if (!possiblyOrphanedAttachments.length) {
25122 return finish();
25123 }
25124 var numDone = 0;
25125 var overallErr;
25126 function checkDone(err) {
25127 /* istanbul ignore if */
25128 if (err) {
25129 overallErr = err;
25130 }
25131 if (++numDone === possiblyOrphanedAttachments.length) {
25132 finish(overallErr);
25133 }
25134 }
25135 var refsToDelete = new Map();
25136 revs.forEach(function (rev$$1) {
25137 refsToDelete.set(docId + '@' + rev$$1, true);
25138 });
25139 possiblyOrphanedAttachments.forEach(function (digest) {
25140 txn.get(stores.attachmentStore, digest, function (err, attData) {
25141 /* istanbul ignore if */
25142 if (err) {
25143 if (err.name === 'NotFoundError') {
25144 return checkDone();
25145 } else {
25146 return checkDone(err);
25147 }
25148 }
25149 var refs = Object.keys(attData.refs || {}).filter(function (ref) {
25150 return !refsToDelete.has(ref);
25151 });
25152 var newRefs = {};
25153 refs.forEach(function (ref) {
25154 newRefs[ref] = true;
25155 });
25156 if (refs.length) { // not orphaned
25157 batch.push({
25158 key: digest,
25159 type: 'put',
25160 value: {refs: newRefs},
25161 prefix: stores.attachmentStore
25162 });
25163 } else { // orphaned, can safely delete
25164 batch = batch.concat([{
25165 key: digest,
25166 type: 'del',
25167 prefix: stores.attachmentStore
25168 }, {
25169 key: digest,
25170 type: 'del',
25171 prefix: stores.binaryStore
25172 }]);
25173 }
25174 checkDone();
25175 });
25176 });
25177 }
25178
25179 seqs.forEach(function (seq) {
25180 batch.push({
25181 key: formatSeq(seq),
25182 type: 'del',
25183 prefix: stores.bySeqStore
25184 });
25185 txn.get(stores.bySeqStore, formatSeq(seq), function (err, doc) {
25186 /* istanbul ignore if */
25187 if (err) {
25188 if (err.name === 'NotFoundError') {
25189 return checkDone();
25190 } else {
25191 return checkDone(err);
25192 }
25193 }
25194 var atts = Object.keys(doc._attachments || {});
25195 atts.forEach(function (attName) {
25196 var digest = doc._attachments[attName].digest;
25197 digestMap[digest] = true;
25198 });
25199 checkDone();
25200 });
25201 });
25202 });
25203 };
25204
25205 api._getLocal = function (id, callback) {
25206 stores.localStore.get(id, function (err, doc) {
25207 if (err) {
25208 callback(createError(MISSING_DOC));
25209 } else {
25210 callback(null, doc);
25211 }
25212 });
25213 };
25214
25215 api._putLocal = function (doc, opts, callback) {
25216 if (typeof opts === 'function') {
25217 callback = opts;
25218 opts = {};
25219 }
25220 if (opts.ctx) {
25221 api._putLocalNoLock(doc, opts, callback);
25222 } else {
25223 api._putLocalWithLock(doc, opts, callback);
25224 }
25225 };
25226
25227 api._putLocalWithLock = writeLock(function (doc, opts, callback) {
25228 api._putLocalNoLock(doc, opts, callback);
25229 });
25230
25231 // the NoLock version is for use by bulkDocs
25232 api._putLocalNoLock = function (doc, opts, callback) {
25233 delete doc._revisions; // ignore this, trust the rev
25234 var oldRev = doc._rev;
25235 var id = doc._id;
25236
25237 var txn = opts.ctx || new LevelTransaction();
25238
25239 txn.get(stores.localStore, id, function (err, resp) {
25240 if (err && oldRev) {
25241 return callback(createError(REV_CONFLICT));
25242 }
25243 if (resp && resp._rev !== oldRev) {
25244 return callback(createError(REV_CONFLICT));
25245 }
25246 doc._rev =
25247 oldRev ? '0-' + (parseInt(oldRev.split('-')[1], 10) + 1) : '0-1';
25248 var batch = [
25249 {
25250 type: 'put',
25251 prefix: stores.localStore,
25252 key: id,
25253 value: doc
25254 }
25255 ];
25256
25257 txn.batch(batch);
25258 var ret = {ok: true, id: doc._id, rev: doc._rev};
25259
25260 if (opts.ctx) {
25261 // don't execute immediately
25262 return callback(null, ret);
25263 }
25264 txn.execute(db, function (err) {
25265 /* istanbul ignore if */
25266 if (err) {
25267 return callback(err);
25268 }
25269 callback(null, ret);
25270 });
25271 });
25272 };
25273
25274 api._removeLocal = function (doc, opts, callback) {
25275 if (typeof opts === 'function') {
25276 callback = opts;
25277 opts = {};
25278 }
25279 if (opts.ctx) {
25280 api._removeLocalNoLock(doc, opts, callback);
25281 } else {
25282 api._removeLocalWithLock(doc, opts, callback);
25283 }
25284 };
25285
25286 api._removeLocalWithLock = writeLock(function (doc, opts, callback) {
25287 api._removeLocalNoLock(doc, opts, callback);
25288 });
25289
25290 // the NoLock version is for use by bulkDocs
25291 api._removeLocalNoLock = function (doc, opts, callback) {
25292 var txn = opts.ctx || new LevelTransaction();
25293 txn.get(stores.localStore, doc._id, function (err, resp) {
25294 if (err) {
25295 /* istanbul ignore if */
25296 if (err.name !== 'NotFoundError') {
25297 return callback(err);
25298 } else {
25299 return callback(createError(MISSING_DOC));
25300 }
25301 }
25302 if (resp._rev !== doc._rev) {
25303 return callback(createError(REV_CONFLICT));
25304 }
25305 txn.batch([{
25306 prefix: stores.localStore,
25307 type: 'del',
25308 key: doc._id
25309 }]);
25310 var ret = {ok: true, id: doc._id, rev: '0-0'};
25311 if (opts.ctx) {
25312 // don't execute immediately
25313 return callback(null, ret);
25314 }
25315 txn.execute(db, function (err) {
25316 /* istanbul ignore if */
25317 if (err) {
25318 return callback(err);
25319 }
25320 callback(null, ret);
25321 });
25322 });
25323 };
25324
25325 // close and delete open leveldb stores
25326 api._destroy = function (opts, callback) {
25327 var dbStore;
25328 var leveldownName = functionName(leveldown);
25329 /* istanbul ignore else */
25330 if (dbStores.has(leveldownName)) {
25331 dbStore = dbStores.get(leveldownName);
25332 } else {
25333 return callDestroy(name, callback);
25334 }
25335
25336 /* istanbul ignore else */
25337 if (dbStore.has(name)) {
25338 levelChanges.removeAllListeners(name);
25339
25340 dbStore.get(name).close(function () {
25341 dbStore.delete(name);
25342 callDestroy(name, callback);
25343 });
25344 } else {
25345 callDestroy(name, callback);
25346 }
25347 };
25348 function callDestroy(name, cb) {
25349 // May not exist if leveldown is backed by memory adapter
25350 /* istanbul ignore else */
25351 if ('destroy' in leveldown) {
25352 leveldown.destroy(name, cb);
25353 } else {
25354 cb(null);
25355 }
25356 }
25357}
25358
25359function MemDownPouch(opts, callback) {
25360 var _opts = Object.assign({
25361 db: memdown
25362 }, opts);
25363
25364 LevelPouch.call(this, _opts, callback);
25365}
25366
25367// overrides for normal LevelDB behavior on Node
25368MemDownPouch.valid = function () {
25369 return true;
25370};
25371MemDownPouch.use_prefix = false;
25372
25373function MemoryPouchPlugin (PouchDB) {
25374 PouchDB.adapter('memory', MemDownPouch, true);
25375}
25376
25377// this code only runs in the browser, as its own dist/ script
25378
25379if (typeof PouchDB === 'undefined') {
25380 guardedConsole('error', 'memory adapter plugin error: ' +
25381 'Cannot find global "PouchDB" object! ' +
25382 'Did you remember to include pouchdb.js?');
25383} else {
25384 PouchDB.plugin(MemoryPouchPlugin);
25385}
25386
25387}).call(this)}).call(this,_dereq_("buffer").Buffer)
25388},{"buffer":4,"double-ended-queue":22,"events":33,"level-codec":48,"levelup":70,"ltgt":72,"memdown":74,"readable-stream":101,"spark-md5":104,"through2":138,"uuid":144,"vuvuzela":159}]},{},[162]);
25389
\No newline at end of file